Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add slash action tags, topic reference tool, and command bus system (#12860)

Innei4438b559e675
diff --git a/.agents/skills/typescript/SKILL.md b/.agents/skills/typescript/SKILL.md
index 561109f5fec..3916d0d69c4 100644
--- a/.agents/skills/typescript/SKILL.md
+++ b/.agents/skills/typescript/SKILL.md
@@ -14,6 +14,9 @@ description: TypeScript code style and optimization guidelines. Use when writing
- Prefer `as const satisfies XyzInterface` over plain `as const`
- Prefer `@ts-expect-error` over `@ts-ignore` over `as any`
- Avoid meaningless null/undefined parameters; design strict function contracts
+- Prefer ES module augmentation (`declare module '...'`) over `namespace`; do not introduce `namespace`-based extension patterns
+- When a type needs extensibility, expose a small mergeable interface at the source type and let each feature/plugin augment it locally instead of centralizing all extension fields in one registry file
+- For package-local extensibility patterns like `PipelineContext.metadata`, define the metadata fields next to the processor/provider/plugin that reads or writes them
## Async Patterns
diff --git a/locales/ar/editor.json b/locales/ar/editor.json
index a3a8cdda691..523b04ff4a3 100644
--- a/locales/ar/editor.json
+++ b/locales/ar/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "أمر",
+ "actionTag.category.skill": "مهارة",
+ "actionTag.category.tool": "أداة",
+ "actionTag.tooltip.command": "يشغّل أمر الشرطة المائلة على جانب العميل قبل الإرسال.",
+ "actionTag.tooltip.skill": "يحمّل حزمة مهارات قابلة لإعادة الاستخدام لهذا الطلب.",
+ "actionTag.tooltip.tool": "يشير إلى أداة اختارها المستخدم صراحةً لهذا الطلب.",
"actions.expand.off": "طي",
"actions.expand.on": "توسيع",
"actions.typobar.off": "إخفاء شريط تنسيق النص",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "الاحتفاظ بالجميع",
"modifier.reject": "تراجع",
"modifier.rejectAll": "تراجع عن الكل",
+ "slash.compact": "ضغط السياق",
"slash.h1": "عنوان 1",
"slash.h2": "عنوان 2",
"slash.h3": "عنوان 3",
"slash.hr": "فاصل",
+ "slash.newTopic": "الإرسال في موضوع جديد",
+ "slash.rewrite": "إعادة الصياغة",
+ "slash.summarize": "تلخيص",
"slash.table": "جدول",
"slash.tex": "صيغة TeX",
+ "slash.translate": "ترجمة",
"table.delete": "حذف الجدول",
"table.deleteColumn": "حذف العمود",
"table.deleteRow": "حذف الصف",
diff --git a/locales/ar/plugin.json b/locales/ar/plugin.json
index 87bb903d225..e7362cd4d81 100644
--- a/locales/ar/plugin.json
+++ b/locales/ar/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "البحث عن المهارات",
"builtins.lobe-skills.title": "المهارات",
"builtins.lobe-tools.apiName.activateTools": "تفعيل الأدوات",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "الحصول على سياق الموضوع",
+ "builtins.lobe-topic-reference.title": "مرجع الموضوع",
"builtins.lobe-user-memory.apiName.addContextMemory": "إضافة ذاكرة السياق",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "إضافة ذاكرة الخبرة",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "إضافة ذاكرة الهوية",
diff --git a/locales/bg-BG/editor.json b/locales/bg-BG/editor.json
index a5981bd9363..62e383bb126 100644
--- a/locales/bg-BG/editor.json
+++ b/locales/bg-BG/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Команда",
+ "actionTag.category.skill": "Умение",
+ "actionTag.category.tool": "Инструмент",
+ "actionTag.tooltip.command": "Изпълнява локална slash команда преди изпращане.",
+ "actionTag.tooltip.skill": "Зарежда многократно използваем пакет с умения за тази заявка.",
+ "actionTag.tooltip.tool": "Маркира инструмент, който потребителят е избрал изрично за тази заявка.",
"actions.expand.off": "Свий",
"actions.expand.on": "Разгъни",
"actions.typobar.off": "Скрий лентата с форматиране",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Запази всички",
"modifier.reject": "Отмени",
"modifier.rejectAll": "Отмени всички",
+ "slash.compact": "Компресирай контекста",
"slash.h1": "Заглавие 1",
"slash.h2": "Заглавие 2",
"slash.h3": "Заглавие 3",
"slash.hr": "Разделител",
+ "slash.newTopic": "Изпрати в нова тема",
+ "slash.rewrite": "Пренапиши",
+ "slash.summarize": "Обобщи",
"slash.table": "Таблица",
"slash.tex": "TeX формула",
+ "slash.translate": "Преведи",
"table.delete": "Изтрий таблицата",
"table.deleteColumn": "Изтрий колона",
"table.deleteRow": "Изтрий ред",
diff --git a/locales/bg-BG/plugin.json b/locales/bg-BG/plugin.json
index 5fc50dceb19..59f886cb3ee 100644
--- a/locales/bg-BG/plugin.json
+++ b/locales/bg-BG/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Търсене на умения",
"builtins.lobe-skills.title": "Умения",
"builtins.lobe-tools.apiName.activateTools": "Активиране на инструменти",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Вземи контекста на темата",
+ "builtins.lobe-topic-reference.title": "Препратка към тема",
"builtins.lobe-user-memory.apiName.addContextMemory": "Добавяне на контекстна памет",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Добавяне на памет за опит",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Добавяне на памет за идентичност",
diff --git a/locales/de-DE/editor.json b/locales/de-DE/editor.json
index 49e92e46786..211dacdea3d 100644
--- a/locales/de-DE/editor.json
+++ b/locales/de-DE/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Befehl",
+ "actionTag.category.skill": "Fähigkeit",
+ "actionTag.category.tool": "Werkzeug",
+ "actionTag.tooltip.command": "Führt vor dem Senden einen clientseitigen Slash-Befehl aus.",
+ "actionTag.tooltip.skill": "Lädt für diese Anfrage ein wiederverwendbares Fähigkeitspaket.",
+ "actionTag.tooltip.tool": "Markiert ein Werkzeug, das der Benutzer für diese Anfrage ausdrücklich ausgewählt hat.",
"actions.expand.off": "Einklappen",
"actions.expand.on": "Ausklappen",
"actions.typobar.off": "Formatierungsleiste ausblenden",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Alle beibehalten",
"modifier.reject": "Zurücksetzen",
"modifier.rejectAll": "Alle zurücksetzen",
+ "slash.compact": "Kontext komprimieren",
"slash.h1": "Überschrift 1",
"slash.h2": "Überschrift 2",
"slash.h3": "Überschrift 3",
"slash.hr": "Trennlinie",
+ "slash.newTopic": "In neuem Thema senden",
+ "slash.rewrite": "Umschreiben",
+ "slash.summarize": "Zusammenfassen",
"slash.table": "Tabelle",
"slash.tex": "TeX-Formel",
+ "slash.translate": "Übersetzen",
"table.delete": "Tabelle löschen",
"table.deleteColumn": "Spalte löschen",
"table.deleteRow": "Zeile löschen",
diff --git a/locales/de-DE/plugin.json b/locales/de-DE/plugin.json
index bf37e96ed5c..9772445c170 100644
--- a/locales/de-DE/plugin.json
+++ b/locales/de-DE/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Fähigkeiten suchen",
"builtins.lobe-skills.title": "Fähigkeiten",
"builtins.lobe-tools.apiName.activateTools": "Werkzeuge aktivieren",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Themenkontext abrufen",
+ "builtins.lobe-topic-reference.title": "Themenreferenz",
"builtins.lobe-user-memory.apiName.addContextMemory": "Kontextgedächtnis hinzufügen",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Erfahrungsgedächtnis hinzufügen",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Identitätsgedächtnis hinzufügen",
diff --git a/locales/en-US/editor.json b/locales/en-US/editor.json
index d76ba3ca2f7..23b8b079051 100644
--- a/locales/en-US/editor.json
+++ b/locales/en-US/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Command",
+ "actionTag.category.skill": "Skill",
+ "actionTag.category.tool": "Tool",
+ "actionTag.tooltip.command": "Runs a client-side slash command before sending.",
+ "actionTag.tooltip.skill": "Loads a reusable skill package for this request.",
+ "actionTag.tooltip.tool": "Marks a tool the user explicitly selected for this request.",
"actions.expand.off": "Collapse",
"actions.expand.on": "Expand",
"actions.typobar.off": "Hide formatting toolbar",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Keep All",
"modifier.reject": "Revert",
"modifier.rejectAll": "Revert All",
+ "slash.compact": "Compact context",
"slash.h1": "Heading 1",
"slash.h2": "Heading 2",
"slash.h3": "Heading 3",
"slash.hr": "Divider",
+ "slash.newTopic": "Send in new topic",
+ "slash.rewrite": "Rewrite",
+ "slash.summarize": "Summarize",
"slash.table": "Table",
"slash.tex": "TeX Formula",
+ "slash.translate": "Translate",
"table.delete": "Delete table",
"table.deleteColumn": "Delete column",
"table.deleteRow": "Delete row",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index a1db1b03fa5..d2ea3966563 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -202,6 +202,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Search Skills",
"builtins.lobe-skills.title": "Skills",
"builtins.lobe-tools.apiName.activateTools": "Activate Tools",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Get Topic Context",
+ "builtins.lobe-topic-reference.title": "Topic Reference",
"builtins.lobe-user-memory.apiName.addContextMemory": "Add context memory",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Add experience memory",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Add identity memory",
diff --git a/locales/es-ES/editor.json b/locales/es-ES/editor.json
index bc53a5bf4e1..10b38b10249 100644
--- a/locales/es-ES/editor.json
+++ b/locales/es-ES/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Comando",
+ "actionTag.category.skill": "Habilidad",
+ "actionTag.category.tool": "Herramienta",
+ "actionTag.tooltip.command": "Ejecuta un comando de barra en el cliente antes de enviar.",
+ "actionTag.tooltip.skill": "Carga un paquete de habilidades reutilizable para esta solicitud.",
+ "actionTag.tooltip.tool": "Marca una herramienta que el usuario seleccionó explícitamente para esta solicitud.",
"actions.expand.off": "Colapsar",
"actions.expand.on": "Expandir",
"actions.typobar.off": "Ocultar barra de formato",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Conservar todo",
"modifier.reject": "Revertir",
"modifier.rejectAll": "Revertir todo",
+ "slash.compact": "Compactar contexto",
"slash.h1": "Encabezado 1",
"slash.h2": "Encabezado 2",
"slash.h3": "Encabezado 3",
"slash.hr": "Separador",
+ "slash.newTopic": "Enviar en un tema nuevo",
+ "slash.rewrite": "Reescribir",
+ "slash.summarize": "Resumir",
"slash.table": "Tabla",
"slash.tex": "Fórmula TeX",
+ "slash.translate": "Traducir",
"table.delete": "Eliminar tabla",
"table.deleteColumn": "Eliminar columna",
"table.deleteRow": "Eliminar fila",
diff --git a/locales/es-ES/plugin.json b/locales/es-ES/plugin.json
index 873ea1cefa0..eff81f0324b 100644
--- a/locales/es-ES/plugin.json
+++ b/locales/es-ES/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Buscar Habilidades",
"builtins.lobe-skills.title": "Habilidades",
"builtins.lobe-tools.apiName.activateTools": "Activar Herramientas",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Obtener contexto del tema",
+ "builtins.lobe-topic-reference.title": "Referencia de tema",
"builtins.lobe-user-memory.apiName.addContextMemory": "Agregar memoria de contexto",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Agregar memoria de experiencia",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Agregar memoria de identidad",
diff --git a/locales/fa-IR/editor.json b/locales/fa-IR/editor.json
index 8e9cdbb7b33..c8ef8947f57 100644
--- a/locales/fa-IR/editor.json
+++ b/locales/fa-IR/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "دستور",
+ "actionTag.category.skill": "مهارت",
+ "actionTag.category.tool": "ابزار",
+ "actionTag.tooltip.command": "پیش از ارسال، یک دستور اسلش سمت کلاینت را اجرا می‌کند.",
+ "actionTag.tooltip.skill": "برای این درخواست، یک بسته مهارت قابل استفاده مجدد را بارگذاری می‌کند.",
+ "actionTag.tooltip.tool": "ابزاری را که کاربر به‌طور صریح برای این درخواست انتخاب کرده است علامت‌گذاری می‌کند.",
"actions.expand.off": "جمع کردن",
"actions.expand.on": "باز کردن",
"actions.typobar.off": "پنهان کردن نوار ابزار قالب‌بندی",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "نگه‌داشتن همه",
"modifier.reject": "بازگرداندن",
"modifier.rejectAll": "بازگرداندن همه",
+ "slash.compact": "فشرده‌سازی زمینه",
"slash.h1": "سرفصل ۱",
"slash.h2": "سرفصل ۲",
"slash.h3": "سرفصل ۳",
"slash.hr": "خط جداکننده",
+ "slash.newTopic": "ارسال در موضوع جدید",
+ "slash.rewrite": "بازنویسی",
+ "slash.summarize": "خلاصه‌سازی",
"slash.table": "جدول",
"slash.tex": "فرمول TeX",
+ "slash.translate": "ترجمه",
"table.delete": "حذف جدول",
"table.deleteColumn": "حذف ستون",
"table.deleteRow": "حذف ردیف",
diff --git a/locales/fa-IR/plugin.json b/locales/fa-IR/plugin.json
index 6cb13d5b3ac..1241afcb847 100644
--- a/locales/fa-IR/plugin.json
+++ b/locales/fa-IR/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "جستجوی مهارت‌ها",
"builtins.lobe-skills.title": "مهارت‌ها",
"builtins.lobe-tools.apiName.activateTools": "فعال کردن ابزارها",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "دریافت زمینه موضوع",
+ "builtins.lobe-topic-reference.title": "ارجاع به موضوع",
"builtins.lobe-user-memory.apiName.addContextMemory": "افزودن حافظه زمینه",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "افزودن حافظه تجربه",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "افزودن حافظه هویتی",
diff --git a/locales/fr-FR/editor.json b/locales/fr-FR/editor.json
index 43cc7bbc7e8..3c6dc25aa44 100644
--- a/locales/fr-FR/editor.json
+++ b/locales/fr-FR/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Commande",
+ "actionTag.category.skill": "Compétence",
+ "actionTag.category.tool": "Outil",
+ "actionTag.tooltip.command": "Exécute une commande slash côté client avant l’envoi.",
+ "actionTag.tooltip.skill": "Charge un paquet de compétences réutilisable pour cette requête.",
+ "actionTag.tooltip.tool": "Marque un outil que l’utilisateur a explicitement sélectionné pour cette requête.",
"actions.expand.off": "Réduire",
"actions.expand.on": "Développer",
"actions.typobar.off": "Masquer la barre de mise en forme",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Tout conserver",
"modifier.reject": "Annuler",
"modifier.rejectAll": "Tout annuler",
+ "slash.compact": "Compacter le contexte",
"slash.h1": "Titre 1",
"slash.h2": "Titre 2",
"slash.h3": "Titre 3",
"slash.hr": "Séparateur",
+ "slash.newTopic": "Envoyer dans un nouveau sujet",
+ "slash.rewrite": "Réécrire",
+ "slash.summarize": "Résumer",
"slash.table": "Tableau",
"slash.tex": "Formule TeX",
+ "slash.translate": "Traduire",
"table.delete": "Supprimer le tableau",
"table.deleteColumn": "Supprimer la colonne",
"table.deleteRow": "Supprimer la ligne",
diff --git a/locales/fr-FR/plugin.json b/locales/fr-FR/plugin.json
index f4ccf2f856f..890269827f0 100644
--- a/locales/fr-FR/plugin.json
+++ b/locales/fr-FR/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Rechercher des Compétences",
"builtins.lobe-skills.title": "Compétences",
"builtins.lobe-tools.apiName.activateTools": "Activer les Outils",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Obtenir le contexte du sujet",
+ "builtins.lobe-topic-reference.title": "Référence de sujet",
"builtins.lobe-user-memory.apiName.addContextMemory": "Ajouter une mémoire de contexte",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Ajouter une mémoire d'expérience",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Ajouter une mémoire d'identité",
diff --git a/locales/it-IT/editor.json b/locales/it-IT/editor.json
index c8fe89ec9dc..458726075a0 100644
--- a/locales/it-IT/editor.json
+++ b/locales/it-IT/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Comando",
+ "actionTag.category.skill": "Abilità",
+ "actionTag.category.tool": "Strumento",
+ "actionTag.tooltip.command": "Esegue un comando slash lato client prima dell'invio.",
+ "actionTag.tooltip.skill": "Carica un pacchetto di abilità riutilizzabile per questa richiesta.",
+ "actionTag.tooltip.tool": "Contrassegna uno strumento selezionato esplicitamente dall'utente per questa richiesta.",
"actions.expand.off": "Comprimi",
"actions.expand.on": "Espandi",
"actions.typobar.off": "Nascondi barra di formattazione",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Mantieni tutto",
"modifier.reject": "Ripristina",
"modifier.rejectAll": "Ripristina tutto",
+ "slash.compact": "Compatta il contesto",
"slash.h1": "Titolo 1",
"slash.h2": "Titolo 2",
"slash.h3": "Titolo 3",
"slash.hr": "Separatore",
+ "slash.newTopic": "Invia in un nuovo argomento",
+ "slash.rewrite": "Riscrivi",
+ "slash.summarize": "Riassumi",
"slash.table": "Tabella",
"slash.tex": "Formula TeX",
+ "slash.translate": "Traduci",
"table.delete": "Elimina tabella",
"table.deleteColumn": "Elimina colonna",
"table.deleteRow": "Elimina riga",
diff --git a/locales/it-IT/plugin.json b/locales/it-IT/plugin.json
index 52fcf28b543..34d0b3a5e05 100644
--- a/locales/it-IT/plugin.json
+++ b/locales/it-IT/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Cerca Abilità",
"builtins.lobe-skills.title": "Abilità",
"builtins.lobe-tools.apiName.activateTools": "Attiva Strumenti",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Ottieni contesto dell'argomento",
+ "builtins.lobe-topic-reference.title": "Riferimento argomento",
"builtins.lobe-user-memory.apiName.addContextMemory": "Aggiungi memoria contestuale",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Aggiungi memoria esperienziale",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Aggiungi memoria identità",
diff --git a/locales/ja-JP/editor.json b/locales/ja-JP/editor.json
index 83b4bc1a4bb..8484303479c 100644
--- a/locales/ja-JP/editor.json
+++ b/locales/ja-JP/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "コマンド",
+ "actionTag.category.skill": "スキル",
+ "actionTag.category.tool": "ツール",
+ "actionTag.tooltip.command": "送信前にクライアント側のスラッシュコマンドを実行します。",
+ "actionTag.tooltip.skill": "このリクエスト用に再利用可能なスキルパッケージを読み込みます。",
+ "actionTag.tooltip.tool": "このリクエストでユーザーが明示的に選択したツールを示します。",
"actions.expand.off": "折りたたむ",
"actions.expand.on": "展開する",
"actions.typobar.off": "書式ツールバーを非表示",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "すべて承諾する",
"modifier.reject": "取り消し",
"modifier.rejectAll": "すべてを取り消す",
+ "slash.compact": "コンテキストを圧縮",
"slash.h1": "見出し1",
"slash.h2": "見出し2",
"slash.h3": "見出し3",
"slash.hr": "区切り線",
+ "slash.newTopic": "新しいトピックで送信",
+ "slash.rewrite": "書き直す",
+ "slash.summarize": "要約",
"slash.table": "表",
"slash.tex": "TeX 数式",
+ "slash.translate": "翻訳",
"table.delete": "表を削除",
"table.deleteColumn": "列を削除",
"table.deleteRow": "行を削除",
diff --git a/locales/ja-JP/plugin.json b/locales/ja-JP/plugin.json
index d837b8e2ba2..f409418d870 100644
--- a/locales/ja-JP/plugin.json
+++ b/locales/ja-JP/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "スキルを検索",
"builtins.lobe-skills.title": "スキル",
"builtins.lobe-tools.apiName.activateTools": "ツールをアクティブ化",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "トピックコンテキストを取得",
+ "builtins.lobe-topic-reference.title": "トピック参照",
"builtins.lobe-user-memory.apiName.addContextMemory": "コンテキスト記憶を追加",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "経験記憶を追加",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "アイデンティティ記憶を追加",
diff --git a/locales/ko-KR/editor.json b/locales/ko-KR/editor.json
index 21936f7db1c..57068441fde 100644
--- a/locales/ko-KR/editor.json
+++ b/locales/ko-KR/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "명령",
+ "actionTag.category.skill": "스킬",
+ "actionTag.category.tool": "도구",
+ "actionTag.tooltip.command": "전송 전에 클라이언트 측 슬래시 명령을 실행합니다.",
+ "actionTag.tooltip.skill": "이번 요청에 사용할 재사용 가능한 스킬 패키지를 불러옵니다.",
+ "actionTag.tooltip.tool": "이번 요청에서 사용자가 명시적으로 선택한 도구를 표시합니다.",
"actions.expand.off": "접기",
"actions.expand.on": "펼치기",
"actions.typobar.off": "서식 도구 모음 숨기기",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "모두 수락",
"modifier.reject": "취소",
"modifier.rejectAll": "모두 취소",
+ "slash.compact": "컨텍스트 압축",
"slash.h1": "제목 1",
"slash.h2": "제목 2",
"slash.h3": "제목 3",
"slash.hr": "구분선",
+ "slash.newTopic": "새 토픽으로 보내기",
+ "slash.rewrite": "다시 쓰기",
+ "slash.summarize": "요약",
"slash.table": "표",
"slash.tex": "TeX 수식",
+ "slash.translate": "번역",
"table.delete": "표 삭제",
"table.deleteColumn": "열 삭제",
"table.deleteRow": "행 삭제",
diff --git a/locales/ko-KR/plugin.json b/locales/ko-KR/plugin.json
index f332c1e1d7d..d000637ec86 100644
--- a/locales/ko-KR/plugin.json
+++ b/locales/ko-KR/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "스킬 검색",
"builtins.lobe-skills.title": "스킬",
"builtins.lobe-tools.apiName.activateTools": "도구 활성화",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "토픽 컨텍스트 가져오기",
+ "builtins.lobe-topic-reference.title": "토픽 참조",
"builtins.lobe-user-memory.apiName.addContextMemory": "상황 기억 추가",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "경험 기억 추가",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "신원 기억 추가",
diff --git a/locales/nl-NL/editor.json b/locales/nl-NL/editor.json
index 65ac3dc7839..65834a211e3 100644
--- a/locales/nl-NL/editor.json
+++ b/locales/nl-NL/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Commando",
+ "actionTag.category.skill": "Vaardigheid",
+ "actionTag.category.tool": "Hulpmiddel",
+ "actionTag.tooltip.command": "Voert vóór het verzenden een slash-commando aan de clientzijde uit.",
+ "actionTag.tooltip.skill": "Laadt voor dit verzoek een herbruikbaar vaardigheidspakket.",
+ "actionTag.tooltip.tool": "Markeert een hulpmiddel dat de gebruiker expliciet voor dit verzoek heeft geselecteerd.",
"actions.expand.off": "Samenvouwen",
"actions.expand.on": "Uitvouwen",
"actions.typobar.off": "Opmaakwerkbalk verbergen",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Alles behouden",
"modifier.reject": "Ongedaan maken",
"modifier.rejectAll": "Alles ongedaan maken",
+ "slash.compact": "Context comprimeren",
"slash.h1": "Kop 1",
"slash.h2": "Kop 2",
"slash.h3": "Kop 3",
"slash.hr": "Scheiding",
+ "slash.newTopic": "Verzenden in nieuw onderwerp",
+ "slash.rewrite": "Herschrijven",
+ "slash.summarize": "Samenvatten",
"slash.table": "Tabel",
"slash.tex": "TeX-formule",
+ "slash.translate": "Vertalen",
"table.delete": "Tabel verwijderen",
"table.deleteColumn": "Kolom verwijderen",
"table.deleteRow": "Rij verwijderen",
diff --git a/locales/nl-NL/plugin.json b/locales/nl-NL/plugin.json
index f7e34de5eb2..02951f80ff4 100644
--- a/locales/nl-NL/plugin.json
+++ b/locales/nl-NL/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Vaardigheden Zoeken",
"builtins.lobe-skills.title": "Vaardigheden",
"builtins.lobe-tools.apiName.activateTools": "Hulpmiddelen Activeren",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Onderwerpcontext ophalen",
+ "builtins.lobe-topic-reference.title": "Onderwerpverwijzing",
"builtins.lobe-user-memory.apiName.addContextMemory": "Contextgeheugen toevoegen",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Ervaringsgeheugen toevoegen",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Identiteitsgeheugen toevoegen",
diff --git a/locales/pl-PL/editor.json b/locales/pl-PL/editor.json
index 57b1baafcfc..1c1eeaa0906 100644
--- a/locales/pl-PL/editor.json
+++ b/locales/pl-PL/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Polecenie",
+ "actionTag.category.skill": "Umiejętność",
+ "actionTag.category.tool": "Narzędzie",
+ "actionTag.tooltip.command": "Uruchamia polecenie slash po stronie klienta przed wysłaniem.",
+ "actionTag.tooltip.skill": "Wczytuje pakiet umiejętności wielokrotnego użytku dla tego żądania.",
+ "actionTag.tooltip.tool": "Oznacza narzędzie, które użytkownik jawnie wybrał dla tego żądania.",
"actions.expand.off": "Zwiń",
"actions.expand.on": "Rozwiń",
"actions.typobar.off": "Ukryj pasek formatowania",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Zachowaj wszystkie",
"modifier.reject": "Cofnij",
"modifier.rejectAll": "Cofnij wszystkie",
+ "slash.compact": "Kompresuj kontekst",
"slash.h1": "Nagłówek 1",
"slash.h2": "Nagłówek 2",
"slash.h3": "Nagłówek 3",
"slash.hr": "Separator",
+ "slash.newTopic": "Wyślij w nowym temacie",
+ "slash.rewrite": "Przepisz",
+ "slash.summarize": "Podsumuj",
"slash.table": "Tabela",
"slash.tex": "Formuła TeX",
+ "slash.translate": "Tłumacz",
"table.delete": "Usuń tabelę",
"table.deleteColumn": "Usuń kolumnę",
"table.deleteRow": "Usuń wiersz",
diff --git a/locales/pl-PL/plugin.json b/locales/pl-PL/plugin.json
index ffd3cda7a09..aa804a96c7c 100644
--- a/locales/pl-PL/plugin.json
+++ b/locales/pl-PL/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Wyszukaj Umiejętności",
"builtins.lobe-skills.title": "Umiejętności",
"builtins.lobe-tools.apiName.activateTools": "Aktywuj Narzędzia",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Pobierz kontekst tematu",
+ "builtins.lobe-topic-reference.title": "Odwołanie do tematu",
"builtins.lobe-user-memory.apiName.addContextMemory": "Dodaj pamięć kontekstu",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Dodaj pamięć doświadczenia",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Dodaj pamięć tożsamości",
diff --git a/locales/pt-BR/editor.json b/locales/pt-BR/editor.json
index 75015d136a3..af924e97a02 100644
--- a/locales/pt-BR/editor.json
+++ b/locales/pt-BR/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Comando",
+ "actionTag.category.skill": "Habilidade",
+ "actionTag.category.tool": "Ferramenta",
+ "actionTag.tooltip.command": "Executa um comando slash no cliente antes do envio.",
+ "actionTag.tooltip.skill": "Carrega um pacote de habilidades reutilizável para esta solicitação.",
+ "actionTag.tooltip.tool": "Marca uma ferramenta que o usuário selecionou explicitamente para esta solicitação.",
"actions.expand.off": "Recolher",
"actions.expand.on": "Expandir",
"actions.typobar.off": "Ocultar barra de formatação",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Manter tudo",
"modifier.reject": "Reverter",
"modifier.rejectAll": "Reverter tudo",
+ "slash.compact": "Compactar contexto",
"slash.h1": "Título 1",
"slash.h2": "Título 2",
"slash.h3": "Título 3",
"slash.hr": "Divisor",
+ "slash.newTopic": "Enviar em novo tópico",
+ "slash.rewrite": "Reescrever",
+ "slash.summarize": "Resumir",
"slash.table": "Tabela",
"slash.tex": "Fórmula TeX",
+ "slash.translate": "Traduzir",
"table.delete": "Excluir tabela",
"table.deleteColumn": "Excluir coluna",
"table.deleteRow": "Excluir linha",
diff --git a/locales/pt-BR/plugin.json b/locales/pt-BR/plugin.json
index 44bbe1c0385..369a0167383 100644
--- a/locales/pt-BR/plugin.json
+++ b/locales/pt-BR/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Buscar Habilidades",
"builtins.lobe-skills.title": "Habilidades",
"builtins.lobe-tools.apiName.activateTools": "Ativar Ferramentas",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Obter contexto do tópico",
+ "builtins.lobe-topic-reference.title": "Referência de tópico",
"builtins.lobe-user-memory.apiName.addContextMemory": "Adicionar memória de contexto",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Adicionar memória de experiência",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Adicionar memória de identidade",
diff --git a/locales/ru-RU/editor.json b/locales/ru-RU/editor.json
index e30bc37a96a..d4ee26806b1 100644
--- a/locales/ru-RU/editor.json
+++ b/locales/ru-RU/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Команда",
+ "actionTag.category.skill": "Навык",
+ "actionTag.category.tool": "Инструмент",
+ "actionTag.tooltip.command": "Выполняет клиентскую slash-команду перед отправкой.",
+ "actionTag.tooltip.skill": "Загружает для этого запроса переиспользуемый пакет навыков.",
+ "actionTag.tooltip.tool": "Помечает инструмент, который пользователь явно выбрал для этого запроса.",
"actions.expand.off": "Свернуть",
"actions.expand.on": "Развернуть",
"actions.typobar.off": "Скрыть панель форматирования",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Оставить все",
"modifier.reject": "Отменить",
"modifier.rejectAll": "Отменить все",
+ "slash.compact": "Сжать контекст",
"slash.h1": "Заголовок 1",
"slash.h2": "Заголовок 2",
"slash.h3": "Заголовок 3",
"slash.hr": "Разделитель",
+ "slash.newTopic": "Отправить в новую тему",
+ "slash.rewrite": "Переписать",
+ "slash.summarize": "Суммировать",
"slash.table": "Таблица",
"slash.tex": "Формула TeX",
+ "slash.translate": "Перевести",
"table.delete": "Удалить таблицу",
"table.deleteColumn": "Удалить столбец",
"table.deleteRow": "Удалить строку",
diff --git a/locales/ru-RU/plugin.json b/locales/ru-RU/plugin.json
index 7a7d6becc0c..16e92c4bda5 100644
--- a/locales/ru-RU/plugin.json
+++ b/locales/ru-RU/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Поиск навыков",
"builtins.lobe-skills.title": "Навыки",
"builtins.lobe-tools.apiName.activateTools": "Активировать инструменты",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Получить контекст темы",
+ "builtins.lobe-topic-reference.title": "Ссылка на тему",
"builtins.lobe-user-memory.apiName.addContextMemory": "Добавить контекстную память",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Добавить память опыта",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Добавить память личности",
diff --git a/locales/tr-TR/editor.json b/locales/tr-TR/editor.json
index 19fc6b7f8c0..7edf72a6250 100644
--- a/locales/tr-TR/editor.json
+++ b/locales/tr-TR/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Komut",
+ "actionTag.category.skill": "Beceri",
+ "actionTag.category.tool": "Araç",
+ "actionTag.tooltip.command": "Göndermeden önce istemci tarafında bir slash komutu çalıştırır.",
+ "actionTag.tooltip.skill": "Bu istek için yeniden kullanılabilir bir beceri paketini yükler.",
+ "actionTag.tooltip.tool": "Kullanıcının bu istek için açıkça seçtiği bir aracı işaretler.",
"actions.expand.off": "Daralt",
"actions.expand.on": "Genişlet",
"actions.typobar.off": "Biçimlendirme araç çubuğunu gizle",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Tümünü koru",
"modifier.reject": "Geri al",
"modifier.rejectAll": "Tümünü geri al",
+ "slash.compact": "Bağlamı sıkıştır",
"slash.h1": "Başlık 1",
"slash.h2": "Başlık 2",
"slash.h3": "Başlık 3",
"slash.hr": "Ayraç",
+ "slash.newTopic": "Yeni konuda gönder",
+ "slash.rewrite": "Yeniden yaz",
+ "slash.summarize": "Özetle",
"slash.table": "Tablo",
"slash.tex": "TeX Formülü",
+ "slash.translate": "Çevir",
"table.delete": "Tabloyu sil",
"table.deleteColumn": "Sütunu sil",
"table.deleteRow": "Satırı sil",
diff --git a/locales/tr-TR/plugin.json b/locales/tr-TR/plugin.json
index 877eac435a9..eb5552d0181 100644
--- a/locales/tr-TR/plugin.json
+++ b/locales/tr-TR/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Becerileri Ara",
"builtins.lobe-skills.title": "Beceriler",
"builtins.lobe-tools.apiName.activateTools": "Araçları Etkinleştir",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Konu bağlamını al",
+ "builtins.lobe-topic-reference.title": "Konu referansı",
"builtins.lobe-user-memory.apiName.addContextMemory": "Bağlam hafızası ekle",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Deneyim hafızası ekle",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Kimlik hafızası ekle",
diff --git a/locales/vi-VN/editor.json b/locales/vi-VN/editor.json
index 25eeb77ce55..5efc33519aa 100644
--- a/locales/vi-VN/editor.json
+++ b/locales/vi-VN/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "Lệnh",
+ "actionTag.category.skill": "Kỹ năng",
+ "actionTag.category.tool": "Công cụ",
+ "actionTag.tooltip.command": "Chạy lệnh slash phía client trước khi gửi.",
+ "actionTag.tooltip.skill": "Tải gói kỹ năng có thể tái sử dụng cho yêu cầu này.",
+ "actionTag.tooltip.tool": "Đánh dấu công cụ mà người dùng đã chọn rõ ràng cho yêu cầu này.",
"actions.expand.off": "Thu gọn",
"actions.expand.on": "Mở rộng",
"actions.typobar.off": "Ẩn thanh công cụ định dạng",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "Giữ tất cả",
"modifier.reject": "Hoàn tác",
"modifier.rejectAll": "Hoàn tác tất cả",
+ "slash.compact": "Nén ngữ cảnh",
"slash.h1": "Tiêu đề 1",
"slash.h2": "Tiêu đề 2",
"slash.h3": "Tiêu đề 3",
"slash.hr": "Đường phân cách",
+ "slash.newTopic": "Gửi trong chủ đề mới",
+ "slash.rewrite": "Viết lại",
+ "slash.summarize": "Tóm tắt",
"slash.table": "Bảng",
"slash.tex": "Công thức TeX",
+ "slash.translate": "Dịch",
"table.delete": "Xóa bảng",
"table.deleteColumn": "Xóa cột",
"table.deleteRow": "Xóa hàng",
diff --git a/locales/vi-VN/plugin.json b/locales/vi-VN/plugin.json
index 3b851b5e2d1..81d835dfd20 100644
--- a/locales/vi-VN/plugin.json
+++ b/locales/vi-VN/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "Tìm kiếm Kỹ năng",
"builtins.lobe-skills.title": "Kỹ năng",
"builtins.lobe-tools.apiName.activateTools": "Kích hoạt Công cụ",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "Lấy ngữ cảnh chủ đề",
+ "builtins.lobe-topic-reference.title": "Tham chiếu chủ đề",
"builtins.lobe-user-memory.apiName.addContextMemory": "Thêm trí nhớ ngữ cảnh",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Thêm trí nhớ kinh nghiệm",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Thêm trí nhớ danh tính",
diff --git a/locales/zh-CN/editor.json b/locales/zh-CN/editor.json
index 709ab4a87e0..37a211a4a72 100644
--- a/locales/zh-CN/editor.json
+++ b/locales/zh-CN/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "指令",
+ "actionTag.category.skill": "技能",
+ "actionTag.category.tool": "工具",
+ "actionTag.tooltip.command": "发送前会先在客户端执行这条 slash 指令。",
+ "actionTag.tooltip.skill": "表示这是一条可为本次请求加载的技能包。",
+ "actionTag.tooltip.tool": "表示这是用户为本次请求显式选中的工具。",
"actions.expand.off": "收起",
"actions.expand.on": "展开",
"actions.typobar.off": "隐藏格式工具栏",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "全部保留",
"modifier.reject": "撤销",
"modifier.rejectAll": "全部撤销",
+ "slash.compact": "压缩上下文",
"slash.h1": "一级标题",
"slash.h2": "二级标题",
"slash.h3": "三级标题",
"slash.hr": "分割线",
+ "slash.newTopic": "在新话题中发送",
+ "slash.rewrite": "重写",
+ "slash.summarize": "总结",
"slash.table": "表格",
"slash.tex": "TeX 公式",
+ "slash.translate": "翻译",
"table.delete": "删除表格",
"table.deleteColumn": "删除列",
"table.deleteRow": "删除行",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 017dfa83ebe..878f154f6f2 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -202,6 +202,8 @@
"builtins.lobe-skills.apiName.searchSkill": "搜索技能",
"builtins.lobe-skills.title": "技能",
"builtins.lobe-tools.apiName.activateTools": "激活工具",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "获取话题上下文",
+ "builtins.lobe-topic-reference.title": "话题引用",
"builtins.lobe-user-memory.apiName.addContextMemory": "添加情境记忆",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "添加经验记忆",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "添加身份记忆",
diff --git a/locales/zh-TW/editor.json b/locales/zh-TW/editor.json
index deb6e648cec..cc0011befc8 100644
--- a/locales/zh-TW/editor.json
+++ b/locales/zh-TW/editor.json
@@ -1,4 +1,10 @@
{
+ "actionTag.category.command": "命令",
+ "actionTag.category.skill": "技能",
+ "actionTag.category.tool": "工具",
+ "actionTag.tooltip.command": "在發送前執行客戶端斜線命令。",
+ "actionTag.tooltip.skill": "為此次請求載入可重用的技能包。",
+ "actionTag.tooltip.tool": "標記使用者在此次請求中明確選擇的工具。",
"actions.expand.off": "收合",
"actions.expand.on": "展開",
"actions.typobar.off": "隱藏格式工具列",
@@ -34,12 +40,17 @@
"modifier.acceptAll": "全部接受",
"modifier.reject": "撤銷",
"modifier.rejectAll": "全部取消",
+ "slash.compact": "壓縮上下文",
"slash.h1": "一級標題",
"slash.h2": "二級標題",
"slash.h3": "三級標題",
"slash.hr": "分隔線",
+ "slash.newTopic": "在新話題中發送",
+ "slash.rewrite": "改寫",
+ "slash.summarize": "摘要",
"slash.table": "表格",
"slash.tex": "TeX 公式",
+ "slash.translate": "翻譯",
"table.delete": "刪除表格",
"table.deleteColumn": "刪除列",
"table.deleteRow": "刪除行",
diff --git a/locales/zh-TW/plugin.json b/locales/zh-TW/plugin.json
index 9b60682a590..4464ac36a4d 100644
--- a/locales/zh-TW/plugin.json
+++ b/locales/zh-TW/plugin.json
@@ -201,6 +201,8 @@
"builtins.lobe-skills.apiName.searchSkill": "搜尋技能",
"builtins.lobe-skills.title": "技能",
"builtins.lobe-tools.apiName.activateTools": "啟用工具",
+ "builtins.lobe-topic-reference.apiName.getTopicContext": "取得話題上下文",
+ "builtins.lobe-topic-reference.title": "話題引用",
"builtins.lobe-user-memory.apiName.addContextMemory": "新增情境記憶",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "新增經驗記憶",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "新增身份記憶",
diff --git a/package.json b/package.json
index e0283a4fe41..d5a33df2258 100644
--- a/package.json
+++ b/package.json
@@ -195,6 +195,7 @@
"@icons-pack/react-simple-icons": "^13.8.0",
"@khmyznikov/pwa-install": "0.3.9",
"@langchain/community": "^0.3.59",
+ "@lexical/utils": "^0.39.0",
"@lobechat/adapter-lark": "workspace:*",
"@lobechat/adapter-qq": "workspace:*",
"@lobechat/agent-runtime": "workspace:*",
@@ -216,6 +217,7 @@
"@lobechat/builtin-tool-skill-store": "workspace:*",
"@lobechat/builtin-tool-skills": "workspace:*",
"@lobechat/builtin-tool-tools": "workspace:*",
+ "@lobechat/builtin-tool-topic-reference": "workspace:*",
"@lobechat/builtin-tool-web-browsing": "workspace:*",
"@lobechat/builtin-tools": "workspace:*",
"@lobechat/business-config": "workspace:*",
@@ -312,6 +314,7 @@
"fflate": "^0.8.2",
"ffmpeg-static": "^5.3.0",
"file-type": "^21.3.0",
+ "fuse.js": "^7.0.0",
"gray-matter": "^4.0.3",
"html-to-text": "^9.0.5",
"i18next": "^25.8.0",
@@ -326,6 +329,7 @@
"langchain": "^0.3.37",
"langfuse": "^3.38.6",
"langfuse-core": "^3.38.6",
+ "lexical": "^0.39.0",
"lucide-react": "^0.562.0",
"mammoth": "^1.11.0",
"marked": "^17.0.1",
diff --git a/packages/builtin-tool-agent-management/src/executor.ts b/packages/builtin-tool-agent-management/src/executor.ts
index d8d7658afad..ff27b553555 100644
--- a/packages/builtin-tool-agent-management/src/executor.ts
+++ b/packages/builtin-tool-agent-management/src/executor.ts
@@ -67,8 +67,14 @@ class AgentManagementExecutor extends BaseExecutor<typeof AgentManagementApiName
params: CallAgentParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- const { agentId, instruction, runAsTask, taskTitle, timeout, skipCallSupervisor = false } =
- params;
+ const {
+ agentId,
+ instruction,
+ runAsTask,
+ taskTitle,
+ timeout,
+ skipCallSupervisor = false,
+ } = params;
if (runAsTask) {
// Execute as async task using GTD exec_task pattern
@@ -184,17 +190,27 @@ class AgentManagementExecutor extends BaseExecutor<typeof AgentManagementApiName
return;
}
+ // If instruction is provided, inject it as a virtual User Message
+ // Same pattern as group orchestration's call_agent executor:
+ // virtual message with <speaker> tag gives the called agent clear direction
+ const now = Date.now();
+ const messagesWithInstruction = instruction
+ ? [
+ ...messages,
+ {
+ content: `<speaker name="Supervisor" />\n${instruction}`,
+ createdAt: now,
+ id: `virtual_speak_instruction_${now}`,
+ role: 'user' as const,
+ updatedAt: now,
+ },
+ ]
+ : messages;
+
try {
- // Execute with subAgentId + scope: 'sub_agent'
- // - context.agentId = current agent (for message storage and message.agentId)
- // - context.topicId = current topic
- // - context.subAgentId = target agent (for agent config - model, prompt, etc.)
- // - context.scope = 'sub_agent' (indicates this is agent-to-agent call, not group)
- // This will create messages in current agent's conversation but use target agent's config
- // The message.agentId will still be current agent, but metadata stores subAgentId + scope
await get().internal_execAgentRuntime({
context: { ...conversationContext, subAgentId: agentId, scope: 'sub_agent' },
- messages,
+ messages: messagesWithInstruction,
parentMessageId: ctx.messageId,
parentMessageType: 'tool',
});
diff --git a/packages/builtin-tool-topic-reference/package.json b/packages/builtin-tool-topic-reference/package.json
new file mode 100644
index 00000000000..1fb9ca4016d
--- /dev/null
+++ b/packages/builtin-tool-topic-reference/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "@lobechat/builtin-tool-topic-reference",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./executor": "./src/executor/index.ts"
+ },
+ "main": "./src/index.ts",
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ }
+}
diff --git a/packages/builtin-tool-topic-reference/src/executor/index.ts b/packages/builtin-tool-topic-reference/src/executor/index.ts
new file mode 100644
index 00000000000..8273978e720
--- /dev/null
+++ b/packages/builtin-tool-topic-reference/src/executor/index.ts
@@ -0,0 +1,40 @@
+import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
+import { BaseExecutor } from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+import { TopicReferenceIdentifier } from '../types';
+
+const TopicReferenceApiName = {
+ getTopicContext: 'getTopicContext',
+} as const;
+
+interface GetTopicContextParams {
+ topicId: string;
+}
+
+class TopicReferenceExecutor extends BaseExecutor<typeof TopicReferenceApiName> {
+ readonly identifier = TopicReferenceIdentifier;
+ protected readonly apiEnum = TopicReferenceApiName;
+
+ getTopicContext = async (
+ params: GetTopicContextParams,
+ _ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { topicId } = params;
+
+ if (!topicId) {
+ return { content: 'topicId is required', success: false };
+ }
+
+ try {
+ const result = await lambdaClient.topic.getTopicContext.query({ topicId });
+ return { content: result.content, success: result.success };
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ return { content: `Failed to fetch topic context: ${errorMessage}`, success: false };
+ }
+ };
+}
+
+export const topicReferenceExecutor = new TopicReferenceExecutor();
diff --git a/packages/builtin-tool-topic-reference/src/index.ts b/packages/builtin-tool-topic-reference/src/index.ts
new file mode 100644
index 00000000000..7d26beed34f
--- /dev/null
+++ b/packages/builtin-tool-topic-reference/src/index.ts
@@ -0,0 +1,6 @@
+export { TopicReferenceManifest } from './manifest';
+export {
+ TopicReferenceApiName,
+ type TopicReferenceApiNameType,
+ TopicReferenceIdentifier,
+} from './types';
diff --git a/packages/builtin-tool-topic-reference/src/manifest.ts b/packages/builtin-tool-topic-reference/src/manifest.ts
new file mode 100644
index 00000000000..0fc30807e25
--- /dev/null
+++ b/packages/builtin-tool-topic-reference/src/manifest.ts
@@ -0,0 +1,32 @@
+import { type BuiltinToolManifest } from '@lobechat/types';
+
+import { TopicReferenceApiName, TopicReferenceIdentifier } from './types';
+
+export const TopicReferenceManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description:
+ 'Retrieve context from a referenced topic conversation. Returns the topic summary if available, otherwise returns the most recent messages. Use this when you see a topic reference tag in the user message and need to understand what was discussed in that topic.',
+ name: TopicReferenceApiName.getTopicContext,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ topicId: {
+ description: 'The ID of the topic to retrieve context from',
+ type: 'string',
+ },
+ },
+ required: ['topicId'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: TopicReferenceIdentifier,
+ meta: {
+ avatar: '📋',
+ description: 'Retrieve context from referenced topic conversations',
+ title: 'Topic Reference',
+ },
+ systemRole: '',
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-topic-reference/src/types.ts b/packages/builtin-tool-topic-reference/src/types.ts
new file mode 100644
index 00000000000..9d1f3b27b73
--- /dev/null
+++ b/packages/builtin-tool-topic-reference/src/types.ts
@@ -0,0 +1,8 @@
+export const TopicReferenceIdentifier = 'lobe-topic-reference';
+
+export const TopicReferenceApiName = {
+ getTopicContext: 'getTopicContext',
+} as const;
+
+export type TopicReferenceApiNameType =
+ (typeof TopicReferenceApiName)[keyof typeof TopicReferenceApiName];
diff --git a/packages/builtin-tool-topic-reference/tsconfig.json b/packages/builtin-tool-topic-reference/tsconfig.json
new file mode 100644
index 00000000000..cf07830f64d
--- /dev/null
+++ b/packages/builtin-tool-topic-reference/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "node",
+ "declaration": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "strict": true,
+ "skipLibCheck": true,
+ "esModuleInterop": true,
+ "allowSyntheticDefaultImports": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true
+ },
+ "exclude": ["node_modules"],
+ "include": ["src/**/*"]
+}
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index 1846da5909e..0bf14cc2ae5 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -30,6 +30,7 @@
"@lobechat/builtin-tool-skill-store": "workspace:*",
"@lobechat/builtin-tool-skills": "workspace:*",
"@lobechat/builtin-tool-tools": "workspace:*",
+ "@lobechat/builtin-tool-topic-reference": "workspace:*",
"@lobechat/builtin-tool-web-browsing": "workspace:*",
"@lobechat/const": "workspace:*"
},
diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.ts
index 524b355fc2e..7d3c828bf7d 100644
--- a/packages/builtin-tools/src/identifiers.ts
+++ b/packages/builtin-tools/src/identifiers.ts
@@ -13,6 +13,7 @@ import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';
import { SkillStoreManifest } from '@lobechat/builtin-tool-skill-store';
import { SkillsManifest } from '@lobechat/builtin-tool-skills';
import { LobeToolsManifest } from '@lobechat/builtin-tool-tools';
+import { TopicReferenceManifest } from '@lobechat/builtin-tool-topic-reference';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
export const builtinToolIdentifiers: string[] = [
@@ -30,6 +31,7 @@ export const builtinToolIdentifiers: string[] = [
GTDManifest.identifier,
MemoryManifest.identifier,
NotebookManifest.identifier,
+ TopicReferenceManifest.identifier,
LobeToolsManifest.identifier,
SkillStoreManifest.identifier,
];
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 85cd2e10f10..de27f5f98f6 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -14,6 +14,7 @@ import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import { SkillStoreManifest } from '@lobechat/builtin-tool-skill-store';
import { SkillsManifest } from '@lobechat/builtin-tool-skills';
import { LobeToolsManifest } from '@lobechat/builtin-tool-tools';
+import { TopicReferenceManifest } from '@lobechat/builtin-tool-topic-reference';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { isDesktop } from '@lobechat/const';
import { type LobeBuiltinTool } from '@lobechat/types';
@@ -31,6 +32,7 @@ export const defaultToolIds = [
MemoryManifest.identifier,
LocalSystemManifest.identifier,
CloudSandboxManifest.identifier,
+ TopicReferenceManifest.identifier,
];
/**
@@ -147,4 +149,11 @@ export const builtinTools: LobeBuiltinTool[] = [
manifest: RemoteDeviceManifest,
type: 'builtin',
},
+ {
+ discoverable: false,
+ hidden: true,
+ identifier: TopicReferenceManifest.identifier,
+ manifest: TopicReferenceManifest,
+ type: 'builtin',
+ },
];
diff --git a/packages/context-engine/src/__tests__/metadata.types.test.ts b/packages/context-engine/src/__tests__/metadata.types.test.ts
new file mode 100644
index 00000000000..2d210b61f84
--- /dev/null
+++ b/packages/context-engine/src/__tests__/metadata.types.test.ts
@@ -0,0 +1,49 @@
+import { describe, expectTypeOf, it } from 'vitest';
+
+import type { PipelineContext, PipelineContextMetadata } from '../types';
+
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ customMetadata?: {
+ enabled: boolean;
+ source: 'test';
+ };
+ }
+}
+
+describe('PipelineContextMetadata', () => {
+ it('should keep built-in metadata fields strongly typed', () => {
+ expectTypeOf<PipelineContextMetadata['historySummary']>().toEqualTypeOf<
+ | {
+ formattedLength: number;
+ injected: boolean;
+ originalLength: number;
+ }
+ | undefined
+ >();
+ expectTypeOf<PipelineContextMetadata['toolMessageReorder']>().toEqualTypeOf<
+ | {
+ originalCount: number;
+ removedInvalidTools: number;
+ reorderedCount: number;
+ }
+ | undefined
+ >();
+ });
+
+ it('should support template literal injected-count metadata keys', () => {
+ expectTypeOf<PipelineContextMetadata['CustomProviderInjectedCount']>().toEqualTypeOf<
+ number | undefined
+ >();
+ });
+
+ it('should expose consumer-side metadata extensions through pipeline context', () => {
+ expectTypeOf<PipelineContext['metadata']['customMetadata']>().toEqualTypeOf<
+ | {
+ enabled: boolean;
+ source: 'test';
+ }
+ | undefined
+ >();
+ });
+});
diff --git a/packages/context-engine/src/__tests__/pipeline.test.ts b/packages/context-engine/src/__tests__/pipeline.test.ts
index 6f947944b75..f0cf8ea2521 100644
--- a/packages/context-engine/src/__tests__/pipeline.test.ts
+++ b/packages/context-engine/src/__tests__/pipeline.test.ts
@@ -176,9 +176,9 @@ describe('ContextEngine', () => {
expect(result.isAborted).toBe(false);
expect(result.messages).toEqual(input.messages);
- expect(result.metadata.p1).toBe(true);
- expect(result.metadata.p2).toBe(true);
- expect(result.metadata.p3).toBe(true);
+ expect((result.metadata as any).p1).toBe(true);
+ expect((result.metadata as any).p2).toBe(true);
+ expect((result.metadata as any).p3).toBe(true);
expect(result.stats.processedCount).toBe(3);
});
diff --git a/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts b/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts
index 3cca568f2b1..13b92f10e79 100644
--- a/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts
+++ b/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts
@@ -185,14 +185,14 @@ describe('BaseProcessor', () => {
it('should preserve all context properties', async () => {
const processor = new TestProcessor();
const context = createContext([{ content: 'test', role: 'user' }]);
- context.metadata.customField = 'customValue';
+ (context.metadata as any).customField = 'customValue';
const result = await processor.process(context);
expect(result.isAborted).toBe(context.isAborted);
expect(result.metadata.model).toBe(context.metadata.model);
expect(result.metadata.maxTokens).toBe(context.metadata.maxTokens);
- expect(result.metadata.customField).toBe('customValue');
+ expect((result.metadata as any).customField).toBe('customValue');
});
});
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 759636535d7..2e520dcbe5f 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -35,6 +35,7 @@ import {
KnowledgeInjector,
PageEditorContextInjector,
PageSelectionsInjector,
+ SelectedSkillInjector,
SkillContextProvider,
SystemDateProvider,
SystemRoleInjector,
@@ -129,6 +130,7 @@ export class MessagesEngine {
formatHistorySummary,
knowledge,
skillsConfig,
+ selectedSkills,
toolDiscoveryConfig,
toolsConfig,
capabilities,
@@ -157,6 +159,8 @@ export class MessagesEngine {
const isGroupContextEnabled =
isAgentGroupEnabled || !!agentGroup?.currentAgentId || !!agentGroup?.members;
const isUserMemoryEnabled = userMemory?.enabled && userMemory?.memories;
+ const hasSelectedSkills = (selectedSkills?.length ?? 0) > 0;
+
// Page editor is enabled if either direct pageContentContext or initialContext.pageEditor is provided
const isPageEditorEnabled = !!pageContentContext || !!initialContext?.pageEditor;
// GTD is enabled if gtd.enabled is true and either plan or todos is provided
@@ -283,16 +287,19 @@ export class MessagesEngine {
historySummary,
}),
- // 14. Page Selections injection (inject user-selected text into each user message that has them)
+ // 14. Selected skill injection (ephemeral user-selected slash skills for this request)
+ ...(hasSelectedSkills ? [new SelectedSkillInjector({ selectedSkills })] : []),
+
+ // 15. Page Selections injection (inject user-selected text into each user message that has them)
new PageSelectionsInjector({ enabled: isPageEditorEnabled }),
- // 15. Page Editor context injection (inject current page content to last user message)
+ // 16. Page Editor context injection (inject current page content to last user message)
new PageEditorContextInjector({
enabled: isPageEditorEnabled,
// Use direct pageContentContext if provided (server-side), otherwise build from initialContext + stepContext (frontend)
- pageContentContext: pageContentContext
- ? pageContentContext
- : initialContext?.pageEditor
+ pageContentContext:
+ pageContentContext ??
+ (initialContext?.pageEditor
? {
markdown: initialContext.pageEditor.markdown,
metadata: {
@@ -303,10 +310,10 @@ export class MessagesEngine {
// Use latest XML from stepContext if available, otherwise fallback to initial XML
xml: stepContext?.stepPageEditor?.xml || initialContext.pageEditor.xml,
}
- : undefined,
+ : undefined),
}),
- // 16. GTD Todo injection (conditionally added, at end of last user message)
+ // 17. GTD Todo injection (conditionally added, at end of last user message)
...(isGTDTodoEnabled ? [new GTDTodoInjector({ enabled: true, todos: gtd.todos })] : []),
// =============================================
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index 7fa7181814d..f45313ea9ae 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -1,6 +1,10 @@
/* eslint-disable perfectionist/sort-interfaces */
import type { FileContent, KnowledgeBaseInfo, PageContentContext } from '@lobechat/prompts';
-import type { RuntimeInitialContext, RuntimeStepContext } from '@lobechat/types';
+import type {
+ RuntimeInitialContext,
+ RuntimeSelectedSkill,
+ RuntimeStepContext,
+} from '@lobechat/types';
import type { OpenAIChatMessage, UIChatMessage } from '@/types/index';
@@ -15,6 +19,7 @@ import type { GTDPlan } from '../../providers/GTDPlanInjector';
import type { GTDTodoList } from '../../providers/GTDTodoInjector';
import type { SkillMeta } from '../../providers/SkillContextProvider';
import type { ToolDiscoveryMeta } from '../../providers/ToolDiscoveryProvider';
+import type { PipelineContextMetadata } from '../../types';
import type { LobeToolManifest } from '../tools/types';
/**
@@ -239,6 +244,8 @@ export interface MessagesEngineParams {
// ========== Skills ==========
/** Skills configuration */
skillsConfig?: SkillsConfig;
+ /** Skills explicitly selected by the user for the current request */
+ selectedSkills?: RuntimeSelectedSkill[];
// ========== Tool Discovery ==========
/** Tool Discovery configuration (available tools for dynamic activation) */
@@ -299,7 +306,7 @@ export interface MessagesEngineResult {
/** Processed messages in OpenAI format */
messages: OpenAIChatMessage[];
/** Processing metadata */
- metadata: Record<string, any>;
+ metadata: PipelineContextMetadata;
/** Processing statistics */
stats: {
/** Number of processors executed */
diff --git a/packages/context-engine/src/processors/AgentCouncilFlatten.ts b/packages/context-engine/src/processors/AgentCouncilFlatten.ts
index a6aedce3864..672ea95b1c4 100644
--- a/packages/context-engine/src/processors/AgentCouncilFlatten.ts
+++ b/packages/context-engine/src/processors/AgentCouncilFlatten.ts
@@ -3,6 +3,15 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ agentCouncilAssistantMessagesCreated?: number;
+ agentCouncilFlattenProcessed?: number;
+ agentCouncilMessagesFlattened?: number;
+ agentCouncilToolMessagesCreated?: number;
+ }
+}
+
const log = debug('context-engine:processor:AgentCouncilFlattenProcessor');
/**
diff --git a/packages/context-engine/src/processors/CompressedGroupRoleTransform.ts b/packages/context-engine/src/processors/CompressedGroupRoleTransform.ts
index 1586d15cd4d..17056ea7227 100644
--- a/packages/context-engine/src/processors/CompressedGroupRoleTransform.ts
+++ b/packages/context-engine/src/processors/CompressedGroupRoleTransform.ts
@@ -3,6 +3,12 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { Message, PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ compressedGroupRoleTransformProcessed?: number;
+ }
+}
+
const log = debug('context-engine:processor:CompressedGroupRoleTransformProcessor');
/**
diff --git a/packages/context-engine/src/processors/GroupMessageFlatten.ts b/packages/context-engine/src/processors/GroupMessageFlatten.ts
index c09fbb12f2b..ee16ce6707e 100644
--- a/packages/context-engine/src/processors/GroupMessageFlatten.ts
+++ b/packages/context-engine/src/processors/GroupMessageFlatten.ts
@@ -3,6 +3,15 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ assistantMessagesCreated?: number;
+ groupMessagesFlattened?: number;
+ groupMessagesFlattenProcessed?: number;
+ toolMessagesCreated?: number;
+ }
+}
+
const log = debug('context-engine:processor:GroupMessageFlattenProcessor');
/**
diff --git a/packages/context-engine/src/processors/GroupOrchestrationFilter.ts b/packages/context-engine/src/processors/GroupOrchestrationFilter.ts
index dcf855c7225..6dfea3fec31 100644
--- a/packages/context-engine/src/processors/GroupOrchestrationFilter.ts
+++ b/packages/context-engine/src/processors/GroupOrchestrationFilter.ts
@@ -3,6 +3,16 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { Message, PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ orchestrationFilterProcessed?: {
+ assistantFiltered: number;
+ filteredCount: number;
+ toolFiltered: number;
+ };
+ }
+}
+
const log = debug('context-engine:processor:GroupOrchestrationFilterProcessor');
/**
diff --git a/packages/context-engine/src/processors/GroupRoleTransform.ts b/packages/context-engine/src/processors/GroupRoleTransform.ts
index 1ba7753cef2..965122e413a 100644
--- a/packages/context-engine/src/processors/GroupRoleTransform.ts
+++ b/packages/context-engine/src/processors/GroupRoleTransform.ts
@@ -3,6 +3,15 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { Message, PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ groupRoleTransformProcessed?: {
+ assistantTransformed: number;
+ toolTransformed: number;
+ };
+ }
+}
+
const log = debug('context-engine:processor:GroupRoleTransformProcessor');
/**
diff --git a/packages/context-engine/src/processors/HistoryTruncate.ts b/packages/context-engine/src/processors/HistoryTruncate.ts
index bf8a6ad1b92..c444ba6f966 100644
--- a/packages/context-engine/src/processors/HistoryTruncate.ts
+++ b/packages/context-engine/src/processors/HistoryTruncate.ts
@@ -3,6 +3,13 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ finalMessageCount?: number;
+ historyTruncated?: number;
+ }
+}
+
const log = debug('context-engine:processor:HistoryTruncateProcessor');
export interface HistoryTruncateConfig {
@@ -261,7 +268,11 @@ export const getSlicedMessages = (
// Step 2: Walk backwards through messages to select last N groups
const selectedGroupIndices = new Set<number>();
- for (let i = messages.length - 1; i >= 0 && selectedGroupIndices.size < options.historyCount; i--) {
+ for (
+ let i = messages.length - 1;
+ i >= 0 && selectedGroupIndices.size < options.historyCount;
+ i--
+ ) {
const msg = messages[i] as MinimalMessage;
const groupIdx = messageToGroup.get(msg.id);
if (groupIdx !== undefined) {
diff --git a/packages/context-engine/src/processors/InputTemplate.ts b/packages/context-engine/src/processors/InputTemplate.ts
index 9b52e5d5e36..e9e7e9f06b3 100644
--- a/packages/context-engine/src/processors/InputTemplate.ts
+++ b/packages/context-engine/src/processors/InputTemplate.ts
@@ -4,6 +4,12 @@ import { template } from 'es-toolkit/compat';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ inputTemplateProcessed?: number;
+ }
+}
+
const log = debug('context-engine:processor:InputTemplateProcessor');
export interface InputTemplateConfig {
@@ -39,7 +45,7 @@ export class InputTemplateProcessor extends BaseProcessor {
try {
// Compile the template
const compiler = template(this.config.inputTemplate, {
- interpolate: /{{\s*(text)\s*}}/g,
+ interpolate: /\{\{\s*(text)\s*\}\}/g,
});
log(`Applying input template: ${this.config.inputTemplate}`);
diff --git a/packages/context-engine/src/processors/MessageCleanup.ts b/packages/context-engine/src/processors/MessageCleanup.ts
index 529584e75ed..26480dbeb68 100644
--- a/packages/context-engine/src/processors/MessageCleanup.ts
+++ b/packages/context-engine/src/processors/MessageCleanup.ts
@@ -3,6 +3,15 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ messageCleanup?: {
+ cleanedCount: number;
+ totalMessages: number;
+ };
+ }
+}
+
const log = debug('context-engine:processor:MessageCleanupProcessor');
/**
diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.ts
index 332def6d6d3..ee8bdc90389 100644
--- a/packages/context-engine/src/processors/MessageContent.ts
+++ b/packages/context-engine/src/processors/MessageContent.ts
@@ -8,6 +8,14 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ assistantMessagesProcessed?: number;
+ messageContentProcessed?: number;
+ userMessagesProcessed?: number;
+ }
+}
+
const log = debug('context-engine:processor:MessageContentProcessor');
/**
diff --git a/packages/context-engine/src/processors/PlaceholderVariables.ts b/packages/context-engine/src/processors/PlaceholderVariables.ts
index 08a89e8730a..ea5b27070de 100644
--- a/packages/context-engine/src/processors/PlaceholderVariables.ts
+++ b/packages/context-engine/src/processors/PlaceholderVariables.ts
@@ -3,9 +3,23 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ placeholderVariablesProcessed?: number;
+ }
+}
+
const log = debug('context-engine:processor:PlaceholderVariablesProcessor');
-const placeholderVariablesRegex = /{{(.*?)}}/g;
+const PLACEHOLDER_START = '{{';
+const PLACEHOLDER_END = '}}';
+
+interface PlaceholderToken {
+ end: number;
+ key: string;
+ raw: string;
+ start: number;
+}
export type PlaceholderValue = unknown | (() => unknown);
export type PlaceholderValueMap = Record<string, PlaceholderValue>;
@@ -63,9 +77,56 @@ export interface PlaceholderVariablesConfig {
* @param text String containing template variables
* @returns Array of variable names, e.g. ['date', 'nickname']
*/
-const extractPlaceholderVariables = (text: string): string[] => {
- const matches = [...text.matchAll(placeholderVariablesRegex)];
- return matches.map((m) => m[1].trim());
+const extractPlaceholderTokens = (text: string): PlaceholderToken[] => {
+ const tokens: PlaceholderToken[] = [];
+ let searchIndex = 0;
+
+ while (searchIndex < text.length) {
+ const start = text.indexOf(PLACEHOLDER_START, searchIndex);
+ if (start === -1) break;
+
+ const end = text.indexOf(PLACEHOLDER_END, start + PLACEHOLDER_START.length);
+ if (end === -1) break;
+
+ const tokenEnd = end + PLACEHOLDER_END.length;
+ tokens.push({
+ end: tokenEnd,
+ key: text.slice(start + PLACEHOLDER_START.length, end).trim(),
+ raw: text.slice(start, tokenEnd),
+ start,
+ });
+
+ searchIndex = tokenEnd;
+ }
+
+ return tokens;
+};
+
+const replaceAvailablePlaceholders = (
+ text: string,
+ placeholders: PlaceholderToken[],
+ availableVariables: Record<string, string>,
+): string => {
+ const output: string[] = [];
+ let cursor = 0;
+ let changed = false;
+
+ for (const placeholder of placeholders) {
+ output.push(text.slice(cursor, placeholder.start));
+
+ if (Object.hasOwn(availableVariables, placeholder.key)) {
+ output.push(availableVariables[placeholder.key]);
+ changed = true;
+ } else {
+ output.push(placeholder.raw);
+ }
+
+ cursor = placeholder.end;
+ }
+
+ output.push(text.slice(cursor));
+
+ return changed ? output.join('') : text;
};
/**
@@ -85,14 +146,17 @@ export const parsePlaceholderVariables = (
// Recursive parsing to handle cases like {{text}} containing additional preset variables
for (let i = 0; i < depth; i++) {
try {
- const extractedVariables = extractPlaceholderVariables(result);
+ const placeholders = extractPlaceholderTokens(result);
+ const extractedVariables = placeholders.map((placeholder) => placeholder.key);
+
+ if (placeholders.length === 0) break;
log('Extracted variables from text: %o', extractedVariables);
log('Available generator keys: %o', Object.keys(variableGenerators));
// Debug: check if text contains {{username}} pattern
if (result.includes('username') || result.includes('{{')) {
- const matches = result.match(/{{[^}]*}}/g);
+ const matches = placeholders.map((placeholder) => placeholder.raw);
log('All {{...}} patterns found in text: %o', matches);
}
@@ -112,16 +176,7 @@ export const parsePlaceholderVariables = (
// Only perform replacement when there are available variables
if (Object.keys(availableVariables).length === 0) break;
- // Replace variables one by one to avoid es-toolkit template's error handling for undefined variables
- let tempResult = result;
- for (const [key, value] of Object.entries(availableVariables)) {
- const regex = new RegExp(
- `{{\\s*${key.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&')}\\s*}}`,
- 'g',
- );
- // @ts-ignore
- tempResult = tempResult.replace(regex, value);
- }
+ const tempResult = replaceAvailablePlaceholders(result, placeholders, availableVariables);
if (tempResult === result) break;
result = tempResult;
diff --git a/packages/context-engine/src/processors/ReactionFeedback.ts b/packages/context-engine/src/processors/ReactionFeedback.ts
index 3f8c0af64d9..1ead3436423 100644
--- a/packages/context-engine/src/processors/ReactionFeedback.ts
+++ b/packages/context-engine/src/processors/ReactionFeedback.ts
@@ -4,6 +4,12 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ reactionFeedbackProcessed?: number;
+ }
+}
+
const log = debug('context-engine:processor:ReactionFeedbackProcessor');
export interface ReactionFeedbackConfig {
diff --git a/packages/context-engine/src/processors/SupervisorRoleRestore.ts b/packages/context-engine/src/processors/SupervisorRoleRestore.ts
index 36b2f03748e..9169791aa81 100644
--- a/packages/context-engine/src/processors/SupervisorRoleRestore.ts
+++ b/packages/context-engine/src/processors/SupervisorRoleRestore.ts
@@ -3,6 +3,12 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { Message, PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ supervisorRoleRestoreProcessed?: number;
+ }
+}
+
const log = debug('context-engine:processor:SupervisorRoleRestoreProcessor');
/**
diff --git a/packages/context-engine/src/processors/TaskMessage.ts b/packages/context-engine/src/processors/TaskMessage.ts
index 2217afbd147..06731a9e4b5 100644
--- a/packages/context-engine/src/processors/TaskMessage.ts
+++ b/packages/context-engine/src/processors/TaskMessage.ts
@@ -3,6 +3,12 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ taskMessagesProcessed?: number;
+ }
+}
+
const log = debug('context-engine:processor:TaskMessageProcessor');
/**
diff --git a/packages/context-engine/src/processors/TasksFlatten.ts b/packages/context-engine/src/processors/TasksFlatten.ts
index 384496fb9db..40ea7b9ab36 100644
--- a/packages/context-engine/src/processors/TasksFlatten.ts
+++ b/packages/context-engine/src/processors/TasksFlatten.ts
@@ -3,6 +3,14 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ taskMessagesCreated?: number;
+ tasksFlattenProcessed?: number;
+ tasksMessagesFlattened?: number;
+ }
+}
+
const log = debug('context-engine:processor:TasksFlattenProcessor');
/**
diff --git a/packages/context-engine/src/processors/ToolCall.ts b/packages/context-engine/src/processors/ToolCall.ts
index 227a692efb6..9e4cd1c713e 100644
--- a/packages/context-engine/src/processors/ToolCall.ts
+++ b/packages/context-engine/src/processors/ToolCall.ts
@@ -3,6 +3,15 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { MessageToolCall, PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ supportTools?: boolean;
+ toolCallProcessed?: number;
+ toolCallsConverted?: number;
+ toolMessagesConverted?: number;
+ }
+}
+
const log = debug('context-engine:processor:ToolCallProcessor');
export interface ToolCallConfig {
diff --git a/packages/context-engine/src/processors/ToolMessageReorder.ts b/packages/context-engine/src/processors/ToolMessageReorder.ts
index a9b1459aa49..e7b95b6afcd 100644
--- a/packages/context-engine/src/processors/ToolMessageReorder.ts
+++ b/packages/context-engine/src/processors/ToolMessageReorder.ts
@@ -3,6 +3,16 @@ import debug from 'debug';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ toolMessageReorder?: {
+ originalCount: number;
+ removedInvalidTools: number;
+ reorderedCount: number;
+ };
+ }
+}
+
const log = debug('context-engine:processor:ToolMessageReorder');
/**
diff --git a/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts b/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts
index f2a3c6ba23c..13b4b57cd01 100644
--- a/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts
+++ b/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts
@@ -301,8 +301,8 @@ describe('MessageCleanupProcessor', () => {
const result = await processor.process(context);
// Both messages are "cleaned" because comparison is done by reference
- expect(result.metadata.messageCleanup.cleanedCount).toBe(2);
- expect(result.metadata.messageCleanup.totalMessages).toBe(2);
+ expect(result.metadata.messageCleanup!.cleanedCount).toBe(2);
+ expect(result.metadata.messageCleanup!.totalMessages).toBe(2);
});
it('should handle empty messages array', async () => {
diff --git a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts
index e201730f94d..1c353e87276 100644
--- a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts
+++ b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts
@@ -53,6 +53,18 @@ describe('PlaceholderVariablesProcessor', () => {
const result = parsePlaceholderVariables(text, mockVariableGenerators);
expect(result).toBe('No placeholders here');
});
+
+ it('should replace placeholders with surrounding whitespace', () => {
+ const text = 'Hello {{ username }}, today is {{ date }}';
+ const result = parsePlaceholderVariables(text, mockVariableGenerators);
+ expect(result).toBe('Hello TestUser, today is 2023-12-25');
+ });
+
+ it('should handle malformed repeated opening braces without backtracking issues', () => {
+ const text = '{{{{'.repeat(2000);
+ const result = parsePlaceholderVariables(text, mockVariableGenerators);
+ expect(result).toBe(text);
+ });
});
describe('parsePlaceholderVariablesMessages', () => {
diff --git a/packages/context-engine/src/providers/AgentBuilderContextInjector.ts b/packages/context-engine/src/providers/AgentBuilderContextInjector.ts
index c5296e5658c..2dab4f78c50 100644
--- a/packages/context-engine/src/providers/AgentBuilderContextInjector.ts
+++ b/packages/context-engine/src/providers/AgentBuilderContextInjector.ts
@@ -1,21 +1,16 @@
+import { escapeXml } from '@lobechat/prompts';
import debug from 'debug';
import { BaseProvider } from '../base/BaseProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
-const log = debug('context-engine:provider:AgentBuilderContextInjector');
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ agentBuilderContextInjected?: boolean;
+ }
+}
-/**
- * Escape XML special characters
- */
-const escapeXml = (str: string): string => {
- return str
- .replaceAll('&', '&amp;')
- .replaceAll('<', '&lt;')
- .replaceAll('>', '&gt;')
- .replaceAll('"', '&quot;')
- .replaceAll("'", '&apos;');
-};
+const log = debug('context-engine:provider:AgentBuilderContextInjector');
/**
* Official tool item for Agent Builder context
diff --git a/packages/context-engine/src/providers/AgentManagementContextInjector.ts b/packages/context-engine/src/providers/AgentManagementContextInjector.ts
index 5b7f0d7b485..a67ce291e0a 100644
--- a/packages/context-engine/src/providers/AgentManagementContextInjector.ts
+++ b/packages/context-engine/src/providers/AgentManagementContextInjector.ts
@@ -1,21 +1,17 @@
+import { escapeXml } from '@lobechat/prompts';
+import type { RuntimeMentionedAgent } from '@lobechat/types';
import debug from 'debug';
import { BaseProvider } from '../base/BaseProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
-const log = debug('context-engine:provider:AgentManagementContextInjector');
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ agentManagementContextInjected?: boolean;
+ }
+}
-/**
- * Escape XML special characters
- */
-const escapeXml = (str: string): string => {
- return str
- .replaceAll('&', '&amp;')
- .replaceAll('<', '&lt;')
- .replaceAll('>', '&gt;')
- .replaceAll('"', '&quot;')
- .replaceAll("'", '&apos;');
-};
+const log = debug('context-engine:provider:AgentManagementContextInjector');
/**
* Available model info for Agent Management context
@@ -70,6 +66,8 @@ export interface AgentManagementContext {
availablePlugins?: AvailablePluginInfo[];
/** Available providers and models */
availableProviders?: AvailableProviderInfo[];
+ /** Agents @mentioned by the user — supervisor should delegate to these via callAgent */
+ mentionedAgents?: RuntimeMentionedAgent[];
}
export interface AgentManagementContextInjectorConfig {
@@ -166,6 +164,21 @@ ${parts.join('\n')}
</agent_management_context>`;
};
+/**
+ * Format mentioned agents as delegation context for injection after the user message.
+ * Instructs the AI to delegate to the mentioned agent(s) via callAgent.
+ */
+const formatMentionedAgentsContext = (mentionedAgents: RuntimeMentionedAgent[]): string => {
+ const agentsXml = mentionedAgents
+ .map((a) => ` <agent id="${escapeXml(a.id)}" name="${escapeXml(a.name)}" />`)
+ .join('\n');
+
+ return `<mentioned_agents>
+<instruction>The user has @mentioned the following agent(s) in their message. You MUST use the callAgent tool to delegate the user's request to the mentioned agent. Do NOT attempt to handle the request yourself — call the agent and let them respond.</instruction>
+${agentsXml}
+</mentioned_agents>`;
+};
+
/**
* Agent Management Context Injector
* Responsible for injecting available models and plugins when Agent Management tool is enabled
@@ -195,40 +208,69 @@ export class AgentManagementContextInjector extends BaseProvider {
return this.markAsExecuted(clonedContext);
}
- // Format context
- const formatFn = this.config.formatContext || defaultFormatContext;
- const formattedContent = formatFn(this.config.context);
+ const hasMentionedAgents =
+ this.config.context.mentionedAgents && this.config.context.mentionedAgents.length > 0;
- // Skip if no content to inject
- if (!formattedContent) {
- log('No content to inject after formatting');
- return this.markAsExecuted(clonedContext);
- }
+ // Format context (excluding mentionedAgents — those are injected separately after the last user message)
+ const contextWithoutMentions: AgentManagementContext = hasMentionedAgents
+ ? {
+ availablePlugins: this.config.context.availablePlugins,
+ availableProviders: this.config.context.availableProviders,
+ }
+ : this.config.context;
- // Find the first user message index
- const firstUserIndex = clonedContext.messages.findIndex((msg) => msg.role === 'user');
-
- if (firstUserIndex === -1) {
- log('No user messages found, skipping injection');
- return this.markAsExecuted(clonedContext);
+ const formatFn = this.config.formatContext || defaultFormatContext;
+ const formattedContent = formatFn(contextWithoutMentions);
+
+ // Inject agent-management context (providers/plugins) before the first user message
+ if (formattedContent) {
+ const firstUserIndex = clonedContext.messages.findIndex((msg) => msg.role === 'user');
+
+ if (firstUserIndex !== -1) {
+ const contextMessage = {
+ content: formattedContent,
+ createdAt: Date.now(),
+ id: `agent-management-context-${Date.now()}`,
+ meta: { injectType: 'agent-management-context', systemInjection: true },
+ role: 'user' as const,
+ updatedAt: Date.now(),
+ };
+
+ clonedContext.messages.splice(firstUserIndex, 0, contextMessage);
+ clonedContext.metadata.agentManagementContextInjected = true;
+ log('Agent Management context injected before first user message');
+ }
}
- // Insert a new user message with context before the first user message
- const contextMessage = {
- content: formattedContent,
- createdAt: Date.now(),
- id: `agent-management-context-${Date.now()}`,
- meta: { injectType: 'agent-management-context', systemInjection: true },
- role: 'user' as const,
- updatedAt: Date.now(),
- };
-
- clonedContext.messages.splice(firstUserIndex, 0, contextMessage);
-
- // Update metadata
- clonedContext.metadata.agentManagementContextInjected = true;
-
- log('Agent Management context injected as new user message');
+ // Inject mentionedAgents delegation context AFTER the last user message
+ // This position makes the delegation instruction most salient to the model
+ if (hasMentionedAgents) {
+ const mentionedContent = formatMentionedAgentsContext(this.config.context.mentionedAgents!);
+
+ // Find the last user message index
+ let lastUserIndex = -1;
+ for (let i = clonedContext.messages.length - 1; i >= 0; i--) {
+ if (clonedContext.messages[i].role === 'user') {
+ lastUserIndex = i;
+ break;
+ }
+ }
+
+ if (lastUserIndex !== -1) {
+ const mentionMessage = {
+ content: mentionedContent,
+ createdAt: Date.now(),
+ id: `agent-mention-delegation-${Date.now()}`,
+ meta: { injectType: 'agent-mention-delegation', systemInjection: true },
+ role: 'user' as const,
+ updatedAt: Date.now(),
+ };
+
+ // Insert after the last user message
+ clonedContext.messages.splice(lastUserIndex + 1, 0, mentionMessage);
+ log('Mentioned agents delegation context injected after last user message');
+ }
+ }
return this.markAsExecuted(clonedContext);
}
diff --git a/packages/context-engine/src/providers/EvalContextSystemInjector.ts b/packages/context-engine/src/providers/EvalContextSystemInjector.ts
index 48d081ec29e..9fd7e405b76 100644
--- a/packages/context-engine/src/providers/EvalContextSystemInjector.ts
+++ b/packages/context-engine/src/providers/EvalContextSystemInjector.ts
@@ -3,6 +3,12 @@ import debug from 'debug';
import { BaseProvider } from '../base/BaseProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ evalContextInjected?: boolean;
+ }
+}
+
const log = debug('context-engine:provider:EvalContextSystemInjector');
export interface EvalContext {
diff --git a/packages/context-engine/src/providers/ForceFinishSummaryInjector.ts b/packages/context-engine/src/providers/ForceFinishSummaryInjector.ts
index 74e4f8a5c7f..6d549a273ef 100644
--- a/packages/context-engine/src/providers/ForceFinishSummaryInjector.ts
+++ b/packages/context-engine/src/providers/ForceFinishSummaryInjector.ts
@@ -3,6 +3,12 @@ import debug from 'debug';
import { BaseProvider } from '../base/BaseProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ forceFinishInjected?: boolean;
+ }
+}
+
const log = debug('context-engine:provider:ForceFinishSummaryInjector');
export interface ForceFinishSummaryInjectorConfig {
diff --git a/packages/context-engine/src/providers/GTDPlanInjector.ts b/packages/context-engine/src/providers/GTDPlanInjector.ts
index 18a944bb32a..7c5d0ea2bc2 100644
--- a/packages/context-engine/src/providers/GTDPlanInjector.ts
+++ b/packages/context-engine/src/providers/GTDPlanInjector.ts
@@ -3,6 +3,13 @@ import debug from 'debug';
import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ gtdPlanId?: string;
+ gtdPlanInjected?: boolean;
+ }
+}
+
const log = debug('context-engine:provider:GTDPlanInjector');
/**
diff --git a/packages/context-engine/src/providers/GTDTodoInjector.ts b/packages/context-engine/src/providers/GTDTodoInjector.ts
index ce86eeddaab..b4959081ac7 100644
--- a/packages/context-engine/src/providers/GTDTodoInjector.ts
+++ b/packages/context-engine/src/providers/GTDTodoInjector.ts
@@ -3,6 +3,15 @@ import debug from 'debug';
import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ gtdTodoCompletedCount?: number;
+ gtdTodoCount?: number;
+ gtdTodoInjected?: boolean;
+ gtdTodoProcessingCount?: number;
+ }
+}
+
const log = debug('context-engine:provider:GTDTodoInjector');
/** Status of a todo item */
diff --git a/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts b/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts
index c653723940c..aad1495a5c6 100644
--- a/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts
+++ b/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts
@@ -1,21 +1,16 @@
+import { escapeXml } from '@lobechat/prompts';
import debug from 'debug';
import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
-const log = debug('context-engine:provider:GroupAgentBuilderContextInjector');
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ groupAgentBuilderContextInjected?: boolean;
+ }
+}
-/**
- * Escape XML special characters
- */
-const escapeXml = (str: string): string => {
- return str
- .replaceAll('&', '&amp;')
- .replaceAll('<', '&lt;')
- .replaceAll('>', '&gt;')
- .replaceAll('"', '&quot;')
- .replaceAll("'", '&apos;');
-};
+const log = debug('context-engine:provider:GroupAgentBuilderContextInjector');
/**
* Group member info for Group Agent Builder context
diff --git a/packages/context-engine/src/providers/GroupContextInjector.ts b/packages/context-engine/src/providers/GroupContextInjector.ts
index b2d1b416319..56e8988b7d9 100644
--- a/packages/context-engine/src/providers/GroupContextInjector.ts
+++ b/packages/context-engine/src/providers/GroupContextInjector.ts
@@ -5,6 +5,12 @@ import debug from 'debug';
import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ groupContextInjected?: boolean;
+ }
+}
+
const log = debug('context-engine:provider:GroupContextInjector');
/**
diff --git a/packages/context-engine/src/providers/HistorySummary.ts b/packages/context-engine/src/providers/HistorySummary.ts
index e1cd51a6318..5f10761c9eb 100644
--- a/packages/context-engine/src/providers/HistorySummary.ts
+++ b/packages/context-engine/src/providers/HistorySummary.ts
@@ -3,6 +3,16 @@ import debug from 'debug';
import { BaseProvider } from '../base/BaseProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ historySummary?: {
+ formattedLength: number;
+ injected: boolean;
+ originalLength: number;
+ };
+ }
+}
+
const log = debug('context-engine:provider:HistorySummaryProvider');
/**
diff --git a/packages/context-engine/src/providers/KnowledgeInjector.ts b/packages/context-engine/src/providers/KnowledgeInjector.ts
index ce4629c01e4..0c3ddc1e8a8 100644
--- a/packages/context-engine/src/providers/KnowledgeInjector.ts
+++ b/packages/context-engine/src/providers/KnowledgeInjector.ts
@@ -5,6 +5,14 @@ import debug from 'debug';
import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ filesCount?: number;
+ knowledgeBasesCount?: number;
+ knowledgeInjected?: boolean;
+ }
+}
+
const log = debug('context-engine:provider:KnowledgeInjector');
export interface KnowledgeInjectorConfig {
diff --git a/packages/context-engine/src/providers/PageEditorContextInjector.ts b/packages/context-engine/src/providers/PageEditorContextInjector.ts
index c64f8637e13..d7925bfc1c6 100644
--- a/packages/context-engine/src/providers/PageEditorContextInjector.ts
+++ b/packages/context-engine/src/providers/PageEditorContextInjector.ts
@@ -5,6 +5,12 @@ import debug from 'debug';
import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ pageEditorContextInjected?: boolean;
+ }
+}
+
const log = debug('context-engine:provider:PageEditorContextInjector');
export interface PageEditorContextInjectorConfig {
diff --git a/packages/context-engine/src/providers/SelectedSkillInjector.ts b/packages/context-engine/src/providers/SelectedSkillInjector.ts
new file mode 100644
index 00000000000..19b760f69c5
--- /dev/null
+++ b/packages/context-engine/src/providers/SelectedSkillInjector.ts
@@ -0,0 +1,92 @@
+import { escapeXml } from '@lobechat/prompts';
+import type { RuntimeSelectedSkill } from '@lobechat/types';
+import debug from 'debug';
+
+import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ selectedSkillContext?: {
+ injected: boolean;
+ skillsCount: number;
+ };
+ }
+}
+
+const log = debug('context-engine:provider:SelectedSkillInjector');
+
+export interface SelectedSkillInjectorConfig {
+ selectedSkills?: RuntimeSelectedSkill[];
+}
+
+const formatSelectedSkills = (selectedSkills: RuntimeSelectedSkill[]): string | null => {
+ if (selectedSkills.length === 0) return null;
+
+ const lines = [
+ 'The user explicitly selected these skills for this request. Prefer them when relevant.',
+ '<selected_skills>',
+ ...selectedSkills.map(
+ (skill) =>
+ ` <skill identifier="${escapeXml(skill.identifier)}" name="${escapeXml(skill.name)}" />`,
+ ),
+ '</selected_skills>',
+ ];
+
+ return lines.join('\n');
+};
+
+/**
+ * Selected Skill Injector
+ * Appends user-selected slash-menu skills to the last user message as ephemeral context.
+ */
+export class SelectedSkillInjector extends BaseLastUserContentProvider {
+ readonly name = 'SelectedSkillInjector';
+
+ constructor(
+ private config: SelectedSkillInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+ const selectedSkills = this.config.selectedSkills ?? [];
+
+ if (selectedSkills.length === 0) {
+ log('No selected skills, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ const content = formatSelectedSkills(selectedSkills);
+
+ if (!content) {
+ log('No selected skill content generated, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ const lastUserIndex = this.findLastUserMessageIndex(clonedContext.messages);
+
+ if (lastUserIndex === -1) {
+ log('No user messages found, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ const hasExistingWrapper = this.hasExistingSystemContext(clonedContext);
+ const contentToAppend = hasExistingWrapper
+ ? this.createContextBlock(content, 'selected_skill_context')
+ : this.wrapWithSystemContext(content, 'selected_skill_context');
+
+ this.appendToLastUserMessage(clonedContext, contentToAppend);
+
+ clonedContext.metadata.selectedSkillContext = {
+ injected: true,
+ skillsCount: selectedSkills.length,
+ };
+
+ log('Selected skill context appended, skills count: %d', selectedSkills.length);
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/SkillContextProvider.ts b/packages/context-engine/src/providers/SkillContextProvider.ts
index 86351427f55..8151c91dc64 100644
--- a/packages/context-engine/src/providers/SkillContextProvider.ts
+++ b/packages/context-engine/src/providers/SkillContextProvider.ts
@@ -4,6 +4,15 @@ import debug from 'debug';
import { BaseProvider } from '../base/BaseProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ skillContext?: {
+ injected: boolean;
+ skillsCount: number;
+ };
+ }
+}
+
const log = debug('context-engine:provider:SkillContextProvider');
/**
diff --git a/packages/context-engine/src/providers/SystemDateProvider.ts b/packages/context-engine/src/providers/SystemDateProvider.ts
index b1d95ff3f8e..59dce9eadea 100644
--- a/packages/context-engine/src/providers/SystemDateProvider.ts
+++ b/packages/context-engine/src/providers/SystemDateProvider.ts
@@ -3,6 +3,12 @@ import debug from 'debug';
import { BaseProvider } from '../base/BaseProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ systemDateInjected?: boolean;
+ }
+}
+
const log = debug('context-engine:provider:SystemDateProvider');
export interface SystemDateProviderConfig {
diff --git a/packages/context-engine/src/providers/SystemRoleInjector.ts b/packages/context-engine/src/providers/SystemRoleInjector.ts
index 51e03667b1f..01c55222e26 100644
--- a/packages/context-engine/src/providers/SystemRoleInjector.ts
+++ b/packages/context-engine/src/providers/SystemRoleInjector.ts
@@ -3,6 +3,12 @@ import debug from 'debug';
import { BaseProvider } from '../base/BaseProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ systemRoleInjected?: boolean;
+ }
+}
+
const log = debug('context-engine:provider:SystemRoleInjector');
export interface SystemRoleInjectorConfig {
diff --git a/packages/context-engine/src/providers/ToolDiscoveryProvider.ts b/packages/context-engine/src/providers/ToolDiscoveryProvider.ts
index 2e70988821e..49f43c7d2d4 100644
--- a/packages/context-engine/src/providers/ToolDiscoveryProvider.ts
+++ b/packages/context-engine/src/providers/ToolDiscoveryProvider.ts
@@ -4,6 +4,15 @@ import debug from 'debug';
import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ toolDiscoveryContext?: {
+ injected: boolean;
+ toolsCount: number;
+ };
+ }
+}
+
const log = debug('context-engine:provider:ToolDiscoveryProvider');
export interface ToolDiscoveryMeta {
diff --git a/packages/context-engine/src/providers/ToolSystemRole.ts b/packages/context-engine/src/providers/ToolSystemRole.ts
index 86e3d785b3f..364e1d3d7aa 100644
--- a/packages/context-engine/src/providers/ToolSystemRole.ts
+++ b/packages/context-engine/src/providers/ToolSystemRole.ts
@@ -7,6 +7,17 @@ import { ToolNameResolver } from '../engine/tools';
import type { LobeToolManifest } from '../engine/tools/types';
import type { PipelineContext, ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ toolSystemRole?: {
+ contentLength: number;
+ injected: boolean;
+ supportsFunctionCall: boolean;
+ toolsCount: number;
+ };
+ }
+}
+
const log = debug('context-engine:provider:ToolSystemRoleProvider');
/**
@@ -58,7 +69,7 @@ export class ToolSystemRoleProvider extends BaseProvider {
clonedContext.metadata.toolSystemRole = {
contentLength: toolSystemRole.length,
injected: true,
- supportsFunctionCall: this.config.isCanUseFC(this.config.model, this.config.provider),
+ supportsFunctionCall: !!this.config.isCanUseFC(this.config.model, this.config.provider),
toolsCount: this.config.manifests.length,
};
diff --git a/packages/context-engine/src/providers/UserMemoryInjector.ts b/packages/context-engine/src/providers/UserMemoryInjector.ts
index ae6dcd7a59b..540c976bb62 100644
--- a/packages/context-engine/src/providers/UserMemoryInjector.ts
+++ b/packages/context-engine/src/providers/UserMemoryInjector.ts
@@ -5,6 +5,12 @@ import debug from 'debug';
import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';
import { type PipelineContext, type ProcessorOptions } from '../types';
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ userMemoryInjected?: boolean;
+ }
+}
+
const log = debug('context-engine:provider:UserMemoryInjector');
export interface UserMemoryInjectorConfig {
diff --git a/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts
new file mode 100644
index 00000000000..a9e56578972
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts
@@ -0,0 +1,205 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { AgentManagementContextInjector } from '../AgentManagementContextInjector';
+
+describe('AgentManagementContextInjector', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata: {},
+ });
+
+ describe('disabled / no context', () => {
+ it('should skip when disabled', async () => {
+ const injector = new AgentManagementContextInjector({ enabled: false });
+ const ctx = createContext([
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'hi' },
+ ]);
+ const result = await injector.process(ctx);
+ expect(result.messages).toHaveLength(2);
+ });
+
+ it('should skip when no context provided', async () => {
+ const injector = new AgentManagementContextInjector({ enabled: true });
+ const ctx = createContext([
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'hi' },
+ ]);
+ const result = await injector.process(ctx);
+ expect(result.messages).toHaveLength(2);
+ });
+ });
+
+ describe('agent-management context (providers/plugins)', () => {
+ it('should inject before the first user message', async () => {
+ const injector = new AgentManagementContextInjector({
+ enabled: true,
+ context: {
+ availableProviders: [
+ {
+ id: 'openai',
+ name: 'OpenAI',
+ models: [{ id: 'gpt-4', name: 'GPT-4' }],
+ },
+ ],
+ },
+ });
+
+ const ctx = createContext([
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'create an agent' },
+ ]);
+ const result = await injector.process(ctx);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].role).toBe('system');
+ // Injected context before user message
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[1].content).toContain('<agent_management_context>');
+ expect(result.messages[1].content).toContain('gpt-4');
+ // Original user message
+ expect(result.messages[2].content).toBe('create an agent');
+ expect(result.metadata.agentManagementContextInjected).toBe(true);
+ });
+ });
+
+ describe('mentionedAgents delegation', () => {
+ it('should inject delegation context after the last user message', async () => {
+ const injector = new AgentManagementContextInjector({
+ enabled: true,
+ context: {
+ mentionedAgents: [{ id: 'agt_designer', name: 'Designer Agent' }],
+ },
+ });
+
+ const ctx = createContext([
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'Let @Designer Agent help me' },
+ ]);
+ const result = await injector.process(ctx);
+
+ // system + user + injected delegation
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[1].content).toBe('Let @Designer Agent help me');
+
+ const delegationMsg = result.messages[2];
+ expect(delegationMsg.role).toBe('user');
+ expect(delegationMsg.content).toContain('<mentioned_agents>');
+ expect(delegationMsg.content).toContain('agt_designer');
+ expect(delegationMsg.content).toContain('Designer Agent');
+ expect(delegationMsg.content).toContain('MUST use the callAgent tool');
+ expect(delegationMsg.meta.injectType).toBe('agent-mention-delegation');
+ });
+
+ it('should inject after the LAST user message, not the first', async () => {
+ const injector = new AgentManagementContextInjector({
+ enabled: true,
+ context: {
+ mentionedAgents: [{ id: 'agt_1', name: 'Agent A' }],
+ },
+ });
+
+ const ctx = createContext([
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'first message' },
+ { role: 'assistant', content: 'reply' },
+ { role: 'user', content: 'Let @Agent A do this' },
+ ]);
+ const result = await injector.process(ctx);
+
+ // system + user + assistant + user + injected
+ expect(result.messages).toHaveLength(5);
+ expect(result.messages[3].content).toBe('Let @Agent A do this');
+ expect(result.messages[4].content).toContain('<mentioned_agents>');
+ expect(result.messages[4].content).toContain('agt_1');
+ });
+
+ it('should handle multiple mentioned agents', async () => {
+ const injector = new AgentManagementContextInjector({
+ enabled: true,
+ context: {
+ mentionedAgents: [
+ { id: 'agt_1', name: 'Agent A' },
+ { id: 'agt_2', name: 'Agent B' },
+ ],
+ },
+ });
+
+ const ctx = createContext([{ role: 'user', content: 'hello' }]);
+ const result = await injector.process(ctx);
+
+ const delegationMsg = result.messages[1];
+ expect(delegationMsg.content).toContain('agt_1');
+ expect(delegationMsg.content).toContain('agt_2');
+ expect(delegationMsg.content).toContain('Agent A');
+ expect(delegationMsg.content).toContain('Agent B');
+ });
+ });
+
+ describe('combined: agent-management + mentionedAgents', () => {
+ it('should inject providers before first user and delegation after last user', async () => {
+ const injector = new AgentManagementContextInjector({
+ enabled: true,
+ context: {
+ availableProviders: [
+ {
+ id: 'anthropic',
+ name: 'Anthropic',
+ models: [{ id: 'claude-sonnet-4-5-20250514', name: 'Claude Sonnet' }],
+ },
+ ],
+ mentionedAgents: [{ id: 'agt_dev', name: 'Developer' }],
+ },
+ });
+
+ const ctx = createContext([
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'Let @Developer build this' },
+ ]);
+ const result = await injector.process(ctx);
+
+ // system + management_context + user + delegation
+ expect(result.messages).toHaveLength(4);
+
+ // Management context before first user
+ expect(result.messages[1].content).toContain('<agent_management_context>');
+ expect(result.messages[1].content).toContain('claude-sonnet-4-5-20250514');
+ // Management context should NOT contain mentionedAgents
+ expect(result.messages[1].content).not.toContain('<mentioned_agents>');
+
+ // Original user message
+ expect(result.messages[2].content).toBe('Let @Developer build this');
+
+ // Delegation after last user
+ expect(result.messages[3].content).toContain('<mentioned_agents>');
+ expect(result.messages[3].content).toContain('agt_dev');
+ });
+ });
+
+ describe('only mentionedAgents (no providers/plugins)', () => {
+ it('should NOT inject empty agent-management context but SHOULD inject delegation', async () => {
+ const injector = new AgentManagementContextInjector({
+ enabled: true,
+ context: {
+ // No providers, no plugins — only mentionedAgents
+ mentionedAgents: [{ id: 'agt_x', name: 'Agent X' }],
+ },
+ });
+
+ const ctx = createContext([
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'Ask @Agent X' },
+ ]);
+ const result = await injector.process(ctx);
+
+ // system + user + delegation (no empty management context)
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[1].content).toBe('Ask @Agent X');
+ expect(result.messages[2].content).toContain('<mentioned_agents>');
+ expect(result.messages[2].content).toContain('agt_x');
+ });
+ });
+});
diff --git a/packages/context-engine/src/providers/__tests__/SelectedSkillInjector.test.ts b/packages/context-engine/src/providers/__tests__/SelectedSkillInjector.test.ts
new file mode 100644
index 00000000000..7b4077e2847
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/SelectedSkillInjector.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { SelectedSkillInjector } from '../SelectedSkillInjector';
+
+const createContext = (messages: any[] = []): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'gpt-4',
+ provider: 'openai',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4096,
+ model: 'gpt-4',
+ },
+});
+
+describe('SelectedSkillInjector', () => {
+ it('should append selected skills to the last user message', async () => {
+ const provider = new SelectedSkillInjector({
+ selectedSkills: [
+ { identifier: 'user_memory', name: 'User Memory' },
+ { identifier: 'instruction', name: 'Instruction' },
+ ],
+ });
+
+ const context = createContext([
+ { content: 'Earlier question', id: 'user-1', role: 'user' },
+ { content: 'Assistant reply', id: 'assistant-1', role: 'assistant' },
+ { content: 'Current request', id: 'user-2', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[2].content).toContain('Current request');
+ expect(result.messages[2].content).toContain('<selected_skill_context>');
+ expect(result.messages[2].content).toContain('<selected_skills>');
+ expect(result.messages[2].content).toContain(
+ '<skill identifier="user_memory" name="User Memory" />',
+ );
+ expect(result.metadata.selectedSkillContext).toEqual({
+ injected: true,
+ skillsCount: 2,
+ });
+ });
+
+ it('should reuse existing system context wrapper on the last user message', async () => {
+ const provider = new SelectedSkillInjector({
+ selectedSkills: [{ identifier: 'user_memory', name: 'User Memory' }],
+ });
+
+ const context = createContext([
+ {
+ content: `Current request
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<current_page_context>
+<page>draft</page>
+</current_page_context>
+<!-- END SYSTEM CONTEXT -->`,
+ id: 'user-1',
+ role: 'user',
+ },
+ ]);
+
+ const result = await provider.process(context);
+ const content = result.messages[0].content as string;
+
+ expect(content.match(/<!-- SYSTEM CONTEXT \(NOT PART OF USER QUERY\) -->/g)).toHaveLength(1);
+ expect(content).toContain('<current_page_context>');
+ expect(content).toContain('<selected_skill_context>');
+ });
+});
diff --git a/packages/context-engine/src/providers/__tests__/ToolSystemRoleProvider.test.ts b/packages/context-engine/src/providers/__tests__/ToolSystemRoleProvider.test.ts
index b99bc122925..7eee4e3e24b 100644
--- a/packages/context-engine/src/providers/__tests__/ToolSystemRoleProvider.test.ts
+++ b/packages/context-engine/src/providers/__tests__/ToolSystemRoleProvider.test.ts
@@ -44,8 +44,8 @@ describe('ToolSystemRoleProvider', () => {
// Should update metadata
expect(result.metadata.toolSystemRole).toBeDefined();
- expect(result.metadata.toolSystemRole.injected).toBe(true);
- expect(result.metadata.toolSystemRole.supportsFunctionCall).toBe(true);
+ expect(result.metadata.toolSystemRole!.injected).toBe(true);
+ expect(result.metadata.toolSystemRole!.supportsFunctionCall).toBe(true);
});
it('should merge tool system role with existing system message', async () => {
diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.ts
index 052e7ceb6af..d3a0bd20804 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -12,6 +12,7 @@ export { HistorySummaryProvider } from './HistorySummary';
export { KnowledgeInjector } from './KnowledgeInjector';
export { PageEditorContextInjector } from './PageEditorContextInjector';
export { PageSelectionsInjector } from './PageSelectionsInjector';
+export { SelectedSkillInjector } from './SelectedSkillInjector';
export { SkillContextProvider } from './SkillContextProvider';
export { SystemDateProvider } from './SystemDateProvider';
export { SystemRoleInjector } from './SystemRoleInjector';
@@ -51,6 +52,7 @@ export type { HistorySummaryConfig } from './HistorySummary';
export type { KnowledgeInjectorConfig } from './KnowledgeInjector';
export type { PageEditorContextInjectorConfig } from './PageEditorContextInjector';
export type { PageSelectionsInjectorConfig } from './PageSelectionsInjector';
+export type { SelectedSkillInjectorConfig } from './SelectedSkillInjector';
export type { SkillContextProviderConfig, SkillMeta } from './SkillContextProvider';
export type { SystemDateProviderConfig } from './SystemDateProvider';
export type { SystemRoleInjectorConfig } from './SystemRoleInjector';
diff --git a/packages/context-engine/src/types.ts b/packages/context-engine/src/types.ts
index 004e4a8674a..b0bee4dd722 100644
--- a/packages/context-engine/src/types.ts
+++ b/packages/context-engine/src/types.ts
@@ -1,5 +1,17 @@
import type { UIChatMessage } from '@lobechat/types';
+/**
+ * Consumer-side metadata extensions for PipelineContext.metadata.
+ *
+ * Example:
+ * declare module '@lobechat/context-engine' {
+ * interface PipelineContextMetadataOverrides {
+ * myCustomFlag?: boolean;
+ * }
+ * }
+ */
+export interface PipelineContextMetadataOverrides {}
+
/**
* Agent state - inferred from original project types
*/
@@ -39,6 +51,19 @@ export interface Message {
role: string;
}
+/**
+ * Metadata shared across pipeline processors.
+ * Consumers can extend this through declaration merging on
+ * `LobeChatContextEngine.PipelineContextMetadataOverrides`.
+ */
+export interface PipelineContextMetadata extends PipelineContextMetadataOverrides {
+ [key: `${string}InjectedCount`]: number | undefined;
+ currentTokenCount?: number;
+ maxTokens?: number;
+ model?: string;
+ provider?: string;
+}
+
/**
* Pipeline context - core data structure flowing through the pipeline
*/
@@ -55,16 +80,7 @@ export interface PipelineContext {
/** Mutable message list being built */
messages: Message[];
/** Metadata for communication between processors */
- metadata: {
- /** Other custom metadata */
- [key: string]: any;
- /** Current token count estimate */
- currentTokenCount?: number;
- /** Maximum token limit */
- maxTokens?: number;
- /** Model identifier */
- model?: string;
- };
+ metadata: PipelineContextMetadata;
}
/**
@@ -98,7 +114,7 @@ export interface PipelineResult {
/** Final processed messages */
messages: any[];
/** Metadata from processing */
- metadata: Record<string, any>;
+ metadata: PipelineContextMetadata;
/** Execution statistics */
stats: {
/** Number of processors processed */
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 1857e1cf4d7..e1c11a9fa0e 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -217,6 +217,7 @@ export class MessageModel {
id: messages.id,
role: messages.role,
content: messages.content,
+ editorData: messages.editorData,
reasoning: messages.reasoning,
search: messages.search,
metadata: messages.metadata,
@@ -555,6 +556,7 @@ export class MessageModel {
id: messages.id,
role: messages.role,
content: messages.content,
+ editorData: messages.editorData,
reasoning: messages.reasoning,
search: messages.search,
metadata: messages.metadata,
diff --git a/packages/prompts/src/prompts/search/index.ts b/packages/prompts/src/prompts/search/index.ts
index 71d4bdca5a8..1b212e873c9 100644
--- a/packages/prompts/src/prompts/search/index.ts
+++ b/packages/prompts/src/prompts/search/index.ts
@@ -1,2 +1,3 @@
export * from './crawlResults';
export * from './searchResults';
+export * from './xmlEscape';
diff --git a/packages/prompts/src/prompts/search/xmlEscape.ts b/packages/prompts/src/prompts/search/xmlEscape.ts
index 33da126f538..72fcd0d4b30 100644
--- a/packages/prompts/src/prompts/search/xmlEscape.ts
+++ b/packages/prompts/src/prompts/search/xmlEscape.ts
@@ -1,3 +1,17 @@
+/**
+ * Escape all XML special characters (safe for both attributes and content)
+ * Includes: & < > " '
+ */
+export const escapeXml = (text: string | undefined | null): string => {
+ if (!text) return '';
+ return text
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&apos;');
+};
+
/**
* Escape special characters for XML attributes
* Includes: & " < >
diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.ts
index 5acc967a36f..986bdde2b52 100644
--- a/packages/types/src/aiChat.ts
+++ b/packages/types/src/aiChat.ts
@@ -1,6 +1,9 @@
import { z } from 'zod';
+import type { MessageMetadata } from './message/common';
+import { ChatToolPayloadSchema, MessageMetadataSchema } from './message/common';
import type { UIChatMessage } from './message';
+import type { CreateMessageParams } from './message/ui/params';
import type { PageSelection } from './message/ui/params';
import { PageSelectionSchema } from './message/ui/params';
import type { OpenAIChatMessage } from './openai/chat';
@@ -12,6 +15,8 @@ import { ThreadType } from './topic/thread';
export interface SendNewMessage {
content: string;
+ /** Lexical editor JSON state for rich text rendering */
+ editorData?: Record<string, any>;
// if message has attached with files, then add files to message and the agent
files?: string[];
/** Page selections attached to this message (for Ask AI functionality) */
@@ -19,6 +24,15 @@ export interface SendNewMessage {
parentId?: string;
}
+export interface SendPreloadMessage
+ extends Omit<
+ Pick<CreateMessageParams, 'content' | 'metadata' | 'plugin' | 'tool_call_id' | 'tools'>,
+ 'metadata'
+ > {
+ metadata?: MessageMetadata;
+ role: 'assistant' | 'tool';
+}
+
/**
* Parameters for creating a new thread along with message
*/
@@ -57,6 +71,7 @@ export interface SendMessageServerParams {
title?: string;
topicMessageIds?: string[];
};
+ preloadMessages?: SendPreloadMessage[];
newUserMessage: SendNewMessage;
sessionId?: string;
threadId?: string;
@@ -71,6 +86,22 @@ export const CreateThreadWithMessageSchema = z.object({
type: z.enum([ThreadType.Continuation, ThreadType.Standalone, ThreadType.Isolation]),
});
+const SendPreloadMessageSchema = z.object({
+ content: z.string(),
+ metadata: MessageMetadataSchema.optional(),
+ plugin: z
+ .object({
+ apiName: z.string(),
+ arguments: z.string(),
+ identifier: z.string(),
+ type: z.string(),
+ })
+ .optional(),
+ role: z.enum(['assistant', 'tool']),
+ tool_call_id: z.string().optional(),
+ tools: z.array(ChatToolPayloadSchema).optional(),
+});
+
export const AiSendMessageServerSchema = z.object({
agentId: z.string().optional(),
groupId: z.string().optional(),
@@ -86,8 +117,10 @@ export const AiSendMessageServerSchema = z.object({
topicMessageIds: z.array(z.string()).optional(),
})
.optional(),
+ preloadMessages: z.array(SendPreloadMessageSchema).optional(),
newUserMessage: z.object({
content: z.string(),
+ editorData: z.record(z.unknown()).optional(),
files: z.array(z.string()).optional(),
pageSelections: z.array(PageSelectionSchema).optional(),
parentId: z.string().optional(),
diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.ts
index b334e2dbe5d..a0df495c87c 100644
--- a/packages/types/src/message/db/params.ts
+++ b/packages/types/src/message/db/params.ts
@@ -91,6 +91,7 @@ export interface NewMessage {
export interface UpdateMessageParams {
content?: string;
+ editorData?: Record<string, any> | null;
error?: ChatMessageError | null;
imageList?: ChatImageItem[];
metadata?: MessageMetadata;
@@ -117,6 +118,7 @@ export interface NewMessageQueryParams {
export const UpdateMessageParamsSchema = z
.object({
content: z.string().optional(),
+ editorData: z.record(z.any()).nullable().optional(),
error: ChatMessageErrorSchema.nullable().optional(),
imageList: z.array(ChatImageItemSchema).optional(),
metadata: MessageMetadataSchema.optional(),
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index f1f2f0caada..2f8d928db71 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -113,6 +113,8 @@ export interface UIChatMessage {
compressedMessages?: UIChatMessage[];
content: string;
createdAt: number;
+ /** Lexical editor JSON state for rich text rendering */
+ editorData?: Record<string, any> | null;
error?: ChatMessageError | null;
// Extended fields
extra?: ChatMessageExtra;
diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.ts
index 544af4fcd7a..150d5282c6c 100644
--- a/packages/types/src/message/ui/params.ts
+++ b/packages/types/src/message/ui/params.ts
@@ -108,6 +108,8 @@ export interface SendMessageParams {
* @deprecated Use ConversationContext.newThread instead
*/
createThread?: boolean;
+ /** Lexical editor JSON state for rich text rendering */
+ editorData?: Record<string, any>;
files?: UploadFileItem[];
/**
*
diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.ts
index 5d7fc983f43..8c95eba1983 100644
--- a/packages/types/src/stepContext.ts
+++ b/packages/types/src/stepContext.ts
@@ -74,6 +74,36 @@ export interface InitialPageEditorContext {
xml: string;
}
+/**
+ * User-selected skill context for the current request
+ * Captured from slash-menu skill action tags before send
+ */
+export interface RuntimeSelectedSkill {
+ /**
+ * Skill identifier used by runtime/tooling
+ */
+ identifier: string;
+ /**
+ * Human-readable skill name shown in the input UI
+ */
+ name: string;
+}
+
+/**
+ * User-selected tool context for the current request
+ * Captured from slash-menu tool action tags before send
+ */
+export interface RuntimeSelectedTool {
+ /**
+ * Tool identifier used by runtime/tooling
+ */
+ identifier: string;
+ /**
+ * Human-readable tool name shown in the input UI
+ */
+ name: string;
+}
+
/**
* Runtime Step Context
*
@@ -112,6 +142,16 @@ export interface RuntimeStepContext {
todos?: StepContextTodos;
}
+/**
+ * Agent mentioned by the user via @ in the input editor
+ */
+export interface RuntimeMentionedAgent {
+ /** Agent ID */
+ id: string;
+ /** Agent display name */
+ name: string;
+}
+
/**
* Initial Context
*
@@ -119,9 +159,25 @@ export interface RuntimeStepContext {
* Remains constant throughout the operation lifecycle.
*/
export interface RuntimeInitialContext {
+ /**
+ * Agents explicitly @mentioned by the user in the input editor.
+ * When present in a non-group conversation, the current agent acts as
+ * supervisor and can delegate to the mentioned agents via callAgent.
+ */
+ mentionedAgents?: RuntimeMentionedAgent[];
/**
* Initial Page Editor context
* Contains markdown content and metadata captured at operation start
*/
pageEditor?: InitialPageEditorContext;
+ /**
+ * Skills explicitly selected by the user for the current request
+ * This is ephemeral runtime context and is not persisted to chat history
+ */
+ selectedSkills?: RuntimeSelectedSkill[];
+ /**
+ * Tools explicitly selected by the user for the current request
+ * This constrains the available tools for the current runtime execution
+ */
+ selectedTools?: RuntimeSelectedTool[];
}
diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.ts
index 34724e2fea4..c774c584e0e 100644
--- a/plugins/vite/sharedRendererConfig.ts
+++ b/plugins/vite/sharedRendererConfig.ts
@@ -172,21 +172,26 @@ export const sharedOptimizeDeps = {
'i18next',
'react-i18next',
'dayjs',
+ 'dayjs/esm/locale/ar',
+ 'dayjs/esm/locale/bg',
+ 'dayjs/esm/locale/de',
+ 'dayjs/esm/locale/en',
+ 'dayjs/esm/locale/es',
+ 'dayjs/esm/locale/fa',
+ 'dayjs/esm/locale/fr',
+ 'dayjs/esm/locale/it',
+ 'dayjs/esm/locale/ja',
+ 'dayjs/esm/locale/ko',
+ 'dayjs/esm/locale/nl',
+ 'dayjs/esm/locale/pl',
+ 'dayjs/esm/locale/pt-br',
+ 'dayjs/esm/locale/ru',
+ 'dayjs/esm/locale/tr',
+ 'dayjs/esm/locale/vi',
+ 'dayjs/esm/locale/zh-cn',
+ 'dayjs/esm/locale/zh-tw',
'ahooks',
'motion/react',
-
- // monorepo packages — pre-bundle to reduce request count
- '@lobechat/model-runtime',
- 'model-bank',
- '@lobechat/types',
- '@lobechat/prompts',
- '@lobechat/context-engine',
- '@lobechat/utils',
- '@lobechat/const',
- '@lobechat/agent-runtime',
- '@lobechat/electron-client-ipc',
- '@lobechat/conversation-flow',
- '@lobechat/builtin-agents',
],
};
diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsx
index 2d6fc7b7e79..d8742b75a03 100644
--- a/src/features/ChatInput/ChatInputProvider.tsx
+++ b/src/features/ChatInput/ChatInputProvider.tsx
@@ -24,6 +24,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
onMarkdownContentChange,
mentionItems,
allowExpand = true,
+ slashPlacement,
}) => {
const editor = useEditor();
const slashMenuRef = useRef<HTMLDivElement>(null);
@@ -41,6 +42,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
sendButtonProps,
sendMenu,
slashMenuRef,
+ slashPlacement,
})
}
>
@@ -54,6 +56,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
rightActions={rightActions}
sendButtonProps={sendButtonProps}
sendMenu={sendMenu}
+ slashPlacement={slashPlacement}
onMarkdownContentChange={onMarkdownContentChange}
onSend={onSend}
/>
diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsx b/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsx
new file mode 100644
index 00000000000..88d24502560
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTag.tsx
@@ -0,0 +1,83 @@
+import { Tag, Tooltip } from '@lobehub/ui';
+import { cx } from 'antd-style';
+import { CLICK_COMMAND, COMMAND_PRIORITY_LOW, type LexicalEditor } from 'lexical';
+import { memo, useCallback, useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ActionTagNode } from './ActionTagNode';
+import { styles } from './style';
+import type { ActionTagCategory } from './types';
+
+interface ActionTagProps {
+ editor: LexicalEditor;
+ label: string;
+ node: ActionTagNode;
+}
+
+const CATEGORY_COLOR: Record<ActionTagCategory, string> = {
+ command: 'purple',
+ skill: 'blue',
+ tool: 'gold',
+};
+
+const CATEGORY_I18N_KEY: Record<ActionTagCategory, string> = {
+ command: 'actionTag.category.command',
+ skill: 'actionTag.category.skill',
+ tool: 'actionTag.category.tool',
+};
+
+const CATEGORY_TOOLTIP_I18N_KEY: Record<ActionTagCategory, string> = {
+ command: 'actionTag.tooltip.command',
+ skill: 'actionTag.tooltip.skill',
+ tool: 'actionTag.tooltip.tool',
+};
+
+const CATEGORY_STYLE_KEY: Record<ActionTagCategory, 'commandTag' | 'skillTag' | 'toolTag'> = {
+ command: 'commandTag',
+ skill: 'skillTag',
+ tool: 'toolTag',
+};
+
+const ActionTag = memo<ActionTagProps>(({ node, editor, label }) => {
+ const spanRef = useRef<HTMLSpanElement>(null);
+ const { t } = useTranslation('editor');
+
+ const category = node.actionCategory;
+ const categoryLabel = t(CATEGORY_I18N_KEY[category] as any);
+ const categoryDescription = t(CATEGORY_TOOLTIP_I18N_KEY[category] as any);
+ const color = CATEGORY_COLOR[category];
+ const styleKey = CATEGORY_STYLE_KEY[category];
+
+ const onClick = useCallback((payload: MouseEvent) => {
+ if (payload.target === spanRef.current || spanRef.current?.contains(payload.target as Node)) {
+ return true;
+ }
+ return false;
+ }, []);
+
+ useEffect(() => {
+ return editor.registerCommand(CLICK_COMMAND, onClick, COMMAND_PRIORITY_LOW);
+ }, [editor, onClick]);
+
+ return (
+ <span className={cx(styles[styleKey])} ref={spanRef}>
+ <Tooltip
+ title={
+ <div>
+ <div style={{ fontWeight: 500 }}>{label}</div>
+ <div>{categoryLabel}</div>
+ <div>{categoryDescription}</div>
+ </div>
+ }
+ >
+ <Tag color={color} variant="filled">
+ {label}
+ </Tag>
+ </Tooltip>
+ </span>
+ );
+});
+
+ActionTag.displayName = 'ActionTag';
+
+export default ActionTag;
diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTagNode.ts b/src/features/ChatInput/InputEditor/ActionTag/ActionTagNode.ts
new file mode 100644
index 00000000000..4df94b98b0c
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTagNode.ts
@@ -0,0 +1,136 @@
+import { addClassNamesToElement } from '@lexical/utils';
+import { getKernelFromEditor } from '@lobehub/editor';
+import {
+ $applyNodeReplacement,
+ DecoratorNode,
+ type DOMExportOutput,
+ type EditorConfig,
+ type LexicalEditor,
+ type LexicalNode,
+ type LexicalUpdateJSON,
+ type SerializedLexicalNode,
+ type Spread,
+} from 'lexical';
+
+import type { ActionTagCategory, ActionTagType } from './types';
+
+export type SerializedActionTagNode = Spread<
+ {
+ actionCategory: ActionTagCategory;
+ actionLabel: string;
+ actionType: ActionTagType;
+ },
+ SerializedLexicalNode
+>;
+
+export class ActionTagNode extends DecoratorNode<any> {
+ __actionType: ActionTagType;
+ __actionCategory: ActionTagCategory;
+ __actionLabel: string;
+
+ static getType(): string {
+ return 'action-tag';
+ }
+
+ static clone(node: ActionTagNode): ActionTagNode {
+ return new ActionTagNode(
+ node.__actionType,
+ node.__actionCategory,
+ node.__actionLabel,
+ node.__key,
+ );
+ }
+
+ static importJSON(serializedNode: SerializedActionTagNode): ActionTagNode {
+ return $createActionTagNode(
+ serializedNode.actionType,
+ serializedNode.actionCategory,
+ serializedNode.actionLabel,
+ ).updateFromJSON(serializedNode);
+ }
+
+ static importDOM(): null {
+ return null;
+ }
+
+ constructor(
+ actionType: ActionTagType,
+ actionCategory: ActionTagCategory,
+ actionLabel: string,
+ key?: string,
+ ) {
+ super(key);
+ this.__actionType = actionType;
+ this.__actionCategory = actionCategory;
+ this.__actionLabel = actionLabel;
+ }
+
+ get actionType(): ActionTagType {
+ return this.__actionType;
+ }
+
+ get actionCategory(): ActionTagCategory {
+ return this.__actionCategory;
+ }
+
+ get actionLabel(): string {
+ return this.__actionLabel;
+ }
+
+ exportDOM(): DOMExportOutput {
+ return { element: document.createElement('span') };
+ }
+
+ createDOM(config: EditorConfig): HTMLElement {
+ const element = document.createElement('span');
+ addClassNamesToElement(element, config.theme.actionTag);
+ return element;
+ }
+
+ getTextContent(): string {
+ return this.__actionLabel;
+ }
+
+ isInline(): true {
+ return true;
+ }
+
+ updateDOM(): boolean {
+ return false;
+ }
+
+ exportJSON(): SerializedActionTagNode {
+ return {
+ ...super.exportJSON(),
+ actionCategory: this.__actionCategory,
+ actionLabel: this.__actionLabel,
+ actionType: this.__actionType,
+ };
+ }
+
+ updateFromJSON(serializedNode: LexicalUpdateJSON<SerializedActionTagNode>): this {
+ return super.updateFromJSON(serializedNode);
+ }
+
+ decorate(editor: LexicalEditor): any {
+ const decorator = getKernelFromEditor(editor)?.getDecorator(ActionTagNode.getType());
+ if (!decorator) return null;
+ if (typeof decorator === 'function') return decorator(this, editor);
+ return {
+ queryDOM: decorator.queryDOM,
+ render: decorator.render(this, editor),
+ };
+ }
+}
+
+export function $createActionTagNode(
+ actionType: ActionTagType,
+ actionCategory: ActionTagCategory,
+ actionLabel: string,
+): ActionTagNode {
+ return $applyNodeReplacement(new ActionTagNode(actionType, actionCategory, actionLabel));
+}
+
+export function $isActionTagNode(node: LexicalNode): node is ActionTagNode {
+ return node.getType() === ActionTagNode.getType();
+}
diff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts
new file mode 100644
index 00000000000..2a7b58c1e54
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts
@@ -0,0 +1,105 @@
+import {
+ type getKernelFromEditor,
+ ILitexmlService,
+ IMarkdownShortCutService,
+} from '@lobehub/editor';
+import type { IEditorPlugin } from '@lobehub/editor/es/types/kernel';
+import type { LexicalEditor, LexicalNode } from 'lexical';
+
+import { $isActionTagNode, ActionTagNode, type SerializedActionTagNode } from './ActionTagNode';
+import { registerActionTagCommand } from './command';
+import { registerActionTagSelectionObserver } from './selectionObserver';
+import type { ActionTagCategory, ActionTagType } from './types';
+
+type IEditorKernel = ReturnType<typeof getKernelFromEditor>;
+
+export interface ActionTagPluginOptions {
+ decorator: (node: ActionTagNode, editor: LexicalEditor) => any;
+ theme?: { actionTag?: string };
+}
+
+/**
+ * Editor plugin for ActionTagNode. Implements {@link IEditorPlugin}.
+ * - Constructor: registers node, decorator, theme
+ * - onInit: called by kernel after Lexical editor creation; registers command, selection observer, markdown/litexml
+ * - destroy: cleanup
+ */
+export class ActionTagPlugin implements IEditorPlugin<ActionTagPluginOptions> {
+ static pluginName = 'ActionTagPlugin';
+
+ config?: ActionTagPluginOptions;
+ private kernel: IEditorKernel;
+ private clears: Array<() => void> = [];
+
+ constructor(kernel: IEditorKernel, config?: ActionTagPluginOptions) {
+ this.kernel = kernel;
+ this.config = config;
+
+ kernel.registerNodes([ActionTagNode]);
+
+ if (config?.theme) {
+ kernel.registerThemes(config.theme);
+ }
+
+ kernel.registerDecorator(
+ ActionTagNode.getType(),
+ (node: LexicalNode, editor: LexicalEditor) => {
+ return config?.decorator ? config.decorator(node as ActionTagNode, editor) : null;
+ },
+ );
+ }
+
+ onInit(editor: LexicalEditor): void {
+ this.clears.push(registerActionTagCommand(editor));
+ this.clears.push(registerActionTagSelectionObserver(editor));
+ this.registerMarkdown();
+ this.registerLiteXml();
+ }
+
+ private registerMarkdown(): void {
+ const mdService = this.kernel.requireService(IMarkdownShortCutService);
+
+ // Writer: ActionTagNode → markdown
+ mdService?.registerMarkdownWriter(ActionTagNode.getType(), (ctx: any, node: any) => {
+ if ($isActionTagNode(node)) {
+ ctx.appendLine(`<action type="${node.actionType}" category="${node.actionCategory}" />`);
+ }
+ });
+ }
+
+ private registerLiteXml(): void {
+ const xmlService = this.kernel.requireService(ILitexmlService);
+
+ xmlService?.registerXMLWriter(ActionTagNode.getType(), (node: any, ctx: any) => {
+ if ($isActionTagNode(node)) {
+ return ctx.createXmlNode('action', {
+ category: node.actionCategory,
+ label: node.actionLabel,
+ type: node.actionType,
+ });
+ }
+ return false;
+ });
+
+ xmlService?.registerXMLReader('action', (xmlElement: any) => {
+ try {
+ const { INodeHelper } = require('@lobehub/editor/es/editor-kernel/inode/helper');
+ return INodeHelper.createElementNode(ActionTagNode.getType(), {
+ actionCategory: (xmlElement.getAttribute('category') || 'skill') as ActionTagCategory,
+ actionLabel: xmlElement.getAttribute('label') || '',
+ actionType: (xmlElement.getAttribute('type') || 'translate') as ActionTagType,
+ } satisfies Partial<SerializedActionTagNode>);
+ } catch {
+ return false;
+ }
+ });
+ }
+
+ destroy(): void {
+ for (const clear of this.clears) {
+ clear();
+ }
+ this.clears = [];
+ this.kernel.unregisterDecorator?.(ActionTagNode.getType());
+ }
+}
diff --git a/src/features/ChatInput/InputEditor/ActionTag/ReactActionTagPlugin.tsx b/src/features/ChatInput/InputEditor/ActionTag/ReactActionTagPlugin.tsx
new file mode 100644
index 00000000000..9cbcc3c6c94
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/ReactActionTagPlugin.tsx
@@ -0,0 +1,30 @@
+import { useLexicalComposerContext } from '@lobehub/editor';
+import { type FC, useLayoutEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ActionTag from './ActionTag';
+import { ActionTagPlugin } from './ActionTagPlugin';
+
+const ReactActionTagPlugin: FC = () => {
+ const [editor] = useLexicalComposerContext();
+ const { t } = useTranslation('editor');
+
+ useLayoutEffect(() => {
+ editor.registerPlugin(ActionTagPlugin, {
+ decorator: (node, lexicalEditor) => {
+ const label =
+ node.actionCategory === 'command'
+ ? t(`slash.${node.actionType}` as any)
+ : node.actionLabel;
+
+ return <ActionTag editor={lexicalEditor} label={label} node={node} />;
+ },
+ });
+ }, [editor, t]);
+
+ return null;
+};
+
+ReactActionTagPlugin.displayName = 'ReactActionTagPlugin';
+
+export default ReactActionTagPlugin;
diff --git a/src/features/ChatInput/InputEditor/ActionTag/command.ts b/src/features/ChatInput/InputEditor/ActionTag/command.ts
new file mode 100644
index 00000000000..b5b7943b474
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/command.ts
@@ -0,0 +1,40 @@
+import { $wrapNodeInElement } from '@lexical/utils';
+import {
+ $createParagraphNode,
+ $insertNodes,
+ $isRootOrShadowRoot,
+ COMMAND_PRIORITY_HIGH,
+ createCommand,
+ type LexicalCommand,
+ type LexicalEditor,
+} from 'lexical';
+
+import { $createActionTagNode } from './ActionTagNode';
+import type { ActionTagCategory, ActionTagType } from './types';
+
+export interface InsertActionTagPayload {
+ category: ActionTagCategory;
+ label: string;
+ type: ActionTagType;
+}
+
+export const INSERT_ACTION_TAG_COMMAND: LexicalCommand<InsertActionTagPayload> = createCommand(
+ 'INSERT_ACTION_TAG_COMMAND',
+);
+
+export function registerActionTagCommand(editor: LexicalEditor): () => void {
+ return editor.registerCommand(
+ INSERT_ACTION_TAG_COMMAND,
+ (payload) => {
+ editor.update(() => {
+ const node = $createActionTagNode(payload.type, payload.category, payload.label);
+ $insertNodes([node]);
+ if ($isRootOrShadowRoot(node.getParentOrThrow())) {
+ $wrapNodeInElement(node, $createParagraphNode).selectEnd();
+ }
+ });
+ return true;
+ },
+ COMMAND_PRIORITY_HIGH,
+ );
+}
diff --git a/src/features/ChatInput/InputEditor/ActionTag/index.ts b/src/features/ChatInput/InputEditor/ActionTag/index.ts
new file mode 100644
index 00000000000..728a6348112
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/index.ts
@@ -0,0 +1,14 @@
+export type { SerializedActionTagNode } from './ActionTagNode';
+export { $createActionTagNode, $isActionTagNode, ActionTagNode } from './ActionTagNode';
+export type { InsertActionTagPayload } from './command';
+export { INSERT_ACTION_TAG_COMMAND } from './command';
+export { default as ReactActionTagPlugin } from './ReactActionTagPlugin';
+export type {
+ ActionTagCategory,
+ ActionTagData,
+ ActionTagType,
+ CommandType,
+ SkillType,
+} from './types';
+export { BUILTIN_COMMANDS } from './types';
+export { useSlashActionItems } from './useSlashActionItems';
diff --git a/src/features/ChatInput/InputEditor/ActionTag/selectionObserver.ts b/src/features/ChatInput/InputEditor/ActionTag/selectionObserver.ts
new file mode 100644
index 00000000000..99d09e641e3
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/selectionObserver.ts
@@ -0,0 +1,41 @@
+import { $getSelection, $isNodeSelection, $isRangeSelection, type LexicalEditor } from 'lexical';
+
+import { $isActionTagNode } from './ActionTagNode';
+
+export function registerActionTagSelectionObserver(editor: LexicalEditor): () => void {
+ let selectedKeys: string[] = [];
+
+ return editor.registerUpdateListener(({ editorState }) => {
+ const selection = editorState.read(() => $getSelection());
+ const newKeys: string[] = [];
+
+ if ($isNodeSelection(selection)) {
+ editorState.read(() => {
+ for (const node of selection.getNodes()) {
+ if ($isActionTagNode(node)) {
+ newKeys.push(node.getKey());
+ }
+ }
+ });
+ } else if ($isRangeSelection(selection) && !selection.isCollapsed()) {
+ editorState.read(() => {
+ for (const node of selection.getNodes()) {
+ if ($isActionTagNode(node)) {
+ newKeys.push(node.getKey());
+ }
+ }
+ });
+ }
+
+ const removeKeys = selectedKeys.filter((key) => !newKeys.includes(key));
+ const addKeys = newKeys.filter((key) => !selectedKeys.includes(key));
+ selectedKeys = [...newKeys];
+
+ for (const key of removeKeys) {
+ editor.getElementByKey(key)?.classList.remove('selected');
+ }
+ for (const key of addKeys) {
+ editor.getElementByKey(key)?.classList.add('selected');
+ }
+ });
+}
diff --git a/src/features/ChatInput/InputEditor/ActionTag/style.ts b/src/features/ChatInput/InputEditor/ActionTag/style.ts
new file mode 100644
index 00000000000..8b9668048fb
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/style.ts
@@ -0,0 +1,27 @@
+import { createStaticStyles } from 'antd-style';
+
+import { TAG_MARGIN_INLINE_END } from '../constants';
+
+const tagBase = (outlineColor: string, borderRadius: string) => `
+ cursor: default;
+ user-select: none;
+ display: inline-flex;
+ margin-inline-end: ${TAG_MARGIN_INLINE_END}px;
+
+ &.selected {
+ border-radius: ${borderRadius};
+ outline: 2px solid ${outlineColor};
+ }
+`;
+
+export const styles = createStaticStyles(({ css, cssVar }) => ({
+ commandTag: css`
+ ${tagBase('#722ED1', cssVar.borderRadius)}
+ `,
+ skillTag: css`
+ ${tagBase(cssVar.colorPrimary, cssVar.borderRadius)}
+ `,
+ toolTag: css`
+ ${tagBase(cssVar.colorWarning, cssVar.borderRadius)}
+ `,
+}));
diff --git a/src/features/ChatInput/InputEditor/ActionTag/types.ts b/src/features/ChatInput/InputEditor/ActionTag/types.ts
new file mode 100644
index 00000000000..ad1ee00b9d6
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/types.ts
@@ -0,0 +1,29 @@
+/**
+ * Slash action architecture:
+ *
+ * 1. Command — Built-in, line-start only, executed client-side before send
+ * 2. Skill — Skill package, line-start, can be preloaded before execution
+ * 3. Tool — Explicit tool selection, line-start, separate from skill packages
+ */
+export type ActionTagCategory = 'command' | 'skill' | 'tool';
+
+// Built-in commands: client-side intercepted, never sent to AI
+export type CommandType = 'compact' | 'newTopic';
+
+// Skills use dynamic identifiers from agent config (plugin/tool identifiers)
+export type SkillType = string & {};
+
+export type ActionTagType = CommandType | SkillType;
+
+export interface ActionTagData {
+ category: ActionTagCategory;
+ icon?: string;
+ label: string;
+ type: ActionTagType;
+}
+
+// Built-in commands — line-start only, client-side execution
+export const BUILTIN_COMMANDS: ActionTagData[] = [
+ { category: 'command', label: 'newTopic', type: 'newTopic' },
+ { category: 'command', label: 'compact', type: 'compact' },
+];
diff --git a/src/features/ChatInput/InputEditor/ActionTag/useEnabledSkills.ts b/src/features/ChatInput/InputEditor/ActionTag/useEnabledSkills.ts
new file mode 100644
index 00000000000..6eb160acc73
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/useEnabledSkills.ts
@@ -0,0 +1,74 @@
+import isEqual from 'fast-deep-equal';
+import { useMemo } from 'react';
+
+import { useToolStore } from '@/store/tool';
+import {
+ agentSkillsSelectors,
+ builtinToolSelectors,
+ klavisStoreSelectors,
+ lobehubSkillStoreSelectors,
+ pluginSelectors,
+} from '@/store/tool/selectors';
+
+import type { ActionTagData } from './types';
+
+/**
+ * Collects all available slash-selectable skills/tools and returns them as ActionTagData[].
+ */
+export const useEnabledSkills = (): ActionTagData[] => {
+ // All data sources
+ const builtinList = useToolStore(builtinToolSelectors.metaList, isEqual);
+ const builtinSkills = useToolStore(builtinToolSelectors.installedBuiltinSkills, isEqual);
+ const installedPlugins = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);
+ const klavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);
+ const lobehubSkillServers = useToolStore(lobehubSkillStoreSelectors.getServers, isEqual);
+ const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);
+ const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);
+
+ return useMemo(() => {
+ const items: ActionTagData[] = [];
+ const skillNameMap = new Map<string, string>();
+ const toolNameMap = new Map<string, string>();
+
+ for (const item of builtinList) {
+ toolNameMap.set(item.identifier, item.meta?.title || item.identifier);
+ }
+ for (const item of installedPlugins) {
+ toolNameMap.set(item.identifier, item.title || item.identifier);
+ }
+ for (const item of klavisServers) {
+ toolNameMap.set(item.identifier, item.serverName || item.identifier);
+ }
+ for (const item of lobehubSkillServers) {
+ toolNameMap.set(item.identifier, item.name || item.identifier);
+ }
+
+ for (const item of builtinSkills) {
+ skillNameMap.set(item.identifier, item.name || item.identifier);
+ }
+ for (const item of marketAgentSkills) {
+ skillNameMap.set(item.identifier, item.name || item.identifier);
+ }
+ for (const item of userAgentSkills) {
+ skillNameMap.set(item.identifier, item.name || item.identifier);
+ }
+
+ for (const [id, label] of skillNameMap) {
+ items.push({ category: 'skill', label, type: id });
+ }
+
+ for (const [id, label] of toolNameMap) {
+ items.push({ category: 'tool', label, type: id });
+ }
+
+ return items;
+ }, [
+ builtinList,
+ builtinSkills,
+ installedPlugins,
+ klavisServers,
+ lobehubSkillServers,
+ marketAgentSkills,
+ userAgentSkills,
+ ]);
+};
diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts
new file mode 100644
index 00000000000..c9a1e08f553
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts
@@ -0,0 +1,119 @@
+import type { IEditor, SlashOptions } from '@lobehub/editor';
+import Fuse from 'fuse.js';
+import { $getSelection, $isRangeSelection } from 'lexical';
+import { ArchiveIcon, MessageSquarePlusIcon, WrenchIcon } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+
+import { useChatInputStore } from '../../store';
+import { INSERT_ACTION_TAG_COMMAND, type InsertActionTagPayload } from './command';
+import { type ActionTagData, BUILTIN_COMMANDS } from './types';
+import { useEnabledSkills } from './useEnabledSkills';
+
+type SlashItem = NonNullable<SlashOptions['items'] extends (infer U)[] ? U : never>;
+
+interface SlashMenuOption {
+ icon?: any;
+ key: string;
+ label: string;
+ metadata?: Record<string, any>;
+ onSelect?: (editor: IEditor, matchingString: string) => void;
+}
+
+const COMMAND_ICONS: Record<string, any> = {
+ compact: ArchiveIcon,
+ newTopic: MessageSquarePlusIcon,
+};
+
+export const useSlashActionItems = (): SlashOptions['items'] => {
+ const { t } = useTranslation('editor');
+ const editorInstance = useChatInputStore((s) => s.editor);
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+ const enabledSkills = useEnabledSkills();
+
+ return useCallback(
+ async (
+ search: { leadOffset: number; matchingString: string; replaceableString: string } | null,
+ ) => {
+ const allItems: SlashItem[] = [];
+
+ const makeCommandItem = (action: ActionTagData): SlashMenuOption => ({
+ icon: COMMAND_ICONS[action.type],
+ key: `action-${action.type}`,
+ label: t(`slash.${action.type}` as any),
+ metadata: { category: action.category, type: action.type },
+ onSelect: (editor: IEditor) => {
+ const payload: InsertActionTagPayload = {
+ category: action.category,
+ label: t(`slash.${action.type}` as any) as string,
+ type: action.type,
+ };
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);
+ },
+ });
+
+ const makeActionItem = (item: ActionTagData): SlashMenuOption => ({
+ icon: WrenchIcon,
+ key: `${item.category}-${item.type}`,
+ label: item.label,
+ metadata: { category: item.category, type: item.type },
+ onSelect: (editor: IEditor) => {
+ const payload: InsertActionTagPayload = {
+ category: item.category,
+ label: item.label,
+ type: item.type,
+ };
+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);
+ },
+ });
+
+ // All action tags are line-start only for now
+ let isAtLineStart = search === null;
+ if (!isAtLineStart && editorInstance) {
+ const lexicalEditor = editorInstance.getLexicalEditor();
+ if (lexicalEditor) {
+ lexicalEditor.getEditorState().read(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ const node = selection.anchor.getNode();
+ const topElement = node.getTopLevelElement();
+ if (topElement) {
+ const paragraphText = topElement.getTextContent();
+ const triggerAndSearch = '/' + (search?.matchingString || '');
+ isAtLineStart = paragraphText === triggerAndSearch;
+ }
+ }
+ });
+ }
+ }
+
+ if (!isAtLineStart) return [];
+
+ // 1. Built-in commands (filter newTopic when no active topic)
+ for (const action of BUILTIN_COMMANDS) {
+ if (action.type === 'newTopic' && !activeTopicId) continue;
+ allItems.push(makeCommandItem(action) as SlashItem);
+ }
+
+ // 2. Enabled slash-selectable skills/tools
+ if (enabledSkills.length > 0) {
+ allItems.push({ type: 'divider' } as SlashItem);
+ for (const item of enabledSkills) {
+ allItems.push(makeActionItem(item) as SlashItem);
+ }
+ }
+
+ // Fuzzy filtering
+ if (search?.matchingString && search.matchingString.length > 0) {
+ const searchable = allItems.filter((i) => !('type' in i) || (i as any).type !== 'divider');
+ const fuse = new Fuse(searchable, { keys: ['key', 'label'], threshold: 0.4 });
+ return fuse.search(search.matchingString).map((r) => r.item);
+ }
+
+ return allItems;
+ },
+ [t, editorInstance, activeTopicId, enabledSkills],
+ );
+};
diff --git a/src/features/ChatInput/InputEditor/ReferTopic/ReactReferTopicPlugin.tsx b/src/features/ChatInput/InputEditor/ReferTopic/ReactReferTopicPlugin.tsx
new file mode 100644
index 00000000000..653115a17a9
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ReferTopic/ReactReferTopicPlugin.tsx
@@ -0,0 +1,23 @@
+import { useLexicalComposerContext } from '@lobehub/editor';
+import { type FC, useLayoutEffect } from 'react';
+
+import ReferTopic from './ReferTopic';
+import { ReferTopicPlugin } from './ReferTopicPlugin';
+
+const ReactReferTopicPlugin: FC = () => {
+ const [editor] = useLexicalComposerContext();
+
+ useLayoutEffect(() => {
+ editor.registerPlugin(ReferTopicPlugin, {
+ decorator: (node) => {
+ return <ReferTopic node={node} />;
+ },
+ });
+ }, [editor]);
+
+ return null;
+};
+
+ReactReferTopicPlugin.displayName = 'ReactReferTopicPlugin';
+
+export default ReactReferTopicPlugin;
diff --git a/src/features/ChatInput/InputEditor/ReferTopic/ReferTopic.tsx b/src/features/ChatInput/InputEditor/ReferTopic/ReferTopic.tsx
new file mode 100644
index 00000000000..d514b85605d
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ReferTopic/ReferTopic.tsx
@@ -0,0 +1,49 @@
+import { Tag } from '@lobehub/ui';
+import { MessageSquarePlusIcon } from 'lucide-react';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+
+import { TAG_MARGIN_INLINE_END } from '../constants';
+import type { ReferTopicNode } from './ReferTopicNode';
+
+interface ReferTopicProps {
+ node: ReferTopicNode;
+}
+
+const ReferTopic = memo<ReferTopicProps>(({ node }) => {
+ const { t } = useTranslation('topic');
+ const title = node.topicTitle || t('defaultTitle');
+ const switchTopic = useChatStore((s) => s.switchTopic);
+
+ const handleClick = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation();
+ if (node.topicId) {
+ switchTopic(node.topicId);
+ }
+ },
+ [node.topicId, switchTopic],
+ );
+
+ return (
+ <span
+ style={{
+ cursor: 'pointer',
+ display: 'inline-flex',
+ userSelect: 'none',
+ marginInlineEnd: TAG_MARGIN_INLINE_END,
+ }}
+ onClick={handleClick}
+ >
+ <Tag color="green" icon={<MessageSquarePlusIcon size={12} />} variant="outlined">
+ {title}
+ </Tag>
+ </span>
+ );
+});
+
+ReferTopic.displayName = 'ReferTopic';
+
+export default ReferTopic;
diff --git a/src/features/ChatInput/InputEditor/ReferTopic/ReferTopicNode.ts b/src/features/ChatInput/InputEditor/ReferTopic/ReferTopicNode.ts
new file mode 100644
index 00000000000..ec8cda629cd
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ReferTopic/ReferTopicNode.ts
@@ -0,0 +1,110 @@
+import { addClassNamesToElement } from '@lexical/utils';
+import { getKernelFromEditor } from '@lobehub/editor';
+import {
+ $applyNodeReplacement,
+ DecoratorNode,
+ type DOMExportOutput,
+ type EditorConfig,
+ type LexicalEditor,
+ type LexicalNode,
+ type LexicalUpdateJSON,
+ type SerializedLexicalNode,
+ type Spread,
+} from 'lexical';
+
+export type SerializedReferTopicNode = Spread<
+ {
+ topicId: string;
+ topicTitle: string;
+ },
+ SerializedLexicalNode
+>;
+
+export class ReferTopicNode extends DecoratorNode<any> {
+ __topicId: string;
+ __topicTitle: string;
+
+ static getType(): string {
+ return 'refer-topic';
+ }
+
+ static clone(node: ReferTopicNode): ReferTopicNode {
+ return new ReferTopicNode(node.__topicId, node.__topicTitle, node.__key);
+ }
+
+ static importJSON(serializedNode: SerializedReferTopicNode): ReferTopicNode {
+ return $createReferTopicNode(serializedNode.topicId, serializedNode.topicTitle).updateFromJSON(
+ serializedNode,
+ );
+ }
+
+ static importDOM(): null {
+ return null;
+ }
+
+ constructor(topicId: string, topicTitle: string, key?: string) {
+ super(key);
+ this.__topicId = topicId;
+ this.__topicTitle = topicTitle;
+ }
+
+ get topicId(): string {
+ return this.__topicId;
+ }
+
+ get topicTitle(): string {
+ return this.__topicTitle;
+ }
+
+ exportDOM(): DOMExportOutput {
+ return { element: document.createElement('span') };
+ }
+
+ createDOM(config: EditorConfig): HTMLElement {
+ const element = document.createElement('span');
+ addClassNamesToElement(element, config.theme.referTopic);
+ return element;
+ }
+
+ getTextContent(): string {
+ return this.__topicTitle;
+ }
+
+ isInline(): true {
+ return true;
+ }
+
+ updateDOM(): boolean {
+ return false;
+ }
+
+ exportJSON(): SerializedReferTopicNode {
+ return {
+ ...super.exportJSON(),
+ topicId: this.__topicId,
+ topicTitle: this.__topicTitle,
+ };
+ }
+
+ updateFromJSON(serializedNode: LexicalUpdateJSON<SerializedReferTopicNode>): this {
+ return super.updateFromJSON(serializedNode);
+ }
+
+ decorate(editor: LexicalEditor): any {
+ const decorator = getKernelFromEditor(editor)?.getDecorator(ReferTopicNode.getType());
+ if (!decorator) return null;
+ if (typeof decorator === 'function') return decorator(this, editor);
+ return {
+ queryDOM: decorator.queryDOM,
+ render: decorator.render(this, editor),
+ };
+ }
+}
+
+export function $createReferTopicNode(topicId: string, topicTitle: string): ReferTopicNode {
+ return $applyNodeReplacement(new ReferTopicNode(topicId, topicTitle));
+}
+
+export function $isReferTopicNode(node: LexicalNode): node is ReferTopicNode {
+ return node.getType() === ReferTopicNode.getType();
+}
diff --git a/src/features/ChatInput/InputEditor/ReferTopic/ReferTopicPlugin.ts b/src/features/ChatInput/InputEditor/ReferTopic/ReferTopicPlugin.ts
new file mode 100644
index 00000000000..70bbaa1f39a
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ReferTopic/ReferTopicPlugin.ts
@@ -0,0 +1,124 @@
+import { $wrapNodeInElement } from '@lexical/utils';
+import {
+ type getKernelFromEditor,
+ ILitexmlService,
+ IMarkdownShortCutService,
+} from '@lobehub/editor';
+import type { IEditorPlugin } from '@lobehub/editor/es/types/kernel';
+import {
+ $createParagraphNode,
+ $insertNodes,
+ $isRootOrShadowRoot,
+ COMMAND_PRIORITY_HIGH,
+ createCommand,
+ type LexicalEditor,
+} from 'lexical';
+
+import {
+ $createReferTopicNode,
+ $isReferTopicNode,
+ ReferTopicNode,
+ type SerializedReferTopicNode,
+} from './ReferTopicNode';
+
+export const INSERT_REFER_TOPIC_COMMAND = createCommand<{ topicId: string; topicTitle: string }>(
+ 'INSERT_REFER_TOPIC_COMMAND',
+);
+
+type IEditorKernel = ReturnType<typeof getKernelFromEditor>;
+
+export interface ReferTopicPluginOptions {
+ decorator: (node: ReferTopicNode, editor: LexicalEditor) => any;
+ theme?: { referTopic?: string };
+}
+
+/**
+ * Editor plugin for ReferTopicNode. Implements {@link IEditorPlugin}.
+ * - Constructor: registers node, decorator, theme
+ * - onInit: called by kernel after Lexical editor creation; registers markdown/litexml writers & readers
+ * - destroy: cleanup
+ */
+export class ReferTopicPlugin implements IEditorPlugin<ReferTopicPluginOptions> {
+ static pluginName = 'ReferTopicPlugin';
+
+ config?: ReferTopicPluginOptions;
+ private kernel: IEditorKernel;
+
+ constructor(kernel: IEditorKernel, config?: ReferTopicPluginOptions) {
+ this.kernel = kernel;
+ this.config = config;
+
+ kernel.registerNodes([ReferTopicNode]);
+
+ if (config?.theme) {
+ kernel.registerThemes(config.theme);
+ }
+
+ kernel.registerDecorator(ReferTopicNode.getType(), (node, editor) => {
+ return config?.decorator ? config.decorator(node as ReferTopicNode, editor) : null;
+ });
+ }
+
+ onInit(editor: LexicalEditor): void {
+ this.registerMarkdown();
+ this.registerLiteXml();
+ this.registerCommand(editor);
+ }
+
+ private registerMarkdown(): void {
+ const mdService = this.kernel.requireService(IMarkdownShortCutService);
+
+ mdService?.registerMarkdownWriter(ReferTopicNode.getType(), (ctx: any, node: any) => {
+ if ($isReferTopicNode(node)) {
+ ctx.appendLine(`<refer_topic name="${node.topicTitle}" id="${node.topicId}" />`);
+ }
+ });
+ }
+
+ private registerCommand(editor: LexicalEditor): void {
+ editor.registerCommand(
+ INSERT_REFER_TOPIC_COMMAND,
+ (payload) => {
+ editor.update(() => {
+ const node = $createReferTopicNode(payload.topicId, payload.topicTitle);
+ $insertNodes([node]);
+ if ($isRootOrShadowRoot(node.getParentOrThrow())) {
+ $wrapNodeInElement(node, $createParagraphNode).selectEnd();
+ }
+ });
+ return true;
+ },
+ COMMAND_PRIORITY_HIGH,
+ );
+ }
+
+ private registerLiteXml(): void {
+ const xmlService = this.kernel.requireService(ILitexmlService);
+
+ xmlService?.registerXMLWriter(ReferTopicNode.getType(), (node: any, ctx: any) => {
+ if ($isReferTopicNode(node)) {
+ return ctx.createXmlNode('referTopic', {
+ id: node.topicId,
+ name: node.topicTitle,
+ });
+ }
+ return false;
+ });
+
+ xmlService?.registerXMLReader('referTopic', (xmlElement: any) => {
+ try {
+ const { INodeHelper } = require('@lobehub/editor/es/editor-kernel/inode/helper');
+ return INodeHelper.createElementNode(ReferTopicNode.getType(), {
+ topicId: xmlElement.getAttribute('id') || '',
+ topicTitle: xmlElement.getAttribute('name') || '',
+ } satisfies Partial<SerializedReferTopicNode>);
+ } catch {
+ return false;
+ }
+ });
+ }
+
+ destroy(): void {
+ this.kernel.unregisterDecorator?.(ReferTopicNode.getType());
+ }
+}
diff --git a/src/features/ChatInput/InputEditor/ReferTopic/index.ts b/src/features/ChatInput/InputEditor/ReferTopic/index.ts
new file mode 100644
index 00000000000..ad289e57b73
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ReferTopic/index.ts
@@ -0,0 +1,4 @@
+export { default as ReactReferTopicPlugin } from './ReactReferTopicPlugin';
+export type { SerializedReferTopicNode } from './ReferTopicNode';
+export { $createReferTopicNode, $isReferTopicNode, ReferTopicNode } from './ReferTopicNode';
+export { INSERT_REFER_TOPIC_COMMAND } from './ReferTopicPlugin';
diff --git a/src/features/ChatInput/InputEditor/constants.ts b/src/features/ChatInput/InputEditor/constants.ts
new file mode 100644
index 00000000000..fe5c775d767
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/constants.ts
@@ -0,0 +1,2 @@
+/** Shared margin between inline tags (ActionTag, ReferTopic) in the input editor */
+export const TAG_MARGIN_INLINE_END = 4;
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index 3b5a4fc42a8..3e9feb178f2 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -1,25 +1,12 @@
import { isDesktop } from '@lobechat/const';
import { HotkeyEnum, KeyEnum } from '@lobechat/types';
import { isCommandPressed } from '@lobechat/utils';
-import {
- INSERT_MENTION_COMMAND,
- INSERT_TABLE_COMMAND,
- ReactCodemirrorPlugin,
- ReactCodePlugin,
- ReactHRPlugin,
- ReactLinkHighlightPlugin,
- ReactListPlugin,
- ReactMathPlugin,
- ReactTablePlugin,
- ReactVirtualBlockPlugin,
-} from '@lobehub/editor';
-import { Editor, FloatMenu, SlashMenu, useEditorState } from '@lobehub/editor/react';
+import { INSERT_MENTION_COMMAND, ReactMathPlugin, type SlashOptions } from '@lobehub/editor';
+import { Editor, FloatMenu, useEditorState } from '@lobehub/editor/react';
import { combineKeys } from '@lobehub/ui';
import { css, cx } from 'antd-style';
-import { Table2Icon } from 'lucide-react';
-import { memo, useEffect, useMemo, useRef } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useHotkeysContext } from 'react-hotkeys-hook';
-import { useTranslation } from 'react-i18next';
import { usePasteFile, useUploadFiles } from '@/components/DragUploadZone';
import { useAgentStore } from '@/store/agent';
@@ -29,7 +16,12 @@ import { labPreferSelectors, preferenceSelectors, settingsSelectors } from '@/st
import { useAgentId } from '../hooks/useAgentId';
import { useChatInputStore, useStoreApi } from '../store';
+import { useSlashActionItems } from './ActionTag';
import Placeholder from './Placeholder';
+import { CHAT_INPUT_EMBED_PLUGINS, createChatInputRichPlugins } from './plugins';
+import { INSERT_REFER_TOPIC_COMMAND } from './ReferTopic';
+import { useAgentMentionItems } from './useAgentMentionItems';
+import { useTopicMentionItems } from './useTopicMentionItems';
const className = cx(css`
p {
@@ -38,7 +30,7 @@ const className = cx(css`
`);
const InputEditor = memo<{ defaultRows?: number }>(({ defaultRows = 2 }) => {
- const [editor, slashMenuRef, send, updateMarkdownContent, expand, mentionItems] =
+ const [editor, slashMenuRef, send, updateMarkdownContent, expand, mentionItems, slashPlacement] =
useChatInputStore((s) => [
s.editor,
s.slashMenuRef,
@@ -46,19 +38,44 @@ const InputEditor = memo<{ defaultRows?: number }>(({ defaultRows = 2 }) => {
s.updateMarkdownContent,
s.expand,
s.mentionItems,
+ s.slashPlacement ?? 'top',
]);
const storeApi = useStoreApi();
const state = useEditorState(editor);
const hotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.AddUserMessage));
const { enableScope, disableScope } = useHotkeysContext();
- const { t } = useTranslation(['editor', 'chat']);
const isChineseInput = useRef(false);
const useCmdEnterToSend = useUserStore(preferenceSelectors.useCmdEnterToSend);
- const enableMention = !!mentionItems && mentionItems.length > 0;
+ const topicMentionItems = useTopicMentionItems();
+ const agentMentionItems = useAgentMentionItems();
+
+ const mergedMentionItems = useMemo<SlashOptions['items'] | undefined>(() => {
+ const topicItems = topicMentionItems || [];
+ // In non-group context, use agent items from hook; in group context, use injected mentionItems
+ const fallbackAgentItems = !mentionItems ? agentMentionItems : [];
+
+ if (!mentionItems && fallbackAgentItems.length === 0 && topicItems.length === 0)
+ return undefined;
+
+ if (typeof mentionItems === 'function') {
+ const fn = mentionItems;
+ return async (search: Parameters<typeof fn>[0]) => {
+ const groupItems = await fn(search);
+ return [...groupItems, ...topicItems];
+ };
+ }
+
+ const externalItems = Array.isArray(mentionItems) ? mentionItems : [];
+ return [...externalItems, ...fallbackAgentItems, ...topicItems];
+ }, [mentionItems, topicMentionItems, agentMentionItems]);
+
+ const enableMention =
+ !!mergedMentionItems &&
+ (typeof mergedMentionItems === 'function' || mergedMentionItems.length > 0);
// Get agent's model info for vision support check and handle paste upload
const agentId = useAgentId();
@@ -85,23 +102,30 @@ const InputEditor = memo<{ defaultRows?: number }>(({ defaultRows = 2 }) => {
const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);
+ const slashActionItems = useSlashActionItems();
+ const slashItems = useCallback(
+ async (
+ search: { leadOffset: number; matchingString: string; replaceableString: string } | null,
+ ) => {
+ const actionItems =
+ typeof slashActionItems === 'function' ? await slashActionItems(search) : slashActionItems;
+
+ return actionItems;
+ },
+ [slashActionItems],
+ );
+
const richRenderProps = useMemo(
() =>
!enableRichRender
? {
enablePasteMarkdown: false,
markdownOption: false,
+ plugins: CHAT_INPUT_EMBED_PLUGINS,
}
: {
- plugins: [
- ReactListPlugin,
- ReactCodePlugin,
- ReactCodemirrorPlugin,
- ReactHRPlugin,
- ReactLinkHighlightPlugin,
- ReactTablePlugin,
- ReactVirtualBlockPlugin,
- Editor.withProps(ReactMathPlugin, {
+ plugins: createChatInputRichPlugins({
+ mathPlugin: Editor.withProps(ReactMathPlugin, {
renderComp: expand
? undefined
: (props) => (
@@ -111,9 +135,9 @@ const InputEditor = memo<{ defaultRows?: number }>(({ defaultRows = 2 }) => {
/>
),
}),
- ],
+ }),
},
- [enableRichRender],
+ [enableRichRender, expand, slashMenuRef],
);
return (
@@ -123,6 +147,7 @@ const InputEditor = memo<{ defaultRows?: number }>(({ defaultRows = 2 }) => {
className={className}
content={''}
editor={editor}
+ {...{ slashPlacement }}
{...richRenderProps}
placeholder={<Placeholder />}
type={'text'}
@@ -130,47 +155,32 @@ const InputEditor = memo<{ defaultRows?: number }>(({ defaultRows = 2 }) => {
mentionOption={
enableMention
? {
- items: mentionItems,
+ fuseOptions: { keys: ['key', 'label', 'metadata.topicTitle'], threshold: 0.3 },
+ items: mergedMentionItems,
markdownWriter: (mention) => {
+ if (mention.metadata?.type === 'topic') {
+ return `<refer_topic name="${mention.metadata.topicTitle}" id="${mention.metadata.topicId}" />`;
+ }
return `<mention name="${mention.label}" id="${mention.metadata.id}" />`;
},
onSelect: (editor, option) => {
- editor.dispatchCommand(INSERT_MENTION_COMMAND, {
- label: String(option.label),
- metadata: option.metadata,
- });
+ if (option.metadata?.type === 'topic') {
+ editor.dispatchCommand(INSERT_REFER_TOPIC_COMMAND, {
+ topicId: option.metadata.topicId as string,
+ topicTitle: String(option.metadata.topicTitle ?? option.label),
+ });
+ } else {
+ editor.dispatchCommand(INSERT_MENTION_COMMAND, {
+ label: String(option.label),
+ metadata: option.metadata,
+ });
+ }
},
- renderComp: expand
- ? undefined
- : (props) => {
- return (
- <SlashMenu
- {...props}
- getPopupContainer={() => (slashMenuRef as any)?.current}
- />
- );
- },
}
: undefined
}
slashOption={{
- items: [
- {
- icon: Table2Icon,
- key: 'table',
- label: t('typobar.table'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_TABLE_COMMAND, { columns: '3', rows: '3' });
- },
- },
- ],
- renderComp: expand
- ? undefined
- : (props) => {
- return (
- <SlashMenu {...props} getPopupContainer={() => (slashMenuRef as any)?.current} />
- );
- },
+ items: slashItems,
}}
style={{
minHeight: defaultRows > 1 ? defaultRows * 23 : undefined,
diff --git a/src/features/ChatInput/InputEditor/plugins.ts b/src/features/ChatInput/InputEditor/plugins.ts
new file mode 100644
index 00000000000..f2942c9f25e
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/plugins.ts
@@ -0,0 +1,39 @@
+import {
+ ReactCodemirrorPlugin,
+ ReactCodePlugin,
+ ReactHRPlugin,
+ ReactLinkHighlightPlugin,
+ ReactListPlugin,
+ ReactMathPlugin,
+ ReactVirtualBlockPlugin,
+} from '@lobehub/editor';
+import { type Editor } from '@lobehub/editor/react';
+
+import { ReactActionTagPlugin } from './ActionTag';
+import { ReactReferTopicPlugin } from './ReferTopic';
+
+type EditorPlugins = NonNullable<Parameters<typeof Editor>[0]['plugins']>;
+
+interface CreateChatInputRichPluginsOptions {
+ linkPlugin?: EditorPlugins[number];
+ mathPlugin?: EditorPlugins[number];
+}
+
+export const CHAT_INPUT_EMBED_PLUGINS: EditorPlugins = [
+ ReactActionTagPlugin,
+ ReactReferTopicPlugin,
+];
+
+export const createChatInputRichPlugins = ({
+ linkPlugin = ReactLinkHighlightPlugin,
+ mathPlugin = ReactMathPlugin,
+}: CreateChatInputRichPluginsOptions = {}): EditorPlugins => [
+ ReactListPlugin,
+ ReactCodePlugin,
+ ReactCodemirrorPlugin,
+ ReactHRPlugin,
+ linkPlugin,
+ ReactVirtualBlockPlugin,
+ mathPlugin,
+ ...CHAT_INPUT_EMBED_PLUGINS,
+];
diff --git a/src/features/ChatInput/InputEditor/useAgentMentionItems.tsx b/src/features/ChatInput/InputEditor/useAgentMentionItems.tsx
new file mode 100644
index 00000000000..7df229c738c
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/useAgentMentionItems.tsx
@@ -0,0 +1,33 @@
+import { Avatar } from '@lobehub/ui';
+import { useMemo } from 'react';
+
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+
+import { useAgentId } from '../hooks/useAgentId';
+
+const MAX_AGENT_ITEMS = 20;
+
+export const useAgentMentionItems = () => {
+ const allAgents = useHomeStore(homeAgentListSelectors.allAgents);
+ const currentAgentId = useAgentId();
+
+ return useMemo(() => {
+ const otherAgents = allAgents.filter((a) => a.type === 'agent' && a.id !== currentAgentId);
+
+ if (otherAgents.length === 0) return [];
+
+ return otherAgents.slice(0, MAX_AGENT_ITEMS).map((agent) => ({
+ icon: (
+ <Avatar
+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}
+ background={agent.backgroundColor ?? undefined}
+ size={24}
+ />
+ ),
+ key: `agent-${agent.id}`,
+ label: agent.title || 'Untitled Agent',
+ metadata: { id: agent.id, type: 'agent' },
+ }));
+ }, [allAgents, currentAgentId]);
+};
diff --git a/src/features/ChatInput/InputEditor/useSlashItems.tsx b/src/features/ChatInput/InputEditor/useSlashItems.tsx
deleted file mode 100644
index 266b6806b8a..00000000000
--- a/src/features/ChatInput/InputEditor/useSlashItems.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { type SlashOptions } from '@lobehub/editor';
-import {
- INSERT_HEADING_COMMAND,
- INSERT_HORIZONTAL_RULE_COMMAND,
- INSERT_MATH_COMMAND,
- INSERT_TABLE_COMMAND,
-} from '@lobehub/editor';
-import { Text } from '@lobehub/ui';
-import {
- Heading1Icon,
- Heading2Icon,
- Heading3Icon,
- MinusIcon,
- SigmaIcon,
- Table2Icon,
-} from 'lucide-react';
-import { useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-export const useSlashItems = (): SlashOptions['items'] => {
- const { t } = useTranslation('editor');
- return useMemo(() => {
- const data: SlashOptions['items'] = [
- {
- icon: Heading1Icon,
- key: 'h1',
- label: t('slash.h1'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h1' });
- },
- },
- {
- icon: Heading2Icon,
- key: 'h2',
- label: t('slash.h2'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h2' });
- },
- },
- {
- icon: Heading3Icon,
- key: 'h3',
- label: t('slash.h3'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h3' });
- },
- },
-
- {
- type: 'divider',
- },
- {
- icon: MinusIcon,
- key: 'hr',
- label: t('slash.hr'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, {});
- },
- },
- {
- icon: Table2Icon,
- key: 'table',
- label: t('slash.table'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_TABLE_COMMAND, { columns: '3', rows: '3' });
- },
- },
- {
- icon: SigmaIcon,
- key: 'tex',
- label: t('slash.tex'),
- onSelect: (editor) => {
- editor.dispatchCommand(INSERT_MATH_COMMAND, { code: 'x^2 + y^2 = z^2' });
- queueMicrotask(() => {
- editor.focus();
- });
- },
- },
- ];
- return data.map((item) => {
- if (item.type === 'divider') return item;
- return {
- ...item,
- extra: (
- <Text code fontSize={12} type={'secondary'}>
- {item.key}
- </Text>
- ),
- };
- });
- }, [t]);
-};
diff --git a/src/features/ChatInput/InputEditor/useTopicMentionItems.tsx b/src/features/ChatInput/InputEditor/useTopicMentionItems.tsx
new file mode 100644
index 00000000000..d51d8d0a79f
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/useTopicMentionItems.tsx
@@ -0,0 +1,40 @@
+import { Icon } from '@lobehub/ui';
+import { MessageSquareText } from 'lucide-react';
+import { useMemo } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+export const useTopicMentionItems = () => {
+ const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+
+ const topicsSelector = useMemo(
+ () => topicSelectors.displayTopicsForSidebar(topicPageSize),
+ [topicPageSize],
+ );
+ const topics = useChatStore(topicsSelector);
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+
+ return useMemo(() => {
+ if (!topics || topics.length === 0) return [];
+
+ const MAX_LABEL_LENGTH = 50;
+
+ return topics
+ .filter((t) => t.id !== activeTopicId)
+ .map((topic) => {
+ const title = topic.title || 'Untitled';
+ const label =
+ title.length > MAX_LABEL_LENGTH ? `${title.slice(0, MAX_LABEL_LENGTH)}...` : title;
+
+ return {
+ icon: <Icon icon={MessageSquareText} size={20} />,
+ key: `topic-${topic.id}`,
+ label,
+ metadata: { topicId: topic.id, topicTitle: topic.title, type: 'topic' },
+ };
+ });
+ }, [topics, activeTopicId]);
+};
diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsx
index 048899cc11b..ef4d7414251 100644
--- a/src/features/ChatInput/StoreUpdater.tsx
+++ b/src/features/ChatInput/StoreUpdater.tsx
@@ -26,6 +26,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
sendMenu,
mentionItems,
allowExpand,
+ slashPlacement,
}) => {
const storeApi = useStoreApi();
const useStoreUpdater = createStoreUpdater(storeApi);
@@ -38,6 +39,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
useStoreUpdater('leftActions', leftActions!);
useStoreUpdater('rightActions', rightActions!);
useStoreUpdater('allowExpand', allowExpand);
+ useStoreUpdater('slashPlacement', slashPlacement);
useStoreUpdater('sendButtonProps', sendButtonProps);
useStoreUpdater('onSend', onSend);
diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.ts
index 39e4b53a931..e08cc1d18d7 100644
--- a/src/features/ChatInput/store/action.ts
+++ b/src/features/ChatInput/store/action.ts
@@ -4,7 +4,7 @@ import { type PublicState, type State } from './initialState';
import { initialState } from './initialState';
export interface Action {
- getJSONState: () => any;
+ getJSONState: () => Record<string, any> | undefined;
getMarkdownContent: () => string;
handleSendButton: () => void;
handleStop: () => void;
@@ -26,7 +26,7 @@ export const store: CreateStore = (publicState) => (set, get) => ({
...publicState,
getJSONState: () => {
- return get().editor?.getDocument('json');
+ return get().editor?.getDocument('json') as Record<string, any> | undefined;
},
getMarkdownContent: () => {
return String(get().editor?.getDocument('markdown') || '').trimEnd();
@@ -39,6 +39,7 @@ export const store: CreateStore = (publicState) => (set, get) => ({
get().onSend?.({
clearContent: () => editor?.cleanDocument(),
editor: editor!,
+ getEditorData: get().getJSONState,
getMarkdownContent: get().getMarkdownContent,
});
},
diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.ts
index a4271d3df91..d37dfc0dce6 100644
--- a/src/features/ChatInput/store/initialState.ts
+++ b/src/features/ChatInput/store/initialState.ts
@@ -7,6 +7,7 @@ import { type ActionKeys } from '@/features/ChatInput';
export type SendButtonHandler = (params: {
clearContent: () => void;
editor: IEditor;
+ getEditorData: () => Record<string, any> | undefined;
getMarkdownContent: () => string;
}) => Promise<void> | void;
@@ -24,6 +25,8 @@ export const initialSendButtonState: SendButtonProps = {
onStop: () => {},
};
+export type SlashPlacement = 'top' | 'bottom';
+
export interface PublicState {
agentId?: string;
allowExpand?: boolean;
@@ -37,6 +40,10 @@ export interface PublicState {
sendButtonProps?: SendButtonProps;
sendMenu?: MenuProps;
showTypoBar?: boolean;
+ /**
+ * Slash menu placement: 'bottom' for home page (input in center), 'top' for page input (at bottom)
+ */
+ slashPlacement?: SlashPlacement;
}
export interface State extends PublicState {
@@ -54,4 +61,5 @@ export const initialState: State = {
markdownContent: '',
rightActions: [],
slashMenuRef: { current: null },
+ slashPlacement: 'top',
};
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 4f01f268428..8a9c2585270 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -128,7 +128,7 @@ const ChatInput = memo<ChatInputProps>(
// Send handler - gets message, clears editor immediately, then sends
const handleSend: SendButtonHandler = useCallback(
- async ({ clearContent, getMarkdownContent }) => {
+ async ({ clearContent, getMarkdownContent, getEditorData }) => {
// Get instant values from stores at trigger time
const fileStore = useFileStore.getState();
const currentFileList = fileChatSelectors.chatUploadFileList(fileStore);
@@ -142,6 +142,9 @@ const ChatInput = memo<ChatInputProps>(
if (!message.trim() && currentFileList.length === 0 && currentContextList.length === 0)
return;
+ // Capture editor JSON state before clearing for rich text rendering
+ const editorData = getEditorData();
+
// Clear content immediately for responsive UX
clearContent();
fileStore.clearChatUploadFileList();
@@ -156,7 +159,7 @@ const ChatInput = memo<ChatInputProps>(
}));
// Fire and forget - send with captured message
- await sendMessage({ files: currentFileList, message, pageSelections });
+ await sendMessage({ editorData, files: currentFileList, message, pageSelections });
},
[isInputLoading, sendMessage],
);
@@ -199,6 +202,7 @@ const ChatInput = memo<ChatInputProps>(
rightActions={rightActions}
sendButtonProps={sendButtonProps}
sendMenu={sendMenu}
+ slashPlacement="top"
chatInputEditorRef={(instance) => {
if (instance) {
setEditor(instance);
diff --git a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
index 4a123edde80..3aa8392491e 100644
--- a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
+++ b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx
@@ -3,7 +3,7 @@ import { createStaticStyles, cx } from 'antd-style';
import { type ReactNode } from 'react';
import { memo, Suspense, useCallback } from 'react';
-import { useConversationStore } from '@/features/Conversation/store';
+import { dataSelectors, useConversationStore } from '@/features/Conversation/store';
import dynamic from '@/libs/next/dynamic';
import { type ChatItemProps } from '../../type';
@@ -64,6 +64,10 @@ const MessageContent = memo<MessageContentProps>(
s.updateMessageContent,
]);
+ const editorData = useConversationStore(
+ (s) => dataSelectors.getDisplayMessageById(id)(s)?.editorData,
+ );
+
const onEditingChange = useCallback(
(edit: boolean) => toggleMessageEditing(id, edit),
[id, toggleMessageEditing],
@@ -88,11 +92,14 @@ const MessageContent = memo<MessageContentProps>(
<Suspense fallback={null}>
{editing && (
<EditorModal
+ editorData={editorData}
open={editing}
value={message ? String(message) : ''}
onCancel={() => onEditingChange(false)}
- onConfirm={async (value) => {
- await updateMessageContent(id, value);
+ onConfirm={async (value, newEditorData) => {
+ await updateMessageContent(id, value, {
+ editorData: newEditorData as Record<string, any> | undefined,
+ });
onEditingChange(false);
}}
/>
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx b/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx
index 6b7feeceda7..60416b6a20c 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/EditState.tsx
@@ -6,10 +6,11 @@ import { useConversationStore } from '../../../store';
export interface EditStateProps {
content: string;
+ editorData?: unknown;
id: string;
}
-const EditState = memo<EditStateProps>(({ id, content }) => {
+const EditState = memo<EditStateProps>(({ id, content, editorData }) => {
const [toggleMessageEditing, updateMessageContent] = useConversationStore((s) => [
s.toggleMessageEditing,
s.modifyMessageContent,
@@ -17,14 +18,15 @@ const EditState = memo<EditStateProps>(({ id, content }) => {
return (
<EditorModal
+ editorData={editorData}
open={!!id}
value={content ? String(content) : ''}
onCancel={() => {
toggleMessageEditing(id, false);
}}
- onConfirm={async (value) => {
+ onConfirm={async (value, newEditorData) => {
if (!id) return;
- await updateMessageContent(id, value);
+ await updateMessageContent(id, value, newEditorData as Record<string, any> | undefined);
toggleMessageEditing(id, false);
}}
/>
diff --git a/src/features/Conversation/Messages/CompressedGroup/index.tsx b/src/features/Conversation/Messages/CompressedGroup/index.tsx
index 1bac3211473..9e773a1a685 100644
--- a/src/features/Conversation/Messages/CompressedGroup/index.tsx
+++ b/src/features/Conversation/Messages/CompressedGroup/index.tsx
@@ -24,6 +24,7 @@ import { shinyTextStyles } from '@/styles/loading';
import { dataSelectors, useConversationStore } from '../../store';
import CompressedMessageItem from './CompressedMessageItem';
+import { isCompressionSummaryGenerating, shouldShowCompressedGroupPanel } from './logic';
const STORAGE_KEY_PREFIX = 'compressed-group-tab:';
@@ -114,10 +115,12 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {
// Check if generateSummary operation is running for this message
const runningOp = useChatStore(operationSelectors.getDeepestRunningOperationByMessage(id));
- const isGeneratingSummary = runningOp?.type === 'generateSummary';
+ const isGeneratingSummary = isCompressionSummaryGenerating(runningOp?.type);
- // Auto-expand when generating summary to show streaming content
- const showContent = expanded || isGeneratingSummary;
+ const showPanelContent = shouldShowCompressedGroupPanel({
+ expanded,
+ isGeneratingSummary,
+ });
const tabItems: TabsProps['items'] = useMemo(
() => [
@@ -172,7 +175,7 @@ const CompressedGroupMessage = memo<CompressedGroupMessageProps>(({ id }) => {
</Flexbox>
</Flexbox>
)}
- {!showContent ? null : activeTab === 'summary' ? (
+ {!showPanelContent ? null : activeTab === 'summary' ? (
<ScrollShadow className={styles.contentScroll} offset={12} size={12}>
<Markdown style={{ overflow: 'unset' }} variant={'chat'}>
{content}
diff --git a/src/features/Conversation/Messages/CompressedGroup/logic.test.ts b/src/features/Conversation/Messages/CompressedGroup/logic.test.ts
new file mode 100644
index 00000000000..aba061e0dcb
--- /dev/null
+++ b/src/features/Conversation/Messages/CompressedGroup/logic.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+
+import { isCompressionSummaryGenerating, shouldShowCompressedGroupPanel } from './logic';
+
+describe('CompressedGroup logic', () => {
+ it.each(['generateSummary', 'contextCompression'])(
+ 'should treat %s as summary generation state',
+ (operationType) => {
+ expect(isCompressionSummaryGenerating(operationType)).toBe(true);
+ expect(
+ shouldShowCompressedGroupPanel({
+ expanded: true,
+ isGeneratingSummary: isCompressionSummaryGenerating(operationType),
+ }),
+ ).toBe(false);
+ },
+ );
+
+ it('should show the summary/history panel when generation is finished and group is expanded', () => {
+ expect(isCompressionSummaryGenerating('sendMessage')).toBe(false);
+ expect(
+ shouldShowCompressedGroupPanel({
+ expanded: true,
+ isGeneratingSummary: false,
+ }),
+ ).toBe(true);
+ });
+
+ it('should keep the panel hidden when the group is collapsed', () => {
+ expect(
+ shouldShowCompressedGroupPanel({
+ expanded: false,
+ isGeneratingSummary: false,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/Messages/CompressedGroup/logic.ts b/src/features/Conversation/Messages/CompressedGroup/logic.ts
new file mode 100644
index 00000000000..88ff2d3df48
--- /dev/null
+++ b/src/features/Conversation/Messages/CompressedGroup/logic.ts
@@ -0,0 +1,10 @@
+export const isCompressionSummaryGenerating = (operationType?: string) =>
+ operationType === 'generateSummary' || operationType === 'contextCompression';
+
+export const shouldShowCompressedGroupPanel = ({
+ expanded,
+ isGeneratingSummary,
+}: {
+ expanded: boolean;
+ isGeneratingSummary: boolean;
+}) => expanded && !isGeneratingSummary;
diff --git a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx b/src/features/Conversation/Messages/User/components/MessageContent.test.tsx
new file mode 100644
index 00000000000..2c44b747007
--- /dev/null
+++ b/src/features/Conversation/Messages/User/components/MessageContent.test.tsx
@@ -0,0 +1,64 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import MessageContent from './MessageContent';
+
+vi.mock('@/features/Conversation/Markdown', () => ({
+ default: ({ children }: any) => <div data-testid="markdown-message">{children}</div>,
+}));
+
+vi.mock('../useMarkdown', () => ({
+ useMarkdown: () => ({}),
+}));
+
+vi.mock('./RichTextMessage', () => ({
+ default: ({ editorState }: any) => (
+ <div data-testid="rich-message">{JSON.stringify(editorState)}</div>
+ ),
+}));
+
+vi.mock('./FileListViewer', () => ({
+ default: () => null,
+}));
+vi.mock('./ImageFileListViewer', () => ({
+ default: () => null,
+}));
+vi.mock('./PageSelections', () => ({
+ default: () => null,
+}));
+vi.mock('./VideoFileListViewer', () => ({
+ default: () => null,
+}));
+
+describe('User MessageContent', () => {
+ it('should prefer rich text rendering when editorData exists', () => {
+ render(
+ <MessageContent
+ content={'markdown-content'}
+ createdAt={Date.now()}
+ editorData={{ root: { children: [], type: 'root', version: 1 } }}
+ id={'msg-1'}
+ role={'user'}
+ updatedAt={Date.now()}
+ />,
+ );
+
+ expect(screen.getByTestId('rich-message')).toBeInTheDocument();
+ expect(screen.queryByTestId('markdown-message')).not.toBeInTheDocument();
+ });
+
+ it('should render markdown when editorData is missing', () => {
+ render(
+ <MessageContent
+ content={'markdown-content'}
+ createdAt={Date.now()}
+ id={'msg-2'}
+ role={'user'}
+ updatedAt={Date.now()}
+ />,
+ );
+
+ expect(screen.getByTestId('markdown-message')).toBeInTheDocument();
+ expect(screen.queryByTestId('rich-message')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/features/Conversation/Messages/User/components/MessageContent.tsx b/src/features/Conversation/Messages/User/components/MessageContent.tsx
index 3f427dbb634..a1fb88a5d62 100644
--- a/src/features/Conversation/Messages/User/components/MessageContent.tsx
+++ b/src/features/Conversation/Messages/User/components/MessageContent.tsx
@@ -9,20 +9,28 @@ import { useMarkdown } from '../useMarkdown';
import FileListViewer from './FileListViewer';
import ImageFileListViewer from './ImageFileListViewer';
import PageSelections from './PageSelections';
+import RichTextMessage from './RichTextMessage';
import VideoFileListViewer from './VideoFileListViewer';
const UserMessageContent = memo<UIChatMessage>(
- ({ id, content, imageList, videoList, fileList, metadata }) => {
+ ({ id, content, editorData, imageList, videoList, fileList, metadata }) => {
const markdownProps = useMarkdown(id);
const pageSelections = metadata?.pageSelections;
const displayContent = useMemo(() => (content ? cleanSpeakerTag(content) : content), [content]);
+ const hasEditorData =
+ editorData && typeof editorData === 'object' && Object.keys(editorData).length > 0;
+
return (
<Flexbox gap={8} id={id}>
{pageSelections && pageSelections.length > 0 && (
<PageSelections selections={pageSelections} />
)}
- {displayContent && <MarkdownMessage {...markdownProps}>{displayContent}</MarkdownMessage>}
+ {hasEditorData ? (
+ <RichTextMessage editorState={editorData} />
+ ) : (
+ displayContent && <MarkdownMessage {...markdownProps}>{displayContent}</MarkdownMessage>
+ )}
{imageList && imageList?.length > 0 && <ImageFileListViewer items={imageList} />}
{videoList && videoList?.length > 0 && <VideoFileListViewer items={videoList} />}
{fileList && fileList?.length > 0 && <FileListViewer items={fileList} />}
diff --git a/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsx b/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsx
new file mode 100644
index 00000000000..d0e4431d6c3
--- /dev/null
+++ b/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsx
@@ -0,0 +1,57 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { moment } from '@lobehub/editor';
+import { act, cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import RichTextMessage from './RichTextMessage';
+
+const mentionEditorState = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'Agent A',
+ metadata: { id: 'agent-a', type: 'agent' },
+ type: 'mention',
+ version: 1,
+ },
+ ],
+ direction: null,
+ format: '',
+ indent: 0,
+ type: 'paragraph',
+ version: 1,
+ },
+ ],
+ direction: null,
+ format: '',
+ indent: 0,
+ type: 'root',
+ version: 1,
+ },
+};
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('RichTextMessage', () => {
+ it('should render mention nodes from editor state', async () => {
+ const { container } = render(<RichTextMessage editorState={mentionEditorState} />);
+
+ await act(async () => {
+ await moment();
+ });
+
+ expect(container.querySelector('.editor_mention')?.textContent).toBe('@Agent A');
+ });
+
+ it('should render nothing for empty editor state', () => {
+ const { container } = render(<RichTextMessage editorState={{}} />);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/src/features/Conversation/Messages/User/components/RichTextMessage.tsx b/src/features/Conversation/Messages/User/components/RichTextMessage.tsx
new file mode 100644
index 00000000000..a96d7adf865
--- /dev/null
+++ b/src/features/Conversation/Messages/User/components/RichTextMessage.tsx
@@ -0,0 +1,51 @@
+import { ReactMentionPlugin, ReactTablePlugin } from '@lobehub/editor';
+import { Editor, useEditor } from '@lobehub/editor/react';
+import { memo, useEffect, useMemo } from 'react';
+
+import { createChatInputRichPlugins } from '@/features/ChatInput/InputEditor/plugins';
+
+interface RichTextMessageProps {
+ editorState: unknown;
+}
+
+const EDITOR_PLUGINS = [...createChatInputRichPlugins(), ReactTablePlugin, ReactMentionPlugin];
+
+const RichTextMessage = memo<RichTextMessageProps>(({ editorState }) => {
+ const editor = useEditor();
+
+ const content = useMemo(() => {
+ if (!editorState || typeof editorState !== 'object') return null;
+ if (Object.keys(editorState as Record<string, unknown>).length === 0) return null;
+
+ try {
+ return JSON.stringify(editorState);
+ } catch {
+ return null;
+ }
+ }, [editorState]);
+
+ useEffect(() => {
+ if (editor && content) {
+ editor.setDocument('json', content);
+ }
+ }, [editor, content]);
+
+ if (!content) return null;
+
+ return (
+ <Editor
+ content={content}
+ editable={false}
+ editor={editor}
+ enablePasteMarkdown={false}
+ markdownOption={false}
+ plugins={EDITOR_PLUGINS}
+ type={'json'}
+ variant={'chat'}
+ />
+ );
+});
+
+RichTextMessage.displayName = 'RichTextMessage';
+
+export default RichTextMessage;
diff --git a/src/features/Conversation/store/slices/message/action/crud.ts b/src/features/Conversation/store/slices/message/action/crud.ts
index b8624e6f443..d5128d1781e 100644
--- a/src/features/Conversation/store/slices/message/action/crud.ts
+++ b/src/features/Conversation/store/slices/message/action/crud.ts
@@ -99,6 +99,7 @@ export interface MessageCRUDAction {
id: string,
content: string,
extra?: {
+ editorData?: Record<string, any> | null;
imageList?: ChatImageItem[];
metadata?: MessageMetadata;
model?: string;
@@ -409,7 +410,7 @@ export const messageCRUDSlice: StateCreator<
internal_dispatchMessage({
id,
type: 'updateMessage',
- value: { content },
+ value: { content, editorData: extra?.editorData },
});
}
@@ -418,6 +419,7 @@ export const messageCRUDSlice: StateCreator<
id,
{
content,
+ editorData: extra?.editorData,
imageList: extra?.imageList,
metadata: extra?.metadata,
model: extra?.model,
diff --git a/src/features/Conversation/store/slices/message/action/state.test.ts b/src/features/Conversation/store/slices/message/action/state.test.ts
index 5724fcd1355..b9dd59526ae 100644
--- a/src/features/Conversation/store/slices/message/action/state.test.ts
+++ b/src/features/Conversation/store/slices/message/action/state.test.ts
@@ -5,6 +5,12 @@ import { messageService } from '@/services/message';
import { createStore } from '../../../index';
+const { chatStoreMock } = vi.hoisted(() => ({
+ chatStoreMock: {
+ cancelOperations: vi.fn(),
+ },
+}));
+
// Mock conversation-flow parse function
vi.mock('@lobechat/conversation-flow', () => ({
parse: (messages: UIChatMessage[]) => {
@@ -20,12 +26,19 @@ vi.mock('@lobechat/conversation-flow', () => ({
// Mock messageService
vi.mock('@/services/message', () => ({
messageService: {
+ cancelCompression: vi.fn(),
getMessages: vi.fn(),
updateMessageGroupMetadata: vi.fn(),
updateMessageMetadata: vi.fn().mockResolvedValue({ success: true, messages: [] }),
},
}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: {
+ getState: () => chatStoreMock,
+ },
+}));
+
// Mock SWR
vi.mock('@/libs/swr', () => ({
useClientDataSWRWithSync: vi.fn(() => ({ data: undefined, isLoading: true })),
@@ -45,6 +58,49 @@ describe('MessageStateAction', () => {
vi.clearAllMocks();
});
+ describe('cancelCompression', () => {
+ it('should cancel running compression operations before restoring messages', async () => {
+ const store = createTestStore();
+
+ const compressedGroup: UIChatMessage = {
+ id: 'group-1',
+ content: 'Summary content',
+ role: 'compressedGroup' as any,
+ createdAt: 1000,
+ updatedAt: 1000,
+ };
+ const restoredMessages: UIChatMessage[] = [
+ {
+ id: 'msg-1',
+ content: 'Original content',
+ role: 'user',
+ createdAt: 1000,
+ updatedAt: 1000,
+ },
+ ];
+
+ store.setState({ displayMessages: [compressedGroup] });
+ vi.mocked(messageService.cancelCompression).mockResolvedValue({ messages: restoredMessages });
+
+ const replaceMessagesSpy = vi.spyOn(store.getState(), 'replaceMessages');
+
+ await store.getState().cancelCompression('group-1');
+
+ expect(chatStoreMock.cancelOperations).toHaveBeenCalledWith(
+ { messageId: 'group-1', status: 'running' },
+ 'Compression cancelled',
+ );
+ expect(messageService.cancelCompression).toHaveBeenCalledWith({
+ agentId: 'test-agent',
+ groupId: undefined,
+ messageGroupId: 'group-1',
+ threadId: null,
+ topicId: 'test-topic',
+ });
+ expect(replaceMessagesSpy).toHaveBeenCalledWith(restoredMessages);
+ });
+ });
+
describe('toggleCompressedGroupExpanded', () => {
it('should toggle expanded state from false to true', async () => {
const store = createTestStore();
diff --git a/src/features/Conversation/store/slices/message/action/state.ts b/src/features/Conversation/store/slices/message/action/state.ts
index f9c99a0abb1..61368917b7f 100644
--- a/src/features/Conversation/store/slices/message/action/state.ts
+++ b/src/features/Conversation/store/slices/message/action/state.ts
@@ -3,6 +3,7 @@ import { produce } from 'immer';
import { type StateCreator } from 'zustand';
import { messageService } from '@/services/message';
+import { useChatStore } from '@/store/chat';
import { type Store as ConversationStore } from '../../../action';
import { dataSelectors } from '../../data/selectors';
@@ -31,7 +32,11 @@ export interface MessageStateAction {
/**
* Modify message content (with optimistic update)
*/
- modifyMessageContent: (id: string, content: string) => Promise<void>;
+ modifyMessageContent: (
+ id: string,
+ content: string,
+ editorData?: Record<string, any> | null,
+ ) => Promise<void>;
/**
* Toggle compressed group expanded state
@@ -62,6 +67,10 @@ export const messageStateSlice: StateCreator<
const { context, replaceMessages } = get();
if (!context.agentId || !context.topicId) return;
+ useChatStore
+ .getState()
+ .cancelOperations({ messageId: id, status: 'running' }, 'Compression cancelled');
+
// Call service to cancel compression
const { messages } = await messageService.cancelCompression({
agentId: context.agentId,
@@ -103,7 +112,7 @@ export const messageStateSlice: StateCreator<
);
},
- modifyMessageContent: async (id, content) => {
+ modifyMessageContent: async (id, content, editorData) => {
const { hooks } = get();
// Get original content for hook
@@ -111,7 +120,7 @@ export const messageStateSlice: StateCreator<
const originalContent = originalMessage?.content;
// Update content
- await get().updateMessageContent(id, content);
+ await get().updateMessageContent(id, content, editorData ? { editorData } : undefined);
// ===== Hook: onMessageModified =====
if (hooks.onMessageModified) {
diff --git a/src/features/EditorCanvas/InternalEditor.tsx b/src/features/EditorCanvas/InternalEditor.tsx
index fb8d8ed96b1..857fb513296 100644
--- a/src/features/EditorCanvas/InternalEditor.tsx
+++ b/src/features/EditorCanvas/InternalEditor.tsx
@@ -3,14 +3,9 @@
import { isDesktop } from '@lobechat/const';
import { type IEditor } from '@lobehub/editor';
import {
- ReactCodemirrorPlugin,
- ReactCodePlugin,
- ReactHRPlugin,
ReactImagePlugin,
ReactLinkPlugin,
- ReactListPlugin,
ReactLiteXmlPlugin,
- ReactMathPlugin,
ReactTablePlugin,
ReactToolbarPlugin,
} from '@lobehub/editor';
@@ -19,6 +14,8 @@ import isEqual from 'fast-deep-equal';
import { memo, type RefObject, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
+import { createChatInputRichPlugins } from '@/features/ChatInput/InputEditor/plugins';
+
import { type EditorCanvasProps } from './EditorCanvas';
import InlineToolbar from './InlineToolbar';
import { useImageUpload } from './useImageUpload';
@@ -32,13 +29,8 @@ const IMAGE_FILTERS = [
*/
const STATIC_PLUGINS = [
ReactLiteXmlPlugin,
- ReactListPlugin,
- ReactCodePlugin,
- ReactCodemirrorPlugin,
- ReactHRPlugin,
- ReactLinkPlugin,
+ ...createChatInputRichPlugins({ linkPlugin: ReactLinkPlugin }),
ReactTablePlugin,
- ReactMathPlugin,
];
export interface InternalEditorProps extends EditorCanvasProps {
diff --git a/src/features/EditorModal/EditorCanvas.test.tsx b/src/features/EditorModal/EditorCanvas.test.tsx
new file mode 100644
index 00000000000..85739478d2d
--- /dev/null
+++ b/src/features/EditorModal/EditorCanvas.test.tsx
@@ -0,0 +1,92 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { type IEditor } from '@lobehub/editor';
+import { moment } from '@lobehub/editor';
+import { useEditor } from '@lobehub/editor/react';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { memo, useEffect, useRef } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import EditorCanvas from './EditorCanvas';
+
+vi.mock('./Typobar', () => ({
+ default: () => null,
+}));
+
+const mentionEditorState = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'Agent A',
+ metadata: { id: 'agent-a', type: 'agent' },
+ type: 'mention',
+ version: 1,
+ },
+ ],
+ direction: null,
+ format: '',
+ indent: 0,
+ type: 'paragraph',
+ version: 1,
+ },
+ ],
+ direction: null,
+ format: '',
+ indent: 0,
+ type: 'root',
+ version: 1,
+ },
+};
+
+interface TestWrapperProps {
+ defaultValue?: string;
+ editorData?: unknown;
+ onEditorReady?: (editor: IEditor) => void;
+}
+
+const TestWrapper = memo<TestWrapperProps>(({ defaultValue, editorData, onEditorReady }) => {
+ const editor = useEditor();
+ const readyRef = useRef(false);
+
+ useEffect(() => {
+ if (editor && !readyRef.current) {
+ readyRef.current = true;
+ onEditorReady?.(editor);
+ }
+ }, [editor, onEditorReady]);
+
+ if (!editor) return null;
+
+ return <EditorCanvas defaultValue={defaultValue} editor={editor} editorData={editorData} />;
+});
+
+TestWrapper.displayName = 'EditorModalEditorCanvasTestWrapper';
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('EditorModal EditorCanvas', () => {
+ it('should render mention nodes from editor data', async () => {
+ const { container } = render(<TestWrapper editorData={mentionEditorState} />);
+
+ await act(async () => {
+ await moment();
+ });
+
+ expect(container.querySelector('.editor_mention')?.textContent).toBe('@Agent A');
+ });
+
+ it('should render markdown default value when editor data is missing', async () => {
+ render(<TestWrapper defaultValue={'Hello from markdown'} />);
+
+ await act(async () => {
+ await moment();
+ });
+
+ expect(screen.getByText('Hello from markdown')).toBeInTheDocument();
+ });
+});
diff --git a/src/features/EditorModal/EditorCanvas.tsx b/src/features/EditorModal/EditorCanvas.tsx
index 63951ba424e..6be65103f0b 100644
--- a/src/features/EditorModal/EditorCanvas.tsx
+++ b/src/features/EditorModal/EditorCanvas.tsx
@@ -1,25 +1,37 @@
import { type IEditor } from '@lobehub/editor';
-import {
- ReactCodemirrorPlugin,
- ReactCodePlugin,
- ReactHRPlugin,
- ReactLinkPlugin,
- ReactListPlugin,
- ReactMathPlugin,
- ReactTablePlugin,
-} from '@lobehub/editor';
+import { ReactLinkPlugin, ReactMentionPlugin, ReactTablePlugin } from '@lobehub/editor';
import { Editor } from '@lobehub/editor/react';
import { Flexbox } from '@lobehub/ui';
-import { type FC } from 'react';
+import { type FC, useMemo } from 'react';
+
+import { createChatInputRichPlugins } from '@/features/ChatInput/InputEditor/plugins';
import TypoBar from './Typobar';
interface EditorCanvasProps {
defaultValue?: string;
editor?: IEditor;
+ editorData?: unknown;
}
-const EditorCanvas: FC<EditorCanvasProps> = ({ defaultValue, editor }) => {
+const EDITOR_PLUGINS = [
+ ...createChatInputRichPlugins({ linkPlugin: ReactLinkPlugin }),
+ ReactTablePlugin,
+ ReactMentionPlugin,
+];
+
+const EditorCanvas: FC<EditorCanvasProps> = ({ defaultValue, editor, editorData }) => {
+ const { content, type } = useMemo(() => {
+ const hasValidEditorData =
+ editorData && typeof editorData === 'object' && Object.keys(editorData).length > 0;
+
+ if (hasValidEditorData) {
+ return { content: JSON.stringify(editorData), type: 'json' as const };
+ }
+
+ return { content: defaultValue || '', type: 'markdown' as const };
+ }, [editorData, defaultValue]);
+
return (
<>
<TypoBar editor={editor} />
@@ -29,30 +41,14 @@ const EditorCanvas: FC<EditorCanvasProps> = ({ defaultValue, editor }) => {
>
<Editor
autoFocus
- content={''}
+ content={content}
editor={editor}
- type={'text'}
+ plugins={EDITOR_PLUGINS}
+ type={type}
variant={'chat'}
- plugins={[
- ReactListPlugin,
- ReactCodePlugin,
- ReactCodemirrorPlugin,
- ReactHRPlugin,
- ReactLinkPlugin,
- ReactTablePlugin,
- ReactMathPlugin,
- ]}
style={{
paddingBottom: 120,
}}
- onInit={(editor) => {
- if (!editor || !defaultValue) return;
- try {
- editor?.setDocument('markdown', defaultValue);
- } catch (e) {
- console.error('setDocument error:', e);
- }
- }}
/>
</Flexbox>
</>
diff --git a/src/features/EditorModal/index.tsx b/src/features/EditorModal/index.tsx
index 9f4688ec037..b6528c7018c 100644
--- a/src/features/EditorModal/index.tsx
+++ b/src/features/EditorModal/index.tsx
@@ -4,59 +4,48 @@ import { createRawModal, Modal } from '@lobehub/ui';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useUserStore } from '@/store/user';
-import { labPreferSelectors } from '@/store/user/selectors';
-
import EditorCanvas from './EditorCanvas';
-import TextareCanvas from './TextArea';
interface EditorModalProps extends ModalProps {
- onConfirm?: (value: string) => Promise<void>;
+ editorData?: unknown;
+ onConfirm?: (value: string, editorData?: unknown) => Promise<void>;
value?: string;
}
-export const EditorModal = memo<EditorModalProps>(({ value, onConfirm, ...rest }) => {
- const [confirmLoading, setConfirmLoading] = useState(false);
- const { t } = useTranslation('common');
- const [v, setV] = useState(value);
- const enableRichRender = useUserStore(labPreferSelectors.enableInputMarkdown);
- const editor = useEditor();
+export const EditorModal = memo<EditorModalProps>(
+ ({ value, editorData: initialEditorData, onConfirm, ...rest }) => {
+ const [confirmLoading, setConfirmLoading] = useState(false);
+ const { t } = useTranslation('common');
+ const editor = useEditor();
- return (
- <Modal
- destroyOnHidden
- cancelText={t('cancel')}
- closable={false}
- confirmLoading={confirmLoading}
- okText={t('ok')}
- title={null}
- width={'min(90vw, 920px)'}
- styles={{
- body: {
- overflow: 'hidden',
- padding: 0,
- },
- }}
- onOk={async () => {
- setConfirmLoading(true);
- let finalValue;
- if (enableRichRender) {
- finalValue = editor?.getDocument('markdown') as unknown as string;
- } else {
- finalValue = v;
- }
- await onConfirm?.(finalValue || '');
- setConfirmLoading(false);
- }}
- {...rest}
- >
- {enableRichRender ? (
- <EditorCanvas defaultValue={value} editor={editor} />
- ) : (
- <TextareCanvas defaultValue={value} value={v} onChange={(v) => setV(v)} />
- )}
- </Modal>
- );
-});
+ return (
+ <Modal
+ destroyOnHidden
+ cancelText={t('cancel')}
+ closable={false}
+ confirmLoading={confirmLoading}
+ okText={t('ok')}
+ title={null}
+ width={'min(90vw, 920px)'}
+ styles={{
+ body: {
+ overflow: 'hidden',
+ padding: 0,
+ },
+ }}
+ onOk={async () => {
+ setConfirmLoading(true);
+ const finalValue = (editor?.getDocument('markdown') as unknown as string) || '';
+ const editorData = editor?.getDocument('json');
+ await onConfirm?.(finalValue, editorData);
+ setConfirmLoading(false);
+ }}
+ {...rest}
+ >
+ <EditorCanvas defaultValue={value} editor={editor} editorData={initialEditorData} />
+ </Modal>
+ );
+ },
+);
export const createEditorModal = (props: EditorModalProps) => createRawModal(EditorModal, props);
diff --git a/src/features/PluginTag/index.tsx b/src/features/PluginTag/index.tsx
index 6b8d25390fd..e9e24ad6dad 100644
--- a/src/features/PluginTag/index.tsx
+++ b/src/features/PluginTag/index.tsx
@@ -1,6 +1,5 @@
'use client';
-import { type MenuProps } from '@lobehub/ui';
import { Center, DropdownMenu, Icon, Tag } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { LucideToyBrick } from 'lucide-react';
@@ -30,33 +29,35 @@ const PluginTag = memo<PluginTagProps>(({ plugins }) => {
if (visiblePlugins.length === 0) return null;
- const items: MenuProps['items'] = visiblePlugins.map((id) => {
- const item = list.find((i) => i.identifier === id);
-
- const isDeprecated = !item;
- const avatar = isDeprecated ? '♻️' : pluginHelpers.getPluginAvatar(item.meta || item);
-
- return {
- icon: (
- <Center style={{ minWidth: 24 }}>
- <Avatar avatar={avatar} size={24} />
- </Center>
- ),
- key: id,
- label: (
- <PluginStatus
- deprecated={isDeprecated}
- id={id}
- title={pluginHelpers.getPluginTitle(item?.meta || item)}
- />
- ),
- };
- });
-
const count = visiblePlugins.length;
return (
- <DropdownMenu items={items}>
+ <DropdownMenu
+ items={() =>
+ visiblePlugins.map((id) => {
+ const item = list.find((i) => i.identifier === id);
+
+ const isDeprecated = !item;
+ const avatar = isDeprecated ? '♻️' : pluginHelpers.getPluginAvatar(item.meta || item);
+
+ return {
+ icon: (
+ <Center style={{ minWidth: 24 }}>
+ <Avatar avatar={avatar} size={24} />
+ </Center>
+ ),
+ key: id,
+ label: (
+ <PluginStatus
+ deprecated={isDeprecated}
+ id={id}
+ title={pluginHelpers.getPluginTitle(item?.meta || item)}
+ />
+ ),
+ };
+ })
+ }
+ >
<Tag style={{ cursor: 'pointer' }}>
{<Icon icon={LucideToyBrick} />}
{pluginHelpers.getPluginTitle(displayPlugin) || visiblePlugins[0]}
diff --git a/src/locales/default/editor.ts b/src/locales/default/editor.ts
index 795e70cb4d5..4c906376f4d 100644
--- a/src/locales/default/editor.ts
+++ b/src/locales/default/editor.ts
@@ -35,12 +35,23 @@ export default {
'modifier.acceptAll': 'Keep All',
'modifier.reject': 'Revert',
'modifier.rejectAll': 'Revert All',
+ 'actionTag.category.command': 'Command',
+ 'actionTag.category.skill': 'Skill',
+ 'actionTag.category.tool': 'Tool',
+ 'actionTag.tooltip.command': 'Runs a client-side slash command before sending.',
+ 'actionTag.tooltip.skill': 'Loads a reusable skill package for this request.',
+ 'actionTag.tooltip.tool': 'Marks a tool the user explicitly selected for this request.',
+ 'slash.compact': 'Compact context',
'slash.h1': 'Heading 1',
'slash.h2': 'Heading 2',
'slash.h3': 'Heading 3',
'slash.hr': 'Divider',
+ 'slash.newTopic': 'Send in new topic',
+ 'slash.rewrite': 'Rewrite',
+ 'slash.summarize': 'Summarize',
'slash.table': 'Table',
'slash.tex': 'TeX Formula',
+ 'slash.translate': 'Translate',
'table.delete': 'Delete table',
'table.deleteColumn': 'Delete column',
'table.deleteRow': 'Delete row',
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index 1cb50f0cfe3..8e796695298 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -220,6 +220,8 @@ export default {
'builtins.lobe-web-browsing.apiName.search': 'Search pages',
'builtins.lobe-web-browsing.inspector.noResults': 'No results',
'builtins.lobe-web-browsing.title': 'Web Search',
+ 'builtins.lobe-topic-reference.apiName.getTopicContext': 'Get Topic Context',
+ 'builtins.lobe-topic-reference.title': 'Topic Reference',
'confirm': 'Confirm',
'debug.arguments': 'Arguments',
'debug.error': 'Error log',
diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
index 2e0b589766d..86cd08bbb9c 100644
--- a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx
@@ -1,21 +1,12 @@
'use client';
-import {
- ReactCodemirrorPlugin,
- ReactCodePlugin,
- ReactHRPlugin,
- ReactLinkHighlightPlugin,
- ReactListPlugin,
- ReactMathPlugin,
- ReactMentionPlugin,
- ReactTablePlugin,
- ReactToolbarPlugin,
-} from '@lobehub/editor';
+import { ReactMentionPlugin, ReactTablePlugin, ReactToolbarPlugin } from '@lobehub/editor';
import { Editor } from '@lobehub/editor/react';
import isEqual from 'fast-deep-equal';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { createChatInputRichPlugins } from '@/features/ChatInput/InputEditor/plugins';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -116,13 +107,8 @@ const EditorCanvas = memo(() => {
mentionOption={mentionOptions}
placeholder={t('settingAgent.prompt.templatePlaceholder')}
plugins={[
- ReactListPlugin,
- ReactCodePlugin,
- ReactCodemirrorPlugin,
- ReactHRPlugin,
- ReactLinkHighlightPlugin,
+ ...createChatInputRichPlugins(),
ReactTablePlugin,
- ReactMathPlugin,
ReactMentionPlugin,
Editor.withProps(ReactToolbarPlugin, {
children: <TypoBar />,
diff --git a/src/routes/(main)/home/features/InputArea/index.tsx b/src/routes/(main)/home/features/InputArea/index.tsx
index 447f42cd7b7..95718265e47 100644
--- a/src/routes/(main)/home/features/InputArea/index.tsx
+++ b/src/routes/(main)/home/features/InputArea/index.tsx
@@ -95,6 +95,7 @@ const InputArea = () => {
agentId={inboxAgentId}
allowExpand={false}
leftActions={leftActions}
+ slashPlacement="bottom"
chatInputEditorRef={(instance) => {
if (!instance) return;
useChatStore.setState({ mainInputEditor: instance });
diff --git a/src/routes/(main)/settings/profile/features/AvatarRow.tsx b/src/routes/(main)/settings/profile/features/AvatarRow.tsx
index e436b87aa01..51a15a24ab0 100644
--- a/src/routes/(main)/settings/profile/features/AvatarRow.tsx
+++ b/src/routes/(main)/settings/profile/features/AvatarRow.tsx
@@ -5,7 +5,7 @@ import { Flexbox, Icon, Text } from '@lobehub/ui';
import { Spin, Upload } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
import { PencilIcon } from 'lucide-react';
-import { useCallback, useState } from 'react';
+import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { fetchErrorNotification } from '@/components/Error/fetchErrorNotification';
@@ -58,31 +58,32 @@ const AvatarRow = ({ mobile }: AvatarRowProps) => {
const updateAvatar = useUserStore((s) => s.updateAvatar);
const [uploading, setUploading] = useState(false);
- const handleUploadAvatar = useCallback(
- createUploadImageHandler(async (avatar) => {
- try {
- setUploading(true);
- const img = new Image();
- img.src = avatar;
-
- await new Promise((resolve, reject) => {
- img.addEventListener('load', resolve);
- img.addEventListener('error', reject);
- });
-
- const webpBase64 = imageToBase64({ img, size: 256 });
- await updateAvatar(webpBase64);
- setUploading(false);
- } catch (error) {
- console.error('Failed to upload avatar:', error);
- setUploading(false);
-
- fetchErrorNotification.error({
- errorMessage: error instanceof Error ? error.message : String(error),
- status: 500,
- });
- }
- }),
+ const handleUploadAvatar = useMemo(
+ () =>
+ createUploadImageHandler(async (avatar) => {
+ try {
+ setUploading(true);
+ const img = new Image();
+ img.src = avatar;
+
+ await new Promise((resolve, reject) => {
+ img.addEventListener('load', resolve);
+ img.addEventListener('error', reject);
+ });
+
+ const webpBase64 = imageToBase64({ img, size: 256 });
+ await updateAvatar(webpBase64);
+ setUploading(false);
+ } catch (error) {
+ console.error('Failed to upload avatar:', error);
+ setUploading(false);
+
+ fetchErrorNotification.error({
+ errorMessage: error instanceof Error ? error.message : String(error),
+ status: 500,
+ });
+ }
+ }),
[updateAvatar],
);
diff --git a/src/server/routers/lambda/__tests__/aiChat.test.ts b/src/server/routers/lambda/__tests__/aiChat.test.ts
index 90f12892aa2..bc33d079ba2 100644
--- a/src/server/routers/lambda/__tests__/aiChat.test.ts
+++ b/src/server/routers/lambda/__tests__/aiChat.test.ts
@@ -166,6 +166,113 @@ describe('aiChatRouter', () => {
);
});
+ it('should persist preload messages before user message and chain parent ids', async () => {
+ const mockCreateMessage = vi
+ .fn()
+ .mockResolvedValueOnce({ id: 'm-preload-assistant' })
+ .mockResolvedValueOnce({ id: 'm-preload-tool' })
+ .mockResolvedValueOnce({ id: 'm-user' })
+ .mockResolvedValueOnce({ id: 'm-assistant' });
+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });
+
+ vi.mocked(MessageModel).mockImplementation(() => ({ create: mockCreateMessage }) as any);
+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);
+
+ const caller = aiChatRouter.createCaller(mockCtx as any);
+
+ await caller.sendMessageInServer({
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newUserMessage: { content: 'hi', parentId: 'm-parent' },
+ preloadMessages: [
+ {
+ content: '',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'runSkill',
+ arguments: '{"name":"Grep"}',
+ id: 'tool-call-1',
+ identifier: 'lobe-skills',
+ type: 'builtin',
+ },
+ ],
+ },
+ {
+ content: 'Use grep to search the codebase.',
+ plugin: {
+ apiName: 'runSkill',
+ arguments: '{"name":"Grep"}',
+ identifier: 'lobe-skills',
+ type: 'builtin',
+ },
+ role: 'tool',
+ tool_call_id: 'tool-call-1',
+ },
+ ],
+ sessionId: 's1',
+ threadId: 'thread-123',
+ topicId: 't1',
+ } as any);
+
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ content: '',
+ parentId: 'm-parent',
+ role: 'assistant',
+ sessionId: 's1',
+ threadId: 'thread-123',
+ topicId: 't1',
+ tools: [
+ expect.objectContaining({
+ apiName: 'runSkill',
+ id: 'tool-call-1',
+ }),
+ ],
+ }),
+ );
+
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ content: 'Use grep to search the codebase.',
+ parentId: 'm-preload-assistant',
+ plugin: expect.objectContaining({
+ apiName: 'runSkill',
+ identifier: 'lobe-skills',
+ }),
+ role: 'tool',
+ sessionId: 's1',
+ threadId: 'thread-123',
+ tool_call_id: 'tool-call-1',
+ topicId: 't1',
+ }),
+ );
+
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 3,
+ expect.objectContaining({
+ content: 'hi',
+ parentId: 'm-preload-tool',
+ role: 'user',
+ sessionId: 's1',
+ threadId: 'thread-123',
+ topicId: 't1',
+ }),
+ );
+
+ expect(mockCreateMessage).toHaveBeenNthCalledWith(
+ 4,
+ expect.objectContaining({
+ parentId: 'm-user',
+ role: 'assistant',
+ sessionId: 's1',
+ threadId: 'thread-123',
+ topicId: 't1',
+ }),
+ );
+ });
+
it('should create thread and use its id for messages when newThread is provided', async () => {
const mockCreateThread = vi.fn().mockResolvedValue({ id: 'thread-new' });
const mockCreateMessage = vi
diff --git a/src/server/routers/lambda/aiChat.ts b/src/server/routers/lambda/aiChat.ts
index f0c1bee33b6..496d380c4a0 100644
--- a/src/server/routers/lambda/aiChat.ts
+++ b/src/server/routers/lambda/aiChat.ts
@@ -1,4 +1,4 @@
-import { type SendMessageServerResponse } from '@lobechat/types';
+import { type CreateMessageParams, type SendMessageServerResponse } from '@lobechat/types';
import { AiSendMessageServerSchema, StructureOutputSchema } from '@lobechat/types';
import debug from 'debug';
@@ -117,6 +117,31 @@ export const aiChatRouter = router({
}
}
+ let parentId = input.newUserMessage.parentId;
+
+ if (input.preloadMessages?.length) {
+ log('creating %d preload messages before user message', input.preloadMessages.length);
+
+ for (const preloadMessage of input.preloadMessages) {
+ const preloadItem = await ctx.messageModel.create({
+ agentId: input.agentId,
+ content: preloadMessage.content,
+ groupId: input.groupId,
+ metadata: preloadMessage.metadata,
+ parentId,
+ plugin: preloadMessage.plugin as CreateMessageParams['plugin'],
+ role: preloadMessage.role,
+ sessionId,
+ threadId,
+ tool_call_id: preloadMessage.tool_call_id,
+ tools: preloadMessage.tools as CreateMessageParams['tools'],
+ topicId,
+ });
+
+ parentId = preloadItem.id;
+ }
+ }
+
// create user message
log('creating user message with content length: %d', input.newUserMessage.content.length);
@@ -128,10 +153,11 @@ export const aiChatRouter = router({
const userMessageItem = await ctx.messageModel.create({
agentId: input.agentId,
content: input.newUserMessage.content,
+ editorData: input.newUserMessage.editorData,
files: input.newUserMessage.files,
groupId: input.groupId,
metadata: userMessageMetadata,
- parentId: input.newUserMessage.parentId,
+ parentId,
role: 'user',
sessionId,
threadId,
diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.ts
index c507550c8fa..fc3058ccf22 100644
--- a/src/server/routers/lambda/topic.ts
+++ b/src/server/routers/lambda/topic.ts
@@ -8,6 +8,7 @@ import { eq, inArray } from 'drizzle-orm';
import { after } from 'next/server';
import { z } from 'zod';
+import { MessageModel } from '@/database/models/message';
import { TopicModel } from '@/database/models/topic';
import { TopicShareModel } from '@/database/models/topicShare';
import { AgentMigrationRepo } from '@/database/repositories/agentMigration';
@@ -38,6 +39,48 @@ const topicProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
});
export const topicRouter = router({
+ getTopicContext: topicProcedure
+ .input(z.object({ topicId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const topic = await ctx.topicModel.findById(input.topicId);
+
+ if (!topic) {
+ return { content: `Topic not found: ${input.topicId}`, success: false };
+ }
+
+ const title = topic.title || 'Untitled';
+
+ // Prefer historySummary if available
+ if (topic.historySummary) {
+ return {
+ content: `# Topic: ${title}\n\n## Summary\n${topic.historySummary}`,
+ success: true,
+ };
+ }
+
+ // Fallback: fetch recent messages with correct agentId/groupId
+ const messageModel = new MessageModel(ctx.serverDB, ctx.userId);
+ const messages = await messageModel.query({
+ agentId: topic.agentId ?? undefined,
+ groupId: topic.groupId ?? undefined,
+ topicId: input.topicId,
+ });
+
+ const recentMessages = messages.slice(-30);
+ const lines = [`# Topic: ${title}`, '', '## Recent Messages', ''];
+
+ for (const msg of recentMessages) {
+ const role =
+ msg.role === 'user' ? 'User' : msg.role === 'assistant' ? 'Assistant' : msg.role;
+ const content = (msg.content || '').trim();
+ if (content) {
+ lines.push(`**${role}**: ${content}`, '');
+ }
+ }
+
+ return { content: lines.join('\n'), success: true };
+ }),
+
batchCreateTopics: topicProcedure
.input(
z.array(
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 804e9f6a15e..2b558a45e7b 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -372,11 +372,18 @@ export class AiAgentService {
isModelSupportToolUse,
};
+ // Dynamically inject topic-reference tool when prompt contains <refer_topic> tags
+ const hasTopicReference = /refer_topic/.test(prompt ?? '');
+ const agentPlugins = [
+ ...(agentConfig?.plugins ?? []),
+ ...(hasTopicReference ? ['lobe-topic-reference'] : []),
+ ];
+
const toolsEngine = createServerAgentToolsEngine(toolsContext, {
additionalManifests: [...lobehubSkillManifests, ...klavisManifests],
agentConfig: {
chatConfig: agentConfig.chatConfig ?? undefined,
- plugins: agentConfig?.plugins ?? undefined,
+ plugins: agentPlugins,
},
deviceContext: gatewayConfigured
? { boundDeviceId, deviceOnline, gatewayConfigured: true }
diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.ts
index 1fe210aada2..b91eddf7233 100644
--- a/src/server/services/toolExecution/serverRuntimes/index.ts
+++ b/src/server/services/toolExecution/serverRuntimes/index.ts
@@ -16,6 +16,7 @@ import { remoteDeviceRuntime } from './remoteDevice';
import { skillsRuntime } from './skills';
import { skillStoreRuntime } from './skillStore';
import { toolsActivatorRuntime } from './tools';
+import { topicReferenceRuntime } from './topicReference';
import { type ServerRuntimeFactory, type ServerRuntimeRegistration } from './types';
import { webBrowsingRuntime } from './webBrowsing';
@@ -45,6 +46,7 @@ registerRuntimes([
toolsActivatorRuntime,
localSystemRuntime,
remoteDeviceRuntime,
+ topicReferenceRuntime,
]);
// ==================== Registry API ====================
diff --git a/src/server/services/toolExecution/serverRuntimes/topicReference.ts b/src/server/services/toolExecution/serverRuntimes/topicReference.ts
new file mode 100644
index 00000000000..7ae959648ca
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/topicReference.ts
@@ -0,0 +1,93 @@
+import { TopicReferenceIdentifier } from '@lobechat/builtin-tool-topic-reference';
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+
+import type { ServerRuntimeRegistration } from './types';
+
+const MAX_MESSAGES = 30;
+
+interface GetTopicContextParams {
+ topicId: string;
+}
+
+class TopicReferenceExecutionRuntime {
+ private db: LobeChatDatabase;
+ private userId: string;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.db = db;
+ this.userId = userId;
+ }
+
+ getTopicContext = async (params: GetTopicContextParams): Promise<BuiltinServerRuntimeOutput> => {
+ const { topicId } = params;
+
+ if (!topicId) {
+ return { content: 'topicId is required', success: false };
+ }
+
+ try {
+ const topicModel = new TopicModel(this.db, this.userId);
+ const topic = await topicModel.findById(topicId);
+
+ if (!topic) {
+ return { content: `Topic not found: ${topicId}`, success: false };
+ }
+
+ // If topic has a summary, prefer it
+ if (topic.historySummary) {
+ const result = [
+ `# Topic: ${topic.title || 'Untitled'}`,
+ '',
+ '## Summary',
+ topic.historySummary,
+ ].join('\n');
+
+ return { content: result, success: true };
+ }
+
+ // Fallback: fetch recent messages
+ // Must pass agentId/groupId from topic, otherwise query filters by isNull(sessionId/groupId)
+ const messageModel = new MessageModel(this.db, this.userId);
+ const messages = await messageModel.query({
+ agentId: topic.agentId ?? undefined,
+ groupId: topic.groupId ?? undefined,
+ topicId,
+ });
+
+ const recentMessages = messages.slice(-MAX_MESSAGES);
+
+ const lines = [`# Topic: ${topic.title || 'Untitled'}`, '', '## Recent Messages', ''];
+
+ for (const msg of recentMessages) {
+ const role =
+ msg.role === 'user' ? 'User' : msg.role === 'assistant' ? 'Assistant' : msg.role;
+ const content = (msg.content || '').trim();
+ if (content) {
+ lines.push(`**${role}**: ${content}`, '');
+ }
+ }
+
+ return { content: lines.join('\n'), success: true };
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ return { content: `Failed to fetch topic context: ${errorMessage}`, error, success: false };
+ }
+ };
+}
+
+export const topicReferenceRuntime: ServerRuntimeRegistration = {
+ factory: (context) => {
+ if (!context.serverDB) {
+ throw new Error('serverDB is required for TopicReference execution');
+ }
+ if (!context.userId) {
+ throw new Error('userId is required for TopicReference execution');
+ }
+ return new TopicReferenceExecutionRuntime(context.serverDB, context.userId);
+ },
+ identifier: TopicReferenceIdentifier,
+};
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index 2b305b92590..8440eec704b 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -830,7 +830,7 @@ describe('ChatService', () => {
</plugins>`,
role: 'system',
},
- { content: 'https://vercel.com/ 请分析 chatGPT 关键词\n\n', role: 'user' },
+ { content: 'https://vercel.com/ 请分析 chatGPT 关键词', role: 'user' },
],
},
expect.anything(),
@@ -983,7 +983,7 @@ describe('ChatService', () => {
</plugins>`,
role: 'system',
},
- { content: 'https://vercel.com/ 请分析 chatGPT 关键词\n\n', role: 'user' },
+ { content: 'https://vercel.com/ 请分析 chatGPT 关键词', role: 'user' },
],
},
expect.anything(),
@@ -1021,7 +1021,7 @@ describe('ChatService', () => {
content: 'system\n\n' + getCurrentDateContent(),
role: 'system',
},
- { content: 'https://vercel.com/ 请分析 chatGPT 关键词\n\n', role: 'user' },
+ { content: 'https://vercel.com/ 请分析 chatGPT 关键词', role: 'user' },
],
},
expect.anything(),
diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.ts
index 8f8213d2fee..b15ed5559ba 100644
--- a/src/services/chat/mecha/contextEngineering.test.ts
+++ b/src/services/chat/mecha/contextEngineering.test.ts
@@ -292,6 +292,34 @@ describe('contextEngineering', () => {
expect(systemMessage!.content).toContain(historySummary);
expect(Object.keys(systemMessage!).length).toEqual(2);
});
+
+ it('should strip raw action tags from user messages before sending to model', async () => {
+ vi.spyOn(isCanUseFCModule, 'isCanUseFC').mockReturnValue(true);
+
+ const messages: UIChatMessage[] = [
+ {
+ role: 'user',
+ content:
+ '<action type="grep" category="skill" /> <action type="lobe-notebook" category="tool" /> hi',
+ createdAt: Date.now(),
+ id: 'selected-skill-user',
+ updatedAt: Date.now(),
+ },
+ ];
+
+ const result = await contextEngineering({
+ messages,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
+ expect(result[1].role).toBe('user');
+ expect(result[1].content).toContain('hi');
+ expect(result[1].content).not.toContain('<action type="grep" category="skill" />');
+ expect(result[1].content).not.toContain('<action type="lobe-notebook" category="tool" />');
+ });
+
describe('getAssistantContent', () => {
it('should handle assistant message with imageList and content', async () => {
// Mock isCanUseVision to return true for vision models
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 2a30e9e171e..95a5120e9d1 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -46,6 +46,7 @@ import {
import { isCanUseVideo, isCanUseVision } from '../helper';
import { combineUserMemoryData, resolveTopicMemories, resolveUserPersona } from './memoryManager';
import { createSkillEngine } from './skillEngineering';
+import { stripActionTagsFromText } from './skillPreload';
const log = debug('context-engine:contextEngineering');
@@ -87,6 +88,39 @@ interface ContextEngineeringContext {
topicId?: string;
}
+type TextContentPart = {
+ text?: string;
+ type?: string;
+ [key: string]: unknown;
+};
+
+const preprocessActionTags = (messages: UIChatMessage[]): UIChatMessage[] =>
+ messages.map((message) => {
+ if (message.role !== 'user') return message;
+
+ if (typeof message.content === 'string') {
+ return {
+ ...message,
+ content: stripActionTagsFromText(message.content),
+ };
+ }
+
+ if (Array.isArray(message.content)) {
+ const contentParts = message.content as TextContentPart[];
+
+ return {
+ ...message,
+ content: contentParts.map((part) =>
+ part?.type === 'text' && typeof part.text === 'string'
+ ? { ...part, text: stripActionTagsFromText(part.text) }
+ : part,
+ ),
+ } as unknown as UIChatMessage;
+ }
+
+ return message;
+ });
+
// REVIEW: Maybe we can constrain identity, preference, exp to reorder or trim the context instead of passing everything in
export const contextEngineering = async ({
messages = [],
@@ -109,6 +143,8 @@ export const contextEngineering = async ({
topicId,
memoryContext,
}: ContextEngineeringContext): Promise<OpenAIChatMessage[]> => {
+ messages = preprocessActionTags(messages);
+
log('tools: %o', tools);
// Check if Agent Builder tool is enabled
@@ -465,6 +501,20 @@ export const contextEngineering = async ({
);
}
+ // Inject mentionedAgents independently of isAgentManagementEnabled.
+ // When user @mentions an agent, delegation context must always be injected
+ // even if the agent doesn't have agent-management tool in its config.
+ const hasMentionedAgents =
+ initialContext?.mentionedAgents && initialContext.mentionedAgents.length > 0;
+
+ if (hasMentionedAgents) {
+ agentManagementContext = {
+ ...agentManagementContext,
+ mentionedAgents: initialContext!.mentionedAgents,
+ };
+ log('mentionedAgents injected: %d agents', initialContext!.mentionedAgents!.length);
+ }
+
// Create MessagesEngine with injected dependencies
const engine = new MessagesEngine({
// Agent configuration
@@ -529,7 +579,7 @@ export const contextEngineering = async ({
// Extended contexts - only pass when enabled
...(isAgentBuilderEnabled && { agentBuilderContext }),
...(isGroupAgentBuilderEnabled && { groupAgentBuilderContext }),
- ...(isAgentManagementEnabled && { agentManagementContext }),
+ ...((isAgentManagementEnabled || hasMentionedAgents) && { agentManagementContext }),
...(agentGroup && { agentGroup }),
...(gtdConfig && { gtd: gtdConfig }),
});
diff --git a/src/services/chat/mecha/skillPreload.test.ts b/src/services/chat/mecha/skillPreload.test.ts
new file mode 100644
index 00000000000..99cc6de23ea
--- /dev/null
+++ b/src/services/chat/mecha/skillPreload.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import * as toolStoreModule from '@/store/tool';
+
+import { prepareSelectedSkillPreload } from './skillPreload';
+
+describe('prepareSelectedSkillPreload', () => {
+ it('should sanitize skill action tags and build persisted preload messages', async () => {
+ vi.spyOn(toolStoreModule, 'getToolStoreState').mockReturnValue({
+ agentSkillDetailMap: {},
+ agentSkills: [],
+ builtinSkills: [
+ {
+ content: 'Use grep to search the codebase.',
+ description: 'Search code with ripgrep',
+ identifier: 'grep',
+ name: 'Grep',
+ source: 'builtin',
+ },
+ ],
+ } as any);
+
+ const result = await prepareSelectedSkillPreload({
+ message: '<action type="grep" category="skill" /> hi',
+ selectedSkills: [{ identifier: 'grep', name: 'Grep' }],
+ });
+
+ expect(result).toHaveLength(2);
+ expect(result[0]).toEqual(
+ expect.objectContaining({
+ content: '',
+ role: 'assistant',
+ tools: [
+ expect.objectContaining({
+ apiName: 'activateSkill',
+ arguments: JSON.stringify({ name: 'Grep' }),
+ id: expect.any(String),
+ identifier: 'lobe-skills',
+ type: 'builtin',
+ }),
+ ],
+ }),
+ );
+ expect(result[1]).toEqual(
+ expect.objectContaining({
+ content: 'Use grep to search the codebase.',
+ plugin: expect.objectContaining({
+ apiName: 'activateSkill',
+ arguments: JSON.stringify({ name: 'Grep' }),
+ identifier: 'lobe-skills',
+ type: 'builtin',
+ }),
+ role: 'tool',
+ tool_call_id: result[0].tools?.[0].id,
+ }),
+ );
+ });
+});
diff --git a/src/services/chat/mecha/skillPreload.ts b/src/services/chat/mecha/skillPreload.ts
new file mode 100644
index 00000000000..8614096e0fd
--- /dev/null
+++ b/src/services/chat/mecha/skillPreload.ts
@@ -0,0 +1,162 @@
+import { SkillsApiName, SkillsIdentifier } from '@lobechat/builtin-tool-skills';
+import { resourcesTreePrompt } from '@lobechat/prompts';
+import type { RuntimeSelectedSkill, SendPreloadMessage } from '@lobechat/types';
+import { nanoid } from '@lobechat/utils';
+
+import { agentSkillService } from '@/services/skill';
+import { getToolStoreState } from '@/store/tool';
+
+interface PreloadedSkill {
+ content: string;
+ identifier: string;
+ name: string;
+}
+
+interface PrepareSelectedSkillPreloadParams {
+ message: string;
+ selectedSkills?: RuntimeSelectedSkill[];
+}
+
+const ACTION_TAG_REGEX = /<action\b([^>]*)\/>/g;
+
+const getActionAttr = (attrs: string, name: string): string | undefined => {
+ const match = new RegExp(`${name}="([^"]*)"`, 'i').exec(attrs);
+ return match?.[1];
+};
+
+const cleanupWhitespace = (text: string) =>
+ text
+ .replaceAll(/[ \t]{2,}/g, ' ')
+ .replaceAll(/\n{3,}/g, '\n\n')
+ .trim();
+
+const extractSelectedSkillsFromText = (text: string): RuntimeSelectedSkill[] => {
+ const parsedSkills: RuntimeSelectedSkill[] = [];
+
+ for (const match of text.matchAll(ACTION_TAG_REGEX)) {
+ const attrs = match[1] || '';
+ if (getActionAttr(attrs, 'category') !== 'skill') continue;
+
+ const identifier = getActionAttr(attrs, 'type');
+
+ if (!identifier) continue;
+
+ parsedSkills.push({
+ identifier,
+ name: getActionAttr(attrs, 'label') || identifier,
+ });
+ }
+
+ return parsedSkills;
+};
+
+export const stripActionTagsFromText = (text: string) =>
+ cleanupWhitespace(text.replaceAll(ACTION_TAG_REGEX, ''));
+
+const resolveSelectedSkills = (
+ message: string,
+ selectedSkills?: RuntimeSelectedSkill[],
+): RuntimeSelectedSkill[] => {
+ const mergedSkills = [...(selectedSkills || []), ...extractSelectedSkillsFromText(message)];
+ const seen = new Set<string>();
+
+ return mergedSkills.reduce<RuntimeSelectedSkill[]>((acc, skill) => {
+ if (!skill.identifier || seen.has(skill.identifier)) return acc;
+
+ seen.add(skill.identifier);
+ acc.push(skill);
+ return acc;
+ }, []);
+};
+
+const loadSkillContent = async (
+ selectedSkill: RuntimeSelectedSkill,
+): Promise<PreloadedSkill | undefined> => {
+ const toolState = getToolStoreState();
+
+ const builtinSkill = (toolState.builtinSkills || []).find(
+ (skill) => skill.identifier === selectedSkill.identifier,
+ );
+
+ if (builtinSkill) {
+ return {
+ content: builtinSkill.content,
+ identifier: builtinSkill.identifier,
+ name: builtinSkill.name,
+ };
+ }
+
+ const listItem = (toolState.agentSkills || []).find(
+ (skill) => skill.identifier === selectedSkill.identifier,
+ );
+
+ const detail =
+ (listItem && toolState.agentSkillDetailMap?.[listItem.id]) ||
+ (listItem ? await agentSkillService.getById(listItem.id) : undefined) ||
+ (await agentSkillService.getByIdentifier(selectedSkill.identifier));
+
+ if (!detail?.content) return undefined;
+
+ const hasResources = !!(detail.resources && Object.keys(detail.resources).length > 0);
+ const content = hasResources
+ ? detail.content + '\n\n' + resourcesTreePrompt(detail.name, detail.resources!)
+ : detail.content;
+
+ return {
+ content,
+ identifier: detail.identifier,
+ name: detail.name,
+ };
+};
+
+const buildPersistedPreloadMessages = (skills: PreloadedSkill[]): SendPreloadMessage[] =>
+ skills.flatMap((skill, index) => {
+ const toolCallId = `selected_skill_${index}_${nanoid()}`;
+ const args = JSON.stringify({ name: skill.name });
+
+ return [
+ {
+ content: '',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: SkillsApiName.activateSkill,
+ arguments: args,
+ id: toolCallId,
+ identifier: SkillsIdentifier,
+ type: 'builtin',
+ },
+ ],
+ },
+ {
+ content: skill.content,
+ plugin: {
+ apiName: SkillsApiName.activateSkill,
+ arguments: args,
+ identifier: SkillsIdentifier,
+ type: 'builtin',
+ },
+ role: 'tool',
+ tool_call_id: toolCallId,
+ },
+ ];
+ });
+
+export const prepareSelectedSkillPreload = async ({
+ message,
+ selectedSkills,
+}: PrepareSelectedSkillPreloadParams): Promise<SendPreloadMessage[]> => {
+ const resolvedSelectedSkills = resolveSelectedSkills(message, selectedSkills);
+
+ if (resolvedSelectedSkills.length === 0) {
+ return [];
+ }
+
+ const resolvedSkills = (
+ await Promise.all(
+ resolvedSelectedSkills.map((selectedSkill) => loadSkillContent(selectedSkill)),
+ )
+ ).filter((skill): skill is PreloadedSkill => !!skill);
+
+ return buildPersistedPreloadMessages(resolvedSkills);
+};
diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
index a6e8329acc2..ca5f8e5c0fb 100644
--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts
@@ -4,6 +4,7 @@ import { type MessageToolCall } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import { chatService } from '@/services/chat';
+import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';
import {
createAssistantMessage,
@@ -168,6 +169,93 @@ describe('call_llm executor', () => {
);
});
+ it('should merge activated tools even when selectedTools are provided', async () => {
+ const mockStore = createMockStore();
+ const context = createTestContext();
+ const userMsg = createUserMessage({ content: 'Use notebook' });
+ const instruction = createCallLLMInstruction({
+ model: 'gpt-4',
+ provider: 'openai',
+ messages: [userMsg],
+ });
+ const state = createInitialState();
+ const notebookTool = {
+ function: { name: 'lobe-notebook____createDocument' },
+ type: 'function',
+ } as const;
+ const activatedTool = {
+ function: { name: 'lobe-skills____runSkill' },
+ type: 'function',
+ } as const;
+ const toolsEngine = {
+ generateToolsDetailed: vi.fn().mockReturnValue({
+ enabledManifests: [{ identifier: 'lobe-skills' }],
+ enabledToolIds: ['lobe-skills'],
+ tools: [activatedTool],
+ }),
+ };
+
+ mockStreamResponse({ content: 'AI response' });
+ mockStore.dbMessagesMap[context.messageKey] = [];
+ mockStore.operations[context.operationId] = {
+ abortController: new AbortController(),
+ childOperationIds: [],
+ context: {
+ agentId: context.agentId,
+ messageId: context.parentId,
+ topicId: context.topicId,
+ },
+ id: context.operationId,
+ metadata: { startTime: Date.now() },
+ status: 'running',
+ type: 'execAgentRuntime',
+ } as any;
+
+ const executors = createAgentExecutors({
+ agentConfig: {
+ agentConfig: { model: 'gpt-4', provider: 'openai' } as any,
+ chatConfig: {} as any,
+ enabledManifests: [{ identifier: 'lobe-notebook' }] as any,
+ enabledToolIds: ['lobe-notebook'],
+ isBuiltinAgent: false,
+ plugins: ['lobe-notebook'],
+ tools: [notebookTool] as any,
+ },
+ get: () => mockStore,
+ messageKey: context.messageKey,
+ operationId: context.operationId,
+ parentId: context.parentId,
+ toolsEngine: toolsEngine as any,
+ });
+
+ await executors.call_llm!(instruction, state, {
+ initialContext: {
+ selectedTools: [{ identifier: 'lobe-notebook', name: 'Notebook' }],
+ },
+ phase: 'init',
+ stepContext: {
+ activatedToolIds: ['lobe-skills', 'lobe-tools'],
+ },
+ } as any);
+
+ expect(toolsEngine.generateToolsDetailed).toHaveBeenCalledWith(
+ expect.objectContaining({
+ skipDefaultTools: true,
+ toolIds: ['lobe-skills', 'lobe-tools'],
+ }),
+ );
+ expect(chatService.createAssistantMessageStream).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ resolvedAgentConfig: expect.objectContaining({
+ enabledToolIds: ['lobe-notebook', 'lobe-skills'],
+ tools: [notebookTool, activatedTool],
+ }),
+ }),
+ }),
+ );
+ });
+
it('should associate message with operation', async () => {
// Given
const mockStore = createMockStore();
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 2ff5ea6753a..b5376c4a94d 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -42,6 +42,7 @@ import { messageService } from '@/services/message';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { getAgentStoreState } from '@/store/agent/store';
import { type ChatStore } from '@/store/chat/store';
+import { getCompressionCandidateMessageIds } from '@/store/chat/utils/compression';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { getFileStoreState } from '@/store/file/store';
import { sleep } from '@/utils/sleep';
@@ -57,6 +58,16 @@ const TOOL_PRICING: Record<string, number> = {
'lobe-web-browsing/search': 0.001,
};
+const isAbortError = (error: unknown, abortController?: AbortController) =>
+ !!abortController?.signal.aborted ||
+ (error instanceof Error &&
+ (error.name === 'AbortError' ||
+ error.message.includes('aborted') ||
+ error.message.includes('cancelled')));
+
+const createAbortError = () =>
+ Object.assign(new Error('Compression cancelled'), { name: 'AbortError' });
+
/**
* Creates custom executors for the Chat Agent Runtime
* These executors wrap existing chat store methods to integrate with agent-runtime
@@ -2534,7 +2545,7 @@ export const createAgentExecutors = (context: {
// Get message IDs from dbMessagesMap (raw db messages)
const dbMessages = context.get().dbMessagesMap[context.messageKey] || [];
- const messageIds = dbMessages.map((m) => m.id).filter(Boolean);
+ const messageIds = getCompressionCandidateMessageIds(dbMessages);
if (!topicId || messageIds.length === 0) {
// No topicId or no messages, skip compression
@@ -2618,13 +2629,16 @@ export const createAgentExecutors = (context: {
let summaryContent = '';
// Start generateSummary operation attached to the compressed group message
- const { operationId: summaryOperationId } = context.get().startOperation({
- context: { ...getOperationContext(), messageId: messageGroupId },
- type: 'generateSummary',
- parentOperationId: compressOperationId,
- });
+ const { abortController: summaryAbortController, operationId: summaryOperationId } = context
+ .get()
+ .startOperation({
+ context: { ...getOperationContext(), messageId: messageGroupId },
+ type: 'generateSummary',
+ parentOperationId: compressOperationId,
+ });
await chatService.fetchPresetTaskResult({
+ abortController: summaryAbortController,
params: { ...compressionPayload, model, provider },
onMessageHandle: (chunk) => {
if (chunk.type === 'text') {
@@ -2646,6 +2660,8 @@ export const createAgentExecutors = (context: {
},
});
+ if (summaryAbortController.signal.aborted) throw createAbortError();
+
log(`${stagePrefix} Generated summary: %d chars`, summaryContent.length);
// 5. Finalize compression with actual content
@@ -2701,6 +2717,34 @@ export const createAgentExecutors = (context: {
} as AgentRuntimeContext,
};
} catch (error) {
+ if (isAbortError(error)) {
+ log(`${stagePrefix} Compression cancelled`);
+
+ if (context.get().operations[compressOperationId]?.status === 'running') {
+ context.get().completeOperation(compressOperationId, { cancelled: true });
+ }
+
+ events.push({ type: 'compression_error', error });
+
+ return {
+ events,
+ newState: state,
+ nextContext: {
+ payload: {
+ compressedMessages: messages,
+ skipped: true,
+ } as GeneralAgentCompressionResultPayload,
+ phase: 'compression_result',
+ session: {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ }
+
log(`${stagePrefix} Compression failed: %O`, error);
// Complete the compress_context operation with error
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
index d5571009a89..ba21e04bf4b 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
@@ -1,10 +1,14 @@
import { act, renderHook } from '@testing-library/react';
+import { TRPCClientError } from '@trpc/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { aiChatService } from '@/services/aiChat';
+import { chatService } from '@/services/chat';
+import { messageService } from '@/services/message';
import * as agentGroupStore from '@/store/agentGroup';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { getSessionStoreState } from '@/store/session';
+import * as toolStoreModule from '@/store/tool';
import { useChatStore } from '../../../../store';
import { createMockMessage, TEST_CONTENT, TEST_IDS } from './fixtures';
@@ -36,6 +40,7 @@ beforeEach(() => {
refreshMessages: vi.fn(),
refreshTopic: vi.fn(),
internal_execAgentRuntime: vi.fn(),
+ mainInputEditor: null,
});
});
});
@@ -96,6 +101,104 @@ describe('ConversationLifecycle actions', () => {
});
describe('message creation', () => {
+ it('should render pending compressedGroup immediately for /compact', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const topicId = TEST_IDS.TOPIC_ID;
+ const agentId = TEST_IDS.SESSION_ID;
+ const key = messageMapKey({ agentId, topicId });
+ const existingMessages = [
+ createMockMessage({ id: 'user-1', role: 'user', topicId }),
+ createMockMessage({ id: 'assistant-1', role: 'assistant', topicId }),
+ ];
+
+ await act(async () => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ dbMessagesMap: { [key]: existingMessages },
+ messagesMap: { [key]: existingMessages },
+ });
+ });
+
+ const createCompressionGroupSpy = vi
+ .spyOn(messageService, 'createCompressionGroup')
+ .mockResolvedValue({
+ messageGroupId: 'group-1',
+ messages: [
+ {
+ id: 'group-1',
+ content: '...',
+ role: 'compressedGroup',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ } as any,
+ ],
+ messagesToSummarize: existingMessages,
+ });
+ vi.spyOn(chatService, 'fetchPresetTaskResult').mockResolvedValue(undefined);
+ vi.spyOn(messageService, 'finalizeCompression').mockResolvedValue({
+ messages: [
+ {
+ id: 'group-1',
+ content: 'summary',
+ role: 'compressedGroup',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ } as any,
+ ],
+ });
+
+ const optimisticCreateTmpMessageSpy = vi.spyOn(
+ result.current,
+ 'optimisticCreateTmpMessage',
+ );
+ const internalDispatchMessageSpy = vi.spyOn(result.current, 'internal_dispatchMessage');
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId, topicId, threadId: null },
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'command',
+ actionLabel: 'Compact context',
+ actionType: 'compact',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ } as any,
+ message: '',
+ });
+ });
+
+ expect(optimisticCreateTmpMessageSpy).not.toHaveBeenCalled();
+ expect(internalDispatchMessageSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: expect.stringMatching(/^tmp_compress_/),
+ type: 'createMessage',
+ value: expect.objectContaining({
+ compressedMessages: [],
+ content: '...',
+ role: 'compressedGroup',
+ }),
+ }),
+ expect.any(Object),
+ );
+ expect(createCompressionGroupSpy).toHaveBeenCalledWith({
+ agentId,
+ messageIds: ['user-1', 'assistant-1'],
+ topicId,
+ });
+ });
+
it('should not process AI when onlyAddUserMessage is true', async () => {
const { result } = renderHook(() => useChatStore());
@@ -116,6 +219,58 @@ describe('ConversationLifecycle actions', () => {
expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();
});
+ it('should restore the pre-send editor snapshot when server send fails', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const inputEditorState = {
+ root: {
+ children: [
+ {
+ children: [{ text: 'Restored rich text', type: 'text', version: 1 }],
+ type: 'paragraph',
+ version: 1,
+ },
+ ],
+ type: 'root',
+ version: 1,
+ },
+ };
+ const clearedEditorState = {
+ root: { children: [], type: 'root', version: 1 },
+ };
+ const setDocument = vi.fn();
+ const setJSONState = vi.fn();
+
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockRejectedValue(
+ new TRPCClientError('restore failed'),
+ );
+
+ act(() => {
+ useChatStore.setState({
+ mainInputEditor: {
+ getJSONState: vi.fn().mockReturnValue(clearedEditorState),
+ setDocument,
+ setJSONState,
+ } as any,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: createTestContext(),
+ editorData: inputEditorState as any,
+ message: 'Restored rich text',
+ });
+ });
+
+ const sendMessageOperation = Object.values(result.current.operations).find(
+ (operation) => operation.type === 'sendMessage',
+ );
+
+ expect(sendMessageOperation?.metadata.inputEditorTempState).toEqual(inputEditorState);
+ expect(setJSONState).toHaveBeenCalledWith(inputEditorState);
+ expect(setDocument).not.toHaveBeenCalled();
+ });
+
it('should create user message and trigger AI processing', async () => {
const { result } = renderHook(() => useChatStore());
@@ -138,6 +293,143 @@ describe('ConversationLifecycle actions', () => {
expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();
});
+ it('should persist selected slash skills as preload messages before sending', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const sendMessageInServerSpy = vi
+ .spyOn(aiChatService, 'sendMessageInServer')
+ .mockResolvedValue({
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topics: [],
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+ vi.spyOn(toolStoreModule, 'getToolStoreState').mockReturnValue({
+ agentSkillDetailMap: {},
+ agentSkills: [],
+ builtinSkills: [
+ {
+ content: 'Use the user memory skill content.',
+ description: 'Load user memory',
+ identifier: 'user_memory',
+ name: 'User Memory',
+ source: 'builtin',
+ },
+ {
+ content: 'Use the instruction skill content.',
+ description: 'Load instruction',
+ identifier: 'instruction',
+ name: 'Instruction',
+ source: 'builtin',
+ },
+ ],
+ } as any);
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: createTestContext(),
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory',
+ actionType: 'user_memory',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'skill',
+ actionLabel: 'Instruction',
+ actionType: 'instruction',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ } as any,
+ message: '<action type="user_memory" category="skill" /> ' + TEST_CONTENT.USER_MESSAGE,
+ });
+ });
+
+ expect(sendMessageInServerSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ newUserMessage: expect.objectContaining({
+ content:
+ '<action type="user_memory" category="skill" /> ' + TEST_CONTENT.USER_MESSAGE,
+ editorData: expect.objectContaining({
+ root: expect.any(Object),
+ }),
+ }),
+ preloadMessages: [
+ expect.objectContaining({
+ content: '',
+ role: 'assistant',
+ tools: [
+ expect.objectContaining({
+ apiName: 'activateSkill',
+ arguments: JSON.stringify({ name: 'User Memory' }),
+ identifier: 'lobe-skills',
+ }),
+ ],
+ }),
+ expect.objectContaining({
+ content: 'Use the user memory skill content.',
+ role: 'tool',
+ }),
+ expect.objectContaining({
+ content: '',
+ role: 'assistant',
+ tools: [
+ expect.objectContaining({
+ apiName: 'activateSkill',
+ arguments: JSON.stringify({ name: 'Instruction' }),
+ identifier: 'lobe-skills',
+ }),
+ ],
+ }),
+ expect.objectContaining({
+ content: 'Use the instruction skill content.',
+ role: 'tool',
+ }),
+ ],
+ }),
+ expect.any(AbortController),
+ );
+ expect(
+ sendMessageInServerSpy.mock.calls[0]?.[0].newUserMessage.editorData?.root.children[0]
+ .children,
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ actionCategory: 'skill',
+ actionType: 'user_memory',
+ type: 'action-tag',
+ }),
+ ]),
+ );
+ expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({
+ initialContext: expect.objectContaining({
+ initialContext: {
+ selectedSkills: [
+ { identifier: 'user_memory', name: 'User Memory' },
+ { identifier: 'instruction', name: 'Instruction' },
+ ],
+ },
+ phase: 'init',
+ }),
+ }),
+ );
+ });
+
it('should work when sending from home page (activeAgentId is empty but context.agentId exists)', async () => {
const { result } = renderHook(() => useChatStore());
@@ -182,6 +474,65 @@ describe('ConversationLifecycle actions', () => {
);
expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();
});
+
+ it('should pass selected tool tags into runtime initialContext', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topics: [],
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: createTestContext(),
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Artifacts',
+ actionType: 'lobe-artifacts',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ } as any,
+ message: TEST_CONTENT.USER_MESSAGE,
+ });
+ });
+
+ expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({
+ initialContext: expect.objectContaining({
+ initialContext: {
+ selectedTools: [
+ { identifier: 'lobe-notebook', name: 'Notebook' },
+ { identifier: 'lobe-artifacts', name: 'Artifacts' },
+ ],
+ },
+ phase: 'init',
+ }),
+ }),
+ );
+ });
});
describe('group chat supervisor metadata', () => {
@@ -420,6 +771,131 @@ describe('ConversationLifecycle actions', () => {
});
});
+ describe('@agent mention delegation', () => {
+ it('should NOT set isSupervisor on assistant message when @agent is mentioned in non-group chat', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const sendMessageInServerSpy = vi
+ .spyOn(aiChatService, 'sendMessageInServer')
+ .mockResolvedValue({
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topics: [],
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+
+ await act(async () => {
+ await result.current.sendMessage({
+ message: '@Agent A hello',
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'Agent A',
+ metadata: { id: 'agent-a', type: 'agent' },
+ type: 'mention',
+ },
+ { text: ' hello', type: 'text' },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ } as any,
+ // Non-group context: no groupId
+ context: createTestContext(),
+ });
+ });
+
+ // Assistant message metadata should NOT contain isSupervisor
+ expect(sendMessageInServerSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ newAssistantMessage: expect.objectContaining({
+ metadata: undefined,
+ }),
+ }),
+ expect.any(AbortController),
+ );
+
+ // But runtime should receive mentionedAgents in initialContext
+ expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({
+ initialContext: expect.objectContaining({
+ initialContext: expect.objectContaining({
+ mentionedAgents: [{ id: 'agent-a', name: 'Agent A' }],
+ }),
+ }),
+ }),
+ );
+ });
+
+ it('should NOT inject mentionedAgents into initialContext when in group chat', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ // Mock group store so groupId resolves
+ vi.spyOn(agentGroupStore, 'getChatGroupStoreState').mockReturnValue({
+ groupMap: {
+ 'test-group': {
+ id: 'test-group',
+ supervisorAgentId: 'supervisor-id',
+ },
+ },
+ } as any);
+
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topics: [],
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+
+ await act(async () => {
+ await result.current.sendMessage({
+ message: '@Agent A in group',
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'Agent A',
+ metadata: { id: 'agent-a', type: 'agent' },
+ type: 'mention',
+ },
+ { text: ' in group', type: 'text' },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ } as any,
+ // Group context
+ context: {
+ agentId: 'sub-agent-id',
+ groupId: 'test-group',
+ topicId: null,
+ threadId: null,
+ },
+ });
+ });
+
+ // Runtime should NOT receive mentionedAgents in group context
+ const execCall = (result.current.internal_execAgentRuntime as any).mock.calls[0]?.[0];
+ const initialCtx = execCall?.initialContext?.initialContext;
+ expect(initialCtx?.mentionedAgents).toBeUndefined();
+ });
+ });
+
describe('new topic creation cleanup', () => {
it('should clear _new key data when new topic is created', async () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
index e9566d39414..6ff9fd338a9 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
@@ -2,8 +2,10 @@ import { type UIChatMessage } from '@lobechat/types';
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as toolEngineering from '@/helpers/toolEngineering';
import { chatService } from '@/services/chat';
import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';
+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
import { useChatStore } from '../../../../store';
import {
@@ -787,6 +789,190 @@ describe('StreamingExecutor actions', () => {
streamSpy.mockRestore();
});
+
+ it('should merge provided initialContext with runtime page editor context', () => {
+ act(() => {
+ useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const userMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: TEST_CONTENT.USER_MESSAGE,
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig(),
+ chatConfig: createMockChatConfig(),
+ isBuiltinAgent: false,
+ plugins: ['lobe-page-agent'],
+ });
+ vi.spyOn(toolEngineering, 'createAgentToolsEngine').mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({
+ enabledManifests: [],
+ enabledToolIds: ['lobe-page-agent'],
+ tools: [],
+ }),
+ } as any);
+ vi.spyOn(pageAgentRuntime, 'getPageContentContext').mockReturnValue({
+ markdown: '# Test Document',
+ xml: '<root><h1>Test</h1></root>',
+ metadata: { title: 'Test Doc', charCount: 15, lineCount: 1 },
+ });
+
+ const { context } = result.current.internal_createAgentState({
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ agentId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ initialContext: {
+ phase: 'init',
+ initialContext: {
+ selectedSkills: [{ identifier: 'user_memory', name: 'User Memory' }],
+ selectedTools: [{ identifier: 'lobe-notebook', name: 'Notebook' }],
+ },
+ },
+ });
+
+ expect(context.initialContext).toEqual({
+ pageEditor: {
+ markdown: '# Test Document',
+ xml: '<root><h1>Test</h1></root>',
+ metadata: { title: 'Test Doc', charCount: 15, lineCount: 1 },
+ },
+ selectedSkills: [{ identifier: 'user_memory', name: 'User Memory' }],
+ selectedTools: [{ identifier: 'lobe-notebook', name: 'Notebook' }],
+ });
+ });
+
+ it('should merge selectedTools into generated tools when provided', () => {
+ act(() => {
+ useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const userMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: TEST_CONTENT.USER_MESSAGE,
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+
+ const generateToolsDetailed = vi.fn().mockReturnValue({
+ enabledManifests: [],
+ enabledToolIds: ['lobe-notebook'],
+ tools: [],
+ });
+
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig(),
+ chatConfig: createMockChatConfig(),
+ isBuiltinAgent: false,
+ plugins: ['lobe-artifacts'],
+ });
+ vi.spyOn(toolEngineering, 'createAgentToolsEngine').mockReturnValue({
+ generateToolsDetailed,
+ } as any);
+
+ result.current.internal_createAgentState({
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ agentId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ initialContext: {
+ phase: 'init',
+ initialContext: {
+ selectedTools: [{ identifier: 'lobe-notebook', name: 'Notebook' }],
+ },
+ },
+ });
+
+ expect(generateToolsDetailed).toHaveBeenCalledWith(
+ expect.objectContaining({
+ skipDefaultTools: undefined,
+ toolIds: ['lobe-artifacts', 'lobe-notebook'],
+ }),
+ );
+ });
+
+ it('should pass merged resolvedAgentConfig to chatService when selectedTools are provided', async () => {
+ act(() => {
+ useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const userMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: TEST_CONTENT.USER_MESSAGE,
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig(),
+ chatConfig: createMockChatConfig(),
+ isBuiltinAgent: false,
+ plugins: ['lobe-artifacts'],
+ });
+ vi.spyOn(toolEngineering, 'createAgentToolsEngine').mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({
+ enabledManifests: [{ identifier: 'lobe-artifacts' }, { identifier: 'lobe-notebook' }],
+ enabledToolIds: ['lobe-artifacts', 'lobe-notebook'],
+ tools: [
+ {
+ function: { name: 'lobe-artifacts____create' },
+ type: 'function',
+ },
+ {
+ function: { name: 'lobe-notebook____createDocument' },
+ type: 'function',
+ },
+ ],
+ }),
+ } as any);
+
+ const streamSpy = vi
+ .spyOn(chatService, 'createAssistantMessageStream')
+ .mockImplementation(async ({ onFinish, params }) => {
+ expect(params.resolvedAgentConfig.enabledToolIds).toEqual([
+ 'lobe-artifacts',
+ 'lobe-notebook',
+ ]);
+ expect(params.resolvedAgentConfig.tools).toEqual([
+ {
+ function: { name: 'lobe-artifacts____create' },
+ type: 'function',
+ },
+ {
+ function: { name: 'lobe-notebook____createDocument' },
+ type: 'function',
+ },
+ ]);
+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
+ });
+
+ await act(async () => {
+ await result.current.internal_execAgentRuntime({
+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
+ initialContext: {
+ phase: 'init',
+ initialContext: {
+ selectedTools: [{ identifier: 'lobe-notebook', name: 'Notebook' }],
+ },
+ },
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ parentMessageType: 'user',
+ });
+ });
+
+ expect(streamSpy).toHaveBeenCalled();
+ });
});
describe('internal_createAgentState with disableTools', () => {
diff --git a/src/store/chat/slices/aiChat/actions/commandBus/editorDataHelpers.ts b/src/store/chat/slices/aiChat/actions/commandBus/editorDataHelpers.ts
new file mode 100644
index 00000000000..dfe2d1343e0
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/commandBus/editorDataHelpers.ts
@@ -0,0 +1,45 @@
+/**
+ * Inject a refer-topic node at the beginning of editorData.
+ * Prepends a new paragraph containing the refer-topic node before existing content.
+ */
+export const injectReferTopicNode = (
+ editorData: Record<string, any> | undefined,
+ topicId: string,
+ topicTitle: string,
+): Record<string, any> => {
+ const referTopicNode = {
+ type: 'refer-topic',
+ topicId,
+ topicTitle,
+ version: 1,
+ };
+
+ const referParagraph = {
+ children: [referTopicNode],
+ direction: 'ltr',
+ format: '',
+ indent: 0,
+ type: 'paragraph',
+ version: 1,
+ };
+
+ // If no editorData, create a minimal structure with just the referTopic
+ if (!editorData?.root) {
+ return {
+ root: {
+ children: [referParagraph],
+ direction: 'ltr',
+ format: '',
+ indent: 0,
+ type: 'root',
+ version: 1,
+ },
+ };
+ }
+
+ // Deep clone and prepend refer-topic paragraph
+ const cloned = structuredClone(editorData);
+ const existingChildren = cloned.root.children || [];
+ cloned.root.children = [referParagraph, ...existingChildren];
+ return cloned;
+};
diff --git a/src/store/chat/slices/aiChat/actions/commandBus/handlers.ts b/src/store/chat/slices/aiChat/actions/commandBus/handlers.ts
new file mode 100644
index 00000000000..0949390c188
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/commandBus/handlers.ts
@@ -0,0 +1,17 @@
+import type { CommandHandler } from './types';
+
+/**
+ * /newTopic — Force the message to be sent in a brand-new topic,
+ * regardless of the current topic context.
+ */
+export const newTopicHandler: CommandHandler = () => {
+ return { forceNewTopic: true };
+};
+
+/**
+ * /compact — Compress the current conversation context.
+ * Triggers a history summarization instead of normal AI response.
+ */
+export const compactHandler: CommandHandler = () => {
+ return { triggerCompression: true };
+};
diff --git a/src/store/chat/slices/aiChat/actions/commandBus/index.ts b/src/store/chat/slices/aiChat/actions/commandBus/index.ts
new file mode 100644
index 00000000000..cde05ab4b1a
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/commandBus/index.ts
@@ -0,0 +1,47 @@
+import type { CommandType } from '@/features/ChatInput/InputEditor/ActionTag/types';
+
+import type { SendMessageWithContextParams } from '../conversationLifecycle';
+import { compactHandler, newTopicHandler } from './handlers';
+import { parseCommandsFromEditorData } from './parseCommands';
+import type { CommandHandlerContext, CommandRegistry, CommandSendOverrides } from './types';
+
+export { injectReferTopicNode } from './editorDataHelpers';
+export {
+ hasNonActionContent,
+ parseCommandsFromEditorData,
+ parseMentionedAgentsFromEditorData,
+ parseSelectedSkillsFromEditorData,
+ parseSelectedToolsFromEditorData,
+} from './parseCommands';
+export type { CommandSendOverrides } from './types';
+
+const COMMAND_REGISTRY: CommandRegistry = {
+ compact: compactHandler,
+ newTopic: newTopicHandler,
+};
+
+/**
+ * Process all command tags found in editorData.
+ * Returns merged overrides from all matched command handlers.
+ */
+export const processCommands = (params: SendMessageWithContextParams): CommandSendOverrides => {
+ const commands = parseCommandsFromEditorData(params.editorData);
+ const commandTags = commands.filter((c) => c.category === 'command');
+
+ if (commandTags.length === 0) return {};
+
+ const ctx: CommandHandlerContext = { params };
+ let merged: CommandSendOverrides = {};
+
+ for (const tag of commandTags) {
+ const handler = COMMAND_REGISTRY[tag.type as CommandType];
+ if (handler) {
+ const overrides = handler(ctx);
+ if (overrides) {
+ merged = { ...merged, ...overrides };
+ }
+ }
+ }
+
+ return merged;
+};
diff --git a/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.test.ts b/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.test.ts
new file mode 100644
index 00000000000..807d8d6a6c5
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.test.ts
@@ -0,0 +1,502 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ parseCommandsFromEditorData,
+ parseMentionedAgentsFromEditorData,
+ parseSelectedSkillsFromEditorData,
+ parseSelectedToolsFromEditorData,
+} from './parseCommands';
+
+describe('parseCommandsFromEditorData', () => {
+ it('should return empty array for undefined editorData', () => {
+ expect(parseCommandsFromEditorData(undefined)).toEqual([]);
+ });
+
+ it('should return empty array for editorData with no action tags', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [{ text: 'hello', type: 'text' }],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+ expect(parseCommandsFromEditorData(editorData)).toEqual([]);
+ });
+
+ it('should extract command tags from editorData', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'command',
+ actionLabel: 'Send in new topic',
+ actionType: 'newTopic',
+ type: 'action-tag',
+ },
+ { text: ' some message', type: 'text' },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ const result = parseCommandsFromEditorData(editorData);
+ expect(result).toEqual([{ category: 'command', label: 'Send in new topic', type: 'newTopic' }]);
+ });
+
+ it('should extract multiple tags in document order', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'command',
+ actionLabel: 'Send in new topic',
+ actionType: 'newTopic',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'skill',
+ actionLabel: 'Translate',
+ actionType: 'translate',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ const result = parseCommandsFromEditorData(editorData);
+ expect(result).toHaveLength(3);
+ expect(result[0].type).toBe('newTopic');
+ expect(result[1].type).toBe('translate');
+ expect(result[2].type).toBe('lobe-notebook');
+ });
+});
+
+describe('parseSelectedSkillsFromEditorData', () => {
+ it('should return selected skills only', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'command',
+ actionLabel: 'Compact context',
+ actionType: 'compact',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory',
+ actionType: 'user_memory',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'skill',
+ actionLabel: 'Instruction',
+ actionType: 'instruction',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseSelectedSkillsFromEditorData(editorData)).toEqual([
+ { identifier: 'user_memory', name: 'User Memory' },
+ { identifier: 'instruction', name: 'Instruction' },
+ ]);
+ });
+
+ it('should deduplicate selected skills by identifier', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory',
+ actionType: 'user_memory',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory Duplicate',
+ actionType: 'user_memory',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseSelectedSkillsFromEditorData(editorData)).toEqual([
+ { identifier: 'user_memory', name: 'User Memory' },
+ ]);
+ });
+
+ it('should ignore tool tags when selecting skills', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'skill',
+ actionLabel: 'User Memory',
+ actionType: 'user_memory',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseSelectedSkillsFromEditorData(editorData)).toEqual([
+ { identifier: 'user_memory', name: 'User Memory' },
+ ]);
+ });
+});
+
+describe('parseSelectedToolsFromEditorData', () => {
+ it('should return selected tools only', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'command',
+ actionLabel: 'Compact context',
+ actionType: 'compact',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Artifacts',
+ actionType: 'lobe-artifacts',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseSelectedToolsFromEditorData(editorData)).toEqual([
+ { identifier: 'lobe-notebook', name: 'Notebook' },
+ { identifier: 'lobe-artifacts', name: 'Artifacts' },
+ ]);
+ });
+
+ it('should deduplicate selected tools by identifier', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'tool',
+ actionLabel: 'Notebook Duplicate',
+ actionType: 'lobe-notebook',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseSelectedToolsFromEditorData(editorData)).toEqual([
+ { identifier: 'lobe-notebook', name: 'Notebook' },
+ ]);
+ });
+});
+
+describe('parseMentionedAgentsFromEditorData', () => {
+ it('should return empty array for undefined editorData', () => {
+ expect(parseMentionedAgentsFromEditorData(undefined)).toEqual([]);
+ });
+
+ it('should return empty array for editorData with no mention nodes', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [{ text: 'hello', type: 'text' }],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+ expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([]);
+ });
+
+ it('should extract agent mentions only (whitelist)', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'My Agent',
+ metadata: { id: 'agent-1', type: 'agent' },
+ type: 'mention',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
+ { id: 'agent-1', name: 'My Agent' },
+ ]);
+ });
+
+ it('should exclude topic mentions', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'Some Topic',
+ metadata: { id: 'topic-1', topicId: 'topic-1', type: 'topic' },
+ type: 'mention',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([]);
+ });
+
+ it('should exclude ALL_MEMBERS and other non-agent mentions', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'All Members',
+ metadata: { id: 'ALL_MEMBERS', type: 'all_members' },
+ type: 'mention',
+ },
+ {
+ label: 'Unknown',
+ metadata: { id: 'x', type: 'custom' },
+ type: 'mention',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([]);
+ });
+
+ it('should deduplicate agents by id', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'Agent A',
+ metadata: { id: 'agent-1', type: 'agent' },
+ type: 'mention',
+ },
+ {
+ label: 'Agent A again',
+ metadata: { id: 'agent-1', type: 'agent' },
+ type: 'mention',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
+ { id: 'agent-1', name: 'Agent A' },
+ ]);
+ });
+
+ it('should extract multiple distinct agent mentions', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'Agent A',
+ metadata: { id: 'agent-1', type: 'agent' },
+ type: 'mention',
+ },
+ {
+ label: 'Agent B',
+ metadata: { id: 'agent-2', type: 'agent' },
+ type: 'mention',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ const result = parseMentionedAgentsFromEditorData(editorData);
+ expect(result).toEqual([
+ { id: 'agent-1', name: 'Agent A' },
+ { id: 'agent-2', name: 'Agent B' },
+ ]);
+ });
+
+ it('should only extract agents when mixed with topic mentions', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: 'Topic X',
+ metadata: { id: 'topic-1', topicId: 'topic-1', type: 'topic' },
+ type: 'mention',
+ },
+ {
+ label: 'Agent Y',
+ metadata: { id: 'agent-y', type: 'agent' },
+ type: 'mention',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
+ { id: 'agent-y', name: 'Agent Y' },
+ ]);
+ });
+
+ it('should handle nested children correctly', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ children: [
+ {
+ label: 'Nested Agent',
+ metadata: { id: 'nested-1', type: 'agent' },
+ type: 'mention',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
+ { id: 'nested-1', name: 'Nested Agent' },
+ ]);
+ });
+
+ it('should use id as fallback name when label is empty', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ label: '',
+ metadata: { id: 'agent-no-label', type: 'agent' },
+ type: 'mention',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(parseMentionedAgentsFromEditorData(editorData)).toEqual([
+ { id: 'agent-no-label', name: 'agent-no-label' },
+ ]);
+ });
+});
diff --git a/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.ts b/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.ts
new file mode 100644
index 00000000000..22e484bdd85
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.ts
@@ -0,0 +1,166 @@
+import type {
+ RuntimeMentionedAgent,
+ RuntimeSelectedSkill,
+ RuntimeSelectedTool,
+} from '@lobechat/types';
+
+import type {
+ ActionTagCategory,
+ ActionTagType,
+} from '@/features/ChatInput/InputEditor/ActionTag/types';
+
+export interface ParsedActionTag {
+ category: ActionTagCategory;
+ label: string;
+ type: ActionTagType;
+}
+
+export interface ParsedCommand extends ParsedActionTag {}
+
+/**
+ * Walk the Lexical JSON tree to find all action-tag nodes.
+ * Returns the extracted action tags in document order.
+ */
+export const parseActionTagsFromEditorData = (
+ editorData: Record<string, any> | undefined,
+): ParsedActionTag[] => {
+ if (!editorData) return [];
+
+ const actionTags: ParsedActionTag[] = [];
+ walkNode(editorData.root, actionTags);
+ return actionTags;
+};
+
+export const parseCommandsFromEditorData = (
+ editorData: Record<string, any> | undefined,
+): ParsedCommand[] => parseActionTagsFromEditorData(editorData);
+
+export const parseSelectedSkillsFromEditorData = (
+ editorData: Record<string, any> | undefined,
+): RuntimeSelectedSkill[] => {
+ const actionTags = parseActionTagsFromEditorData(editorData);
+ const selectedSkills = actionTags.filter((tag) => tag.category === 'skill');
+
+ if (selectedSkills.length === 0) return [];
+
+ const seen = new Set<string>();
+
+ return selectedSkills.reduce<RuntimeSelectedSkill[]>((acc, skill) => {
+ const identifier = String(skill.type);
+ if (!identifier || seen.has(identifier)) return acc;
+
+ seen.add(identifier);
+ acc.push({
+ identifier,
+ name: skill.label || identifier,
+ });
+
+ return acc;
+ }, []);
+};
+
+export const parseSelectedToolsFromEditorData = (
+ editorData: Record<string, any> | undefined,
+): RuntimeSelectedTool[] => {
+ const actionTags = parseActionTagsFromEditorData(editorData);
+ const selectedTools = actionTags.filter((tag) => tag.category === 'tool');
+
+ if (selectedTools.length === 0) return [];
+
+ const seen = new Set<string>();
+
+ return selectedTools.reduce<RuntimeSelectedTool[]>((acc, tool) => {
+ const identifier = String(tool.type);
+ if (!identifier || seen.has(identifier)) return acc;
+
+ seen.add(identifier);
+ acc.push({
+ identifier,
+ name: tool.label || identifier,
+ });
+
+ return acc;
+ }, []);
+};
+
+/**
+ * Walk the editor JSON tree to find all mention nodes (type: 'mention')
+ * and extract agent info from their metadata.
+ */
+export const parseMentionedAgentsFromEditorData = (
+ editorData: Record<string, any> | undefined,
+): RuntimeMentionedAgent[] => {
+ if (!editorData) return [];
+
+ const agents: RuntimeMentionedAgent[] = [];
+ const seen = new Set<string>();
+
+ walkMentionNode(editorData.root, (label, metadata) => {
+ // Only accept explicit agent mentions — skip topics, ALL_MEMBERS, and other types
+ if (metadata?.type !== 'agent') return;
+ const id = metadata?.id as string | undefined;
+ if (!id || seen.has(id)) return;
+
+ seen.add(id);
+ agents.push({ id, name: label || id });
+ });
+
+ return agents;
+};
+
+/**
+ * Check if editorData contains any meaningful text content
+ * besides action-tag nodes (whitespace-only counts as empty).
+ */
+export const hasNonActionContent = (editorData: Record<string, any> | undefined): boolean => {
+ if (!editorData) return false;
+ const parts: string[] = [];
+ collectText(editorData.root, parts);
+ return parts.join('').trim().length > 0;
+};
+
+function collectText(node: any, out: string[]): void {
+ if (!node) return;
+ if (node.type === 'action-tag') return;
+ if (node.type === 'text' && typeof node.text === 'string') {
+ out.push(node.text);
+ }
+ if (Array.isArray(node.children)) {
+ for (const child of node.children) {
+ collectText(child, out);
+ }
+ }
+}
+
+function walkMentionNode(
+ node: any,
+ cb: (label: string, metadata: Record<string, unknown>) => void,
+): void {
+ if (!node) return;
+ if (node.type === 'mention' && node.metadata) {
+ cb(node.label ?? '', node.metadata);
+ }
+ if (Array.isArray(node.children)) {
+ for (const child of node.children) {
+ walkMentionNode(child, cb);
+ }
+ }
+}
+
+function walkNode(node: any, out: ParsedActionTag[]): void {
+ if (!node) return;
+
+ if (node.type === 'action-tag') {
+ out.push({
+ category: node.actionCategory,
+ label: node.actionLabel,
+ type: node.actionType,
+ });
+ }
+
+ if (Array.isArray(node.children)) {
+ for (const child of node.children) {
+ walkNode(child, out);
+ }
+ }
+}
diff --git a/src/store/chat/slices/aiChat/actions/commandBus/processCommands.test.ts b/src/store/chat/slices/aiChat/actions/commandBus/processCommands.test.ts
new file mode 100644
index 00000000000..8ab6e2a5a6f
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/commandBus/processCommands.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it } from 'vitest';
+
+import { processCommands } from './index';
+
+const baseParams = {
+ message: 'hello',
+ context: {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ },
+} as any;
+
+describe('processCommands', () => {
+ it('should return empty overrides when no editorData', () => {
+ expect(processCommands(baseParams)).toEqual({});
+ });
+
+ it('should return empty overrides when no command tags', () => {
+ const params = {
+ ...baseParams,
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'skill',
+ actionLabel: 'Translate',
+ actionType: 'translate',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ },
+ };
+ expect(processCommands(params)).toEqual({});
+ });
+
+ it('should return forceNewTopic for newTopic command', () => {
+ const params = {
+ ...baseParams,
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'command',
+ actionLabel: 'Send in new topic',
+ actionType: 'newTopic',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ },
+ };
+
+ const result = processCommands(params);
+ expect(result.forceNewTopic).toBe(true);
+ });
+
+ it('should return triggerCompression for compact command', () => {
+ const params = {
+ ...baseParams,
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'command',
+ actionLabel: 'Compact context',
+ actionType: 'compact',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ },
+ };
+
+ const result = processCommands(params);
+ expect(result.triggerCompression).toBe(true);
+ });
+
+ it('should merge overrides from multiple commands', () => {
+ const params = {
+ ...baseParams,
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'command',
+ actionLabel: 'Send in new topic',
+ actionType: 'newTopic',
+ type: 'action-tag',
+ },
+ {
+ actionCategory: 'command',
+ actionLabel: 'Compact context',
+ actionType: 'compact',
+ type: 'action-tag',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ },
+ };
+
+ const result = processCommands(params);
+ expect(result.forceNewTopic).toBe(true);
+ expect(result.triggerCompression).toBe(true);
+ });
+});
diff --git a/src/store/chat/slices/aiChat/actions/commandBus/types.ts b/src/store/chat/slices/aiChat/actions/commandBus/types.ts
new file mode 100644
index 00000000000..419b9c4d3cc
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/commandBus/types.ts
@@ -0,0 +1,23 @@
+import type { CommandType } from '@/features/ChatInput/InputEditor/ActionTag/types';
+
+import type { SendMessageWithContextParams } from '../conversationLifecycle';
+
+/**
+ * The mutable send params that command handlers can modify.
+ * After all commands run, these overrides are merged into the original params.
+ */
+export interface CommandSendOverrides {
+ /** Force creation of a new topic (ignore current topicId) */
+ forceNewTopic?: boolean;
+ /** Trigger context compression directly (no message sent) */
+ triggerCompression?: boolean;
+}
+
+export interface CommandHandlerContext {
+ /** Original send params (read-only reference) */
+ params: SendMessageWithContextParams;
+}
+
+export type CommandHandler = (ctx: CommandHandlerContext) => CommandSendOverrides | void;
+
+export type CommandRegistry = Record<CommandType, CommandHandler>;
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index e49a5ec7cd7..2b8289372fc 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -1,6 +1,8 @@
// Disable the auto sort key eslint rule to make the code more logic and readable
+import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';
import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
import { LOADING_FLAT } from '@lobechat/const';
+import { chainCompressContext } from '@lobechat/prompts';
import {
type ChatImageItem,
type ChatThreadType,
@@ -15,10 +17,18 @@ import { t } from 'i18next';
import { markUserValidAction } from '@/business/client/markUserValidAction';
import { aiChatService } from '@/services/aiChat';
+import { chatService } from '@/services/chat';
+import { prepareSelectedSkillPreload } from '@/services/chat/mecha/skillPreload';
+import { messageService } from '@/services/message';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';
import { type ChatStore } from '@/store/chat/store';
+import {
+ createPendingCompressedGroup,
+ getCompressionCandidateMessageIds,
+ hasRunningCompressionOperation,
+} from '@/store/chat/utils/compression';
import { getFileStoreState } from '@/store/file/store';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -27,6 +37,15 @@ import { useUserMemoryStore } from '@/store/userMemory';
import { dbMessageSelectors, displayMessageSelectors, topicSelectors } from '../../../selectors';
import { messageMapKey } from '../../../utils/messageMapKey';
+import {
+ type CommandSendOverrides,
+ hasNonActionContent,
+ injectReferTopicNode,
+ parseMentionedAgentsFromEditorData,
+ parseSelectedSkillsFromEditorData,
+ parseSelectedToolsFromEditorData,
+ processCommands,
+} from './commandBus';
/**
* Extended params for sendMessage with context
@@ -60,6 +79,16 @@ type Setter = StoreSetter<ChatStore>;
export const conversationLifecycle = (set: Setter, get: () => ChatStore, _api?: unknown) =>
new ConversationLifecycleActionImpl(set, get, _api);
+const isAbortError = (error: unknown, abortController?: AbortController) =>
+ !!abortController?.signal.aborted ||
+ (error instanceof Error &&
+ (error.name === 'AbortError' ||
+ error.message.includes('aborted') ||
+ error.message.includes('cancelled')));
+
+const createAbortError = () =>
+ Object.assign(new Error('Compression cancelled'), { name: 'AbortError' });
+
export class ConversationLifecycleActionImpl {
readonly #get: () => ChatStore;
@@ -71,6 +100,7 @@ export class ConversationLifecycleActionImpl {
sendMessage = async ({
message,
+ editorData: inputEditorData,
files,
onlyAddUserMessage,
context,
@@ -78,7 +108,11 @@ export class ConversationLifecycleActionImpl {
parentId: inputParentId,
pageSelections,
}: SendMessageWithContextParams): Promise<SendMessageResult | undefined> => {
+ let editorData = inputEditorData;
const { internal_execAgentRuntime, mainInputEditor } = this.#get();
+ const selectedSkills = parseSelectedSkillsFromEditorData(editorData);
+ const selectedTools = parseSelectedToolsFromEditorData(editorData);
+ const mentionedAgents = parseMentionedAgentsFromEditorData(editorData);
// Use context from params (required)
const { agentId } = context;
@@ -96,6 +130,53 @@ export class ConversationLifecycleActionImpl {
if (!agentId) return;
+ // ── Command Bus: extract and process built-in commands from editorData ──
+ const commandOverrides: CommandSendOverrides = processCommands({
+ message,
+ editorData,
+ files,
+ onlyAddUserMessage,
+ context,
+ messages: inputMessages,
+ parentId: inputParentId,
+ pageSelections,
+ });
+
+ // /compact — directly compress context without sending any message
+ if (commandOverrides.triggerCompression) {
+ const compressContext = { ...context };
+ if (
+ compressContext.topicId &&
+ !hasRunningCompressionOperation(Object.values(this.#get().operations), compressContext)
+ ) {
+ await this.#executeCompression(compressContext, '');
+ }
+ return;
+ }
+
+ // /newTopic — force a fresh topic regardless of current context
+ let forceNewTopicFromExisting = false;
+ if (commandOverrides.forceNewTopic) {
+ const hasFile = files && files.length > 0;
+ // If no message content besides the action tag and no files, just navigate to a new topic without sending
+ if (!hasNonActionContent(editorData) && !hasFile) {
+ await this.#get().switchTopic(null);
+ return;
+ }
+
+ if (context.topicId) {
+ const originalTopic = topicSelectors.getTopicById(context.topicId)(this.#get());
+ const topicTitle = originalTopic?.title || '';
+ // Inject referTopic into content for LLM context
+ const referTag = `<refer_topic name="${topicTitle}" id="${context.topicId}" />`;
+ message = `${referTag}\n${message}`;
+ // Inject refer-topic node into editorData for rich text display
+ editorData = injectReferTopicNode(editorData, context.topicId, topicTitle);
+ forceNewTopicFromExisting = true;
+ }
+ context = { ...context, topicId: undefined };
+ }
+
// When creating new thread, override threadId to undefined (server will create it)
// Check if current agentId is the supervisor agent of the group
let isGroupSupervisor = false;
@@ -103,13 +184,22 @@ export class ConversationLifecycleActionImpl {
const group = agentGroupByIdSelectors.groupById(context.groupId)(getChatGroupStoreState());
isGroupSupervisor = group?.supervisorAgentId === agentId;
}
+ // In non-group context, @agent mentions make the current agent act as supervisor
+ const hasMentionedAgents = !context.groupId && mentionedAgents.length > 0;
+
const operationContext = {
...context,
...(isCreatingNewThread && { threadId: undefined }),
+ // Only set isSupervisor for actual group supervisors — NOT for @agent mentions.
+ // isSupervisor triggers group-specific UI rendering (SupervisorMessage with group avatars).
...(isGroupSupervisor && { isSupervisor: true }),
};
const fileIdList = files?.map((f) => f.id);
+ const preloadMessages = await prepareSelectedSkillPreload({
+ message,
+ selectedSkills,
+ });
const hasFile = !!fileIdList && fileIdList.length > 0;
@@ -123,9 +213,11 @@ export class ConversationLifecycleActionImpl {
}
// Use provided messages or query from store
+ // For /newTopic from existing topic, start with empty message list (fresh topic)
const contextKey = messageMapKey(context);
- const messages =
- inputMessages ?? displayMessageSelectors.getDisplayMessagesByKey(contextKey)(this.#get());
+ const messages = forceNewTopicFromExisting
+ ? []
+ : (inputMessages ?? displayMessageSelectors.getDisplayMessagesByKey(contextKey)(this.#get()));
const lastMessage = messages.at(-1);
useUserMemoryStore.getState().setActiveMemoryContext({
@@ -136,7 +228,7 @@ export class ConversationLifecycleActionImpl {
});
// Use provided parentId or calculate from messages
- let parentId: string | undefined = inputParentId;
+ let parentId: string | undefined = forceNewTopicFromExisting ? undefined : inputParentId;
if (!parentId && lastMessage) {
parentId = displayMessageSelectors.findLastMessageId(lastMessage.id)(this.#get());
}
@@ -175,6 +267,7 @@ export class ConversationLifecycleActionImpl {
this.#get().optimisticCreateTmpMessage(
{
content: message,
+ editorData: editorData ?? undefined,
// if message has attached with files, then add files to message and the agent
files: fileIdList,
role: 'user',
@@ -209,7 +302,7 @@ export class ConversationLifecycleActionImpl {
this.#get().associateMessageWithOperation(tempAssistantId, operationId);
// Store editor state in operation metadata for cancel restoration
- const jsonState = mainInputEditor?.getJSONState();
+ const jsonState = inputEditorData ?? mainInputEditor?.getJSONState();
this.#get().updateOperationMetadata(operationId, {
inputEditorTempState: jsonState,
inputSendErrorMsg: undefined,
@@ -222,7 +315,14 @@ export class ConversationLifecycleActionImpl {
const topicId = operationContext.topicId;
data = await aiChatService.sendMessageInServer(
{
- newUserMessage: { content: message, files: fileIdList, pageSelections, parentId },
+ newUserMessage: {
+ content: message,
+ editorData,
+ files: fileIdList,
+ pageSelections,
+ parentId,
+ },
+ preloadMessages: preloadMessages.length > 0 ? preloadMessages : undefined,
// if there is topicId,then add topicId to message
topicId: topicId ?? undefined,
threadId: operationContext.threadId ?? undefined,
@@ -235,7 +335,7 @@ export class ConversationLifecycleActionImpl {
: undefined,
newTopic: !topicId
? {
- topicMessageIds: messages.map((m) => m.id),
+ topicMessageIds: forceNewTopicFromExisting ? [] : messages.map((m) => m.id),
title: message.slice(0, 20) || t('defaultTitle', { ns: 'topic' }),
}
: undefined,
@@ -316,7 +416,12 @@ export class ConversationLifecycleActionImpl {
// Check if error is due to cancellation
if (!isAbort) {
this.#get().updateOperationMetadata(operationId, { inputSendErrorMsg: e.message });
- this.#get().mainInputEditor?.setDocument('markdown', message);
+ const op = this.#get().operations[operationId];
+ if (op?.metadata.inputEditorTempState) {
+ this.#get().mainInputEditor?.setJSONState(op.metadata.inputEditorTempState);
+ } else {
+ this.#get().mainInputEditor?.setDocument('markdown', message);
+ }
}
}
} finally {
@@ -370,42 +475,72 @@ export class ConversationLifecycleActionImpl {
// execAgentRuntime is a separate operation (child) that handles AI response generation
this.#get().completeOperation(operationId);
- // Create final context for AI execution (with updated topicId/threadId from server)
- const execContext = {
- ...operationContext,
- topicId: data.topicId ?? operationContext.topicId,
- threadId: data.createdThreadId ?? operationContext.threadId,
- };
-
- // Get the current messages to generate AI response
- const displayMessages = displayMessageSelectors.getDisplayMessagesByKey(
- messageMapKey(execContext),
- )(this.#get());
-
- try {
- await internal_execAgentRuntime({
- context: execContext,
- messages: displayMessages,
- parentMessageId: data.assistantMessageId,
- parentMessageType: 'assistant',
- parentOperationId: operationId, // Pass as parent operation
- // If a new thread was created, mark as inPortalThread for consistent behavior
- inPortalThread: !!data.createdThreadId,
- skipCreateFirstMessage: true,
- });
+ // ── AI execution ──
+ {
+ const execContext = {
+ ...operationContext,
+ topicId: data.topicId ?? operationContext.topicId,
+ threadId: data.createdThreadId ?? operationContext.threadId,
+ };
+
+ const displayMessages = displayMessageSelectors.getDisplayMessagesByKey(
+ messageMapKey(execContext),
+ )(this.#get());
+
+ try {
+ // When agents are @mentioned in non-group context, auto-enable agent-management tool
+ // so the supervisor can delegate via callAgent
+ const effectiveSelectedTools =
+ hasMentionedAgents &&
+ !selectedTools.some((t) => t.identifier === AgentManagementIdentifier)
+ ? [
+ ...selectedTools,
+ { identifier: AgentManagementIdentifier, name: 'Agent Management' },
+ ]
+ : selectedTools;
+
+ const hasInitialContext =
+ effectiveSelectedTools.length > 0 || selectedSkills.length > 0 || hasMentionedAgents;
+
+ const agentRuntimeInitialContext = hasInitialContext
+ ? {
+ initialContext: {
+ ...(selectedSkills.length > 0 ? { selectedSkills } : undefined),
+ ...(effectiveSelectedTools.length > 0
+ ? { selectedTools: effectiveSelectedTools }
+ : undefined),
+ // Only inject mentionedAgents in non-group context to avoid
+ // group @member mentions (including ALL_MEMBERS) leaking into agent-management
+ ...(hasMentionedAgents ? { mentionedAgents } : undefined),
+ },
+ phase: 'init' as const,
+ }
+ : undefined;
+
+ await internal_execAgentRuntime({
+ context: execContext,
+ initialContext: agentRuntimeInitialContext,
+ messages: displayMessages,
+ parentMessageId: data.assistantMessageId,
+ parentMessageType: 'assistant',
+ parentOperationId: operationId,
+ inPortalThread: !!data.createdThreadId,
+ skipCreateFirstMessage: true,
+ });
- const userFiles = dbMessageSelectors
- .dbUserFiles(this.#get())
- .map((f) => f?.id)
- .filter(Boolean) as string[];
+ const userFiles = dbMessageSelectors
+ .dbUserFiles(this.#get())
+ .map((f) => f?.id)
+ .filter(Boolean) as string[];
- if (userFiles.length > 0) {
- await getAgentStoreState().addFilesToAgent(userFiles, false);
+ if (userFiles.length > 0) {
+ await getAgentStoreState().addFilesToAgent(userFiles, false);
+ }
+ } catch (e) {
+ console.error(e);
+ } finally {
+ if (data.topicId) this.#get().internal_updateTopicLoading(data.topicId, false);
}
- } catch (e) {
- console.error(e);
- } finally {
- if (data.topicId) this.#get().internal_updateTopicLoading(data.topicId, false);
}
// Return result for callers who need message IDs
@@ -456,6 +591,114 @@ export class ConversationLifecycleActionImpl {
throw error;
}
};
+
+ /**
+ * Execute context compression for /compact command.
+ * Reuses the same service methods as the agent runtime's compress_context executor.
+ */
+ #executeCompression = async (
+ context: Record<string, any>,
+ parentOperationId: string,
+ ): Promise<void> => {
+ const { agentId, topicId } = context;
+ if (!topicId) return;
+
+ const contextKey = messageMapKey(context as any);
+ const dbMessages = dbMessageSelectors.getDbMessagesByKey(contextKey)(this.#get()) || [];
+ const messageIds = getCompressionCandidateMessageIds(dbMessages);
+
+ if (messageIds.length === 0) return;
+
+ const tempId = 'tmp_compress_' + nanoid();
+ const { abortController, operationId } = this.#get().startOperation({
+ context: { ...context, messageId: tempId },
+ parentOperationId,
+ type: 'contextCompression',
+ });
+
+ // Immediate UI feedback: render a pending compressed group from the first frame
+ this.#get().internal_dispatchMessage(
+ {
+ id: tempId,
+ type: 'createMessage',
+ value: createPendingCompressedGroup({
+ agentId,
+ groupId: context.groupId,
+ id: tempId,
+ threadId: context.threadId,
+ topicId,
+ }) as any,
+ },
+ { operationId },
+ );
+
+ try {
+ // 1. Create compression group on server
+ const result = await messageService.createCompressionGroup({
+ agentId,
+ messageIds,
+ topicId,
+ });
+ const { messageGroupId, messages: serverMessages, messagesToSummarize } = result;
+
+ // Replace local pending group with server compression group
+ this.#get().replaceMessages(serverMessages, { context: context as any });
+ this.#get().associateMessageWithOperation(messageGroupId, operationId);
+
+ // 2. Generate summary via LLM
+ const { model, provider } = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());
+ const compressionPayload = chainCompressContext(messagesToSummarize);
+ let summaryContent = '';
+
+ await chatService.fetchPresetTaskResult({
+ abortController,
+ onMessageHandle: (chunk) => {
+ if (chunk.type === 'text') {
+ summaryContent += chunk.text || '';
+ this.#get().internal_dispatchMessage(
+ { id: messageGroupId, type: 'updateMessage', value: { content: summaryContent } },
+ { operationId },
+ );
+ }
+ },
+ params: { ...compressionPayload, model, provider },
+ });
+
+ if (abortController.signal.aborted) throw createAbortError();
+
+ // 3. Finalize compression
+ const finalResult = await messageService.finalizeCompression({
+ agentId,
+ content: summaryContent,
+ messageGroupId,
+ topicId,
+ });
+
+ if (finalResult.messages) {
+ this.#get().replaceMessages(finalResult.messages, { context: context as any });
+ }
+
+ this.#get().completeOperation(operationId);
+ } catch (error) {
+ if (isAbortError(error, abortController)) {
+ this.#get().internal_dispatchMessage(
+ { type: 'deleteMessages', ids: [tempId] },
+ { operationId },
+ );
+ return;
+ }
+
+ console.error('[/compact] Compression failed:', error);
+ this.#get().internal_dispatchMessage(
+ { type: 'deleteMessages', ids: [tempId] },
+ { operationId },
+ );
+ this.#get().failOperation(operationId, {
+ message: error instanceof Error ? error.message : String(error),
+ type: 'compression_failed',
+ });
+ }
+ };
}
export type ConversationLifecycleAction = Pick<
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 218ee741d6b..90b9a07ede9 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -43,6 +43,17 @@ import {
const log = debug('lobe-store:streaming-executor');
+const hasReferTopicNode = (editorData: Record<string, any> | null | undefined): boolean => {
+ if (!editorData) return false;
+ const walk = (node: any): boolean => {
+ if (!node) return false;
+ if (node.type === 'refer-topic') return true;
+ if (Array.isArray(node.children)) return node.children.some(walk);
+ return false;
+ };
+ return walk(editorData.root);
+};
+
/**
* Core streaming execution actions for AI chat
*/
@@ -126,6 +137,13 @@ export class StreamingExecutorActionImpl {
});
const { agentConfig: agentConfigData, plugins: pluginIds } = agentConfig;
+ const selectedToolIds = initialContext?.initialContext?.selectedTools?.map(
+ (tool) => tool.identifier,
+ );
+ const mergedToolIds =
+ selectedToolIds && selectedToolIds.length > 0
+ ? [...new Set([...(pluginIds || []), ...selectedToolIds])]
+ : pluginIds;
if (!agentConfigData || !agentConfigData.model) {
throw new Error(
@@ -133,25 +151,32 @@ export class StreamingExecutorActionImpl {
);
}
+ // Dynamically inject topic-reference tool when messages contain refer-topic nodes
+ const hasTopicReference = messages.some((m) => hasReferTopicNode(m.editorData));
+ const effectivePluginIds = hasTopicReference
+ ? [...(pluginIds || []), 'lobe-topic-reference']
+ : pluginIds;
+
log(
- '[internal_createAgentState] resolved plugins=%o, isSubTask=%s, disableTools=%s',
- pluginIds,
+ '[internal_createAgentState] resolved plugins=%o, isSubTask=%s, disableTools=%s, hasTopicReference=%s',
+ effectivePluginIds,
isSubTask,
disableTools,
+ hasTopicReference,
);
// Generate tools using ToolsEngine (centralized here, passed to chatService via agentConfig)
// When disableTools is true (broadcast mode), skipDefaultTools prevents default tools from being added
const toolsEngine = createAgentToolsEngine(
{ model: agentConfigData.model, provider: agentConfigData.provider! },
- pluginIds,
+ effectivePluginIds,
);
const toolsDetailed = toolsEngine.generateToolsDetailed({
model: agentConfigData.model,
provider: agentConfigData.provider!,
skipDefaultTools: disableTools,
- toolIds: pluginIds,
+ toolIds: mergedToolIds,
});
const enabledToolIds = toolsDetailed.enabledToolIds;
@@ -249,23 +274,36 @@ export class StreamingExecutorActionImpl {
}
}
+ const mergedRuntimeInitialContext =
+ runtimeInitialContext || initialContext?.initialContext
+ ? {
+ ...runtimeInitialContext,
+ ...initialContext?.initialContext,
+ }
+ : undefined;
+
// Create initial context or use provided context
- const context: AgentRuntimeContext = initialContext || {
- phase: 'init',
- payload: {
- model: agentConfigData.model,
- provider: agentConfigData.provider,
- parentMessageId,
- },
- session: {
- sessionId: agentId,
- messageCount: messages.length,
- status: state.status,
- stepCount: 0,
- },
- // Inject initialContext if available
- initialContext: runtimeInitialContext,
- };
+ const context: AgentRuntimeContext = initialContext
+ ? {
+ ...initialContext,
+ initialContext: mergedRuntimeInitialContext,
+ }
+ : {
+ phase: 'init',
+ payload: {
+ model: agentConfigData.model,
+ provider: agentConfigData.provider,
+ parentMessageId,
+ },
+ session: {
+ sessionId: agentId,
+ messageCount: messages.length,
+ status: state.status,
+ stepCount: 0,
+ },
+ // Inject initialContext if available
+ initialContext: mergedRuntimeInitialContext,
+ };
return { agentConfig: agentConfigWithTools, context, state, toolsEngine };
};
diff --git a/src/store/chat/utils/compression.test.ts b/src/store/chat/utils/compression.test.ts
new file mode 100644
index 00000000000..4f8aa9cd264
--- /dev/null
+++ b/src/store/chat/utils/compression.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from 'vitest';
+
+import { type Operation } from '../slices/operation/types';
+import {
+ createPendingCompressedGroup,
+ getCompressionCandidateMessageIds,
+ hasRunningCompressionOperation,
+ isCompressionOperationType,
+} from './compression';
+
+describe('compression utils', () => {
+ it('should treat contextCompression and generateSummary as compression operations', () => {
+ expect(isCompressionOperationType('contextCompression')).toBe(true);
+ expect(isCompressionOperationType('generateSummary')).toBe(true);
+ expect(isCompressionOperationType('sendMessage')).toBe(false);
+ });
+
+ it('should exclude compressedGroup ids from compression candidates', () => {
+ expect(
+ getCompressionCandidateMessageIds([
+ { id: 'user-1', role: 'user' } as any,
+ { id: 'group-1', role: 'compressedGroup' } as any,
+ { id: 'tool-1', role: 'tool' } as any,
+ ]),
+ ).toEqual(['user-1', 'tool-1']);
+ });
+
+ it('should detect running compression operations in the same conversation context', () => {
+ const operations: Operation[] = [
+ {
+ abortController: new AbortController(),
+ context: { agentId: 'agent-1', threadId: null, topicId: 'topic-1' },
+ id: 'op-1',
+ metadata: { startTime: Date.now() },
+ status: 'running',
+ type: 'contextCompression',
+ },
+ {
+ abortController: new AbortController(),
+ context: { agentId: 'agent-1', threadId: null, topicId: 'topic-2' },
+ id: 'op-2',
+ metadata: { startTime: Date.now() },
+ status: 'running',
+ type: 'generateSummary',
+ },
+ ];
+
+ expect(
+ hasRunningCompressionOperation(operations, {
+ agentId: 'agent-1',
+ groupId: undefined,
+ threadId: null,
+ topicId: 'topic-1',
+ }),
+ ).toBe(true);
+ expect(
+ hasRunningCompressionOperation(operations, {
+ agentId: 'agent-1',
+ groupId: undefined,
+ threadId: null,
+ topicId: 'topic-3',
+ }),
+ ).toBe(false);
+ });
+
+ it('should build a pending compressedGroup message', () => {
+ const message = createPendingCompressedGroup({
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ id: 'temp-group-1',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ });
+
+ expect(message.role).toBe('compressedGroup');
+ expect(message.id).toBe('temp-group-1');
+ expect(message.metadata).toEqual({ expanded: true });
+ expect(message.compressedMessages).toEqual([]);
+ });
+});
diff --git a/src/store/chat/utils/compression.ts b/src/store/chat/utils/compression.ts
new file mode 100644
index 00000000000..eded0739a97
--- /dev/null
+++ b/src/store/chat/utils/compression.ts
@@ -0,0 +1,64 @@
+import {
+ type CompressionGroupMetadata,
+ type ConversationContext,
+ type UIChatMessage,
+} from '@lobechat/types';
+
+import { type Operation } from '../slices/operation/types';
+
+export const isCompressionOperationType = (type?: string) =>
+ type === 'contextCompression' || type === 'generateSummary';
+
+export const getCompressionCandidateMessageIds = (messages: UIChatMessage[]) =>
+ messages
+ .filter((message) => message.role !== 'compressedGroup')
+ .map((message) => message.id)
+ .filter(Boolean);
+
+export const createPendingCompressedGroup = ({
+ agentId,
+ content = '...',
+ groupId,
+ id,
+ threadId,
+ topicId,
+}: {
+ agentId: string;
+ content?: string;
+ groupId?: string | null;
+ id: string;
+ threadId?: string | null;
+ topicId?: string | null;
+}): UIChatMessage => {
+ const now = Date.now();
+ const metadata: CompressionGroupMetadata = { expanded: true };
+
+ return {
+ agentId,
+ compressedMessages: [],
+ content,
+ createdAt: now,
+ groupId: groupId ?? undefined,
+ id,
+ metadata: metadata as UIChatMessage['metadata'],
+ role: 'compressedGroup',
+ threadId: threadId ?? undefined,
+ topicId: topicId ?? undefined,
+ updatedAt: now,
+ };
+};
+
+export const hasRunningCompressionOperation = (
+ operations: Operation[],
+ context: Pick<ConversationContext, 'agentId' | 'groupId' | 'threadId' | 'topicId'>,
+) =>
+ operations.some((operation) => {
+ if (operation.status !== 'running' || !isCompressionOperationType(operation.type)) return false;
+
+ return (
+ operation.context.agentId === context.agentId &&
+ (operation.context.groupId ?? null) === (context.groupId ?? null) &&
+ (operation.context.threadId ?? null) === (context.threadId ?? null) &&
+ (operation.context.topicId ?? null) === (context.topicId ?? null)
+ );
+ });
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index e3a10a26962..d562c953546 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -14,6 +14,7 @@ import { gtdExecutor } from '@lobechat/builtin-tool-gtd/executor';
import { knowledgeBaseExecutor } from '@lobechat/builtin-tool-knowledge-base/executor';
import { localSystemExecutor } from '@lobechat/builtin-tool-local-system/executor';
import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';
+import { topicReferenceExecutor } from '@lobechat/builtin-tool-topic-reference/executor';
import type { BuiltinToolContext, BuiltinToolResult, IBuiltinToolExecutor } from '../types';
import { notebookExecutor } from './lobe-notebook';
@@ -140,5 +141,6 @@ registerExecutors([
skillStoreExecutor,
skillsExecutor,
toolsActivatorExecutor,
+ topicReferenceExecutor,
webBrowsing,
]);
diff --git a/vite.config.ts b/vite.config.ts
index 7b3fc0774da..64eb5615e7f 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -115,7 +115,49 @@ export default defineConfig({
},
warmup: {
clientFiles: [
- platform === 'mobile' ? './src/spa/entry.mobile.tsx' : './src/spa/entry.web.tsx',
+ // src/ business code
+ './src/initialize.ts',
+ './src/spa/**/*.tsx',
+ './src/business/**/*.{ts,tsx}',
+ './src/components/**/*.{ts,tsx}',
+ './src/config/**/*.ts',
+ './src/const/**/*.ts',
+ './src/envs/**/*.ts',
+ './src/features/**/*.{ts,tsx}',
+ './src/helpers/**/*.ts',
+ './src/hooks/**/*.{ts,tsx}',
+ './src/layout/**/*.{ts,tsx}',
+ './src/libs/**/*.{ts,tsx}',
+ './src/locales/**/*.ts',
+ './src/routes/**/*.{ts,tsx}',
+ './src/services/**/*.ts',
+ './src/store/**/*.{ts,tsx}',
+ './src/styles/**/*.ts',
+ './src/utils/**/*.{ts,tsx}',
+
+ // monorepo packages
+ './packages/types/src/**/*.ts',
+ './packages/const/src/**/*.ts',
+ './packages/utils/src/**/*.ts',
+ './packages/context-engine/src/**/*.ts',
+ './packages/prompts/src/**/*.ts',
+ './packages/model-bank/src/**/*.ts',
+ './packages/model-runtime/src/**/*.ts',
+ './packages/agent-runtime/src/**/*.ts',
+ './packages/conversation-flow/src/**/*.ts',
+ './packages/electron-client-ipc/src/**/*.ts',
+ './packages/builtin-agents/src/**/*.ts',
+ './packages/builtin-skills/src/**/*.ts',
+ './packages/builtin-tool-*/src/**/*.ts',
+ './packages/builtin-tools/src/**/*.ts',
+ './packages/business/*/src/**/*.ts',
+ './packages/config/src/**/*.ts',
+ './packages/edge-config/src/**/*.ts',
+ './packages/editor-runtime/src/**/*.ts',
+ './packages/fetch-sse/src/**/*.ts',
+ './packages/desktop-bridge/src/**/*.ts',
+ './packages/python-interpreter/src/**/*.ts',
+ './packages/agent-manager-runtime/src/**/*.ts',
],
},
},