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(agent): add floating chat panel and workspace improvements (#13887)

Innei043d2a81fb10
diff --git a/apps/desktop/resources/locales/ar/menu.json b/apps/desktop/resources/locales/ar/menu.json
index 812ace4e4eb..40352eb8432 100644
--- a/apps/desktop/resources/locales/ar/menu.json
+++ b/apps/desktop/resources/locales/ar/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "خدمات",
"macOS.unhide": "إظهار الكل",
"tray.open": "فتح {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "خروج",
"tray.show": "عرض {{appName}}",
"view.forceReload": "إعادة تحميل قسري",
@@ -86,6 +87,5 @@
"window.minimize": "تصغير",
"window.title": "نافذة",
"window.toggleFullscreen": "تبديل وضع ملء الشاشة",
- "window.zoom": "تكبير",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "تكبير"
}
diff --git a/apps/desktop/resources/locales/bg-BG/menu.json b/apps/desktop/resources/locales/bg-BG/menu.json
index bb4ef87a840..420c7548195 100644
--- a/apps/desktop/resources/locales/bg-BG/menu.json
+++ b/apps/desktop/resources/locales/bg-BG/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Услуги",
"macOS.unhide": "Покажи всичко",
"tray.open": "Отвори {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Изход",
"tray.show": "Покажи {{appName}}",
"view.forceReload": "Принудително презареждане",
@@ -86,6 +87,5 @@
"window.minimize": "Минимизирай",
"window.title": "Прозорец",
"window.toggleFullscreen": "Превключи на цял екран",
- "window.zoom": "Мащаб",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Мащаб"
}
diff --git a/apps/desktop/resources/locales/de-DE/menu.json b/apps/desktop/resources/locales/de-DE/menu.json
index b12a880ff59..913237686fd 100644
--- a/apps/desktop/resources/locales/de-DE/menu.json
+++ b/apps/desktop/resources/locales/de-DE/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Dienste",
"macOS.unhide": "Alle anzeigen",
"tray.open": "{{appName}} öffnen",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Beenden",
"tray.show": "{{appName}} anzeigen",
"view.forceReload": "Erzwinge Neuladen",
@@ -86,6 +87,5 @@
"window.minimize": "Minimieren",
"window.title": "Fenster",
"window.toggleFullscreen": "Vollbild umschalten",
- "window.zoom": "Zoom",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Zoom"
}
diff --git a/apps/desktop/resources/locales/es-ES/menu.json b/apps/desktop/resources/locales/es-ES/menu.json
index 63f5154b989..88544d1f13d 100644
--- a/apps/desktop/resources/locales/es-ES/menu.json
+++ b/apps/desktop/resources/locales/es-ES/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Servicios",
"macOS.unhide": "Mostrar todo",
"tray.open": "Abrir {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Salir",
"tray.show": "Mostrar {{appName}}",
"view.forceReload": "Recargar forzosamente",
@@ -86,6 +87,5 @@
"window.minimize": "Minimizar",
"window.title": "Ventana",
"window.toggleFullscreen": "Alternar pantalla completa",
- "window.zoom": "Zoom",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Zoom"
}
diff --git a/apps/desktop/resources/locales/fa-IR/menu.json b/apps/desktop/resources/locales/fa-IR/menu.json
index 22821f2a52b..dc9f264f24e 100644
--- a/apps/desktop/resources/locales/fa-IR/menu.json
+++ b/apps/desktop/resources/locales/fa-IR/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "خدمات",
"macOS.unhide": "نمایش همه",
"tray.open": "باز کردن {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "خروج",
"tray.show": "نمایش {{appName}}",
"view.forceReload": "بارگذاری اجباری",
@@ -86,6 +87,5 @@
"window.minimize": "کوچک کردن",
"window.title": "پنجره",
"window.toggleFullscreen": "تغییر به حالت تمام صفحه",
- "window.zoom": "زوم",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "زوم"
}
diff --git a/apps/desktop/resources/locales/fr-FR/menu.json b/apps/desktop/resources/locales/fr-FR/menu.json
index 64668536812..45ea133fed7 100644
--- a/apps/desktop/resources/locales/fr-FR/menu.json
+++ b/apps/desktop/resources/locales/fr-FR/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Services",
"macOS.unhide": "Tout afficher",
"tray.open": "Ouvrir {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Quitter",
"tray.show": "Afficher {{appName}}",
"view.forceReload": "Recharger de force",
@@ -86,6 +87,5 @@
"window.minimize": "Réduire",
"window.title": "Fenêtre",
"window.toggleFullscreen": "Basculer en plein écran",
- "window.zoom": "Zoom",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Zoom"
}
diff --git a/apps/desktop/resources/locales/it-IT/menu.json b/apps/desktop/resources/locales/it-IT/menu.json
index faeabd89a8e..da96717b735 100644
--- a/apps/desktop/resources/locales/it-IT/menu.json
+++ b/apps/desktop/resources/locales/it-IT/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Servizi",
"macOS.unhide": "Mostra tutto",
"tray.open": "Apri {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Esci",
"tray.show": "Mostra {{appName}}",
"view.forceReload": "Ricarica forzata",
@@ -86,6 +87,5 @@
"window.minimize": "Minimizza",
"window.title": "Finestra",
"window.toggleFullscreen": "Attiva/disattiva schermo intero",
- "window.zoom": "Zoom",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Zoom"
}
diff --git a/apps/desktop/resources/locales/ja-JP/menu.json b/apps/desktop/resources/locales/ja-JP/menu.json
index e281d9d10ff..c68d4fa3590 100644
--- a/apps/desktop/resources/locales/ja-JP/menu.json
+++ b/apps/desktop/resources/locales/ja-JP/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "サービス",
"macOS.unhide": "すべて表示",
"tray.open": "{{appName}} を開く",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "終了",
"tray.show": "{{appName}} を表示",
"view.forceReload": "強制再読み込み",
@@ -86,6 +87,5 @@
"window.minimize": "最小化",
"window.title": "ウィンドウ",
"window.toggleFullscreen": "フルスクリーン切替",
- "window.zoom": "ズーム",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "ズーム"
}
diff --git a/apps/desktop/resources/locales/ko-KR/menu.json b/apps/desktop/resources/locales/ko-KR/menu.json
index 94669e4288c..e92959680ab 100644
--- a/apps/desktop/resources/locales/ko-KR/menu.json
+++ b/apps/desktop/resources/locales/ko-KR/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "서비스",
"macOS.unhide": "모두 표시",
"tray.open": "{{appName}} 열기",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "종료",
"tray.show": "{{appName}} 표시",
"view.forceReload": "강제 새로 고침",
@@ -86,6 +87,5 @@
"window.minimize": "최소화",
"window.title": "창",
"window.toggleFullscreen": "전체 화면 전환",
- "window.zoom": "줌",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "줌"
}
diff --git a/apps/desktop/resources/locales/nl-NL/menu.json b/apps/desktop/resources/locales/nl-NL/menu.json
index 7df5ff2a086..b45642aacf7 100644
--- a/apps/desktop/resources/locales/nl-NL/menu.json
+++ b/apps/desktop/resources/locales/nl-NL/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Diensten",
"macOS.unhide": "Toon alles",
"tray.open": "Open {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Afsluiten",
"tray.show": "Toon {{appName}}",
"view.forceReload": "Forceer herladen",
@@ -86,6 +87,5 @@
"window.minimize": "Minimaliseren",
"window.title": "Venster",
"window.toggleFullscreen": "Schakel volledig scherm in/uit",
- "window.zoom": "Inzoomen",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Inzoomen"
}
diff --git a/apps/desktop/resources/locales/pl-PL/menu.json b/apps/desktop/resources/locales/pl-PL/menu.json
index bad6ee97894..97a23d1383d 100644
--- a/apps/desktop/resources/locales/pl-PL/menu.json
+++ b/apps/desktop/resources/locales/pl-PL/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Usługi",
"macOS.unhide": "Pokaż wszystko",
"tray.open": "Otwórz {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Zakończ",
"tray.show": "Pokaż {{appName}}",
"view.forceReload": "Wymuś ponowne załadowanie",
@@ -86,6 +87,5 @@
"window.minimize": "Zminimalizuj",
"window.title": "Okno",
"window.toggleFullscreen": "Przełącz tryb pełnoekranowy",
- "window.zoom": "Powiększenie",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Powiększenie"
}
diff --git a/apps/desktop/resources/locales/pt-BR/menu.json b/apps/desktop/resources/locales/pt-BR/menu.json
index c6fd4c6c396..6fcb48adc80 100644
--- a/apps/desktop/resources/locales/pt-BR/menu.json
+++ b/apps/desktop/resources/locales/pt-BR/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Serviços",
"macOS.unhide": "Mostrar Todos",
"tray.open": "Abrir {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Sair",
"tray.show": "Mostrar {{appName}}",
"view.forceReload": "Recarregar Forçadamente",
@@ -86,6 +87,5 @@
"window.minimize": "Minimizar",
"window.title": "Janela",
"window.toggleFullscreen": "Alternar Tela Cheia",
- "window.zoom": "Zoom",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Zoom"
}
diff --git a/apps/desktop/resources/locales/ru-RU/menu.json b/apps/desktop/resources/locales/ru-RU/menu.json
index 37220ab1f45..4bc9ecae575 100644
--- a/apps/desktop/resources/locales/ru-RU/menu.json
+++ b/apps/desktop/resources/locales/ru-RU/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Сервисы",
"macOS.unhide": "Показать все",
"tray.open": "Открыть {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Выйти",
"tray.show": "Показать {{appName}}",
"view.forceReload": "Принудительная перезагрузка",
@@ -86,6 +87,5 @@
"window.minimize": "Свернуть",
"window.title": "Окно",
"window.toggleFullscreen": "Переключить полноэкранный режим",
- "window.zoom": "Масштаб",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Масштаб"
}
diff --git a/apps/desktop/resources/locales/tr-TR/menu.json b/apps/desktop/resources/locales/tr-TR/menu.json
index 30e7f69f2f7..d3a5ab4c4c8 100644
--- a/apps/desktop/resources/locales/tr-TR/menu.json
+++ b/apps/desktop/resources/locales/tr-TR/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Hizmetler",
"macOS.unhide": "Hepsini Göster",
"tray.open": "{{appName}}'i Aç",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Çık",
"tray.show": "{{appName}}'i Göster",
"view.forceReload": "Zorla Yenile",
@@ -86,6 +87,5 @@
"window.minimize": "Küçült",
"window.title": "Pencere",
"window.toggleFullscreen": "Tam Ekrana Geç",
- "window.zoom": "Yakınlaştır",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Yakınlaştır"
}
diff --git a/apps/desktop/resources/locales/vi-VN/menu.json b/apps/desktop/resources/locales/vi-VN/menu.json
index 9b2b2d3a08b..6c10e8f184c 100644
--- a/apps/desktop/resources/locales/vi-VN/menu.json
+++ b/apps/desktop/resources/locales/vi-VN/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "Dịch vụ",
"macOS.unhide": "Hiện tất cả",
"tray.open": "Mở {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "Thoát",
"tray.show": "Hiện {{appName}}",
"view.forceReload": "Tải lại cưỡng bức",
@@ -86,6 +87,5 @@
"window.minimize": "Thu nhỏ",
"window.title": "Cửa sổ",
"window.toggleFullscreen": "Chuyển đổi toàn màn hình",
- "window.zoom": "Thu phóng",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "Thu phóng"
}
diff --git a/apps/desktop/resources/locales/zh-TW/menu.json b/apps/desktop/resources/locales/zh-TW/menu.json
index c3ae0e62525..bf8123102e2 100644
--- a/apps/desktop/resources/locales/zh-TW/menu.json
+++ b/apps/desktop/resources/locales/zh-TW/menu.json
@@ -71,6 +71,7 @@
"macOS.services": "服務",
"macOS.unhide": "全部顯示",
"tray.open": "打開 {{appName}}",
+ "tray.openMiniToolbar": "Quick Composer",
"tray.quit": "退出",
"tray.show": "顯示 {{appName}}",
"view.forceReload": "強制重新載入",
@@ -86,6 +87,5 @@
"window.minimize": "最小化",
"window.title": "視窗",
"window.toggleFullscreen": "切換全螢幕",
- "window.zoom": "縮放",
- "tray.openMiniToolbar": "Quick Composer"
+ "window.zoom": "縮放"
}
diff --git a/apps/desktop/src/overlay/Avatar.tsx b/apps/desktop/src/overlay/Avatar.tsx
index 0fb1f301310..727e54b9c57 100644
--- a/apps/desktop/src/overlay/Avatar.tsx
+++ b/apps/desktop/src/overlay/Avatar.tsx
@@ -17,7 +17,7 @@ const isUrl = (value: string) => URL_PATTERN.test(value);
const firstGlyph = (value?: string | null) => {
if (!value) return '?';
const trimmed = value.trim();
- return trimmed ? Array.from(trimmed)[0] ?? '?' : '?';
+ return trimmed ? (Array.from(trimmed)[0] ?? '?') : '?';
};
const OverlayAvatar = memo<OverlayAvatarProps>(({ avatar, background, size = 18, title }) => {
diff --git a/apps/desktop/src/overlay/overlaySelectionState.test.ts b/apps/desktop/src/overlay/overlaySelectionState.test.ts
index 07382fbe42f..12a8e408291 100644
--- a/apps/desktop/src/overlay/overlaySelectionState.test.ts
+++ b/apps/desktop/src/overlay/overlaySelectionState.test.ts
@@ -1,9 +1,6 @@
import { describe, expect, it } from 'vitest';
-import {
- resolveCommittedSelectionRect,
- shouldHideChatPanel,
-} from './overlaySelectionState';
+import { resolveCommittedSelectionRect, shouldHideChatPanel } from './overlaySelectionState';
describe('overlaySelectionState', () => {
it('keeps the pending selection rect visible until the committed selection arrives', () => {
diff --git a/apps/desktop/src/overlay/useDockPosition.ts b/apps/desktop/src/overlay/useDockPosition.ts
index 42d3e03d63f..b1f6a06a4f6 100644
--- a/apps/desktop/src/overlay/useDockPosition.ts
+++ b/apps/desktop/src/overlay/useDockPosition.ts
@@ -15,8 +15,7 @@ export interface DockResult {
top: number;
}
-const clamp = (v: number, lo: number, hi: number): number =>
- Math.max(lo, Math.min(hi, v));
+const clamp = (v: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, v));
export function computeDockPosition({
rect,
diff --git a/apps/desktop/src/overlay/useWindowHighlight.test.ts b/apps/desktop/src/overlay/useWindowHighlight.test.ts
index b9cd42562c8..c16f2c9a8c0 100644
--- a/apps/desktop/src/overlay/useWindowHighlight.test.ts
+++ b/apps/desktop/src/overlay/useWindowHighlight.test.ts
@@ -3,9 +3,7 @@ import { describe, expect, it } from 'vitest';
import { getTopmostWindowAtPoint } from './useWindowHighlight';
-const createWindow = (
- overrides: Partial<ScreenCaptureWindowInfo>,
-): ScreenCaptureWindowInfo => ({
+const createWindow = (overrides: Partial<ScreenCaptureWindowInfo>): ScreenCaptureWindowInfo => ({
appName: 'Test App',
bounds: { height: 300, width: 400, x: 1000, y: 200 },
order: 0,
diff --git a/docs/.cdn.cache.json b/docs/.cdn.cache.json
index d19e3bdb5f9..add66bcfa34 100644
--- a/docs/.cdn.cache.json
+++ b/docs/.cdn.cache.json
@@ -1,6 +1,7 @@
{
"https://file.rene.wang/540830955-0fe626a3-0ddc-4f67-b595-3c5b3f1701e0.png": "/blog/assetsa8e504275f2cd891fabecca985998de0.webp",
"https://file.rene.wang/changlog-04-14.png": "/blog/assets300abe7e259d293da6c5ed4f642a1be6.webp",
+ "https://file.rene.wang/changlog-04-14.png": "/blog/assets300abe7e259d293da6c5ed4f642a1be6.webp",
"https://file.rene.wang/clipboard-1768907980491-9cc0669fc3a38.png": "/blog/assets8be3a46c8f9c5d3b61bc541f44b7f245.webp",
"https://file.rene.wang/clipboard-1768908081787-ed9eb1cb78bdb.png": "/blog/assetsab009b79dd794f02aec24b7607f342e8.webp",
"https://file.rene.wang/clipboard-1768908121691-b3517bf882633.png": "/blog/assetsd3cae44cba0d3f57df6440b46246e5e7.webp",
@@ -52,6 +53,8 @@
"https://file.rene.wang/clipboard-1770266335710-1fec523143aab.png": "/blog/assets636c78daf95c590cd7d80284c68eb6d9.webp",
"https://file.rene.wang/clipboard-1774923001079-89ce6aa271a62.png": "/blog/assets53e6ec9cf72554dbc1f8224fc0550a03.webp",
"https://file.rene.wang/clipboard-1775701725582-123f8f8cf73f8.png": "/blog/assets7ea204859aeb5aa9be5810a20ba1669a.webp",
+ "https://file.rene.wang/clipboard-1775701725582-123f8f8cf73f8.png": "/blog/assets7ea204859aeb5aa9be5810a20ba1669a.webp",
+ "https://file.rene.wang/clipboard-1776909505252-94b051f3ea0a7.png": "/blog/assetsdfda32866c4bc59af0526e52f31d1da2.webp",
"https://file.rene.wang/lobehub/467951f5-ad65-498d-aea9-fca8f35a4314.png": "/blog/assets907ea775d228958baca38e2dbb65939a.webp",
"https://file.rene.wang/lobehub/58d91528-373a-4a42-b520-cf6cb1f8ce1e.png": "/blog/assets7dccdd4df55aede71001da649639437f.webp",
"https://file.rene.wang/lobehub/ee700103-3c08-41dc-9ddf-c7705bb7bc6a.png": "/blog/assets196d679bc7071abbf71f2a8566f05aa3.webp",
@@ -467,8 +470,5 @@
"https://github.com/user-attachments/assets/fa8fab19-ace2-4f85-8428-a3a0e28845bb": "/blog/assets/2d678631c55369ba7d753c3ffcb73782.webp",
"https://github.com/user-attachments/assets/facdc83c-e789-4649-8060-7f7a10a1b1dd": "/blog/assets05b20e40c03ced0ec8707fed2e8e0f25.webp",
"https://github.com/user-attachments/assets/fcdfb9c5-819a-488f-b28d-0857fe861219": "/blog/assets8477415ecec1f37e38ab38ff1217d0a7.webp",
- "https://github.com/user-attachments/assets/fd60ab55-ead2-4930-ad00-fdf77662f5a0": "/blog/assets276a4e8748e9bd300b30dcd9d0e24980.webp",
- "https://file.rene.wang/clipboard-1775701725582-123f8f8cf73f8.png": "/blog/assets7ea204859aeb5aa9be5810a20ba1669a.webp",
- "https://file.rene.wang/changlog-04-14.png": "/blog/assets300abe7e259d293da6c5ed4f642a1be6.webp",
- "https://file.rene.wang/clipboard-1776909505252-94b051f3ea0a7.png": "/blog/assetsdfda32866c4bc59af0526e52f31d1da2.webp"
+ "https://github.com/user-attachments/assets/fd60ab55-ead2-4930-ad00-fdf77662f5a0": "/blog/assets276a4e8748e9bd300b30dcd9d0e24980.webp"
}
diff --git a/docs/changelog/index.json b/docs/changelog/index.json
index 1bd3bcfa328..459642e04be 100644
--- a/docs/changelog/index.json
+++ b/docs/changelog/index.json
@@ -6,330 +6,221 @@
"image": "/blog/assetsdfda32866c4bc59af0526e52f31d1da2.webp",
"id": "2026-04-20-daily-brief",
"date": "2026-04-20",
- "versionRange": [
- "2.1.50",
- "2.1.52"
- ]
+ "versionRange": ["2.1.50", "2.1.52"]
},
{
"image": "/blog/assets300abe7e259d293da6c5ed4f642a1be6.webp",
"id": "2026-04-13-gateway-sidebar",
"date": "2026-04-13",
- "versionRange": [
- "2.1.48",
- "2.1.49"
- ]
+ "versionRange": ["2.1.48", "2.1.49"]
},
{
"image": "/blog/assets7ea204859aeb5aa9be5810a20ba1669a.webp",
"id": "2026-04-06-auto-completion",
"date": "2026-04-06",
- "versionRange": [
- "2.1.47"
- ]
+ "versionRange": ["2.1.47"]
},
{
"id": "2026-03-30-agent-tasks",
"date": "2026-03-30",
- "versionRange": [
- "2.1.45",
- "2.1.46"
- ]
+ "versionRange": ["2.1.45", "2.1.46"]
},
{
"image": "/blog/assets53e6ec9cf72554dbc1f8224fc0550a03.webp",
"id": "2026-03-23-media-memory",
"date": "2026-03-23",
- "versionRange": [
- "2.1.44"
- ]
+ "versionRange": ["2.1.44"]
},
{
"image": "https://hub-apac-1.lobeobjects.space/blog/assets/4a68a7644501cb513d08670b102a446e.webp",
"id": "2026-03-16-search",
"date": "2026-03-16",
- "versionRange": [
- "2.1.38",
- "2.1.43"
- ]
+ "versionRange": ["2.1.38", "2.1.43"]
},
{
"id": "2026-02-08-runtime-auth",
"date": "2026-02-08",
- "versionRange": [
- "2.1.6",
- "2.1.26"
- ]
+ "versionRange": ["2.1.6", "2.1.26"]
},
{
"image": "/blog/assetsa8e504275f2cd891fabecca985998de0.webp",
"id": "2026-01-27-v2",
"date": "2026-01-27",
- "versionRange": [
- "2.0.1",
- "2.1.5"
- ]
+ "versionRange": ["2.0.1", "2.1.5"]
},
{
"image": "/blog/assets7f3b38c1d76cceb91edb29d6b1eb60db.webp",
"id": "2025-12-20-mcp",
"date": "2025-12-20",
- "versionRange": [
- "1.142.8",
- "1.143.0"
- ]
+ "versionRange": ["1.142.8", "1.143.0"]
},
{
"image": "/blog/assets3a7f0b29839603336e39e923b423409b.webp",
"id": "2025-11-08-comfy-ui",
"date": "2025-11-08",
- "versionRange": [
- "1.133.5",
- "1.142.8"
- ]
+ "versionRange": ["1.133.5", "1.142.8"]
},
{
"image": "/blog/assets35e6aa692b0c16009c61964279514166.webp",
"id": "2025-10-08-python",
"date": "2025-10-08",
- "versionRange": [
- "1.120.7",
- "1.133.5"
- ]
+ "versionRange": ["1.120.7", "1.133.5"]
},
{
"image": "/blog/assetsce5d6dc93676f974be2e162e8ace03f0.webp",
"id": "2025-09-08-gemini",
"date": "2025-09-08",
- "versionRange": [
- "1.109.1",
- "1.120.7"
- ]
+ "versionRange": ["1.109.1", "1.120.7"]
},
{
"image": "/blog/assetsdf48eed9de76b7e37c269b294285f09d.webp",
"id": "2025-08-08-image-generation",
"date": "2025-08-08",
- "versionRange": [
- "1.97.10",
- "1.109.1"
- ]
+ "versionRange": ["1.97.10", "1.109.1"]
},
{
"image": "/blog/assets902eb746fe2042fc2ea831c71002be72.webp",
"id": "2025-07-08-mcp-market",
"date": "2025-07-08",
- "versionRange": [
- "1.93.3",
- "1.97.10"
- ]
+ "versionRange": ["1.93.3", "1.97.10"]
},
{
"image": "/blog/assets5cc27b8cae995074da20d4ffe06a1460.webp",
"id": "2025-06-08-claude-4",
"date": "2025-06-08",
- "versionRange": [
- "1.84.27",
- "1.93.3"
- ]
+ "versionRange": ["1.84.27", "1.93.3"]
},
{
"image": "/blog/assets2a36d86a4eed6e7938dd6e9c684701ed.webp",
"id": "2025-05-08-desktop-app",
"date": "2025-05-08",
- "versionRange": [
- "1.77.17",
- "1.84.27"
- ]
+ "versionRange": ["1.77.17", "1.84.27"]
},
{
"image": "/blog/assetsc0efdb82443556ae3acefe00099b3f23.webp",
"id": "2025-04-06-exports",
"date": "2025-04-06",
- "versionRange": [
- "1.67.2",
- "1.77.17"
- ]
+ "versionRange": ["1.67.2", "1.77.17"]
},
{
"image": "/blog/assetse743f0a47127390dde766a0a790476db.webp",
"id": "2025-03-02-new-models",
"date": "2025-03-02",
- "versionRange": [
- "1.49.13",
- "1.67.2"
- ]
+ "versionRange": ["1.49.13", "1.67.2"]
},
{
"image": "/blog/assets18168d5fe64ea34905a7e52fd82d0e9d.webp",
"id": "2025-02-02-deepseek-r1",
"date": "2025-02-02",
- "versionRange": [
- "1.47.8",
- "1.49.12"
- ]
+ "versionRange": ["1.47.8", "1.49.12"]
},
{
"image": "/blog/assetsf9ed064fe764cbeff2f46910e7099a91.webp",
"id": "2025-01-22-new-ai-provider",
"date": "2025-01-22",
- "versionRange": [
- "1.43.1",
- "1.47.7"
- ]
+ "versionRange": ["1.43.1", "1.47.7"]
},
{
"image": "/blog/assets2d409f43b58953ad5396c6beab8a0719.webp",
"id": "2025-01-03-user-profile",
"date": "2025-01-03",
- "versionRange": [
- "1.34.1",
- "1.43.0"
- ]
+ "versionRange": ["1.34.1", "1.43.0"]
},
{
"image": "/blog/assets/d9cbfcbef130183bc490d515d8a38aa4.webp",
"id": "2024-11-27-forkable-chat",
"date": "2024-11-27",
- "versionRange": [
- "1.33.1",
- "1.34.0"
- ]
+ "versionRange": ["1.33.1", "1.34.0"]
},
{
"image": "/blog/assets/2d678631c55369ba7d753c3ffcb73782.webp",
"id": "2024-11-25-november-providers",
"date": "2024-11-25",
- "versionRange": [
- "1.30.1",
- "1.33.0"
- ]
+ "versionRange": ["1.30.1", "1.33.0"]
},
{
"image": "/blog/assets/f10a4b98782e36797c38071eed785c6f.webp",
"id": "2024-11-06-share-text-json",
"date": "2024-11-06",
- "versionRange": [
- "1.26.1",
- "1.28.0"
- ]
+ "versionRange": ["1.26.1", "1.28.0"]
},
{
"image": "/blog/assets/944c671604833cd2457445b211ebba33.webp",
"id": "2024-10-27-pin-assistant",
"date": "2024-10-27",
- "versionRange": [
- "1.19.1",
- "1.26.0"
- ]
+ "versionRange": ["1.19.1", "1.26.0"]
},
{
"image": "/blog/assets/f6d047a345e47a52592cff916c9a64ce.webp",
"id": "2024-09-20-artifacts",
"date": "2024-09-20",
- "versionRange": [
- "1.17.1",
- "1.19.0"
- ]
+ "versionRange": ["1.17.1", "1.19.0"]
},
{
"image": "/blog/assets/d7e57f8e69f97b76b3c2414f3441b6e4.webp",
"id": "2024-09-13-openai-o1-models",
"date": "2024-09-13",
- "versionRange": [
- "1.12.1",
- "1.17.0"
- ]
+ "versionRange": ["1.12.1", "1.17.0"]
},
{
"image": "/blog/assets/d6129350de510a62fe87b2d2f0fb9477.webp",
"id": "2024-08-21-file-upload-and-knowledge-base",
"date": "2024-08-21",
- "versionRange": [
- "1.8.1",
- "1.12.0"
- ]
+ "versionRange": ["1.8.1", "1.12.0"]
},
{
"image": "/blog/assets/37d85fdfccff9ed56e9c6827faee01c7.webp",
"id": "2024-08-02-lobe-chat-database-docker",
"date": "2024-08-02",
- "versionRange": [
- "1.6.1",
- "1.8.0"
- ]
+ "versionRange": ["1.6.1", "1.8.0"]
},
{
"image": "/blog/assets/39d7890f8cbe21e77db8d3c94f7f22e4.webp",
"id": "2024-07-19-gpt-4o-mini",
"date": "2024-07-19",
- "versionRange": [
- "1.0.1",
- "1.6.0"
- ]
+ "versionRange": ["1.0.1", "1.6.0"]
},
{
"image": "/blog/assets/eb477e62217f4d1b644eff975c7ac168.webp",
"id": "2024-06-19-lobe-chat-v1",
"date": "2024-06-19",
- "versionRange": [
- "0.147.0",
- "1.0.0"
- ]
+ "versionRange": ["0.147.0", "1.0.0"]
},
{
"image": "/blog/assets/8a8d361b4c0cce6da350cc0de65c0ad6.webp",
"id": "2024-02-14-ollama",
"date": "2024-02-14",
- "versionRange": [
- "0.125.1",
- "0.127.0"
- ]
+ "versionRange": ["0.125.1", "0.127.0"]
},
{
"image": "/blog/assets/9498087e85f27e692716a63cb3b58d79.webp",
"id": "2024-02-08-sso-oauth",
"date": "2024-02-08",
- "versionRange": [
- "0.118.1",
- "0.125.0"
- ]
+ "versionRange": ["0.118.1", "0.125.0"]
},
{
"image": "/blog/assets/603fefbb944bc6761ebdab5956fc0084.webp",
"id": "2023-12-22-dalle-3",
"date": "2023-12-22",
- "versionRange": [
- "0.102.1",
- "0.118.0"
- ]
+ "versionRange": ["0.102.1", "0.118.0"]
},
{
"image": "/blog/assets/8d4c2cc0ce8654fa8ac06cc036a7f941.webp",
"id": "2023-11-19-tts-stt",
"date": "2023-11-19",
- "versionRange": [
- "0.101.1",
- "0.102.0"
- ]
+ "versionRange": ["0.101.1", "0.102.0"]
},
{
"image": "/blog/assets/d47654360d626f80144cdedb979a3526.webp",
"id": "2023-11-14-gpt4-vision",
"date": "2023-11-14",
- "versionRange": [
- "0.90.0",
- "0.101.0"
- ]
+ "versionRange": ["0.90.0", "0.101.0"]
},
{
"image": "/blog/assets/50b38eac1769ae6f13aef72f3d725eec.webp",
"id": "2023-09-09-plugin-system",
"date": "2023-09-09",
- "versionRange": [
- "0.67.0",
- "0.72.0"
- ]
+ "versionRange": ["0.67.0", "0.72.0"]
}
]
}
diff --git a/docs/superpowers/specs/2026-04-20-topic-page-url-binding-design.md b/docs/superpowers/specs/2026-04-20-topic-page-url-binding-design.md
new file mode 100644
index 00000000000..394e325649b
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-20-topic-page-url-binding-design.md
@@ -0,0 +1,182 @@
+# Topic Page URL Binding
+
+Date: 2026-04-20
+Scope: SPA routing for the agent topic page view.
+
+## Context
+
+Today `/agent/:aid/:topicId/page` renders `TopicPage`, which maintains the
+currently-active document in React state (hoisted to `(chat)/_layout` via
+`PageDocContext`). Clicking a document in the resources sidebar swaps the
+in-memory `active` and replaces canvas content. The URL never reflects which
+document is being edited, so the state cannot be deep-linked, refreshed, or
+navigated via browser back/forward.
+
+## Goals
+
+1. Make the document id a first-class URL segment: `/page/:docId`.
+2. Keep `/page` (bare) as a convenient entry — it redirects to the topic's
+ auto-created notebook document.
+3. Gracefully fall back when the URL carries an invalid `docId`.
+4. Remove the layout-level context now that URL is the source of truth.
+
+## Decisions
+
+- **Default document on entry**: the topic's auto-created notebook document
+ (`useAutoCreateTopicDocument`). Agent documents opened via the sidebar are
+ transient selections reflected only in URL; no cross-session memory.
+- **Bare `/page`**: component mounts, waits for `useAutoCreateTopicDocument`
+ to resolve a `topicDocId`, then `navigate(/page/<topicDocId>, { replace })`.
+- **Invalid `/page/:docId`**: silent fallback to `/page/<topicDocId>` via
+ `navigate(replace)`. No error UI.
+
+## Architecture
+
+### Route tree
+
+Update `src/spa/router/desktopRouter.config.tsx` **and**
+`src/spa/router/desktopRouter.config.desktop.tsx` together. Register a nested
+route tree for `page`:
+
+```
+path: 'page'
+├── { index: true } → PageRedirect
+└── { path: ':docId' } → TopicPage
+```
+
+### Components
+
+**`src/routes/(main)/agent/features/Page/PageRedirect.tsx`** (new)
+
+- Reads `topicId` from `useParams`.
+- Uses `useAutoCreateTopicDocument(topicId)` to fetch or auto-create.
+- Once a `document.id` is available, calls
+ `navigate(`/agent/${aid}/${topicId}/page/${document.id}`, { replace: true })`.
+- While loading, renders the existing editor skeleton (reuse
+ `EditorCanvas`'s skeleton styling or a lightweight centered `Spin`).
+
+**`src/routes/(main)/agent/features/Page/index.tsx`** (update)
+
+- `docId` comes from `useParams<{ docId: string }>()`.
+- Fetch metadata via
+ `useClientDataSWR(['page-document-meta', docId], () => documentService.getDocumentById(docId))`.
+- If the fetch resolves to `null`/throws, call
+ `useAutoCreateTopicDocument(topicId)` and
+ `navigate(`/agent/${aid}/${topicId}/page/${topicDocId}`, { replace: true })`.
+- When valid, render `TopicCanvas` with `documentId={docId}` plus the
+ debounced title save. Saving covers both doc kinds by:
+ 1. `documentService.updateDocument({ id, title, saveSource: 'autosave' })`
+ 2. `mutate(agentDocumentSWRKeys.documentsList(agentId))` (refreshes
+ sidebar tiles when the doc is an agent-document)
+ 3. `mutate([SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId])` (refreshes
+ notebook list so topic-notebook docs reflect the new title)
+ The notebook key may be inlined or exported from `src/store/notebook/action.ts`.
+- Reset `titleDraft` when `docId` changes.
+
+**`src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx`** (update)
+
+- `DocumentItem` becomes URL-aware: each leaf calls
+ `useMatch('/agent/:aid/:topicId/page/:docId?')` itself.
+- When the match hits, `handleOpen` calls
+ `navigate(/agent/${aid}/${topicId}/page/${document.documentId})`
+ instead of the old `onOpenDocument` / `openDocument(Portal)` path.
+- `isActive` derived from the match's `params.docId`.
+- Fall back to `openDocument` (Portal) only when no page-match (chat mode).
+- Prop chain for `onOpenDocument` / `activeDocumentId` is dropped:
+ intermediate components no longer need to know.
+
+**`src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx`** (update)
+
+- Remove the `onOpenDocument` / `activeDocumentId` props added earlier.
+- No URL awareness lives at this level — the decision is pushed down to
+ `DocumentItem` so intermediate components stay dumb.
+- `useMatch('/agent/:aid/:topicId/page/*')` may still be used here **only**
+ to decide whether the sidebar header, etc. should take page-specific
+ styling (if needed); leave out if not necessary.
+- Critically: `pathname.endsWith('/page')` must **not** be used — it
+ breaks once the URL carries `/:docId`.
+
+**`src/routes/(main)/agent/(chat)/_layout/index.tsx`** (update)
+
+- Keep horizontal layout, keep `Portal` + `AgentWorkingSidebar` mounts.
+- Remove the `PageDocContext` provider and the `useState` for `active`.
+
+**`src/routes/(main)/agent/(chat)/_layout/pageDocContext.ts`** (delete)
+
+**`src/features/TopicCanvas/useAutoCreateTopicDocument.ts`** (harden)
+
+- Promote the `creatingRef` de-dup from component-instance scope to a
+ module-level `Map<topicId, Promise<NotebookDocument>>`. Concurrent
+ mounts / rapid remounts then share the same in-flight creation promise
+ and never issue duplicate inserts.
+- The module-level map entry is cleared on promise resolution or
+ rejection.
+
+**`src/features/Electron/titlebar/RecentlyViewed/plugins/agentTopicPagePlugin.ts`** (update)
+
+- Extend `AGENT_TOPIC_PAGE_PATH_REGEX` to tolerate an optional trailing
+ `/:docId` segment:
+ `^\/agent\/([^/?]+)\/(tpc_[^/?]+)\/page(?:\/[^/?]+)?$`
+- `generateUrl` continues to return bare `/page` (round-trips into the
+ redirect); callers that want a deep link with docId can carry it in
+ `reference.params` and include it in the path. Add
+ `docId?: string` to `AgentTopicPageParams` (in `types.ts`) and plumb
+ through `parseUrl` (capture 3rd group) and `generateUrl` (append
+ `/${docId}` when present).
+
+## Data Flow
+
+```
+URL /page/:docId (source of truth)
+ │
+ ├─▶ TopicPage
+ │ • fetch doc metadata + validate
+ │ • render TopicCanvas with documentId
+ │ • debounced title save via documentService
+ │
+ └─▶ AgentWorkingSidebar
+ • reads docId via useParams
+ • highlights matching DocumentItem
+ • click → navigate(/page/:newId)
+```
+
+Clicking a doc in the sidebar causes a URL change; both `TopicPage` and
+the sidebar re-render to match.
+
+## Error Handling
+
+| Case | Behavior |
+| -------------------------------------- | ----------------------------------------------------------------------------- |
+| Bare `/page` | Mount `PageRedirect`, auto-create if needed, `navigate(replace)` to concrete. |
+| `/page/:docId` with nonexistent docId | Fetch returns null → `navigate(replace)` to topic doc. |
+| `/page/:docId` belonging to other user | Same as above (fetch returns null). |
+| `topicDocId` creation fails | Existing `notebookStore.createDocument` error surface; no special UI. |
+
+## Testing
+
+- Enter `/agent/:aid/:topicId/page` bare → URL rewrites to `/page/<topicDocId>`.
+- Enter `/page/<topicDocId>` directly → canvas loads without redirect.
+- Enter `/page/<invalid>` → URL rewrites to topic doc; no error banner.
+- Click another document in sidebar → URL changes, canvas swaps, sidebar
+ highlight follows (verifies `useMatch` detection works on `/page/:docId`).
+- Browser back/forward cycles through visited docs.
+- Refresh `/page/<docId>` → same doc loads.
+- Switch topic (`:topicId` change) → URL reset to that topic's main doc;
+ previous in-memory selection discarded.
+- Chat route `/agent/:aid/:topicId` — Portal/Sidebar still behave as before;
+ clicking sidebar doc opens Portal (not page).
+- Title edit persists for **both** topic-notebook docs and agent-docs
+ (verify notebook-store SWR cache + agent-documents SWR cache both
+ show the new title after debounce).
+- Rapid remount of the topic page (e.g., hot-reload or fast topic
+ switching) does not produce duplicate topic-notebook docs (module-level
+ de-dup map).
+- Electron Recently Viewed entry for `/page/<docId>` round-trips: parse
+ → resolve → generate yields the same URL including docId.
+
+## Out of Scope
+
+- Per-topic memory of last-viewed document (rejected in favor of A).
+- Multi-document tabbing inside the page view.
+- Emoji / icon persistence for topic docs.
+- Cross-agent document sharing UX.
diff --git a/e2e/src/steps/agent/conversation-mgmt.steps.ts b/e2e/src/steps/agent/conversation-mgmt.steps.ts
index d7aa86c0353..8dd2ec1b6bf 100644
--- a/e2e/src/steps/agent/conversation-mgmt.steps.ts
+++ b/e2e/src/steps/agent/conversation-mgmt.steps.ts
@@ -312,21 +312,21 @@ When('用户输入新的对话名称 {string}', async function (this: CustomWorl
// Wait a short moment for the popover to render
await this.page.waitForTimeout(300);
- // Try to find the popover input using various selectors
- // @lobehub/ui Popover uses antd's Popover internally
- const popoverInputSelectors = [
- // antd popover structure
+ // The rename UI can render as a dialog/modal in CI, not only as a popover.
+ const renameInputSelectors = [
+ '[role="dialog"] input[type="text"]',
+ '.ant-modal input[type="text"]',
+ '[data-testid="editing-popover"] input',
'.ant-popover-inner input',
'.ant-popover-content input',
'.ant-popover input',
- // Generic input that's visible and not the chat input
- 'input:not([data-testid="chat-input"] input)',
+ 'input[type="text"]:visible',
];
let renameInput = null;
- // Wait for any popover input to appear
- for (const selector of popoverInputSelectors) {
+ // Wait for any rename input to appear
+ for (const selector of renameInputSelectors) {
try {
const locator = this.page.locator(selector).first();
await locator.waitFor({ state: 'visible', timeout: 2000 });
@@ -348,18 +348,23 @@ When('用户输入新的对话名称 {string}', async function (this: CustomWorl
for (let i = 0; i < count; i++) {
const input = allInputs.nth(i);
const placeholder = await input.getAttribute('placeholder').catch(() => '');
- const testId = await input.dataset.testid.catch(() => '');
+ const testId = await input.getAttribute('data-testid').catch(() => '');
// Skip search inputs and chat inputs
if (placeholder?.includes('Search') || placeholder?.includes('搜索')) continue;
if (testId === 'chat-input') continue;
- // Check if it's inside a popover-like container
- const isInPopover = await input.evaluate((el) => {
- return el.closest('.ant-popover') !== null || el.closest('[class*="popover"]') !== null;
+ // Prefer inputs rendered inside rename containers.
+ const isInRenameContainer = await input.evaluate((el) => {
+ return (
+ el.closest('[role="dialog"]') !== null ||
+ el.closest('.ant-modal') !== null ||
+ el.closest('.ant-popover') !== null ||
+ el.closest('[class*="popover"]') !== null
+ );
});
- if (isInPopover || count === 1) {
+ if (isInRenameContainer || count === 1) {
renameInput = input;
console.log(` 📍 Found candidate input at index ${i}`);
break;
@@ -374,8 +379,21 @@ When('用户输入新的对话名称 {string}', async function (this: CustomWorl
await renameInput.fill(newName);
console.log(` 📍 Filled input with "${newName}"`);
- // Press Enter to confirm
- await renameInput.press('Enter');
+ const saveButton = this.page
+ .locator('[role="dialog"]')
+ .getByRole('button', { exact: true, name: /^(Save|保存)$/ })
+ .first();
+
+ try {
+ await saveButton.waitFor({ state: 'visible', timeout: 1000 });
+ await saveButton.click();
+ console.log(' 📍 Clicked save button');
+ } catch {
+ // Popover-based rename UIs still confirm with Enter.
+ await renameInput.press('Enter');
+ console.log(' 📍 Confirmed rename with Enter');
+ }
+
console.log(` ✅ 已输入新名称 "${newName}"`);
} else {
// Last resort: the input should have autoFocus, so keyboard should work
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index cc5138d1490..6c2cafb6bf0 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -674,6 +674,9 @@
"viewMode.fullWidth": "Full Width",
"viewMode.normal": "Standard",
"viewMode.wideScreen": "Widescreen",
+ "viewSwitcher.chat": "Chat",
+ "viewSwitcher.page": "Page",
+ "viewSwitcher.task": "Task",
"workflow.awaitingConfirmation": "Awaiting your confirmation",
"workflow.collapse": "Collapse",
"workflow.expandFull": "Expand fully",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 18e6d22eb5a..6574125357a 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -30,7 +30,7 @@
"builtins.lobe-agent-documents.apiName.createDocument": "Create document",
"builtins.lobe-agent-documents.apiName.editDocument": "Edit document",
"builtins.lobe-agent-documents.apiName.listDocuments": "List documents",
- "builtins.lobe-agent-documents.apiName.patchDocument": "Patch document",
+ "builtins.lobe-agent-documents.apiName.modifyNodes": "Modify document",
"builtins.lobe-agent-documents.apiName.readDocument": "Read document",
"builtins.lobe-agent-documents.apiName.readDocumentByFilename": "Read document by filename",
"builtins.lobe-agent-documents.apiName.removeDocument": "Remove document",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 5cd9c67d60c..d35500da946 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -674,6 +674,9 @@
"viewMode.fullWidth": "全宽显示",
"viewMode.normal": "普通",
"viewMode.wideScreen": "宽屏",
+ "viewSwitcher.chat": "对话",
+ "viewSwitcher.page": "文稿",
+ "viewSwitcher.task": "任务",
"workflow.awaitingConfirmation": "需要你确认",
"workflow.collapse": "收起",
"workflow.expandFull": "全部展开",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index d0367ef8098..29a944d0786 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -30,7 +30,7 @@
"builtins.lobe-agent-documents.apiName.createDocument": "创建文档",
"builtins.lobe-agent-documents.apiName.editDocument": "编辑文档",
"builtins.lobe-agent-documents.apiName.listDocuments": "列出文档",
- "builtins.lobe-agent-documents.apiName.patchDocument": "修订文档",
+ "builtins.lobe-agent-documents.apiName.modifyNodes": "修改文档",
"builtins.lobe-agent-documents.apiName.readDocument": "读取文档",
"builtins.lobe-agent-documents.apiName.readDocumentByFilename": "按文件名读取文档",
"builtins.lobe-agent-documents.apiName.removeDocument": "删除文档",
diff --git a/package.json b/package.json
index 22848d34482..dfb84bf160a 100644
--- a/package.json
+++ b/package.json
@@ -270,11 +270,11 @@
"@lobehub/analytics": "^1.6.2",
"@lobehub/charts": "^5.0.0",
"@lobehub/desktop-ipc-typings": "workspace:*",
- "@lobehub/editor": "^4.8.1",
+ "@lobehub/editor": "4.9.0",
"@lobehub/icons": "^5.0.0",
"@lobehub/market-sdk": "0.32.2",
"@lobehub/tts": "^5.1.2",
- "@lobehub/ui": "^5.9.0",
+ "@lobehub/ui": "5.9.1",
"@modelcontextprotocol/sdk": "^1.26.0",
"@napi-rs/canvas": "^0.1.88",
"@neondatabase/serverless": "^1.0.2",
diff --git a/packages/builtin-tool-agent-documents/package.json b/packages/builtin-tool-agent-documents/package.json
index 92508f35824..d5dce379c0f 100644
--- a/packages/builtin-tool-agent-documents/package.json
+++ b/packages/builtin-tool-agent-documents/package.json
@@ -9,9 +9,6 @@
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
- "dependencies": {
- "@lobechat/markdown-patch": "workspace:*"
- },
"devDependencies": {
"@lobechat/types": "workspace:*"
},
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
index ac899acaced..2e49907a831 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
@@ -1,4 +1,3 @@
-import { applyMarkdownPatch, formatMarkdownPatchError } from '@lobechat/markdown-patch';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
import type {
@@ -6,7 +5,7 @@ import type {
CreateDocumentArgs,
EditDocumentArgs,
ListDocumentsArgs,
- PatchDocumentArgs,
+ ModifyDocumentNodesArgs,
ReadDocumentArgs,
ReadDocumentByFilenameArgs,
RemoveDocumentArgs,
@@ -30,13 +29,20 @@ interface AgentDocumentRecord {
* and uses for subsequent operations (read/edit/remove/...).
*/
id: string;
+ litexml?: string;
title?: string;
}
interface AgentDocumentOperationContext {
agentId?: string | null;
+ currentDocumentId?: string | null;
+ scope?: string | null;
+ topicId?: string | null;
}
+const CURRENT_PAGE_DOCUMENT_WRITE_ERROR_CODE = 'CURRENT_PAGE_DOCUMENT_WRITE_FORBIDDEN';
+const CURRENT_PAGE_DOCUMENT_WRITE_ERROR_TYPE = 'CurrentPageDocumentWriteForbidden';
+
export interface AgentDocumentsRuntimeService {
copyDocument: (
params: CopyDocumentArgs & {
@@ -48,6 +54,12 @@ export interface AgentDocumentsRuntimeService {
agentId: string;
},
) => Promise<AgentDocumentRecord | undefined>;
+ createTopicDocument: (
+ params: CreateDocumentArgs & {
+ agentId: string;
+ topicId: string;
+ },
+ ) => Promise<AgentDocumentRecord | undefined>;
editDocument: (
params: EditDocumentArgs & {
agentId: string;
@@ -58,6 +70,17 @@ export interface AgentDocumentsRuntimeService {
agentId: string;
},
) => Promise<AgentDocumentRecord[]>;
+ listTopicDocuments: (
+ params: ListDocumentsArgs & {
+ agentId: string;
+ topicId: string;
+ },
+ ) => Promise<AgentDocumentRecord[]>;
+ modifyNodes: (
+ params: ModifyDocumentNodesArgs & {
+ agentId: string;
+ },
+ ) => Promise<AgentDocumentRecord | undefined>;
readDocument: (
params: ReadDocumentArgs & {
agentId: string;
@@ -98,8 +121,72 @@ export class AgentDocumentsExecutionRuntime {
return context.agentId;
}
+ private getCurrentDocumentId(context?: AgentDocumentOperationContext) {
+ if (context?.scope !== 'page') return;
+ return context.currentDocumentId ?? undefined;
+ }
+
+ private resolveTopicId(context?: AgentDocumentOperationContext) {
+ if (!context?.topicId) return;
+ return context.topicId;
+ }
+
+ private buildCurrentPageDocumentWriteBlockedResult(apiName: string): BuiltinServerRuntimeOutput {
+ const message =
+ `Cannot use lobe-agent-documents.${apiName} on the current page document ` +
+ `while page scope is active. Use lobe-page-agent so the open editor shows a diff node ` +
+ `for review instead of writing directly to the database.`;
+
+ return {
+ content: message,
+ error: {
+ code: CURRENT_PAGE_DOCUMENT_WRITE_ERROR_CODE,
+ kind: 'replan',
+ message,
+ type: CURRENT_PAGE_DOCUMENT_WRITE_ERROR_TYPE,
+ },
+ success: false,
+ };
+ }
+
+ private isCurrentPageDocument(
+ doc: AgentDocumentRecord | undefined,
+ context?: AgentDocumentOperationContext,
+ ) {
+ const currentDocumentId = this.getCurrentDocumentId(context);
+ if (!currentDocumentId || !doc?.documentId) return false;
+
+ return doc.documentId === currentDocumentId;
+ }
+
+ private async shouldBlockUpsertForCurrentPageDocument(
+ agentId: string,
+ filename: string,
+ context?: AgentDocumentOperationContext,
+ ) {
+ const currentDocumentId = this.getCurrentDocumentId(context);
+ if (!currentDocumentId) return false;
+
+ const docs = await this.service.listDocuments({ agentId });
+
+ return docs.some((doc) => doc.documentId === currentDocumentId && doc.filename === filename);
+ }
+
+ private formatDocumentReadContent(
+ doc: AgentDocumentRecord,
+ format: 'xml' | 'markdown' | 'both' = 'xml',
+ ) {
+ const markdown = doc.content || '';
+ const xml = doc.litexml || '';
+
+ if (format === 'markdown') return markdown;
+ if (format === 'both') return JSON.stringify({ markdown, xml });
+
+ return xml || markdown;
+ }
+
async listDocuments(
- _args: ListDocumentsArgs,
+ args: ListDocumentsArgs,
context?: AgentDocumentOperationContext,
): Promise<BuiltinServerRuntimeOutput> {
const agentId = this.resolveAgentId(context);
@@ -110,8 +197,21 @@ export class AgentDocumentsExecutionRuntime {
};
}
- const docs = await this.service.listDocuments({ agentId });
+ const target = args.target ?? 'agent';
+ const topicId = this.resolveTopicId(context);
+ if (target === 'currentTopic' && !topicId) {
+ return {
+ content: 'Cannot list current topic documents without topicId context.',
+ success: false,
+ };
+ }
+
+ const docs =
+ target === 'currentTopic'
+ ? await this.service.listTopicDocuments({ agentId, target, topicId: topicId! })
+ : await this.service.listDocuments({ agentId, target });
const list = docs.map((d) => ({
+ ...(d.documentId ? { documentId: d.documentId } : {}),
filename: d.filename ?? d.title ?? '',
id: d.id,
title: d.title,
@@ -139,9 +239,17 @@ export class AgentDocumentsExecutionRuntime {
const doc = await this.service.readDocumentByFilename({ ...args, agentId });
if (!doc) return { content: `Document not found: ${args.filename}`, success: false };
+ const format = args.format ?? 'xml';
+
return {
- content: doc.content || '',
- state: { content: doc.content, filename: args.filename, id: doc.id, title: doc.title },
+ content: this.formatDocumentReadContent(doc, format),
+ state: {
+ content: doc.content,
+ filename: args.filename,
+ id: doc.id,
+ title: doc.title,
+ xml: doc.litexml,
+ },
success: true,
};
}
@@ -158,6 +266,10 @@ export class AgentDocumentsExecutionRuntime {
};
}
+ if (await this.shouldBlockUpsertForCurrentPageDocument(agentId, args.filename, context)) {
+ return this.buildCurrentPageDocumentWriteBlockedResult('upsertDocumentByFilename');
+ }
+
const doc = await this.service.upsertDocumentByFilename({ ...args, agentId });
if (!doc) return { content: `Failed to upsert document: ${args.filename}`, success: false };
@@ -180,7 +292,19 @@ export class AgentDocumentsExecutionRuntime {
};
}
- const created = await this.service.createDocument({ ...args, agentId });
+ const target = args.target ?? 'agent';
+ const topicId = this.resolveTopicId(context);
+ if (target === 'currentTopic' && !topicId) {
+ return {
+ content: 'Cannot create current topic document without topicId context.',
+ success: false,
+ };
+ }
+
+ const created =
+ target === 'currentTopic'
+ ? await this.service.createTopicDocument({ ...args, agentId, topicId: topicId! })
+ : await this.service.createDocument({ ...args, agentId });
if (!created) return { content: 'Failed to create agent document.', success: false };
return {
@@ -205,9 +329,11 @@ export class AgentDocumentsExecutionRuntime {
const doc = await this.service.readDocument({ ...args, agentId });
if (!doc) return { content: `Document not found: ${args.id}`, success: false };
+ const format = args.format ?? 'xml';
+
return {
- content: doc.content || '',
- state: { content: doc.content, id: doc.id, title: doc.title },
+ content: this.formatDocumentReadContent(doc, format),
+ state: { content: doc.content, id: doc.id, title: doc.title, xml: doc.litexml },
success: true,
};
}
@@ -224,8 +350,15 @@ export class AgentDocumentsExecutionRuntime {
};
}
+ const existing = await this.service.readDocument({ agentId, id: args.id });
+ if (!existing) return { content: `Document not found: ${args.id}`, success: false };
+
+ if (this.isCurrentPageDocument(existing, context)) {
+ return this.buildCurrentPageDocumentWriteBlockedResult('editDocument');
+ }
+
const doc = await this.service.editDocument({ ...args, agentId });
- if (!doc) return { content: `Document not found: ${args.id}`, success: false };
+ if (!doc) return { content: `Failed to update document ${args.id}.`, success: false };
return {
content: `Updated document ${args.id}.`,
@@ -234,42 +367,46 @@ export class AgentDocumentsExecutionRuntime {
};
}
- async patchDocument(
- args: PatchDocumentArgs,
+ async modifyNodes(
+ args: ModifyDocumentNodesArgs,
context?: AgentDocumentOperationContext,
): Promise<BuiltinServerRuntimeOutput> {
const agentId = this.resolveAgentId(context);
if (!agentId) {
return {
- content: 'Cannot patch agent document without agentId context.',
+ content: 'Cannot modify agent document nodes without agentId context.',
success: false,
};
}
- const doc = await this.service.readDocument({ agentId, id: args.id });
- if (!doc) return { content: `Document not found: ${args.id}`, success: false };
+ const existing = await this.service.readDocument({ agentId, id: args.id });
+ if (!existing) return { content: `Document not found: ${args.id}`, success: false };
- const patched = applyMarkdownPatch(doc.content ?? '', args.hunks);
- if (!patched.ok) {
- const message = formatMarkdownPatchError(patched.error);
- return {
- content: message,
- error: { body: patched.error, message, type: patched.error.code },
- state: { error: patched.error, id: args.id },
- success: false,
- };
+ if (this.isCurrentPageDocument(existing, context)) {
+ return this.buildCurrentPageDocumentWriteBlockedResult('modifyNodes');
+ }
+
+ const operations = Array.isArray(args.operations) ? args.operations : [];
+ if (operations.length === 0) {
+ return { content: 'No operations provided.', success: false };
}
- const updated = await this.service.editDocument({
- agentId,
- content: patched.content,
- id: args.id,
- });
- if (!updated) return { content: `Failed to patch document ${args.id}.`, success: false };
+ const updated = await this.service.modifyNodes({ agentId, id: args.id, operations });
+ if (!updated) return { content: `Failed to modify document ${args.id}.`, success: false };
+
+ const results = operations.map((operation) => ({
+ action: operation.action,
+ success: true,
+ }));
return {
- content: `Patched document ${args.id}. Applied ${patched.applied} hunk(s).`,
- state: { applied: patched.applied, id: args.id, patched: true },
+ content: `Modified document ${args.id}. Applied ${results.length} operation(s).`,
+ state: {
+ id: args.id,
+ results,
+ successCount: results.length,
+ totalCount: results.length,
+ },
success: true,
};
}
@@ -308,8 +445,15 @@ export class AgentDocumentsExecutionRuntime {
};
}
+ const existing = await this.service.readDocument({ agentId, id: args.id });
+ if (!existing) return { content: `Document not found: ${args.id}`, success: false };
+
+ if (this.isCurrentPageDocument(existing, context)) {
+ return this.buildCurrentPageDocumentWriteBlockedResult('renameDocument');
+ }
+
const doc = await this.service.renameDocument({ ...args, agentId });
- if (!doc) return { content: `Document not found: ${args.id}`, success: false };
+ if (!doc) return { content: `Failed to rename document ${args.id}.`, success: false };
return {
content: `Renamed document ${args.id} to "${args.newTitle}".`,
diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/PatchDocument/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/ModifyNodes/index.tsx
similarity index 64%
rename from packages/builtin-tool-agent-documents/src/client/Inspector/PatchDocument/index.tsx
rename to packages/builtin-tool-agent-documents/src/client/Inspector/ModifyNodes/index.tsx
index e13bb9ce574..a61f605f503 100644
--- a/packages/builtin-tool-agent-documents/src/client/Inspector/PatchDocument/index.tsx
+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/ModifyNodes/index.tsx
@@ -7,10 +7,10 @@ import { useTranslation } from 'react-i18next';
import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
-import type { PatchDocumentArgs, PatchDocumentState } from '../../../types';
+import type { ModifyDocumentNodesArgs, ModifyDocumentNodesState } from '../../../types';
-export const PatchDocumentInspector = memo<
- BuiltinInspectorProps<PatchDocumentArgs, PatchDocumentState>
+export const ModifyNodesInspector = memo<
+ BuiltinInspectorProps<ModifyDocumentNodesArgs, ModifyDocumentNodesState>
>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
const { t } = useTranslation('plugin');
const id = args?.id || partialArgs?.id;
@@ -18,7 +18,7 @@ export const PatchDocumentInspector = memo<
if (isArgumentsStreaming && !id) {
return (
<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
- <span>{t('builtins.lobe-agent-documents.apiName.patchDocument')}</span>
+ <span>{t('builtins.lobe-agent-documents.apiName.modifyNodes')}</span>
</div>
);
}
@@ -30,12 +30,12 @@ export const PatchDocumentInspector = memo<
(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
)}
>
- <span>{t('builtins.lobe-agent-documents.apiName.patchDocument')}: </span>
+ <span>{t('builtins.lobe-agent-documents.apiName.modifyNodes')}: </span>
{id && <span className={highlightTextStyles.primary}>{id}</span>}
</div>
);
});
-PatchDocumentInspector.displayName = 'PatchDocumentInspector';
+ModifyNodesInspector.displayName = 'ModifyNodesInspector';
-export default PatchDocumentInspector;
+export default ModifyNodesInspector;
diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/index.ts b/packages/builtin-tool-agent-documents/src/client/Inspector/index.ts
index e7ad82e4857..8d1aefcdc40 100644
--- a/packages/builtin-tool-agent-documents/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/index.ts
@@ -5,7 +5,7 @@ import { CopyDocumentInspector } from './CopyDocument';
import { CreateDocumentInspector } from './CreateDocument';
import { EditDocumentInspector } from './EditDocument';
import { ListDocumentsInspector } from './ListDocuments';
-import { PatchDocumentInspector } from './PatchDocument';
+import { ModifyNodesInspector } from './ModifyNodes';
import { ReadDocumentInspector } from './ReadDocument';
import { ReadDocumentByFilenameInspector } from './ReadDocumentByFilename';
import { RemoveDocumentInspector } from './RemoveDocument';
@@ -18,7 +18,7 @@ export const AgentDocumentsInspectors: Record<string, BuiltinInspector> = {
[AgentDocumentsApiName.createDocument]: CreateDocumentInspector as BuiltinInspector,
[AgentDocumentsApiName.editDocument]: EditDocumentInspector as BuiltinInspector,
[AgentDocumentsApiName.listDocuments]: ListDocumentsInspector as BuiltinInspector,
- [AgentDocumentsApiName.patchDocument]: PatchDocumentInspector as BuiltinInspector,
+ [AgentDocumentsApiName.modifyNodes]: ModifyNodesInspector as BuiltinInspector,
[AgentDocumentsApiName.readDocument]: ReadDocumentInspector as BuiltinInspector,
[AgentDocumentsApiName.readDocumentByFilename]:
ReadDocumentByFilenameInspector as BuiltinInspector,
diff --git a/packages/builtin-tool-agent-documents/src/executor/index.ts b/packages/builtin-tool-agent-documents/src/executor/index.ts
index fecb7144aaf..b110b391d5a 100644
--- a/packages/builtin-tool-agent-documents/src/executor/index.ts
+++ b/packages/builtin-tool-agent-documents/src/executor/index.ts
@@ -8,7 +8,7 @@ import {
type CreateDocumentArgs,
type EditDocumentArgs,
type ListDocumentsArgs,
- type PatchDocumentArgs,
+ type ModifyDocumentNodesArgs,
type ReadDocumentArgs,
type ReadDocumentByFilenameArgs,
type RemoveDocumentArgs,
@@ -32,85 +32,134 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsAp
params: ListDocumentsArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.listDocuments(params, { agentId: ctx.agentId });
+ return this.runtime.listDocuments(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ topicId: ctx.topicId,
+ });
};
readDocumentByFilename = async (
params: ReadDocumentByFilenameArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.readDocumentByFilename(params, { agentId: ctx.agentId });
+ return this.runtime.readDocumentByFilename(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ });
};
upsertDocumentByFilename = async (
params: UpsertDocumentByFilenameArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.upsertDocumentByFilename(params, { agentId: ctx.agentId });
+ return this.runtime.upsertDocumentByFilename(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ });
};
createDocument = async (
params: CreateDocumentArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.createDocument(params, { agentId: ctx.agentId });
+ return this.runtime.createDocument(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ topicId: ctx.topicId,
+ });
};
readDocument = async (
params: ReadDocumentArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.readDocument(params, { agentId: ctx.agentId });
+ return this.runtime.readDocument(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ });
};
editDocument = async (
params: EditDocumentArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.editDocument(params, { agentId: ctx.agentId });
+ return this.runtime.editDocument(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ });
};
- patchDocument = async (
- params: PatchDocumentArgs,
+ modifyNodes = async (
+ params: ModifyDocumentNodesArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.patchDocument(params, { agentId: ctx.agentId });
+ return this.runtime.modifyNodes(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ });
};
removeDocument = async (
params: RemoveDocumentArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.removeDocument(params, { agentId: ctx.agentId });
+ return this.runtime.removeDocument(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ });
};
renameDocument = async (
params: RenameDocumentArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.renameDocument(params, { agentId: ctx.agentId });
+ return this.runtime.renameDocument(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ });
};
copyDocument = async (
params: CopyDocumentArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.copyDocument(params, { agentId: ctx.agentId });
+ return this.runtime.copyDocument(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ });
};
updateLoadRule = async (
params: UpdateLoadRuleArgs,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- return this.runtime.updateLoadRule(params, { agentId: ctx.agentId });
+ return this.runtime.updateLoadRule(params, {
+ agentId: ctx.agentId,
+ currentDocumentId: ctx.documentId,
+ scope: ctx.scope,
+ });
};
}
const fallbackRuntime = new AgentDocumentsExecutionRuntime({
copyDocument: async ({ agentId: _agentId }) => undefined,
createDocument: async () => undefined,
+ createTopicDocument: async () => undefined,
editDocument: async ({ agentId: _agentId }) => undefined,
listDocuments: async () => [],
+ listTopicDocuments: async () => [],
+ modifyNodes: async ({ agentId: _agentId }) => undefined,
readDocument: async ({ agentId: _agentId }) => undefined,
readDocumentByFilename: async () => undefined,
removeDocument: async ({ agentId: _agentId }) => false,
diff --git a/packages/builtin-tool-agent-documents/src/index.ts b/packages/builtin-tool-agent-documents/src/index.ts
index f98587d0aa7..c762059986a 100644
--- a/packages/builtin-tool-agent-documents/src/index.ts
+++ b/packages/builtin-tool-agent-documents/src/index.ts
@@ -12,8 +12,9 @@ export {
type EditDocumentState,
type ListDocumentsArgs,
type ListDocumentsState,
- type PatchDocumentArgs,
- type PatchDocumentState,
+ type ModifyDocumentNodesArgs,
+ type ModifyDocumentNodesState,
+ type ModifyDocumentOperation,
type ReadDocumentArgs,
type ReadDocumentByFilenameArgs,
type ReadDocumentByFilenameState,
diff --git a/packages/builtin-tool-agent-documents/src/manifest.ts b/packages/builtin-tool-agent-documents/src/manifest.ts
index 68536d5fc28..c5eab6a25c0 100644
--- a/packages/builtin-tool-agent-documents/src/manifest.ts
+++ b/packages/builtin-tool-agent-documents/src/manifest.ts
@@ -15,6 +15,13 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
description: 'Document content in markdown or plain text.',
type: 'string',
},
+ target: {
+ default: 'agent',
+ description:
+ 'Where to create the document. Use currentTopic to associate it with the current topic; defaults to agent-scoped documents.',
+ enum: ['agent', 'currentTopic'],
+ type: 'string',
+ },
title: {
description: 'Document title.',
type: 'string',
@@ -26,10 +33,17 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
},
{
description:
- 'Read an existing agent document by ID (similar intent to cat/read operation). Use this before edits or deletes when needed.',
+ 'Read an existing agent document by ID. Prefer XML format before node-level edits because XML includes stable node IDs.',
name: AgentDocumentsApiName.readDocument,
parameters: {
properties: {
+ format: {
+ default: 'xml',
+ description:
+ 'The format to return. Use "xml" for node-level edits, "markdown" for plain text, or "both". Defaults to "xml".',
+ enum: ['xml', 'markdown', 'both'],
+ type: 'string',
+ },
id: {
description: 'Target document ID.',
type: 'string',
@@ -41,7 +55,7 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
},
{
description:
- 'Edit an existing agent document content by ID. Use this for content changes, not title rename. Prefer patchDocument for small edits.',
+ 'Edit an existing agent document content by ID. Use this for full-content replacement, not title rename. Prefer modifyNodes for targeted content edits.',
name: AgentDocumentsApiName.editDocument,
parameters: {
properties: {
@@ -60,41 +74,64 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
},
{
description:
- "Apply byte-exact SEARCH/REPLACE hunks to an existing agent document by ID. Preferred over editDocument for small edits because it avoids resending the full document. Each hunk's search must match the current document exactly (whitespace, punctuation, casing). If the search appears multiple times, add surrounding context to make it unique or set replaceAll=true. On failure (HUNK_NOT_FOUND / HUNK_AMBIGUOUS), adjust and retry; fall back to editDocument only for structural rewrites that touch most of the file.",
- name: AgentDocumentsApiName.patchDocument,
+ 'Perform LiteXML node operations (insert, modify, remove) on an agent document by ID. Use this for content edits after reading the document in XML format.',
+ name: AgentDocumentsApiName.modifyNodes,
parameters: {
properties: {
- hunks: {
- description: 'Ordered list of SEARCH/REPLACE hunks applied sequentially.',
+ id: {
+ description: 'Target document ID.',
+ type: 'string',
+ },
+ operations: {
+ description:
+ 'Array of node operations. For insert, provide beforeId or afterId plus LiteXML without an id. For modify, provide LiteXML with existing node IDs. For remove, provide the node id.',
items: {
- additionalProperties: false,
- properties: {
- replace: {
- description: 'Replacement text; may be empty to delete the matched region.',
- type: 'string',
+ oneOf: [
+ {
+ properties: {
+ action: { const: 'insert', type: 'string' },
+ beforeId: { description: 'ID of the node to insert before.', type: 'string' },
+ litexml: { description: 'LiteXML node to insert.', type: 'string' },
+ },
+ required: ['action', 'beforeId', 'litexml'],
+ type: 'object',
},
- replaceAll: {
- description:
- 'Replace every occurrence of search. Defaults to false; leave unset unless you explicitly want a global replace.',
- type: 'boolean',
+ {
+ properties: {
+ action: { const: 'insert', type: 'string' },
+ afterId: { description: 'ID of the node to insert after.', type: 'string' },
+ litexml: { description: 'LiteXML node to insert.', type: 'string' },
+ },
+ required: ['action', 'afterId', 'litexml'],
+ type: 'object',
},
- search: {
- description: 'Byte-exact substring to locate in the current document.',
- type: 'string',
+ {
+ properties: {
+ action: { const: 'modify', type: 'string' },
+ litexml: {
+ description:
+ 'LiteXML string or array of strings with existing node IDs to update.',
+ oneOf: [{ type: 'string' }, { items: { type: 'string' }, type: 'array' }],
+ },
+ },
+ required: ['action', 'litexml'],
+ type: 'object',
},
- },
- required: ['search', 'replace'],
- type: 'object',
+ {
+ properties: {
+ action: { const: 'remove', type: 'string' },
+ id: { description: 'ID of the node to remove.', type: 'string' },
+ },
+ required: ['action', 'id'],
+ type: 'object',
+ },
+ ],
},
minItems: 1,
type: 'array',
},
- id: {
- description: 'Target document ID.',
- type: 'string',
- },
},
- required: ['id', 'hunks'],
+ required: ['id', 'operations'],
type: 'object',
},
},
@@ -151,20 +188,35 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
},
{
description:
- 'List all agent documents. Returns document id, filename, and title for each document.',
+ 'List agent documents. Defaults to all agent documents; use target=currentTopic to list documents associated with the current topic.',
name: AgentDocumentsApiName.listDocuments,
parameters: {
- properties: {},
+ properties: {
+ target: {
+ default: 'agent',
+ description:
+ 'Which document set to list. currentTopic filters to documents associated with the current topic.',
+ enum: ['agent', 'currentTopic'],
+ type: 'string',
+ },
+ },
required: [],
type: 'object',
},
},
{
description:
- 'Read an existing agent document by its filename (similar intent to cat by filename). Use when you know the filename but not the id.',
+ 'Read an existing agent document by its filename. Prefer XML format before node-level edits because XML includes stable node IDs.',
name: AgentDocumentsApiName.readDocumentByFilename,
parameters: {
properties: {
+ format: {
+ default: 'xml',
+ description:
+ 'The format to return. Use "xml" for node-level edits, "markdown" for plain text, or "both". Defaults to "xml".',
+ enum: ['xml', 'markdown', 'both'],
+ type: 'string',
+ },
filename: {
description: 'Target document filename.',
type: 'string',
diff --git a/packages/builtin-tool-agent-documents/src/systemRole.ts b/packages/builtin-tool-agent-documents/src/systemRole.ts
index e25d3e751f2..43f65e9d49f 100644
--- a/packages/builtin-tool-agent-documents/src/systemRole.ts
+++ b/packages/builtin-tool-agent-documents/src/systemRole.ts
@@ -4,7 +4,7 @@ export const systemPrompt = `You have access to an Agent Documents tool for crea
1. Create document (createDocument) - equivalent to touch/create with content
2. Read document (readDocument) - equivalent to cat/read
3. Edit document (editDocument) - full-content overwrite
-4. Patch document (patchDocument) - apply byte-exact SEARCH/REPLACE hunks; preferred for small edits
+4. Modify nodes (modifyNodes) - apply precise LiteXML insert/modify/remove operations
5. Remove document (removeDocument) - equivalent to rm/delete
6. Rename document (renameDocument) - equivalent to mv/rename
7. Copy document (copyDocument) - equivalent to cp/copy
@@ -21,10 +21,11 @@ export const systemPrompt = `You have access to an Agent Documents tool for crea
<tool_selection_guidelines>
- By default, if the user does not explicitly specify otherwise, and the relevant Agent Documents tool is available for the task, prefer Agent Documents over Cloud Sandbox because it is easier for collaboration and multi-agent coordination.
-- **createDocument**: create a new document with title + content.
-- **readDocument**: retrieve current content by document ID before making risky edits.
-- **editDocument**: overwrite the full content of an existing document. Prefer patchDocument for small edits.
-- **patchDocument**: apply ordered SEARCH/REPLACE hunks to an existing document. Each search must match byte-exact (whitespace/punctuation/casing). Preferred over editDocument for small edits because it avoids resending the full file; on HUNK_NOT_FOUND or HUNK_AMBIGUOUS, adjust the hunk and retry.
+- **createDocument**: create a new document with title + content. Use target="currentTopic" only when the user asks to create a document in the current topic; otherwise omit target for an agent-scoped document.
+- **listDocuments**: list agent documents. Use target="currentTopic" when the user asks about documents in the current topic.
+- **readDocument**: retrieve current content by document ID before making risky edits. Prefer format="xml" when you may edit content, because XML includes stable node IDs.
+- **modifyNodes**: preferred content-edit API. Use LiteXML insert/modify/remove operations after reading XML. For modify operations, include the existing node ID in the LiteXML.
+- **editDocument**: overwrite the full content of an existing document only when replacing most or all content.
- **removeDocument**: permanently remove a document by ID.
- **renameDocument**: change document title only.
- **copyDocument**: duplicate a document, optionally with a new title.
@@ -33,7 +34,7 @@ export const systemPrompt = `You have access to an Agent Documents tool for crea
<best_practices>
- Prefer Agent Documents for shared working context unless the user explicitly requires Cloud Sandbox or another tool.
-- Prefer readDocument before edit/remove if content state is uncertain.
+- Prefer readDocument with format="xml" before modifyNodes/remove if content state is uncertain.
- Use renameDocument for title-only changes; avoid rewriting content unnecessarily.
- Use copyDocument before major edits when user may want a backup version.
- Keep load-rule changes explicit and summarize their effect, especially when they change permissions, sharing scope, load location, or load strategy.
diff --git a/packages/builtin-tool-agent-documents/src/types.ts b/packages/builtin-tool-agent-documents/src/types.ts
index 633f4569b5e..fa1a4ad0759 100644
--- a/packages/builtin-tool-agent-documents/src/types.ts
+++ b/packages/builtin-tool-agent-documents/src/types.ts
@@ -1,5 +1,3 @@
-import type { MarkdownPatchHunk } from '@lobechat/markdown-patch';
-
export const AgentDocumentsIdentifier = 'lobe-agent-documents';
export const AgentDocumentsApiName = {
@@ -7,7 +5,7 @@ export const AgentDocumentsApiName = {
copyDocument: 'copyDocument',
editDocument: 'editDocument',
listDocuments: 'listDocuments',
- patchDocument: 'patchDocument',
+ modifyNodes: 'modifyNodes',
readDocument: 'readDocument',
readDocumentByFilename: 'readDocumentByFilename',
removeDocument: 'removeDocument',
@@ -18,6 +16,7 @@ export const AgentDocumentsApiName = {
export interface CreateDocumentArgs {
content: string;
+ target?: 'agent' | 'currentTopic';
title: string;
}
@@ -26,6 +25,7 @@ export interface CreateDocumentState {
}
export interface ReadDocumentArgs {
+ format?: 'xml' | 'markdown' | 'both';
id: string;
}
@@ -33,6 +33,7 @@ export interface ReadDocumentState {
content?: string;
id: string;
title?: string;
+ xml?: string;
}
export interface EditDocumentArgs {
@@ -45,15 +46,46 @@ export interface EditDocumentState {
updated: boolean;
}
-export interface PatchDocumentArgs {
- hunks: MarkdownPatchHunk[];
+export type ModifyDocumentInsertOperation =
+ | {
+ action: 'insert';
+ afterId: string;
+ litexml: string;
+ }
+ | {
+ action: 'insert';
+ beforeId: string;
+ litexml: string;
+ };
+
+export interface ModifyDocumentUpdateOperation {
+ action: 'modify';
+ litexml: string | string[];
+}
+
+export interface ModifyDocumentRemoveOperation {
+ action: 'remove';
id: string;
}
-export interface PatchDocumentState {
- applied: number;
+export type ModifyDocumentOperation =
+ | ModifyDocumentInsertOperation
+ | ModifyDocumentRemoveOperation
+ | ModifyDocumentUpdateOperation;
+
+export interface ModifyDocumentNodesArgs {
id: string;
- patched: boolean;
+ operations: ModifyDocumentOperation[];
+}
+
+export interface ModifyDocumentNodesState {
+ id: string;
+ results: Array<{
+ action: 'insert' | 'remove' | 'modify';
+ success: boolean;
+ }>;
+ successCount: number;
+ totalCount: number;
}
export interface RemoveDocumentArgs {
@@ -121,14 +153,17 @@ export interface AgentDocumentReference {
title?: string;
}
-export interface ListDocumentsArgs {}
+export interface ListDocumentsArgs {
+ target?: 'agent' | 'currentTopic';
+}
export interface ListDocumentsState {
- documents: { filename: string; id: string; title?: string }[];
+ documents: { documentId?: string; filename: string; id: string; title?: string }[];
}
export interface ReadDocumentByFilenameArgs {
filename: string;
+ format?: 'xml' | 'markdown' | 'both';
}
export interface ReadDocumentByFilenameState {
@@ -136,6 +171,7 @@ export interface ReadDocumentByFilenameState {
filename: string;
id: string;
title?: string;
+ xml?: string;
}
export interface UpsertDocumentByFilenameArgs {
diff --git a/packages/builtin-tool-notebook/src/executor/index.ts b/packages/builtin-tool-notebook/src/executor/index.ts
index c4e233eb8e5..4833c2c8577 100644
--- a/packages/builtin-tool-notebook/src/executor/index.ts
+++ b/packages/builtin-tool-notebook/src/executor/index.ts
@@ -5,6 +5,11 @@
* The NotebookService is injected via constructor so both client and server can provide their own implementation.
*
* Note: listDocuments is not exposed as a tool - it's automatically injected by the system.
+ *
+ * @deprecated The notebook tool is no longer injected into the LLM tools
+ * engine. This executor is retained so that legacy tool-call messages can
+ * still resolve on execution. New flows should use
+ * `@lobechat/builtin-tool-agent-documents`.
*/
import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
diff --git a/packages/builtin-tool-notebook/src/manifest.ts b/packages/builtin-tool-notebook/src/manifest.ts
index 4a57d34864f..95e9d6c27bb 100644
--- a/packages/builtin-tool-notebook/src/manifest.ts
+++ b/packages/builtin-tool-notebook/src/manifest.ts
@@ -3,6 +3,14 @@ import type { BuiltinToolManifest } from '@lobechat/types';
import { systemPrompt } from './systemRole';
import { NotebookApiName, NotebookIdentifier } from './types';
+/**
+ * @deprecated Notebook is no longer injected into the LLM tools engine.
+ * Use `@lobechat/builtin-tool-agent-documents` for new document tooling; the
+ * topic → page flow now calls `agentDocumentService.createForTopic`, which
+ * creates an agent document and records a `topic_documents` association in
+ * the same transaction. This manifest is kept for type/import compatibility
+ * with legacy code that still references `NotebookManifest.identifier`.
+ */
export const NotebookManifest: BuiltinToolManifest = {
api: [
{
diff --git a/packages/builtin-tool-notebook/src/types.ts b/packages/builtin-tool-notebook/src/types.ts
index 33293a367ee..6db13dab96c 100644
--- a/packages/builtin-tool-notebook/src/types.ts
+++ b/packages/builtin-tool-notebook/src/types.ts
@@ -1,3 +1,14 @@
+/**
+ * @deprecated The notebook builtin tool is deprecated. Topic-scoped documents
+ * now flow through the agent-documents pipeline (see
+ * `@lobechat/builtin-tool-agent-documents`) while retaining the
+ * `topic_documents` junction for topic-scoped listing.
+ *
+ * The manifest is no longer registered with the LLM tools engine, so the model
+ * can no longer invoke this tool. The identifier, executor, and server runtime
+ * are preserved only to keep legacy tool-call messages rendering and
+ * executing. Do not use these exports in new code.
+ */
export const NotebookIdentifier = 'lobe-notebook';
export const NotebookApiName = {
diff --git a/packages/builtin-tool-page-agent/src/executor/index.ts b/packages/builtin-tool-page-agent/src/executor/index.ts
index 2efc03c162b..a6aa7f9f96b 100644
--- a/packages/builtin-tool-page-agent/src/executor/index.ts
+++ b/packages/builtin-tool-page-agent/src/executor/index.ts
@@ -8,6 +8,7 @@ import type {
} from '@lobechat/editor-runtime';
import type { BuiltinToolResult } from '@lobechat/types';
import { BaseExecutor } from '@lobechat/types';
+import debug from 'debug';
import type {
EditTitleState,
@@ -18,6 +19,8 @@ import type {
} from '../types';
import { PageAgentIdentifier } from '../types';
+const log = debug('lobe-page-agent:executor');
+
/**
* API enum for Page Agent executor
* Only includes APIs that are exposed in the manifest
@@ -39,6 +42,49 @@ const PageAgentApiName = {
replaceText: 'replaceText',
} as const;
+const summarizeError = (error: unknown) => {
+ if (error instanceof Error) {
+ return {
+ message: error.message,
+ name: error.name,
+ stack: error.stack,
+ };
+ }
+
+ return { message: String(error) };
+};
+
+const getRuntimeDebugSnapshot = (runtime: EditorRuntime) => {
+ const candidate = runtime as EditorRuntime & {
+ getDebugSnapshot?: () => unknown;
+ };
+
+ return candidate.getDebugSnapshot?.();
+};
+
+const PAGE_EDITOR_NOT_MOUNTED_MESSAGE =
+ 'Page editor is not currently mounted. This topic was started in the page editor, but the editor is not active in the current view. ' +
+ 'Do not retry initPage / editTitle / modifyNodes / replaceText / getPageContent here — they require a mounted editor. ' +
+ 'To read or modify the topic document, use lobe-agent-documents (readDocument / editDocument / modifyNodes / upsertDocumentByFilename).';
+
+const buildEditorNotMountedResult = (
+ runtime: EditorRuntime,
+ apiName: string,
+): BuiltinToolResult => ({
+ content: PAGE_EDITOR_NOT_MOUNTED_MESSAGE,
+ error: {
+ body: {
+ apiName,
+ code: 'PAGE_EDITOR_NOT_MOUNTED',
+ kind: 'replan',
+ runtime: getRuntimeDebugSnapshot(runtime),
+ },
+ message: PAGE_EDITOR_NOT_MOUNTED_MESSAGE,
+ type: 'PageEditorNotMounted',
+ },
+ success: false,
+});
+
/**
* Page Agent Executor
*
@@ -61,6 +107,22 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
constructor(runtime: EditorRuntime) {
super();
this.runtime = runtime;
+
+ // scope is topic-bound, not route-bound: navigating away from the page
+ // editor keeps scope==='page' on the same topic, so without this guard
+ // the LLM can still call page-agent APIs against a stale editor ref.
+ const baseInvoke = this.invoke;
+ this.invoke = async (apiName, params, ctx) => {
+ if (this.hasApi(apiName) && !this.runtime.isReady()) {
+ console.warn('[PageAgentToolCall] blocked: editor not mounted', {
+ apiName,
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+ return buildEditorNotMountedResult(this.runtime, apiName);
+ }
+
+ return baseInvoke(apiName, params, ctx);
+ };
}
// ==================== Initialize ====================
@@ -69,6 +131,11 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
* Initialize a new document from Markdown content
*/
initPage = async (params: InitDocumentArgs): Promise<BuiltinToolResult> => {
+ log('[PageAgentToolCall] initPage:start', {
+ markdownLength: params.markdown.length,
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+
try {
const result = await this.runtime.initPage(params);
@@ -81,9 +148,20 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
rootId: 'root',
};
+ log('[PageAgentToolCall] initPage:success', {
+ nodeCount: result.nodeCount,
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ titleExtracted: !!result.extractedTitle,
+ });
+
return { content, state, success: true };
} catch (error) {
const err = error as Error;
+ console.error('[PageAgentToolCall] initPage:error', {
+ error: summarizeError(error),
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+
return {
error: {
body: error,
@@ -101,6 +179,11 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
* Edit the page title
*/
editTitle = async (params: EditTitleArgs): Promise<BuiltinToolResult> => {
+ log('[PageAgentToolCall] editTitle:start', {
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ titleLength: params.title.length,
+ });
+
try {
const result = await this.runtime.editTitle(params);
@@ -111,9 +194,19 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
previousTitle: result.previousTitle,
};
+ log('[PageAgentToolCall] editTitle:success', {
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ titleLength: params.title.length,
+ });
+
return { content, state, success: true };
} catch (error) {
const err = error as Error;
+ console.error('[PageAgentToolCall] editTitle:error', {
+ error: summarizeError(error),
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+
return {
error: {
body: error,
@@ -131,6 +224,11 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
* Get page content in XML, markdown, or both formats
*/
getPageContent = async (params: GetPageContentArgs): Promise<BuiltinToolResult> => {
+ log('[PageAgentToolCall] getPageContent:start', {
+ format: params.format,
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+
try {
const result = await this.runtime.getPageContent(params);
@@ -150,9 +248,21 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
// We return the formatted content based on the requested format
const content = result.markdown || result.xml || '';
+ log('[PageAgentToolCall] getPageContent:success', {
+ format: params.format,
+ markdownLength: result.markdown?.length,
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ xmlLength: result.xml?.length,
+ });
+
return { content, state, success: true };
} catch (error) {
const err = error as Error;
+ console.error('[PageAgentToolCall] getPageContent:error', {
+ error: summarizeError(error),
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+
return {
error: {
body: error,
@@ -170,6 +280,18 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
* Perform unified node operations (insert, modify, remove)
*/
modifyNodes = async (params: ModifyNodesArgs): Promise<BuiltinToolResult> => {
+ const operations = Array.isArray(params.operations)
+ ? params.operations
+ : params.operations
+ ? [params.operations]
+ : [];
+
+ log('[PageAgentToolCall] modifyNodes:start', {
+ operationActions: operations.map((op) => op.action),
+ operationCount: operations.length,
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+
try {
const result = await this.runtime.modifyNodes(params);
@@ -193,9 +315,20 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
totalCount: result.totalCount,
};
+ log('[PageAgentToolCall] modifyNodes:success', {
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ successCount: result.successCount,
+ totalCount: result.totalCount,
+ });
+
return { content, state, success: result.successCount > 0 };
} catch (error) {
const err = error as Error;
+ console.error('[PageAgentToolCall] modifyNodes:error', {
+ error: summarizeError(error),
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+
return {
error: {
body: error,
@@ -213,6 +346,13 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
* Find and replace text across the document
*/
replaceText = async (params: ReplaceTextArgs): Promise<BuiltinToolResult> => {
+ log('[PageAgentToolCall] replaceText:start', {
+ newTextLength: params.newText.length,
+ nodeCount: params.nodeIds?.length,
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ searchTextLength: params.searchText.length,
+ });
+
try {
const result = await this.runtime.replaceText(params);
@@ -231,9 +371,20 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {
replacementCount: result.replacementCount,
};
+ log('[PageAgentToolCall] replaceText:success', {
+ modifiedNodeCount: result.modifiedNodeIds.length,
+ replacementCount: result.replacementCount,
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+
return { content, state, success: true };
} catch (error) {
const err = error as Error;
+ console.error('[PageAgentToolCall] replaceText:error', {
+ error: summarizeError(error),
+ runtime: getRuntimeDebugSnapshot(this.runtime),
+ });
+
return {
error: {
body: error,
diff --git a/packages/const/src/url.ts b/packages/const/src/url.ts
index 8f95f66e27f..6536922ee46 100644
--- a/packages/const/src/url.ts
+++ b/packages/const/src/url.ts
@@ -47,6 +47,16 @@ export const SESSION_CHAT_URL = (agentId: string, mobile?: boolean) => {
return `/agent/${agentId}`;
};
+export const SESSION_CHAT_TOPIC_URL = (agentId: string, topicId: string, mobile?: boolean) => {
+ if (mobile) return urlJoin('/agent', agentId, topicId);
+ return urlJoin('/agent', agentId, topicId);
+};
+
+export const SESSION_CHAT_TOPIC_PAGE_URL = (agentId: string, topicId: string, mobile?: boolean) => {
+ if (mobile) return urlJoin('/agent', agentId, topicId, 'page');
+ return urlJoin('/agent', agentId, topicId, 'page');
+};
+
export const AGENT_PROFILE_URL = (agentId: string) => `/agent/${agentId}/profile`;
export const GROUP_CHAT_URL = (groupId: string) => `/group/${groupId}`;
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index b6b361eb004..031715159e3 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -6,6 +6,7 @@ import { ContextEngine } from '../../pipeline';
import {
AgentCouncilFlattenProcessor,
CompressedGroupRoleTransformProcessor,
+ DisabledToolCallFilter,
GroupMessageFlattenProcessor,
GroupOrchestrationFilterProcessor,
GroupRoleTransformProcessor,
@@ -22,6 +23,7 @@ import {
ToolMessageReorder,
} from '../../processors';
import {
+ ActiveTopicDocumentContextInjector,
AgentBuilderContextInjector,
AgentDocumentBeforeSystemInjector,
AgentDocumentContextInjector,
@@ -183,6 +185,7 @@ export class MessagesEngine {
const hasAgentDocuments = !!agentDocuments && agentDocuments.length > 0;
// Page editor is enabled if either direct pageContentContext or initialContext.pageEditor is provided
const isPageEditorEnabled = !!pageContentContext || !!initialContext?.pageEditor;
+ const hasActiveTopicDocument = !!initialContext?.activeTopicDocument;
// GTD is enabled if gtd.enabled is true and either plan or todos is provided
const isGTDPlanEnabled = gtd?.enabled && gtd?.plan;
const isGTDTodoEnabled = gtd?.enabled && gtd?.todos;
@@ -315,6 +318,11 @@ export class MessagesEngine {
// Agent documents → after-first-user, context-end
new AgentDocumentMessageInjector(agentDocConfig),
+ // Active topic document → last user message, for continuing document work outside page scope
+ new ActiveTopicDocumentContextInjector({
+ activeTopicDocument: initialContext?.activeTopicDocument,
+ enabled: hasActiveTopicDocument && !isPageEditorEnabled,
+ }),
// Selected skills (ephemeral user-selected slash skills for this request)
new SelectedSkillInjector({ enabled: hasSelectedSkills, selectedSkills }),
// Selected tools (ephemeral user-selected @tool for this request)
@@ -440,6 +448,10 @@ export class MessagesEngine {
model,
provider,
}),
+ // Disabled historical tool calls (for scope-specific tool removal)
+ new DisabledToolCallFilter({
+ disabledToolIdentifiers: toolsConfig?.disabledToolIdentifiers,
+ }),
// =============================================
// Phase 7: Cleanup
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
index f4adf10f7b1..0dc23f262a1 100644
--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
@@ -500,6 +500,148 @@ Document content here.
});
});
+ describe('Active Topic Document context', () => {
+ it('should inject active topic document context to the last user message', async () => {
+ const messages: UIChatMessage[] = [
+ {
+ content: '继续修改刚才的文档',
+ createdAt: Date.now(),
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ];
+
+ const params = createBasicParams({
+ initialContext: {
+ activeTopicDocument: {
+ agentDocumentId: 'agd_123',
+ documentId: 'docs_123',
+ title: 'Topic Plan',
+ },
+ },
+ messages,
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+ const userMessage = result.messages.find((m) => m.role === 'user');
+
+ expect(userMessage?.content).toContain('<active_topic_document>');
+ expect(userMessage?.content).toContain('document_id="docs_123"');
+ expect(userMessage?.content).toContain('agent_document_id="agd_123"');
+ expect(userMessage?.content).toContain('target="currentTopic"');
+ expect(userMessage?.content).toContain('Do not use PageAgent editor tools');
+ expect(result.metadata.activeTopicDocumentContextInjected).toBe(true);
+ });
+
+ it('should skip active topic document context when page editor context is enabled', async () => {
+ const messages: UIChatMessage[] = [
+ {
+ content: 'Question',
+ createdAt: Date.now(),
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ];
+
+ const params = createBasicParams({
+ initialContext: {
+ activeTopicDocument: {
+ agentDocumentId: 'agd_123',
+ documentId: 'docs_123',
+ title: 'Topic Plan',
+ },
+ pageEditor: {
+ markdown: '# Page',
+ metadata: { title: 'Page' },
+ xml: '<root />',
+ },
+ },
+ messages,
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+ const userMessage = result.messages.find((m) => m.role === 'user');
+
+ expect(userMessage?.content).not.toContain('<active_topic_document>');
+ expect(result.metadata.activeTopicDocumentContextInjected).toBeUndefined();
+ expect(result.metadata.pageEditorContextInjected).toBe(true);
+ });
+ });
+
+ describe('Disabled tool call filtering', () => {
+ it('should remove historical PageAgent tool calls when the tool is disabled', async () => {
+ const messages: UIChatMessage[] = [
+ {
+ content: '先更新表格',
+ createdAt: Date.now(),
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ {
+ content: '',
+ createdAt: Date.now(),
+ id: 'msg-2',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: '{}',
+ name: 'lobe-page-agent____modifyNodes____builtin',
+ },
+ id: 'call_1',
+ type: 'function',
+ },
+ ],
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ {
+ content: 'Successfully executed 1 modify.',
+ createdAt: Date.now(),
+ id: 'msg-3',
+ role: 'tool',
+ tool_call_id: 'call_1',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ {
+ content: '继续修改文档',
+ createdAt: Date.now(),
+ id: 'msg-4',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ];
+
+ const params = createBasicParams({
+ messages,
+ toolsConfig: {
+ disabledToolIdentifiers: ['lobe-page-agent'],
+ tools: ['lobe-agent-documents'],
+ },
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ expect(result.messages.some((m) => m.role === 'tool')).toBe(false);
+ expect(
+ result.messages.some(
+ (m) =>
+ m.role === 'assistant' &&
+ JSON.stringify(m).includes('lobe-page-agent____modifyNodes____builtin'),
+ ),
+ ).toBe(false);
+ expect(result.metadata.disabledToolCallFilter).toEqual({
+ filteredAssistantMessages: 1,
+ filteredToolCalls: 1,
+ });
+ });
+ });
+
describe('Page Selections', () => {
it('should inject page selections to each user message that has them', async () => {
const messages: UIChatMessage[] = [
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index 1335251175f..b225644d62c 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -54,6 +54,8 @@ export interface KnowledgeConfig {
* Tools configuration
*/
export interface ToolsConfig {
+ /** Tool identifiers that must be removed from historical tool calls in this runtime scope */
+ disabledToolIdentifiers?: string[];
/** Tool manifests with systemRole and API definitions */
manifests?: LobeToolManifest[];
/** Enabled tool IDs (kept for compatibility) */
diff --git a/packages/context-engine/src/processors/DisabledToolCallFilter.ts b/packages/context-engine/src/processors/DisabledToolCallFilter.ts
new file mode 100644
index 00000000000..004dcd27a82
--- /dev/null
+++ b/packages/context-engine/src/processors/DisabledToolCallFilter.ts
@@ -0,0 +1,125 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { Message, PipelineContext, ProcessorOptions } from '../types';
+
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ disabledToolCallFilter?: {
+ filteredAssistantMessages: number;
+ filteredToolCalls: number;
+ };
+ }
+}
+
+const log = debug('context-engine:processor:DisabledToolCallFilter');
+
+export interface DisabledToolCallFilterConfig {
+ disabledToolIdentifiers?: string[];
+}
+
+const TOOL_NAME_SEPARATOR = '____';
+
+const isDisabledToolName = (name: string | undefined, disabledToolIdentifiers: Set<string>) => {
+ if (!name) return false;
+
+ for (const identifier of disabledToolIdentifiers) {
+ if (name === identifier || name.startsWith(`${identifier}${TOOL_NAME_SEPARATOR}`)) {
+ return true;
+ }
+ }
+
+ return false;
+};
+
+/**
+ * Removes historical tool calls for tools that are not valid in the current runtime scope.
+ *
+ * Some models infer tool names from prior assistant/tool messages even when the current
+ * request's `tools` schema no longer contains that tool. Filtering the historical call
+ * removes that imitation path; ToolMessageReorder will then drop the orphaned tool result.
+ */
+export class DisabledToolCallFilter extends BaseProcessor {
+ readonly name = 'DisabledToolCallFilter';
+
+ constructor(
+ private config: DisabledToolCallFilterConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const disabledToolIdentifiers = new Set(this.config.disabledToolIdentifiers ?? []);
+
+ if (disabledToolIdentifiers.size === 0) {
+ return this.markAsExecuted(context);
+ }
+
+ const clonedContext = this.cloneContext(context);
+ let filteredAssistantMessages = 0;
+ let filteredToolCalls = 0;
+
+ clonedContext.messages = clonedContext.messages.map((message) => {
+ if (message.role !== 'assistant') return message;
+
+ const nextMessage = this.filterAssistantMessage(message, disabledToolIdentifiers);
+ if (nextMessage === message) return message;
+
+ filteredAssistantMessages++;
+ filteredToolCalls +=
+ (Array.isArray(message.tool_calls) ? message.tool_calls.length : 0) -
+ (Array.isArray(nextMessage.tool_calls) ? nextMessage.tool_calls.length : 0);
+
+ return nextMessage;
+ });
+
+ clonedContext.metadata.disabledToolCallFilter = {
+ filteredAssistantMessages,
+ filteredToolCalls,
+ };
+
+ if (filteredToolCalls > 0) {
+ log(
+ 'Filtered %d disabled tool calls from %d assistant messages',
+ filteredToolCalls,
+ filteredAssistantMessages,
+ );
+ }
+
+ return this.markAsExecuted(clonedContext);
+ }
+
+ private filterAssistantMessage(message: Message, disabledToolIdentifiers: Set<string>): Message {
+ let nextMessage = message;
+
+ if (Array.isArray(message.tool_calls)) {
+ const toolCalls = message.tool_calls.filter(
+ (toolCall) => !isDisabledToolName(toolCall?.function?.name, disabledToolIdentifiers),
+ );
+
+ if (toolCalls.length !== message.tool_calls.length) {
+ const messageWithoutToolCalls = { ...nextMessage };
+ delete messageWithoutToolCalls.tool_calls;
+ nextMessage =
+ toolCalls.length > 0
+ ? { ...nextMessage, tool_calls: toolCalls }
+ : messageWithoutToolCalls;
+ }
+ }
+
+ if (Array.isArray(message.tools)) {
+ const tools = message.tools.filter(
+ (tool) => !disabledToolIdentifiers.has(String(tool?.identifier ?? '')),
+ );
+
+ if (tools.length !== message.tools.length) {
+ const messageWithoutTools = { ...nextMessage };
+ delete messageWithoutTools.tools;
+ nextMessage = tools.length > 0 ? { ...nextMessage, tools } : messageWithoutTools;
+ }
+ }
+
+ return nextMessage;
+ }
+}
diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.ts
index bca5d40dcdc..577951eb821 100644
--- a/packages/context-engine/src/processors/index.ts
+++ b/packages/context-engine/src/processors/index.ts
@@ -1,6 +1,7 @@
// Transformer processors
export { AgentCouncilFlattenProcessor } from './AgentCouncilFlatten';
export { CompressedGroupRoleTransformProcessor } from './CompressedGroupRoleTransform';
+export { DisabledToolCallFilter } from './DisabledToolCallFilter';
export { GroupMessageFlattenProcessor } from './GroupMessageFlatten';
export {
type GroupOrchestrationFilterConfig,
diff --git a/packages/context-engine/src/providers/ActiveTopicDocumentContextInjector.ts b/packages/context-engine/src/providers/ActiveTopicDocumentContextInjector.ts
new file mode 100644
index 00000000000..072d1157fb7
--- /dev/null
+++ b/packages/context-engine/src/providers/ActiveTopicDocumentContextInjector.ts
@@ -0,0 +1,78 @@
+import { escapeXmlAttr } from '@lobechat/prompts';
+import type { RuntimeActiveTopicDocumentContext } from '@lobechat/types';
+import debug from 'debug';
+
+import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ activeTopicDocumentContextInjected?: boolean;
+ }
+}
+
+const log = debug('context-engine:provider:ActiveTopicDocumentContextInjector');
+
+export interface ActiveTopicDocumentContextInjectorConfig {
+ activeTopicDocument?: RuntimeActiveTopicDocumentContext;
+ enabled?: boolean;
+}
+
+const formatActiveTopicDocumentContext = (document: RuntimeActiveTopicDocumentContext) => {
+ const attrs = [
+ `document_id="${escapeXmlAttr(document.documentId)}"`,
+ document.agentDocumentId
+ ? `agent_document_id="${escapeXmlAttr(document.agentDocumentId)}"`
+ : undefined,
+ document.title ? `title="${escapeXmlAttr(document.title)}"` : undefined,
+ ]
+ .filter(Boolean)
+ .join(' ');
+
+ return `<document ${attrs} />
+<guidance>
+The current conversation is not inside the page editor. Do not use PageAgent editor tools.
+When the user asks to continue editing this topic document, use lobe-agent-documents tools instead.
+Prefer readDocument with format="xml" and modifyNodes with agent_document_id when it is present.
+If agent_document_id is missing, call listDocuments with target="currentTopic" and match document_id.
+</guidance>`;
+};
+
+export class ActiveTopicDocumentContextInjector extends BaseLastUserContentProvider {
+ readonly name = 'ActiveTopicDocumentContextInjector';
+
+ constructor(
+ private config: ActiveTopicDocumentContextInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+ const { activeTopicDocument, enabled } = this.config;
+
+ if (!enabled || !activeTopicDocument?.documentId) {
+ log('No active topic document context, 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 formattedContent = formatActiveTopicDocumentContext(activeTopicDocument);
+ const hasExistingWrapper = this.hasExistingSystemContext(clonedContext);
+ const contentToAppend = hasExistingWrapper
+ ? this.createContextBlock(formattedContent, 'active_topic_document')
+ : this.wrapWithSystemContext(formattedContent, 'active_topic_document');
+
+ this.appendToLastUserMessage(clonedContext, contentToAppend);
+ clonedContext.metadata.activeTopicDocumentContextInjected = true;
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.ts
index 302ec089108..c0e6c0d75a9 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -1,4 +1,5 @@
// Context Provider exports
+export { ActiveTopicDocumentContextInjector } from './ActiveTopicDocumentContextInjector';
export { AgentBuilderContextInjector } from './AgentBuilderContextInjector';
export {
AGENT_DOCUMENT_INJECTION_POSITIONS,
@@ -44,6 +45,7 @@ export { TopicReferenceContextInjector } from './TopicReferenceContextInjector';
export { UserMemoryInjector } from './UserMemoryInjector';
// Re-export types
+export type { ActiveTopicDocumentContextInjectorConfig } from './ActiveTopicDocumentContextInjector';
export type {
AgentBuilderContext,
AgentBuilderContextInjectorConfig,
diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
index 1b6d6e6e575..9ea9992e19e 100644
--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
@@ -191,6 +191,29 @@ describe('AgentDocumentModel', () => {
const byFilename = await agentDocumentModel.findByFilename(agentId, 'own.md');
expect(byFilename?.id).toBe(ownDoc.id);
});
+
+ it('should find current-agent records by underlying document ids', async () => {
+ const ownDoc = await agentDocumentModel.create(agentId, 'own.md', 'own content');
+ const secondAgentDoc = await agentDocumentModel.create(
+ secondAgentId,
+ 'second.md',
+ 'second content',
+ );
+ const otherUserDoc = await otherAgentDocumentModel.create(
+ otherAgentId,
+ 'other.md',
+ 'other content',
+ );
+
+ const result = await agentDocumentModel.findByDocumentIds(agentId, [
+ ownDoc.documentId,
+ secondAgentDoc.documentId,
+ otherUserDoc.documentId,
+ 'missing-document',
+ ]);
+
+ expect(result.map((doc) => doc.id)).toEqual([ownDoc.id]);
+ });
});
describe('update and upsert', () => {
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.ts
index 5d7246f025c..087b6946e45 100644
--- a/packages/database/src/models/agentDocuments/agentDocument.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument.ts
@@ -1,4 +1,4 @@
-import { and, desc, eq, isNull } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNull } from 'drizzle-orm';
import type { DocumentItem, NewAgentDocument, NewDocument } from '../../schemas';
import { agentDocuments, documents } from '../../schemas';
@@ -71,6 +71,7 @@ export class AgentDocumentModel {
deletedByUserId: settings.deletedByUserId,
description: doc.description ?? null,
documentId: settings.documentId,
+ editorData: doc.editorData ?? null,
filename: doc.filename ?? '',
id: settings.id,
metadata: (doc.metadata as Record<string, any> | null) ?? null,
@@ -132,6 +133,7 @@ export class AgentDocumentModel {
content: string,
params?: {
createdAt?: Date;
+ editorData?: Record<string, any>;
loadPosition?: DocumentLoadPosition;
loadRules?: DocumentLoadRules;
metadata?: Record<string, any>;
@@ -144,6 +146,7 @@ export class AgentDocumentModel {
): Promise<AgentDocument> {
const {
createdAt,
+ editorData,
loadPosition,
loadRules,
metadata,
@@ -163,6 +166,7 @@ export class AgentDocumentModel {
content,
createdAt,
description: metadata?.description,
+ editorData,
fileType: 'agent/document',
filename,
metadata,
@@ -214,6 +218,7 @@ export class AgentDocumentModel {
documentId: string,
params?: {
content?: string;
+ editorData?: Record<string, any>;
loadPosition?: DocumentLoadPosition;
loadRules?: Partial<DocumentLoadRules>;
metadata?: Record<string, any>;
@@ -221,7 +226,8 @@ export class AgentDocumentModel {
policyLoad?: PolicyLoad;
},
): Promise<void> {
- const { content, loadPosition, loadRules, metadata, policy, policyLoad } = params ?? {};
+ const { content, editorData, loadPosition, loadRules, metadata, policy, policyLoad } =
+ params ?? {};
const existing = await this.findById(documentId);
@@ -257,7 +263,7 @@ export class AgentDocumentModel {
};
await this.db.transaction(async (trx) => {
- if (content !== undefined || metadata !== undefined) {
+ if (content !== undefined || editorData !== undefined || metadata !== undefined) {
const documentUpdate: Partial<NewDocument> = {};
if (content !== undefined) {
@@ -267,6 +273,10 @@ export class AgentDocumentModel {
documentUpdate.totalLineCount = stats.totalLineCount;
}
+ if (editorData !== undefined) {
+ documentUpdate.editorData = editorData;
+ }
+
if (metadata !== undefined) {
documentUpdate.metadata = metadata;
documentUpdate.description = metadata?.description;
@@ -317,6 +327,7 @@ export class AgentDocumentModel {
: `copy-${Date.now()}-${existing.filename}`;
return this.create(existing.agentId, filename, existing.content, {
+ editorData: existing.editorData || undefined,
title,
loadPosition:
(existing.policy?.context?.position as DocumentLoadPosition | undefined) ||
@@ -381,6 +392,7 @@ export class AgentDocumentModel {
content: string,
params?: {
createdAt?: Date;
+ editorData?: Record<string, any>;
loadPosition?: DocumentLoadPosition;
loadRules?: DocumentLoadRules;
metadata?: Record<string, any>;
@@ -392,6 +404,7 @@ export class AgentDocumentModel {
): Promise<AgentDocument> {
const {
createdAt,
+ editorData,
loadPosition,
loadRules,
metadata,
@@ -412,6 +425,7 @@ export class AgentDocumentModel {
await this.update(existing.id, {
content,
+ editorData,
loadPosition,
loadRules: mergedRules,
metadata: mergedMetadata,
@@ -424,6 +438,7 @@ export class AgentDocumentModel {
return this.create(agentId, filename, content, {
createdAt,
+ editorData,
loadPosition,
loadRules,
metadata,
@@ -457,6 +472,35 @@ export class AgentDocumentModel {
});
}
+ async findByDocumentIds(
+ agentId: string,
+ documentIds: string[],
+ ): Promise<AgentDocumentWithRules[]> {
+ if (documentIds.length === 0) return [];
+
+ const results = await this.db
+ .select({ doc: documents, settings: agentDocuments })
+ .from(agentDocuments)
+ .innerJoin(documents, eq(agentDocuments.documentId, documents.id))
+ .where(
+ and(
+ eq(agentDocuments.userId, this.userId),
+ eq(agentDocuments.agentId, agentId),
+ inArray(agentDocuments.documentId, documentIds),
+ isNull(agentDocuments.deletedAt),
+ ),
+ )
+ .orderBy(desc(agentDocuments.updatedAt));
+
+ return results.map(({ settings, doc }) => {
+ const item = this.toAgentDocument(settings, doc);
+ return {
+ ...item,
+ loadRules: parseLoadRules(item),
+ };
+ });
+ }
+
async hasByAgent(agentId: string): Promise<boolean> {
const [result] = await this.db
.select({ id: agentDocuments.id })
diff --git a/packages/database/src/models/agentDocuments/types.ts b/packages/database/src/models/agentDocuments/types.ts
index 4697e9cf8b6..cb235055482 100644
--- a/packages/database/src/models/agentDocuments/types.ts
+++ b/packages/database/src/models/agentDocuments/types.ts
@@ -37,6 +37,7 @@ export interface AgentDocument {
deleteReason: string | null;
description: string | null;
documentId: string;
+ editorData: Record<string, any> | null;
filename: string;
id: string;
metadata: Record<string, any> | null;
diff --git a/packages/editor-runtime/src/EditorRuntime.ts b/packages/editor-runtime/src/EditorRuntime.ts
index 79ed89bc144..94d02368035 100644
--- a/packages/editor-runtime/src/EditorRuntime.ts
+++ b/packages/editor-runtime/src/EditorRuntime.ts
@@ -19,6 +19,37 @@ import type {
const log = debug('lobe:editor-runtime');
+interface InspectableEditor {
+ dataTypeMap?: Map<string, unknown> | Record<string, unknown>;
+ editor?: unknown;
+ getLexicalEditor?: () => unknown | null;
+ plugins?: unknown[];
+ pluginsInstances?: unknown[];
+}
+
+export interface EditorRuntimeDebugSnapshot {
+ currentDocId?: string;
+ dataSourceTypes: string[];
+ hasBeforeMutateHandler: boolean;
+ hasEditor: boolean;
+ hasLexicalEditor: boolean;
+ hasTitleGetter: boolean;
+ hasTitleSetter: boolean;
+ pluginCount?: number;
+ pluginInstanceCount?: number;
+}
+
+const getDataSourceTypes = (editor: InspectableEditor): string[] => {
+ const dataTypeMap = editor.dataTypeMap;
+ if (!dataTypeMap) return [];
+
+ if (dataTypeMap instanceof Map) {
+ return [...dataTypeMap.keys()].sort();
+ }
+
+ return Object.keys(dataTypeMap).sort();
+};
+
/**
* Editor Execution Runtime
* Handles the execution logic for editor operations including:
@@ -40,6 +71,7 @@ export class EditorRuntime {
*/
setEditor(editor: IEditor | null) {
this.editor = editor;
+ log('[EditorRuntime] setEditor', this.getDebugSnapshot());
}
/**
@@ -48,6 +80,7 @@ export class EditorRuntime {
setCurrentDocId(docId: string | undefined) {
log('Setting current doc ID:', docId);
this.currentDocId = docId;
+ log('[EditorRuntime] setCurrentDocId', this.getDebugSnapshot());
}
/**
@@ -63,6 +96,7 @@ export class EditorRuntime {
*/
setBeforeMutateHandler(handler: (() => void | Promise<void>) | null) {
this.beforeMutateHandler = handler;
+ log('[EditorRuntime] setBeforeMutateHandler', this.getDebugSnapshot());
}
/**
@@ -71,6 +105,45 @@ export class EditorRuntime {
setTitleHandlers(setter: ((title: string) => void) | null, getter: (() => string) | null) {
this.titleSetter = setter;
this.titleGetter = getter;
+ log('[EditorRuntime] setTitleHandlers', this.getDebugSnapshot());
+ }
+
+ /**
+ * Lightweight runtime snapshot for page-agent tool call diagnostics.
+ * This intentionally avoids reading document content.
+ */
+ getDebugSnapshot(): EditorRuntimeDebugSnapshot {
+ const inspectableEditor = this.editor as InspectableEditor | null;
+ const hasLexicalEditor = (() => {
+ try {
+ return !!inspectableEditor?.getLexicalEditor?.();
+ } catch {
+ return false;
+ }
+ })();
+
+ return {
+ currentDocId: this.currentDocId,
+ dataSourceTypes: inspectableEditor ? getDataSourceTypes(inspectableEditor) : [],
+ hasBeforeMutateHandler: !!this.beforeMutateHandler,
+ hasEditor: !!this.editor,
+ hasLexicalEditor,
+ hasTitleGetter: !!this.titleGetter,
+ hasTitleSetter: !!this.titleSetter,
+ pluginCount: inspectableEditor?.plugins?.length,
+ pluginInstanceCount: inspectableEditor?.pluginsInstances?.length,
+ };
+ }
+
+ isReady(): boolean {
+ if (!this.editor) return false;
+
+ const inspectableEditor = this.editor as InspectableEditor;
+ try {
+ return !!inspectableEditor.getLexicalEditor?.();
+ } catch {
+ return false;
+ }
}
/**
@@ -100,6 +173,11 @@ export class EditorRuntime {
* @returns Raw result with nodeCount and extractedTitle
*/
async initPage(args: InitDocumentArgs): Promise<InitPageRuntimeResult> {
+ log('[EditorRuntime] initPage:start', {
+ markdownLength: args.markdown.length,
+ snapshot: this.getDebugSnapshot(),
+ });
+
try {
await this.beforeMutateHandler?.();
} catch {
@@ -131,7 +209,14 @@ export class EditorRuntime {
const jsonState = editor.getDocument('json') as any;
const nodeCount = jsonState?.children?.length || 0;
- return { extractedTitle, nodeCount };
+ const result = { extractedTitle, nodeCount };
+ log('[EditorRuntime] initPage:success', {
+ nodeCount,
+ snapshot: this.getDebugSnapshot(),
+ titleExtracted: !!extractedTitle,
+ });
+
+ return result;
}
// ==================== Metadata ====================
@@ -141,6 +226,11 @@ export class EditorRuntime {
* @returns Raw result with newTitle and previousTitle
*/
async editTitle(args: EditTitleArgs): Promise<EditTitleRuntimeResult> {
+ log('[EditorRuntime] editTitle:start', {
+ snapshot: this.getDebugSnapshot(),
+ titleLength: args.title.length,
+ });
+
try {
await this.beforeMutateHandler?.();
} catch {
@@ -152,7 +242,13 @@ export class EditorRuntime {
// Update the title
setter(args.title);
- return { newTitle: args.title, previousTitle };
+ const result = { newTitle: args.title, previousTitle };
+ log('[EditorRuntime] editTitle:success', {
+ snapshot: this.getDebugSnapshot(),
+ titleLength: args.title.length,
+ });
+
+ return result;
}
// ==================== Query & Read ====================
@@ -162,6 +258,11 @@ export class EditorRuntime {
* @returns Raw result with document content and metadata
*/
async getPageContent(args: GetPageContentArgs): Promise<GetPageContentRuntimeResult> {
+ log('[EditorRuntime] getPageContent:start', {
+ format: args.format,
+ snapshot: this.getDebugSnapshot(),
+ });
+
const context = this.getPageContentContext(args.format);
return {
@@ -213,6 +314,18 @@ export class EditorRuntime {
* @returns Raw result with results, successCount and totalCount
*/
async modifyNodes(args: ModifyNodesArgs): Promise<ModifyNodesRuntimeResult> {
+ const rawOperations = Array.isArray(args.operations)
+ ? args.operations
+ : args.operations
+ ? [args.operations]
+ : [];
+
+ log('[EditorRuntime] modifyNodes:start', {
+ operationActions: rawOperations.map((op) => op.action),
+ operationCount: rawOperations.length,
+ snapshot: this.getDebugSnapshot(),
+ });
+
try {
await this.beforeMutateHandler?.();
} catch {
@@ -298,7 +411,14 @@ export class EditorRuntime {
const successCount = results.filter((r) => r.success).length;
const totalCount = results.length;
- return { results, successCount, totalCount };
+ const result = { results, successCount, totalCount };
+ log('[EditorRuntime] modifyNodes:success', {
+ snapshot: this.getDebugSnapshot(),
+ successCount,
+ totalCount,
+ });
+
+ return result;
}
// ==================== Text Operations ====================
diff --git a/packages/electron-client-ipc/src/ipc.ts b/packages/electron-client-ipc/src/ipc.ts
index 65b7ac51fed..6116e88a22f 100644
--- a/packages/electron-client-ipc/src/ipc.ts
+++ b/packages/electron-client-ipc/src/ipc.ts
@@ -46,9 +46,7 @@ declare global {
interface Window {
electronAPI?: {
invoke?: IpcInvoke;
- onScreenCaptureSession?: (
- listener: (session: ScreenCaptureSession) => void,
- ) => () => void;
+ onScreenCaptureSession?: (listener: (session: ScreenCaptureSession) => void) => () => void;
onStreamInvoke: (
params: StreamInvokeRequestParams,
callbacks: StreamerCallbacks,
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index a15d49ecb4f..ef7c16587d7 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -5,6 +5,8 @@ import type { ChatTopic } from '../topic';
* Application context for message storage
*/
export interface ExecAgentAppContext {
+ /** Current document ID for page-scoped conversations */
+ documentId?: string | null;
/** Group ID for group chat */
groupId?: string | null;
/** Scope identifier */
diff --git a/packages/types/src/conversation.ts b/packages/types/src/conversation.ts
index b2d187689ea..777f0acd23b 100644
--- a/packages/types/src/conversation.ts
+++ b/packages/types/src/conversation.ts
@@ -118,6 +118,12 @@ export interface MessageMapContext {
*/
export interface ConversationContext {
agentId: string;
+ /**
+ * Current document ID for page-scoped conversations.
+ * Used by page editor integrations to distinguish the active document from
+ * other agent resources tied to the same topic.
+ */
+ documentId?: string;
/**
* Group ID for group conversations
* Used when scope is 'group' or 'group_agent'
diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.ts
index 73d39a9d002..2f93bb4c627 100644
--- a/packages/types/src/stepContext.ts
+++ b/packages/types/src/stepContext.ts
@@ -74,6 +74,26 @@ export interface InitialPageEditorContext {
xml: string;
}
+/**
+ * Active topic document context
+ * Captured when a user leaves the topic page editor but continues the same
+ * topic conversation from the regular chat surface.
+ */
+export interface RuntimeActiveTopicDocumentContext {
+ /**
+ * Agent-document row ID used by lobe-agent-documents read/patch/edit APIs.
+ */
+ agentDocumentId?: string;
+ /**
+ * Underlying documents.id used by topic page routes.
+ */
+ documentId: string;
+ /**
+ * Human-readable title for model disambiguation.
+ */
+ title?: string | null;
+}
+
/**
* User-selected skill context for the current request
* Captured from slash-menu skill action tags before send
@@ -194,6 +214,11 @@ export interface InjectedToolManifest {
* Remains constant throughout the operation lifecycle.
*/
export interface RuntimeInitialContext {
+ /**
+ * Active topic document carried from page route to regular chat route.
+ * This lets the model continue document work without page-editor tools.
+ */
+ activeTopicDocument?: RuntimeActiveTopicDocumentContext;
/**
* Ad-hoc tool manifests injected by callers for the current request.
* Merged into the tool resolution output without passing through ToolsEngine.
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 71a33f85f2e..44b0fc0d579 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -405,6 +405,12 @@ export interface BuiltinToolContext {
*/
agentId?: string;
+ /**
+ * The current page document ID when the conversation is scoped to an open editor
+ * Uses the underlying `documents.id`, not tool-specific association IDs
+ */
+ documentId?: string | null;
+
/**
* The current group ID (only available in group chat context)
* Used by group management tools to access group member information
@@ -446,6 +452,11 @@ export interface BuiltinToolContext {
*/
registerAfterCompletion?: (callback: AfterCompletionCallback) => void;
+ /**
+ * Conversation scope captured when the operation was created
+ */
+ scope?: string | null;
+
/**
* AbortSignal for cancellation detection
*/
diff --git a/src/features/AgentHome/RecentTopics.tsx b/src/features/AgentHome/RecentTopics.tsx
index b85a7a44ac1..268f8ce2adb 100644
--- a/src/features/AgentHome/RecentTopics.tsx
+++ b/src/features/AgentHome/RecentTopics.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import { Link, useParams } from 'react-router-dom';
import useSWR from 'swr';
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { topicService } from '@/services/topic';
import SectionHeader from './SectionHeader';
@@ -16,9 +17,8 @@ const AgentRecentTopics = memo(() => {
const { t } = useTranslation('chat');
const { aid } = useParams<{ aid: string }>();
- const { data: result, isLoading } = useSWR(
- aid ? ['agentHome.topics', aid] : null,
- () => topicService.getTopics({ agentId: aid!, current: 0, pageSize: 10 }),
+ const { data: result, isLoading } = useSWR(aid ? ['agentHome.topics', aid] : null, () =>
+ topicService.getTopics({ agentId: aid!, current: 0, pageSize: 10 }),
);
const topics = result?.items;
@@ -28,17 +28,17 @@ const AgentRecentTopics = memo(() => {
return (
<Flexbox gap={16}>
<SectionHeader
+ actionLabel={t('topic.viewAll')}
+ actionUrl={`/agent/${aid}`}
icon={BotMessageSquareIcon}
title={t('topic.recent')}
- actionUrl={`/agent/${aid}`}
- actionLabel={t('topic.viewAll')}
/>
<Flexbox horizontal gap={12} style={{ overflowX: 'auto', paddingBottom: 4 }}>
{topics.map((topic) => (
<Link
key={topic.id}
- to={`/agent/${aid}?topic=${topic.id}`}
style={{ color: 'inherit', flexShrink: 0, textDecoration: 'none' }}
+ to={SESSION_CHAT_TOPIC_URL(aid!, topic.id)}
>
<Block
clickable
@@ -56,9 +56,7 @@ const AgentRecentTopics = memo(() => {
{topic.title || t('topic.defaultTitle')}
</Text>
<Text ellipsis fontSize={12} type={'secondary'}>
- {topic.updatedAt
- ? new Date(topic.updatedAt).toLocaleDateString()
- : ''}
+ {topic.updatedAt ? new Date(topic.updatedAt).toLocaleDateString() : ''}
</Text>
</Flexbox>
</Block>
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
index b0c345ccebf..f1a92a57506 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
@@ -60,7 +60,7 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ agentId, taskId }) => {
right={<ToggleRightPanelButton hideWhenExpanded />}
left={
<>
- <Breadcrumb taskId={taskId} />
+ <Breadcrumb agentId={agentId} taskId={taskId} />
<TaskDetailHeaderActions />
{saveStatus === 'saving' ? <AutoSaveHint saveStatus={saveStatus} /> : undefined}
</>
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index 2701f5154f1..93b7dbb4d49 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -3,13 +3,14 @@ import { Plus } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
+import AutoSaveHint from '@/components/Editor/AutoSaveHint';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useTaskStore } from '@/store/task';
-import { taskListSelectors } from '@/store/task/selectors';
+import { taskDetailSelectors, taskListSelectors } from '@/store/task/selectors';
import { createTaskModal } from '../CreateTaskModal';
import Breadcrumb from '../shared/Breadcrumb';
@@ -20,11 +21,19 @@ import { normalizeTaskListViewOptions } from './listViewOptions';
import TaskList from './TaskList';
import TasksGroupConfig from './TasksGroupConfig';
-const AgentTasksPage = memo(() => {
+interface AgentTasksPageProps {
+ /**
+ * When omitted, the page shows tasks across all agents (used by the `/tasks` route).
+ */
+ agentId?: string;
+}
+
+const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId }) => {
const navigate = useNavigate();
const viewMode = useTaskStore(taskListSelectors.viewMode);
+ const saveStatus = useTaskStore(taskDetailSelectors.taskSaveStatus);
const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);
- useFetchTaskList({ allAgents: true });
+ useFetchTaskList({ agentId, allAgents: !agentId });
const rawViewOptions = useGlobalStore(systemStatusSelectors.taskListViewOptions);
const viewOptions = useMemo(() => normalizeTaskListViewOptions(rawViewOptions), [rawViewOptions]);
const inlineCollapsed = useGlobalStore(systemStatusSelectors.taskCreateInlineCollapsed);
@@ -39,11 +48,20 @@ const AgentTasksPage = memo(() => {
const handleCreateTask = useCallback(() => {
createTaskModal({
+ agentId,
onCreated: (task) => {
+ if (agentId) {
+ const targetAgentId = task.agentId || agentId;
+ if (targetAgentId) {
+ navigate(`/agent/${targetAgentId}/tasks/${task.identifier}`);
+ return;
+ }
+ }
+
navigate(`/task/${task.identifier}`);
},
});
- }, [navigate]);
+ }, [agentId, navigate]);
const handleShowHiddenCompleted = useCallback(() => {
setViewOptions((prev) => ({ ...prev, hideCompleted: false }));
@@ -52,7 +70,12 @@ const AgentTasksPage = memo(() => {
return (
<Flexbox flex={1} height={'100%'}>
<NavHeader
- left={<Breadcrumb />}
+ left={
+ <>
+ <Breadcrumb agentId={agentId} />
+ {saveStatus !== 'idle' && <AutoSaveHint saveStatus={saveStatus} />}
+ </>
+ }
right={
<Flexbox horizontal align={'center'} gap={4}>
{inlineCollapsed && (
@@ -63,14 +86,14 @@ const AgentTasksPage = memo(() => {
}
styles={{
left: {
- paddingLeft: 4,
gap: 8,
+ paddingLeft: 4,
},
}}
/>
{viewMode === 'kanban' ? (
<Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>
- <KanbanBoard />
+ <KanbanBoard agentId={agentId} />
</Flexbox>
) : (
<WideScreenContainer
@@ -78,7 +101,7 @@ const AgentTasksPage = memo(() => {
paddingBlock={16}
wrapperStyle={{ flex: 1, overflowY: 'auto' }}
>
- {!inlineCollapsed && <CreateTaskInlineEntry />}
+ {!inlineCollapsed && <CreateTaskInlineEntry agentId={agentId} />}
<TaskList options={viewOptions} onShowHiddenCompleted={handleShowHiddenCompleted} />
</WideScreenContainer>
)}
diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
index 126934dd514..4ad02611b14 100644
--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
@@ -71,12 +71,16 @@ const optimisticMoveTask = (
});
};
-const KanbanBoard = memo(() => {
+interface KanbanBoardProps {
+ agentId?: string;
+}
+
+const KanbanBoard = memo<KanbanBoardProps>(({ agentId }) => {
const { t } = useTranslation('chat');
const navigate = useNavigate();
const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);
- useFetchTaskGroupList({ allAgents: true });
+ useFetchTaskGroupList({ agentId, allAgents: !agentId });
const taskGroups = useTaskStore(taskListSelectors.taskGroups);
const isInit = useTaskStore(taskListSelectors.isTaskGroupListInit);
@@ -133,12 +137,21 @@ const KanbanBoard = memo(() => {
const handleCreateTask = useCallback(() => {
createTaskModal({
+ agentId,
onCreated: (task) => {
+ if (agentId) {
+ const targetAgentId = task.agentId || agentId;
+ if (targetAgentId) {
+ navigate(`/agent/${targetAgentId}/tasks/${task.identifier}`);
+ return;
+ }
+ }
+
navigate(`/task/${task.identifier}`);
},
showInlineToggle: false,
});
- }, [navigate]);
+ }, [agentId, navigate]);
const handleHideColumn = useCallback(
(columnKey: string) => {
diff --git a/src/features/AgentTasks/shared/Breadcrumb.tsx b/src/features/AgentTasks/shared/Breadcrumb.tsx
index b4267a66dee..c9cb7c3b5e7 100644
--- a/src/features/AgentTasks/shared/Breadcrumb.tsx
+++ b/src/features/AgentTasks/shared/Breadcrumb.tsx
@@ -1,4 +1,5 @@
-import { Icon, Text } from '@lobehub/ui';
+import { DEFAULT_AVATAR } from '@lobechat/const';
+import { Avatar, Flexbox, Icon, Text } from '@lobehub/ui';
import { Breadcrumb as AntBreadcrumb } from 'antd';
import { ChevronRight } from 'lucide-react';
import { memo } from 'react';
@@ -6,16 +7,30 @@ import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { useShallow } from 'zustand/react/shallow';
+import { DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useTaskStore } from '@/store/task';
+import { isInboxAgentId } from './isInboxAgent';
import { styles } from './style';
interface BreadcrumbProps {
+ /**
+ * When omitted, the breadcrumb renders a single "All tasks" crumb for the
+ * cross-agent `/tasks` route.
+ */
+ agentId?: string;
taskId?: string;
}
-const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {
+const Breadcrumb = memo<BreadcrumbProps>(({ agentId, taskId }) => {
const { t } = useTranslation('chat');
+ const { t: tCommon } = useTranslation('common');
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const agentMeta = useAgentStore((s) =>
+ agentId ? agentSelectors.getAgentMetaById(agentId)(s) : undefined,
+ );
const taskTitle = useTaskStore((s) => (taskId ? s.taskDetailMap[taskId]?.name : undefined));
const taskIdentifier = useTaskStore((s) =>
taskId ? s.taskDetailMap[taskId]?.identifier : undefined,
@@ -35,48 +50,27 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {
}),
);
- const allTasksLabel = (
- <Text color={'inherit'} weight={500}>
- {t('taskList.all')}
- </Text>
- );
-
- const ancestorCrumbs = ancestors.map((identifier) => ({
- key: identifier,
- title: (
- <Link to={`/task/${identifier}`}>
- <Text color={'inherit'} weight={500}>
- {identifier}
- </Text>
- </Link>
- ),
- }));
-
- const currentTaskCrumb = taskId
- ? {
- title: (
- <span
- style={{
- alignItems: 'center',
- display: 'inline-flex',
- gap: 6,
- lineHeight: 1,
- minWidth: 0,
- overflow: 'hidden',
- }}
- >
- {taskIdentifier && (
- <Text color={'inherit'} style={{ flexShrink: 0 }} type={'secondary'} weight={500}>
- {taskIdentifier}
+ if (!agentId) {
+ return (
+ <AntBreadcrumb
+ separator={<Icon icon={ChevronRight} />}
+ items={[
+ {
+ title: (
+ <Text color={'inherit'} weight={500}>
+ {t('taskList.all')}
</Text>
- )}
- <Text ellipsis color={'inherit'} style={{ maxWidth: 240 }} weight={500}>
- {taskTitle || taskId}
- </Text>
- </span>
- ),
- }
- : undefined;
+ ),
+ },
+ ]}
+ />
+ );
+ }
+
+ const isInboxAgent = isInboxAgentId(agentId, inboxAgentId);
+ const agentName =
+ agentMeta?.title?.trim() || (isInboxAgent ? t('inbox.title') : tCommon('defaultSession'));
+ const agentAvatar = agentMeta?.avatar || (isInboxAgent ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR);
return (
<AntBreadcrumb
@@ -84,10 +78,79 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {
separator={<Icon icon={ChevronRight} />}
items={[
{
- title: taskId ? <Link to={'/tasks'}>{allTasksLabel}</Link> : allTasksLabel,
+ title: (
+ <Link to={`/agent/${agentId}`}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={6}
+ style={{ minWidth: 0, overflow: 'hidden' }}
+ >
+ <Flexbox style={{ flexShrink: 0 }}>
+ <Avatar avatar={agentAvatar} background={agentMeta?.backgroundColor} size={18} />
+ </Flexbox>
+ <Text ellipsis color={'inherit'} weight={500}>
+ {agentName}
+ </Text>
+ </Flexbox>
+ </Link>
+ ),
},
- ...ancestorCrumbs,
- ...(currentTaskCrumb ? [currentTaskCrumb] : []),
+ ...(taskId
+ ? []
+ : [
+ {
+ title: (
+ <Link to={`/agent/${agentId}/tasks`}>
+ <Text color={'inherit'} weight={500}>
+ {t('taskList.breadcrumb.task')}
+ </Text>
+ </Link>
+ ),
+ },
+ ]),
+ ...ancestors.map((identifier) => ({
+ key: identifier,
+ title: (
+ <Link to={`/agent/${agentId}/tasks/${identifier}`}>
+ <Text color={'inherit'} weight={500}>
+ {identifier}
+ </Text>
+ </Link>
+ ),
+ })),
+ ...(taskId
+ ? [
+ {
+ title: (
+ <span
+ style={{
+ alignItems: 'center',
+ display: 'inline-flex',
+ gap: 6,
+ lineHeight: 1,
+ minWidth: 0,
+ overflow: 'hidden',
+ }}
+ >
+ {taskIdentifier && (
+ <Text
+ color={'inherit'}
+ style={{ flexShrink: 0 }}
+ type={'secondary'}
+ weight={500}
+ >
+ {taskIdentifier}
+ </Text>
+ )}
+ <Text ellipsis color={'inherit'} style={{ maxWidth: 240 }} weight={500}>
+ {taskTitle || taskId}
+ </Text>
+ </span>
+ ),
+ },
+ ]
+ : []),
]}
/>
);
diff --git a/src/features/CommandMenu/SearchResults.tsx b/src/features/CommandMenu/SearchResults.tsx
index ca625b3c64e..9ef37ac3d72 100644
--- a/src/features/CommandMenu/SearchResults.tsx
+++ b/src/features/CommandMenu/SearchResults.tsx
@@ -18,6 +18,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { type SearchResult } from '@/database/repositories/search';
import { useCommandMenuContext } from '@/features/CommandMenu/CommandMenuContext';
import { useImageStore } from '@/store/image';
@@ -73,7 +74,7 @@ const SearchResults = memo<SearchResultsProps>(
}
case 'topic': {
if (result.agentId) {
- navigate(`/agent/${result.agentId}?topic=${result.id}`);
+ navigate(SESSION_CHAT_TOPIC_URL(result.agentId, result.id));
} else {
navigate(`/chat?topic=${result.id}`);
}
@@ -82,7 +83,7 @@ const SearchResults = memo<SearchResultsProps>(
case 'message': {
// Navigate to the topic/agent where the message is
if (result.topicId && result.agentId) {
- navigate(`/agent/${result.agentId}?topic=${result.topicId}#${result.id}`);
+ navigate(`${SESSION_CHAT_TOPIC_URL(result.agentId, result.topicId)}#${result.id}`);
} else if (result.topicId) {
navigate(`/chat?topic=${result.topicId}#${result.id}`);
} else if (result.agentId) {
diff --git a/src/features/CommandMenu/utils/context.test.ts b/src/features/CommandMenu/utils/context.test.ts
new file mode 100644
index 00000000000..3fd445b01f8
--- /dev/null
+++ b/src/features/CommandMenu/utils/context.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { detectContext } from './context';
+
+describe('detectContext', () => {
+ it('detects agent context for base and topic routes', () => {
+ expect(detectContext('/agent/agt_123')).toBe('agent');
+ expect(detectContext('/agent/agt_123/tpc_456')).toBe('agent');
+ });
+
+ it('keeps agent context for page routes nested under a topic', () => {
+ expect(detectContext('/agent/agt_123/tpc_456/page')).toBe('agent');
+ expect(detectContext('/agent/agt_123/tpc_456/page/doc_789')).toBe('agent');
+ });
+
+ it('preserves page context for standalone page routes', () => {
+ expect(detectContext('/page/doc_789')).toBe('page');
+ });
+
+ it('falls back to general for unknown routes', () => {
+ expect(detectContext('/unknown')).toBe('general');
+ });
+});
diff --git a/src/features/CommandMenu/utils/context.ts b/src/features/CommandMenu/utils/context.ts
index 6c7b98fbed8..ccbadf984ae 100644
--- a/src/features/CommandMenu/utils/context.ts
+++ b/src/features/CommandMenu/utils/context.ts
@@ -15,7 +15,7 @@ interface ContextConfig {
*/
const CONTEXT_CONFIGS: ContextConfig[] = [
{
- matcher: /^\/agent\/[^/]+$/,
+ matcher: /^\/agent\/[^/]+(?:\/[^/]+(?:\/page(?:\/[^/]+)?)?)?$/,
name: 'Agent',
type: 'agent',
},
diff --git a/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx b/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx
index 2f5d970402f..ef1c2a29ca4 100644
--- a/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx
+++ b/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx
@@ -26,8 +26,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
contentCollapsed: css`
overflow: hidden;
-
- mask-image: linear-gradient(to bottom, #000 calc(100% - 48px), transparent);
mask-image: linear-gradient(to bottom, #000 calc(100% - 48px), transparent);
`,
contentExpanded: css`
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index 4a912dd900d..9c1a27e1a40 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -10,6 +10,10 @@ import {
} from '@/store/chat/slices/aiChat/actions/commandBus';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+import {
+ mergeAgentRuntimeInitialContexts,
+ resolveActiveTopicDocumentInitialContext,
+} from '@/store/chat/utils/activeTopicDocumentContext';
import { type Store as ConversationStore } from '../../action';
@@ -323,7 +327,10 @@ export const generationSlice: StateCreator<
const currentIndex = displayMessages.findIndex((c) => c.id === messageId);
const item = displayMessages[currentIndex];
if (!item) return;
- const initialContext = buildRetryInitialContext(item.editorData);
+ const initialContext = mergeAgentRuntimeInitialContexts(
+ await resolveActiveTopicDocumentInitialContext(context),
+ buildRetryInitialContext(item.editorData),
+ );
// Get context messages up to and including the target message
const contextMessages = displayMessages.slice(0, currentIndex + 1);
diff --git a/src/features/Conversation/utils/markdown.test.ts b/src/features/Conversation/utils/markdown.test.ts
index b4dbddb9593..484fad015bd 100644
--- a/src/features/Conversation/utils/markdown.test.ts
+++ b/src/features/Conversation/utils/markdown.test.ts
@@ -332,7 +332,7 @@ Content 2 still going`;
// Move the snake every frame
const url = " // keep string content untouched";
window.snakeStarted = true;
-</script
+</script${'\t'}
bar>
</body>
</html>
diff --git a/src/features/DevPanel/RenderGallery/index.tsx b/src/features/DevPanel/RenderGallery/index.tsx
index fafeca54331..2ce46a43c8a 100644
--- a/src/features/DevPanel/RenderGallery/index.tsx
+++ b/src/features/DevPanel/RenderGallery/index.tsx
@@ -23,8 +23,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
card: css`
overflow: hidden;
+
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: 20px;
+
background: ${cssVar.colorBgContainer};
box-shadow: ${cssVar.boxShadowSecondary};
`,
@@ -34,26 +36,32 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
cardHeader: css`
gap: 10px;
padding: 16px;
- border-bottom: 1px solid ${cssVar.colorBorderSecondary};
- background:
- linear-gradient(180deg, ${cssVar.colorFillQuaternary} 0%, ${cssVar.colorBgContainer} 100%);
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ background: linear-gradient(
+ 180deg,
+ ${cssVar.colorFillQuaternary} 0%,
+ ${cssVar.colorBgContainer} 100%
+ );
`,
code: css`
overflow: auto;
+
max-height: 280px;
margin: 0;
padding: 12px;
border-radius: 12px;
+
font-size: 12px;
line-height: 1.55;
color: ${cssVar.colorTextSecondary};
+
background: ${cssVar.colorFillQuaternary};
`,
fixtureSummary: css`
cursor: pointer;
+ user-select: none;
font-size: 12px;
color: ${cssVar.colorTextTertiary};
- user-select: none;
`,
group: css`
gap: 16px;
@@ -89,10 +97,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-class RenderBoundary extends Component<
- { children: ReactNode },
- { error?: Error | undefined }
-> {
+class RenderBoundary extends Component<{ children: ReactNode }, { error?: Error | undefined }> {
constructor(props: { children: ReactNode }) {
super(props);
this.state = { error: undefined };
diff --git a/src/features/EditorCanvas/DiffAllToolbar.tsx b/src/features/EditorCanvas/DiffAllToolbar.tsx
index dd25e407532..0e2376fc704 100644
--- a/src/features/EditorCanvas/DiffAllToolbar.tsx
+++ b/src/features/EditorCanvas/DiffAllToolbar.tsx
@@ -1,6 +1,6 @@
'use client';
-import { type IEditor } from '@lobehub/editor';
+import type { IEditor } from '@lobehub/editor';
import { DiffAction, LITEXML_DIFFNODE_ALL_COMMAND } from '@lobehub/editor';
import { Block, Icon } from '@lobehub/ui';
import { Button, Space } from 'antd';
@@ -36,7 +36,7 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const useIsEditorInit = (editor: IEditor) => {
+const useIsEditorInit = (editor?: IEditor) => {
const [isEditInit, setEditInit] = useState<boolean>(!!editor?.getLexicalEditor());
useEffect(() => {
@@ -54,7 +54,7 @@ const useIsEditorInit = (editor: IEditor) => {
return isEditInit;
};
-const useEditorHasPendingDiffs = (editor: IEditor) => {
+const useEditorHasPendingDiffs = (editor?: IEditor) => {
const [hasPendingDiffs, setHasPendingDiffs] = useState(false);
const isEditInit = useIsEditorInit(editor);
@@ -98,24 +98,20 @@ const useEditorHasPendingDiffs = (editor: IEditor) => {
interface DiffAllToolbarProps {
documentId: string;
- editor: IEditor;
+ editor?: IEditor;
}
-const DiffAllToolbar = memo<DiffAllToolbarProps>(({ documentId }) => {
+const DiffAllToolbar = memo<DiffAllToolbarProps>(({ documentId, editor }) => {
const { t } = useTranslation('editor');
const isDarkMode = useIsDark();
- const [storeEditor, performSave, markDirty] = useDocumentStore((s) => [
- s.editor!,
- s.performSave,
- s.markDirty,
- ]);
+ const [performSave, markDirty] = useDocumentStore((s) => [s.performSave, s.markDirty]);
- const hasPendingDiffs = useEditorHasPendingDiffs(storeEditor);
+ const hasPendingDiffs = useEditorHasPendingDiffs(editor);
- if (!hasPendingDiffs) return null;
+ if (!editor || !hasPendingDiffs) return null;
const handleSave = async () => {
markDirty(documentId);
- await performSave(undefined, undefined, { saveSource: 'manual' });
+ await performSave(documentId, undefined, { saveSource: 'manual' });
};
return (
@@ -133,7 +129,7 @@ const DiffAllToolbar = memo<DiffAllToolbarProps>(({ documentId }) => {
size={'small'}
type="text"
onClick={async () => {
- storeEditor?.dispatchCommand(LITEXML_DIFFNODE_ALL_COMMAND, {
+ editor.dispatchCommand(LITEXML_DIFFNODE_ALL_COMMAND, {
action: DiffAction.Reject,
});
await handleSave();
@@ -147,7 +143,7 @@ const DiffAllToolbar = memo<DiffAllToolbarProps>(({ documentId }) => {
size={'small'}
variant="filled"
onClick={async () => {
- storeEditor?.dispatchCommand(LITEXML_DIFFNODE_ALL_COMMAND, {
+ editor.dispatchCommand(LITEXML_DIFFNODE_ALL_COMMAND, {
action: DiffAction.Accept,
});
await handleSave();
diff --git a/src/features/EditorCanvas/DocumentIdMode.test.tsx b/src/features/EditorCanvas/DocumentIdMode.test.tsx
index e2e6b793408..5560602b699 100644
--- a/src/features/EditorCanvas/DocumentIdMode.test.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.test.tsx
@@ -1,7 +1,7 @@
/**
* @vitest-environment happy-dom
*/
-import { act, render, screen } from '@testing-library/react';
+import { act, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import DocumentIdMode from './DocumentIdMode';
@@ -95,4 +95,35 @@ describe('DocumentIdMode', () => {
expect(performSave).toHaveBeenCalledWith('doc-1', undefined, { saveSource: 'manual' });
expect(flushSave).not.toHaveBeenCalled();
});
+
+ it('should call external onInit after document hydration', async () => {
+ const onInit = vi.fn();
+ const editor = {
+ getLexicalEditor: vi.fn(() => ({})),
+ } as any;
+
+ render(<DocumentIdMode documentId="doc-1" editor={editor} onInit={onInit} />);
+
+ await waitFor(() => {
+ expect(onEditorInit).toHaveBeenCalledWith(editor);
+ expect(onInit).toHaveBeenCalledWith(editor);
+ });
+ });
+
+ it('should pass topicId into document fetching options', () => {
+ const editor = {
+ getLexicalEditor: vi.fn(() => ({})),
+ } as any;
+
+ render(
+ <DocumentIdMode documentId="doc-1" editor={editor} sourceType="notebook" topicId="topic-1" />,
+ );
+
+ expect(useFetchDocument).toHaveBeenCalledWith('doc-1', {
+ autoSave: true,
+ editor,
+ sourceType: 'notebook',
+ topicId: 'topic-1',
+ });
+ });
});
diff --git a/src/features/EditorCanvas/DocumentIdMode.tsx b/src/features/EditorCanvas/DocumentIdMode.tsx
index 7bc7bae9a33..c9b18b9a9db 100644
--- a/src/features/EditorCanvas/DocumentIdMode.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.tsx
@@ -54,7 +54,9 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
documentId,
autoSave = true,
sourceType = 'page',
+ topicId,
onContentChange,
+ onInit,
unsavedChangesGuard,
style,
...editorProps
@@ -81,8 +83,24 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
useSaveDocumentHotkey(handleManualSave);
+ const handleEditorInit = useCallback(
+ (editorInstance: IEditor) => {
+ void onEditorInit(editorInstance).finally(() => {
+ onInit?.(editorInstance);
+ });
+ },
+ [onEditorInit, onInit],
+ );
+
// Use SWR hook for document fetching (auto-initializes via onSuccess in DocumentStore)
- const { error } = useFetchDocument(documentId, { autoSave, editor, sourceType });
+ const { data: remoteDocument, error } = useFetchDocument(documentId, {
+ autoSave,
+ editor,
+ sourceType,
+ topicId,
+ });
+ const remoteDocumentUpdatedAt = remoteDocument?.updatedAt;
+ const remoteDocumentVersion = remoteDocumentUpdatedAt?.toISOString();
// Check loading state via selector (document not yet in store)
const isLoading = useDocumentStore(editorSelectors.isDocumentLoading(documentId));
@@ -120,6 +138,7 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
// Track which documentId has already had onEditorInit called
const initializedDocIdRef = useRef<string | null>(null);
+ const hydratedVersionRef = useRef<string | undefined>(undefined);
// Critical fix: if the editor is already initialized, we need to manually call onEditorInit
// because the onInit callback only fires on the first editor initialization
@@ -133,11 +152,13 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
) {
const runId = ++initRunIdRef.current;
initializedDocIdRef.current = documentId;
+ hydratedVersionRef.current = remoteDocumentVersion;
// Lock content-change callback while hydrating document content into editor.
contentChangeLockRef.current = true;
void onEditorInit(editor).finally(() => {
+ onInit?.(editor);
queueMicrotask(() => {
if (initRunIdRef.current === runId) {
contentChangeLockRef.current = false;
@@ -145,7 +166,44 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
});
});
}
- }, [documentId, editor, isEditorInitialized, isLoading, onEditorInit]);
+ }, [
+ documentId,
+ editor,
+ isEditorInitialized,
+ isLoading,
+ onEditorInit,
+ onInit,
+ remoteDocumentVersion,
+ ]);
+
+ useEffect(() => {
+ if (!editor || !isEditorInitialized || isLoading || !remoteDocumentVersion) return;
+ if (initializedDocIdRef.current !== documentId) return;
+ if (hydratedVersionRef.current === remoteDocumentVersion) return;
+ if (isDirty) return;
+
+ const runId = ++initRunIdRef.current;
+ hydratedVersionRef.current = remoteDocumentVersion;
+ contentChangeLockRef.current = true;
+
+ void onEditorInit(editor).finally(() => {
+ onInit?.(editor);
+ queueMicrotask(() => {
+ if (initRunIdRef.current === runId) {
+ contentChangeLockRef.current = false;
+ }
+ });
+ });
+ }, [
+ documentId,
+ editor,
+ isDirty,
+ isEditorInitialized,
+ isLoading,
+ onEditorInit,
+ onInit,
+ remoteDocumentVersion,
+ ]);
// Show loading state
if (isLoading) {
@@ -169,7 +227,7 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
placeholder={editorProps.placeholder || t('pageEditor.editorPlaceholder')}
style={style}
onContentChange={handleChange}
- onInit={onEditorInit}
+ onInit={handleEditorInit}
{...editorProps}
/>
</>
diff --git a/src/features/EditorCanvas/EditorCanvas.test.tsx b/src/features/EditorCanvas/EditorCanvas.test.tsx
index ad3bc0f3029..410938719e8 100644
--- a/src/features/EditorCanvas/EditorCanvas.test.tsx
+++ b/src/features/EditorCanvas/EditorCanvas.test.tsx
@@ -108,6 +108,7 @@ describe('EditorCanvas', () => {
editor={mockEditor}
placeholder="Custom placeholder"
sourceType="notebook"
+ topicId="topic-123"
unsavedChangesGuard={{ enabled: true, message: 'unsaved', title: 'Unsaved' }}
onContentChange={onContentChange}
onInit={onInit}
@@ -125,6 +126,7 @@ describe('EditorCanvas', () => {
onInit,
placeholder: 'Custom placeholder',
sourceType: 'notebook',
+ topicId: 'topic-123',
unsavedChangesGuard: { enabled: true, message: 'unsaved', title: 'Unsaved' },
});
});
diff --git a/src/features/EditorCanvas/EditorCanvas.tsx b/src/features/EditorCanvas/EditorCanvas.tsx
index 715d34d997b..1a3c424c204 100644
--- a/src/features/EditorCanvas/EditorCanvas.tsx
+++ b/src/features/EditorCanvas/EditorCanvas.tsx
@@ -116,6 +116,12 @@ export interface EditorCanvasProps {
*/
toolbarExtraItems?: ChatInputActionsProps['items'];
+ /**
+ * Topic ID for notebook documents.
+ * Used to preserve active topic document context after leaving the page route.
+ */
+ topicId?: string | null;
+
/**
* Unsaved changes guard for documentId mode.
*/
diff --git a/src/features/EditorCanvas/InternalEditor.tsx b/src/features/EditorCanvas/InternalEditor.tsx
index ad5cdfcd6db..e560251bb83 100644
--- a/src/features/EditorCanvas/InternalEditor.tsx
+++ b/src/features/EditorCanvas/InternalEditor.tsx
@@ -1,7 +1,7 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import { type IEditor } from '@lobehub/editor';
+import type { IEditor } from '@lobehub/editor';
import {
ReactImagePlugin,
ReactLinkPlugin,
@@ -33,6 +33,39 @@ const STATIC_PLUGINS = [
ReactTablePlugin,
];
+const EDITOR_INIT_DATA_SOURCE_TYPES = ['json', 'markdown'] as const;
+const EDITOR_INIT_RETRY_LIMIT = 30;
+const EDITOR_INIT_RETRY_INTERVAL = 16;
+
+interface InspectableEditor extends IEditor {
+ dataTypeMap?: Map<string, unknown> | Record<string, unknown>;
+}
+
+const getEditorDataSourceTypes = (editor: InspectableEditor): string[] => {
+ const dataTypeMap = editor.dataTypeMap;
+
+ if (!dataTypeMap) return [];
+
+ if (dataTypeMap instanceof Map) {
+ return [...dataTypeMap.keys()].sort();
+ }
+
+ return Object.keys(dataTypeMap).sort();
+};
+
+const isEditorInitReady = (editor: IEditor) => {
+ const inspectableEditor = editor as InspectableEditor;
+ const dataSourceTypes = getEditorDataSourceTypes(inspectableEditor);
+
+ return {
+ dataSourceTypes,
+ hasLexicalEditor: !!editor.getLexicalEditor?.(),
+ isReady:
+ !!editor.getLexicalEditor?.() &&
+ EDITOR_INIT_DATA_SOURCE_TYPES.every((type) => dataSourceTypes.includes(type)),
+ };
+};
+
export interface InternalEditorProps extends EditorCanvasProps {
/**
* Optional lock ref to suppress content-change callback during programmatic document hydration.
@@ -134,6 +167,51 @@ const InternalEditor = memo<InternalEditorProps>(
};
}, [editor]);
+ const onInitRef = useRef(onInit);
+ const initializedEditorRef = useRef<IEditor | null>(null);
+
+ useEffect(() => {
+ onInitRef.current = onInit;
+ }, [onInit]);
+
+ useEffect(() => {
+ if (!onInit) return;
+
+ let retryCount = 0;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let disposed = false;
+
+ const notifyWhenReady = () => {
+ if (disposed) return;
+
+ const snapshot = isEditorInitReady(editor);
+
+ if (snapshot.isReady) {
+ if (initializedEditorRef.current !== editor) {
+ initializedEditorRef.current = editor;
+ onInitRef.current?.(editor);
+ }
+
+ return;
+ }
+
+ if (retryCount >= EDITOR_INIT_RETRY_LIMIT) {
+ console.warn('[InternalEditor] onInit delayed because editor is not ready:', snapshot);
+ return;
+ }
+
+ retryCount += 1;
+ timer = setTimeout(notifyWhenReady, EDITOR_INIT_RETRY_INTERVAL);
+ };
+
+ notifyWhenReady();
+
+ return () => {
+ disposed = true;
+ if (timer) clearTimeout(timer);
+ };
+ }, [editor, onInit]);
+
// Use refs for stable references across re-renders
const previousDocumentSnapshotRef = useRef<unknown>(undefined);
const onContentChangeRef = useRef(onContentChange);
@@ -191,7 +269,6 @@ const InternalEditor = memo<InternalEditorProps>(
paddingBottom: 32,
...style,
}}
- onInit={onInit}
/>
</div>
);
diff --git a/src/features/EditorCanvas/index.ts b/src/features/EditorCanvas/index.ts
index 0c0b25b7c1f..e175152599d 100644
--- a/src/features/EditorCanvas/index.ts
+++ b/src/features/EditorCanvas/index.ts
@@ -1,5 +1,6 @@
export { openFileSelector } from './actions';
export { default as AutoSaveHint, type AutoSaveHintProps } from './AutoSaveHint';
+export { default as DiffAllToolbar } from './DiffAllToolbar';
export {
EditorCanvas,
type EditorCanvasProps,
diff --git a/src/features/Electron/navigation/cachedData.ts b/src/features/Electron/navigation/cachedData.ts
index 6251110e156..823d414deb7 100644
--- a/src/features/Electron/navigation/cachedData.ts
+++ b/src/features/Electron/navigation/cachedData.ts
@@ -17,7 +17,8 @@ import { sessionGroupSelectors } from '@/store/session/slices/sessionGroup/selec
export const getCachedDataForReference = (reference: PageReference): CachedPageData | undefined => {
switch (reference.type) {
case 'agent':
- case 'agent-topic': {
+ case 'agent-topic':
+ case 'agent-topic-page': {
const agentId = 'agentId' in reference.params ? reference.params.agentId : undefined;
if (!agentId) return undefined;
@@ -25,7 +26,10 @@ export const getCachedDataForReference = (reference: PageReference): CachedPageD
if (!meta || Object.keys(meta).length === 0) return undefined;
let title = meta.title;
- if (reference.type === 'agent-topic' && 'topicId' in reference.params) {
+ if (
+ (reference.type === 'agent-topic' || reference.type === 'agent-topic-page') &&
+ 'topicId' in reference.params
+ ) {
const topicId = reference.params.topicId;
const topicDataMap = useChatStore.getState().topicDataMap;
for (const data of Object.values(topicDataMap)) {
diff --git a/src/features/Electron/navigation/routeMetadata.ts b/src/features/Electron/navigation/routeMetadata.ts
index 712b6eb351c..fe5b646a3bd 100644
--- a/src/features/Electron/navigation/routeMetadata.ts
+++ b/src/features/Electron/navigation/routeMetadata.ts
@@ -50,6 +50,12 @@ const routePatterns: RoutePattern[] = [
},
// Agent/Chat routes - use dynamic title for specific chat names
+ {
+ icon: pageIcon,
+ test: (p) => /^\/agent\/[^/]+\/tpc_[^/]+\/page$/.test(p),
+ titleKey: 'navigation.page',
+ useDynamicTitle: true,
+ },
{
icon: MessageSquare,
test: (p) => p.startsWith('/agent/'),
diff --git a/src/features/Electron/titlebar/RecentlyViewed/plugins/agentTopicPagePlugin.ts b/src/features/Electron/titlebar/RecentlyViewed/plugins/agentTopicPagePlugin.ts
new file mode 100644
index 00000000000..a2255e68f24
--- /dev/null
+++ b/src/features/Electron/titlebar/RecentlyViewed/plugins/agentTopicPagePlugin.ts
@@ -0,0 +1,90 @@
+import { FileText } from 'lucide-react';
+
+import { getRouteById } from '@/config/routes';
+import { SESSION_CHAT_TOPIC_PAGE_URL } from '@/const/url';
+import { useChatStore } from '@/store/chat';
+
+import { type AgentTopicPageParams, type PageReference, type ResolvedPageData } from '../types';
+import { type PluginContext, type RecentlyViewedPlugin } from './types';
+import { createPageReference } from './types';
+
+const AGENT_TOPIC_PAGE_PATH_REGEX = /^\/agent\/([^/?]+)\/(tpc_[^/?]+)\/page(?:\/([^/?]+))?$/;
+
+const pageIcon = getRouteById('page')?.icon || FileText;
+
+export const agentTopicPagePlugin: RecentlyViewedPlugin<'agent-topic-page'> = {
+ checkExists(reference: PageReference<'agent-topic-page'>, ctx: PluginContext): boolean {
+ const { agentId, topicId } = reference.params;
+ const agentMeta = ctx.getAgentMeta(agentId);
+ const topic = ctx.getTopic(topicId);
+
+ return agentMeta !== undefined && Object.keys(agentMeta).length > 0 && topic !== undefined;
+ },
+
+ generateId(reference: PageReference<'agent-topic-page'>): string {
+ const { agentId, topicId, docId } = reference.params;
+ return docId
+ ? `agent-topic-page:${agentId}:${topicId}:${docId}`
+ : `agent-topic-page:${agentId}:${topicId}`;
+ },
+
+ generateUrl(reference: PageReference<'agent-topic-page'>): string {
+ const { agentId, topicId, docId } = reference.params;
+ const base = SESSION_CHAT_TOPIC_PAGE_URL(agentId, topicId);
+ return docId ? `${base}/${docId}` : base;
+ },
+
+ getDefaultIcon() {
+ return pageIcon;
+ },
+
+ matchUrl(pathname: string, _searchParams: URLSearchParams): boolean {
+ return AGENT_TOPIC_PAGE_PATH_REGEX.test(pathname);
+ },
+
+ onActivate(reference: PageReference<'agent-topic-page'>) {
+ useChatStore.getState().switchTopic(reference.params.topicId);
+ },
+
+ parseUrl(
+ pathname: string,
+ _searchParams: URLSearchParams,
+ ): PageReference<'agent-topic-page'> | null {
+ const match = pathname.match(AGENT_TOPIC_PAGE_PATH_REGEX);
+ if (!match) return null;
+
+ const [, agentId, topicId, docId] = match;
+ const params: AgentTopicPageParams = { agentId, topicId, ...(docId ? { docId } : {}) };
+ const id = this.generateId({ params } as PageReference<'agent-topic-page'>);
+ return createPageReference('agent-topic-page', params, id);
+ },
+
+ priority: 30,
+
+ resolve(reference: PageReference<'agent-topic-page'>, ctx: PluginContext): ResolvedPageData {
+ const { agentId, topicId } = reference.params;
+ const agentMeta = ctx.getAgentMeta(agentId);
+ const topic = ctx.getTopic(topicId);
+ const cached = reference.cached;
+
+ const agentExists = agentMeta !== undefined && Object.keys(agentMeta).length > 0;
+ const topicExists = topic !== undefined;
+ const hasStoreData = agentExists && topicExists;
+
+ return {
+ avatar: agentMeta?.avatar ?? cached?.avatar,
+ backgroundColor: agentMeta?.backgroundColor ?? cached?.backgroundColor,
+ exists: hasStoreData || cached !== undefined,
+ icon: this.getDefaultIcon!(),
+ reference,
+ title:
+ cached?.title ||
+ topic?.title ||
+ agentMeta?.title ||
+ ctx.t('navigation.page', { ns: 'electron' }),
+ url: this.generateUrl(reference),
+ };
+ },
+
+ type: 'agent-topic-page',
+};
diff --git a/src/features/Electron/titlebar/RecentlyViewed/plugins/agentTopicPlugin.ts b/src/features/Electron/titlebar/RecentlyViewed/plugins/agentTopicPlugin.ts
index c1547389147..77a99038bd5 100644
--- a/src/features/Electron/titlebar/RecentlyViewed/plugins/agentTopicPlugin.ts
+++ b/src/features/Electron/titlebar/RecentlyViewed/plugins/agentTopicPlugin.ts
@@ -1,5 +1,6 @@
import { MessageSquare } from 'lucide-react';
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { useChatStore } from '@/store/chat';
import { type AgentTopicParams, type PageReference, type ResolvedPageData } from '../types';
@@ -8,6 +9,7 @@ import { type NewTabAction, type PluginContext, type RecentlyViewedPlugin } from
import { createPageReference } from './types';
const AGENT_PATH_REGEX = /^\/agent\/([^/?]+)$/;
+const AGENT_TOPIC_PATH_REGEX = /^\/agent\/([^/?]+)\/(tpc_[^/?]+)$/;
export const agentTopicPlugin: RecentlyViewedPlugin<'agent-topic'> = {
checkExists(reference: PageReference<'agent-topic'>, ctx: PluginContext): boolean {
@@ -33,7 +35,7 @@ export const agentTopicPlugin: RecentlyViewedPlugin<'agent-topic'> = {
generateUrl(reference: PageReference<'agent-topic'>): string {
const { agentId, topicId } = reference.params;
- return `/agent/${agentId}?topic=${topicId}`;
+ return SESSION_CHAT_TOPIC_URL(agentId, topicId);
},
getDefaultIcon() {
@@ -42,8 +44,10 @@ export const agentTopicPlugin: RecentlyViewedPlugin<'agent-topic'> = {
// Higher priority than agent plugin to match topic URLs first
matchUrl(pathname: string, searchParams: URLSearchParams): boolean {
- // Match /agent/:id with topic param
- return AGENT_PATH_REGEX.test(pathname) && searchParams.has('topic');
+ return (
+ AGENT_TOPIC_PATH_REGEX.test(pathname) ||
+ (AGENT_PATH_REGEX.test(pathname) && searchParams.has('topic'))
+ );
},
onActivate(reference: PageReference<'agent-topic'>) {
@@ -51,6 +55,16 @@ export const agentTopicPlugin: RecentlyViewedPlugin<'agent-topic'> = {
},
parseUrl(pathname: string, searchParams: URLSearchParams): PageReference<'agent-topic'> | null {
+ const pathMatch = pathname.match(AGENT_TOPIC_PATH_REGEX);
+
+ if (pathMatch) {
+ const [, agentId, topicId] = pathMatch;
+ const params: AgentTopicParams = { agentId, topicId };
+ const id = this.generateId({ params } as PageReference<'agent-topic'>);
+
+ return createPageReference('agent-topic', params, id);
+ }
+
const match = pathname.match(AGENT_PATH_REGEX);
if (!match) return null;
diff --git a/src/features/Electron/titlebar/RecentlyViewed/plugins/index.ts b/src/features/Electron/titlebar/RecentlyViewed/plugins/index.ts
index 454b50ae717..3bd78caa239 100644
--- a/src/features/Electron/titlebar/RecentlyViewed/plugins/index.ts
+++ b/src/features/Electron/titlebar/RecentlyViewed/plugins/index.ts
@@ -1,4 +1,5 @@
import { agentPlugin } from './agentPlugin';
+import { agentTopicPagePlugin } from './agentTopicPagePlugin';
import { agentTopicPlugin } from './agentTopicPlugin';
import { communityPlugin } from './communityPlugin';
import { groupPlugin } from './groupPlugin';
@@ -17,6 +18,7 @@ export * from './types';
export const loadAllRecentlyViewedPlugins = () => {
pluginRegistry.register([
agentPlugin,
+ agentTopicPagePlugin,
agentTopicPlugin,
communityPlugin,
groupPlugin,
@@ -26,6 +28,6 @@ export const loadAllRecentlyViewedPlugins = () => {
memoryPlugin,
pagePlugin,
resourcePlugin,
- settingsPlugin,
]);
+ pluginRegistry.register([settingsPlugin]);
};
diff --git a/src/features/Electron/titlebar/RecentlyViewed/types.ts b/src/features/Electron/titlebar/RecentlyViewed/types.ts
index 64b93bb1bea..99f1b9fe63f 100644
--- a/src/features/Electron/titlebar/RecentlyViewed/types.ts
+++ b/src/features/Electron/titlebar/RecentlyViewed/types.ts
@@ -8,6 +8,7 @@ import { type LucideIcon } from 'lucide-react';
export type PageType =
| 'agent'
| 'agent-topic'
+ | 'agent-topic-page'
| 'group'
| 'group-topic'
| 'page'
@@ -29,6 +30,12 @@ export interface AgentTopicParams {
topicId: string;
}
+export interface AgentTopicPageParams {
+ agentId: string;
+ docId?: string;
+ topicId: string;
+}
+
export interface GroupParams {
groupId: string;
}
@@ -70,6 +77,7 @@ export interface HomeParams {}
export interface PageParamsMap {
'agent': AgentParams;
'agent-topic': AgentTopicParams;
+ 'agent-topic-page': AgentTopicPageParams;
'community': CommunityParams;
'group': GroupParams;
'group-topic': GroupTopicParams;
diff --git a/src/features/FloatingChatPanel/ChatBody.test.tsx b/src/features/FloatingChatPanel/ChatBody.test.tsx
new file mode 100644
index 00000000000..da1acbe8180
--- /dev/null
+++ b/src/features/FloatingChatPanel/ChatBody.test.tsx
@@ -0,0 +1,63 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { CSSProperties, ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import ChatBody from './ChatBody';
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({
+ children,
+ flex,
+ height,
+ style,
+ width,
+ ...props
+ }: {
+ children?: ReactNode;
+ flex?: number;
+ height?: string;
+ style?: CSSProperties;
+ width?: string;
+ [key: string]: unknown;
+ }) => (
+ <div
+ data-flex={flex === undefined ? '' : String(flex)}
+ data-height={height ?? ''}
+ data-width={width ?? ''}
+ style={style}
+ {...props}
+ >
+ {children}
+ </div>
+ ),
+}));
+
+vi.mock('@/features/Conversation', () => ({
+ ChatList: () => <div data-testid="floating-chat-list">chat list</div>,
+}));
+
+vi.mock('@/routes/(main)/agent/features/Conversation/MainChatInput', () => ({
+ default: () => <div data-testid="floating-chat-input">chat input</div>,
+}));
+
+describe('FloatingChatPanel ChatBody', () => {
+ it('keeps the chat input after the list while leaving scroll ownership to the virtual list', () => {
+ render(<ChatBody />);
+
+ const body = screen.getByTestId('floating-chat-panel-body');
+ const list = screen.getByTestId('floating-chat-panel-list');
+ const input = screen.getByTestId('floating-chat-input');
+
+ expect(body).toHaveAttribute('data-flex', '1');
+ expect(body).toHaveAttribute('data-height', '100%');
+ expect(list).toHaveAttribute('data-flex', '1');
+ expect(body).toContainElement(list);
+ expect(body).toContainElement(input);
+ expect(body).toHaveStyle({ overflow: 'hidden' });
+ expect(list).toHaveStyle({ overflow: 'hidden' });
+ expect(list.compareDocumentPosition(input)).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+ });
+});
diff --git a/src/features/FloatingChatPanel/ChatBody.tsx b/src/features/FloatingChatPanel/ChatBody.tsx
new file mode 100644
index 00000000000..a38171818b3
--- /dev/null
+++ b/src/features/FloatingChatPanel/ChatBody.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { ChatList } from '@/features/Conversation';
+import MainChatInput from '@/routes/(main)/agent/features/Conversation/MainChatInput';
+
+/**
+ * Inner body of FloatingChatPanel.
+ *
+ * Assumes it is rendered inside a ConversationProvider. Pure layout — does not
+ * read the chat store directly.
+ */
+const ChatBody = memo(() => {
+ return (
+ <Flexbox
+ data-testid="floating-chat-panel-body"
+ flex={1}
+ height={'100%'}
+ style={{ minHeight: 0, overflow: 'hidden' }}
+ width={'100%'}
+ >
+ <Flexbox
+ data-testid="floating-chat-panel-list"
+ flex={1}
+ width={'100%'}
+ style={{
+ minHeight: 0,
+ overflow: 'hidden',
+ position: 'relative',
+ }}
+ >
+ <ChatList />
+ </Flexbox>
+ <MainChatInput />
+ </Flexbox>
+ );
+});
+
+ChatBody.displayName = 'FloatingChatPanelBody';
+
+export default ChatBody;
diff --git a/src/features/FloatingChatPanel/guard.test.ts b/src/features/FloatingChatPanel/guard.test.ts
new file mode 100644
index 00000000000..64e778549bd
--- /dev/null
+++ b/src/features/FloatingChatPanel/guard.test.ts
@@ -0,0 +1,26 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { __resetFloatingChatPanelRegistry, useSingleInstanceGuard } from './guard';
+
+describe('useSingleInstanceGuard', () => {
+ beforeEach(() => {
+ __resetFloatingChatPanelRegistry();
+ });
+
+ it('allows a single instance to mount without throwing', () => {
+ expect(() => renderHook(() => useSingleInstanceGuard())).not.toThrow();
+ });
+
+ it('throws when a second instance mounts while the first is alive', () => {
+ const first = renderHook(() => useSingleInstanceGuard());
+ expect(() => renderHook(() => useSingleInstanceGuard())).toThrow(/Only one instance allowed/);
+ first.unmount();
+ });
+
+ it('allows a new instance after the previous one unmounts', () => {
+ const first = renderHook(() => useSingleInstanceGuard());
+ first.unmount();
+ expect(() => renderHook(() => useSingleInstanceGuard())).not.toThrow();
+ });
+});
diff --git a/src/features/FloatingChatPanel/guard.ts b/src/features/FloatingChatPanel/guard.ts
new file mode 100644
index 00000000000..d4adf580c41
--- /dev/null
+++ b/src/features/FloatingChatPanel/guard.ts
@@ -0,0 +1,45 @@
+import { useLayoutEffect, useRef } from 'react';
+
+// FIXME: This guard is a v1 workaround. The underlying problem is that
+// `MainChatInput` writes its editor instance into the global `useChatStore.mainInputEditor`
+// slot without scoping it to the ConversationProvider store. As a result, mounting
+// two chat inputs on the same page silently clobbers each other. The real fix is to
+// scope `mainInputEditor` to the ConversationProvider store. Remove this guard once
+// that refactor lands.
+const mountedInstances = new Set<symbol>();
+
+/**
+ * Enforces a single-instance-per-page invariant for FloatingChatPanel.
+ * Throws inside `useLayoutEffect` if a second instance mounts while the first is alive.
+ *
+ * Note: this guard only detects multiple FloatingChatPanel siblings. It does NOT detect
+ * coexistence with the main-page ConversationArea, which also uses MainChatInput.
+ * Consumers must ensure FloatingChatPanel and ConversationArea don't render simultaneously.
+ */
+export const useSingleInstanceGuard = () => {
+ const idRef = useRef<symbol | null>(null);
+ if (!idRef.current) idRef.current = Symbol('FloatingChatPanel');
+
+ useLayoutEffect(() => {
+ if (mountedInstances.size > 0) {
+ throw new Error(
+ '[FloatingChatPanel] Only one instance allowed per page. ' +
+ 'Multiple instances would conflict over global chatStore.mainInputEditor. ' +
+ 'Ensure the previous instance is unmounted before mounting a new one.',
+ );
+ }
+ const id = idRef.current!;
+ mountedInstances.add(id);
+ return () => {
+ mountedInstances.delete(id);
+ };
+ }, []);
+};
+
+/**
+ * Test-only: reset the internal registry between tests.
+ * Do not call this in production code.
+ */
+export const __resetFloatingChatPanelRegistry = () => {
+ mountedInstances.clear();
+};
diff --git a/src/features/FloatingChatPanel/index.test.tsx b/src/features/FloatingChatPanel/index.test.tsx
new file mode 100644
index 00000000000..559e73222d8
--- /dev/null
+++ b/src/features/FloatingChatPanel/index.test.tsx
@@ -0,0 +1,129 @@
+import { render } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { __resetFloatingChatPanelRegistry } from './guard';
+import FloatingChatPanel from './index';
+
+vi.mock('./ChatBody', () => ({
+ default: () => <div data-testid="chat-body">body</div>,
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ FloatingSheet: ({
+ children,
+ dismissible,
+ headerActions,
+ snapPoints,
+ title,
+ variant,
+ }: {
+ children: ReactNode;
+ dismissible?: boolean;
+ headerActions?: ReactNode;
+ snapPoints?: number[];
+ title?: ReactNode;
+ variant?: string;
+ }) => (
+ <div
+ data-dismissible={String(dismissible)}
+ data-snap-points={JSON.stringify(snapPoints ?? [])}
+ data-testid="floating-panel-shell"
+ data-variant={variant ?? ''}
+ >
+ <div data-testid="sheet-title">{title}</div>
+ <div data-testid="sheet-actions">{headerActions}</div>
+ {children}
+ </div>
+ ),
+}));
+
+vi.mock('@/features/Conversation', () => ({
+ ChatList: () => null,
+ ConversationProvider: ({ children, context }: any) => (
+ <div data-context={JSON.stringify(context)} data-testid="provider">
+ {children}
+ </div>
+ ),
+}));
+
+vi.mock('@/routes/(main)/agent/features/Conversation/useActionsBarConfig', () => ({
+ useActionsBarConfig: () => ({ assistant: {}, user: {} }),
+}));
+
+vi.mock('@/hooks/useOperationState', () => ({
+ useOperationState: () => undefined,
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: any) =>
+ selector({
+ dbMessagesMap: {},
+ replaceMessages: vi.fn(),
+ }),
+}));
+
+vi.mock('@/store/chat/utils/messageMapKey', () => ({
+ messageMapKey: (ctx: any) => `${ctx.agentId}:${ctx.topicId}:${ctx.threadId}`,
+}));
+
+describe('FloatingChatPanel', () => {
+ beforeEach(() => {
+ __resetFloatingChatPanelRegistry();
+ });
+
+ it('builds a main-scope context from agentId + topicId', () => {
+ const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" topicId="topic-1" />);
+ const ctx = JSON.parse(getByTestId('provider').dataset.context!);
+ expect(ctx).toEqual({
+ agentId: 'agent-1',
+ scope: 'main',
+ threadId: null,
+ topicId: 'topic-1',
+ });
+ });
+
+ it('switches scope to thread when threadId is provided', () => {
+ const { getByTestId } = render(
+ <FloatingChatPanel agentId="agent-1" threadId="thread-1" topicId="topic-1" />,
+ );
+ const ctx = JSON.parse(getByTestId('provider').dataset.context!);
+ expect(ctx.scope).toBe('thread');
+ expect(ctx.threadId).toBe('thread-1');
+ });
+
+ it('supports page-scoped context with the active document id', () => {
+ const { getByTestId } = render(
+ <FloatingChatPanel agentId="agent-1" documentId="doc-1" scope="page" topicId="topic-1" />,
+ );
+ const ctx = JSON.parse(getByTestId('provider').dataset.context!);
+ expect(ctx).toEqual({
+ agentId: 'agent-1',
+ documentId: 'doc-1',
+ scope: 'page',
+ threadId: null,
+ topicId: 'topic-1',
+ });
+ });
+
+ it('forwards title and headerActions to floating panel header', () => {
+ const { getByTestId } = render(
+ <FloatingChatPanel
+ agentId="a"
+ headerActions={<button>Action</button>}
+ title={<span>My Title</span>}
+ topicId="t"
+ />,
+ );
+ expect(getByTestId('sheet-title').textContent).toBe('My Title');
+ expect(getByTestId('sheet-actions').textContent).toBe('Action');
+ });
+
+ it('applies default shell props', () => {
+ const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
+ const sheet = getByTestId('floating-panel-shell');
+ expect(sheet.dataset.snapPoints).toBe(JSON.stringify([180, 320, 520, 800]));
+ expect(sheet.dataset.variant).toBe('embedded');
+ expect(sheet.dataset.dismissible).toBe('false');
+ });
+});
diff --git a/src/features/FloatingChatPanel/index.tsx b/src/features/FloatingChatPanel/index.tsx
new file mode 100644
index 00000000000..f2674d390bd
--- /dev/null
+++ b/src/features/FloatingChatPanel/index.tsx
@@ -0,0 +1,218 @@
+'use client';
+
+import { type UIChatMessage } from '@lobechat/types';
+import { FloatingSheet, type FloatingSheetProps } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import type { ReactNode } from 'react';
+import { memo, useMemo, useState } from 'react';
+
+import {
+ type ActionsBarConfig,
+ type ConversationHooks,
+ ConversationProvider,
+} from '@/features/Conversation';
+import { type ConversationContext } from '@/features/Conversation/types';
+import { useOperationState } from '@/hooks/useOperationState';
+import { useActionsBarConfig } from '@/routes/(main)/agent/features/Conversation/useActionsBarConfig';
+import { useChatStore } from '@/store/chat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import ChatBody from './ChatBody';
+import { useSingleInstanceGuard } from './guard';
+
+const SNAP_POINTS = [180, 320, 520, 800] as const;
+const MAX_SNAP_POINT = SNAP_POINTS.at(-1)!;
+const REST_SNAP_POINT = SNAP_POINTS[0];
+
+const styles = createStaticStyles(({ css }) => ({
+ sheet: css`
+ overflow: hidden;
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+
+ min-height: 0;
+ `,
+ header: css`
+ display: flex;
+ flex-shrink: 0;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
+ `,
+ title: css`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ body: css`
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ `,
+}));
+
+export interface FloatingChatPanelProps {
+ /**
+ * Override the actions bar config. When omitted, defaults to the shared
+ * `useActionsBarConfig()` hook for parity with the main agent page.
+ */
+ actionsBar?: ActionsBarConfig;
+ activeSnapPoint?: number;
+ /** Agent identifier. */
+ agentId: string;
+ className?: string;
+ dismissible?: boolean;
+ /** Current document identifier for page-scoped conversations. */
+ documentId?: string;
+ headerActions?: ReactNode;
+ /**
+ * Conversation lifecycle hooks. Forwarded into the internal
+ * `ConversationProvider`. The panel wraps `onAfterSendMessage` to auto-expand
+ * the sheet to its tallest snap point on send.
+ */
+ hooks?: ConversationHooks;
+ maxHeight?: number;
+ minHeight?: number;
+ mode?: 'embedded' | 'overlay';
+ onOpenChange?: (open: boolean) => void;
+ onSnapPointChange?: (point: number) => void;
+ open?: boolean;
+ /** Optional conversation scope override for non-thread contexts. */
+ scope?: 'main' | 'page';
+ snapPoints?: number[];
+ /** Optional thread identifier. When provided, scope becomes `'thread'`. */
+ threadId?: string | null;
+ title?: ReactNode;
+ /** Topic identifier. `null` means a new / unpersisted conversation. */
+ topicId: string | null;
+ variant?: 'elevated' | 'embedded';
+ width?: number | string;
+}
+
+/**
+ * FloatingChatPanel
+ *
+ * A reusable floating conversation panel. Composes ChatList + MainChatInput inside
+ * a container shell. Consumers provide conversation coordinates via flat
+ * `agentId`/`topicId` props; the component builds its own `ConversationContext`
+ * internally.
+ *
+ * @FIXME ⚠️ Single instance per page. Mounting a second FloatingChatPanel while one is
+ * already mounted will throw. See `./guard.ts` for the rationale.
+ *
+ * @FIXME ⚠️ Must not coexist with the main-page ConversationArea (both use MainChatInput,
+ * which writes to the global `useChatStore.mainInputEditor` slot). This is NOT
+ * enforced at runtime — consumer responsibility.
+ */
+const FloatingChatPanel = memo<FloatingChatPanelProps>(
+ ({
+ agentId,
+ topicId,
+ threadId = null,
+ documentId,
+ scope,
+ actionsBar,
+ hooks,
+
+ minHeight: _minHeight = 240,
+ maxHeight: _maxHeight = 0.9,
+
+ width = '100%',
+
+ title,
+ headerActions,
+ }) => {
+ useSingleInstanceGuard();
+
+ const context = useMemo<ConversationContext>(
+ () => ({
+ agentId,
+ documentId,
+ scope: threadId ? 'thread' : (scope ?? 'main'),
+ threadId,
+ topicId,
+ }),
+ [agentId, documentId, scope, topicId, threadId],
+ );
+
+ const chatKey = useMemo(() => messageMapKey(context), [context]);
+ const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);
+ const replaceMessages = useChatStore((s) => s.replaceMessages);
+
+ const operationState = useOperationState(context);
+ const defaultActionsBar = useActionsBarConfig();
+ const resolvedActionsBar = actionsBar ?? defaultActionsBar;
+
+ const handleMessagesChange = useMemo(
+ () => (next: UIChatMessage[], ctx: ConversationContext) => {
+ replaceMessages(next, { context: ctx });
+ },
+ [replaceMessages],
+ );
+
+ const [open, setOpen] = useState(true);
+ const [activeSnapPoint, setActiveSnapPoint] = useState<number>(REST_SNAP_POINT);
+
+ const mergedHooks = useMemo<ConversationHooks>(
+ () => ({
+ ...hooks,
+ // Expand the sheet the moment the user presses Send, so the chat grows
+ // into view before the AI response streams in — not after it finishes.
+ onBeforeSendMessage: async (params) => {
+ setActiveSnapPoint(MAX_SNAP_POINT);
+ return hooks?.onBeforeSendMessage?.(params);
+ },
+ }),
+ [hooks],
+ );
+
+ const sheetProps: FloatingSheetProps = {
+ activeSnapPoint,
+ className: 'floating-sheet-demo-inline',
+ closeThreshold: 0.3,
+ defaultOpen: true,
+ dismissible: false,
+ headerActions,
+
+ maxHeight: MAX_SNAP_POINT,
+ minHeight: SNAP_POINTS[1],
+ mode: 'inline',
+ onOpenChange: setOpen,
+ onSnapPointChange: setActiveSnapPoint,
+ open,
+ restingHeight: REST_SNAP_POINT,
+ snapPoints: [...SNAP_POINTS],
+ title,
+
+ variant: 'embedded',
+ width,
+ };
+
+ return (
+ <FloatingSheet {...sheetProps}>
+ <div className={styles.body}>
+ <ConversationProvider
+ actionsBar={resolvedActionsBar}
+ context={context}
+ hasInitMessages={!!messages}
+ hooks={mergedHooks}
+ messages={messages}
+ operationState={operationState}
+ onMessagesChange={handleMessagesChange}
+ >
+ <ChatBody />
+ </ConversationProvider>
+ </div>
+ </FloatingSheet>
+ );
+ },
+);
+
+FloatingChatPanel.displayName = 'FloatingChatPanel';
+
+export default FloatingChatPanel;
diff --git a/src/features/NavHeader/index.tsx b/src/features/NavHeader/index.tsx
index ffb3e0aa9ee..9921ca70ae3 100644
--- a/src/features/NavHeader/index.tsx
+++ b/src/features/NavHeader/index.tsx
@@ -12,6 +12,11 @@ export interface NavHeaderProps extends Omit<FlexboxProps, 'children'> {
left?: ReactNode;
right?: ReactNode;
showTogglePanelButton?: boolean;
+ slotClassNames?: {
+ center?: string;
+ left?: string;
+ right?: string;
+ };
styles?: {
center?: CSSProperties;
left?: CSSProperties;
@@ -20,7 +25,16 @@ export interface NavHeaderProps extends Omit<FlexboxProps, 'children'> {
}
const NavHeader = memo<NavHeaderProps>(
- ({ showTogglePanelButton = true, style, children, left, right, styles, ...rest }) => {
+ ({
+ showTogglePanelButton = true,
+ style,
+ children,
+ left,
+ right,
+ slotClassNames,
+ styles,
+ ...rest
+ }) => {
const expand = useGlobalStore(systemStatusSelectors.showLeftPanel);
const noContent = !left && !right;
@@ -45,6 +59,7 @@ const NavHeader = memo<NavHeaderProps>(
allowShrink
horizontal
align={'center'}
+ className={slotClassNames?.left}
gap={2}
justify={'flex-start'}
style={styles?.left}
@@ -53,11 +68,18 @@ const NavHeader = memo<NavHeaderProps>(
{left}
</Flexbox>
{children && (
- <Flexbox flex={1} style={styles?.center}>
+ <Flexbox className={slotClassNames?.center} flex={1} style={styles?.center}>
{children}
</Flexbox>
)}
- <Flexbox horizontal align={'center'} gap={2} justify={'flex-end'} style={styles?.right}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={slotClassNames?.right}
+ gap={2}
+ justify={'flex-end'}
+ style={styles?.right}
+ >
{right}
</Flexbox>
</TooltipGroup>
diff --git a/src/features/Onboarding/Agent/index.tsx b/src/features/Onboarding/Agent/index.tsx
index 7cac8ece8d4..a0cf451c2e9 100644
--- a/src/features/Onboarding/Agent/index.tsx
+++ b/src/features/Onboarding/Agent/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
-import { SESSION_CHAT_URL } from '@lobechat/const';
+import { SESSION_CHAT_TOPIC_URL } from '@lobechat/const';
import { Button, ErrorBoundary, Flexbox } from '@lobehub/ui';
import { Drawer } from 'antd';
import { History } from 'lucide-react';
@@ -94,7 +94,7 @@ const AgentOnboardingPage = memo(() => {
const onboardingFinished = !!agentOnboarding?.finishedAt;
const finishTargetUrl = useMemo(() => {
if (!onboardingFinished || !inboxAgentId || !effectiveTopicId) return undefined;
- return `${SESSION_CHAT_URL(inboxAgentId)}?topic=${effectiveTopicId}`;
+ return SESSION_CHAT_TOPIC_URL(inboxAgentId, effectiveTopicId);
}, [onboardingFinished, inboxAgentId, effectiveTopicId]);
const viewingHistoricalTopic =
diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsx
index 75b6c518ff4..685e7ee5e5e 100644
--- a/src/features/PageEditor/PageEditor.tsx
+++ b/src/features/PageEditor/PageEditor.tsx
@@ -76,7 +76,7 @@ const PageEditorCanvas = memo(() => {
</Flexbox>
</WideScreenContainer>
</Flexbox>
- {documentId && <DiffAllToolbar documentId={documentId} editor={editor!} />}
+ {documentId && <DiffAllToolbar documentId={documentId} editor={editor} />}
</Flexbox>
<RightPanel />
</Flexbox>
diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsx
index 0ddddd7ed2d..56dc50732dd 100644
--- a/src/features/PageEditor/StoreUpdater.tsx
+++ b/src/features/PageEditor/StoreUpdater.tsx
@@ -1,6 +1,5 @@
'use client';
-import debug from 'debug';
import { memo, useEffect } from 'react';
import { createStoreUpdater } from 'zustand-utils';
@@ -10,8 +9,6 @@ import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-pag
import { type PublicState } from './store';
import { usePageEditorStore, useStoreApi } from './store';
-const log = debug('page:editor:store-updater');
-
type PageAgentEditor = NonNullable<Parameters<typeof pageAgentRuntime.setEditor>[0]>;
export interface StoreUpdaterProps extends Partial<PublicState> {
@@ -80,19 +77,10 @@ const StoreUpdater = memo<StoreUpdaterProps>(
pageAgentRuntime.setCurrentDocId(pageId);
pageAgentRuntime.setTitleHandlers(storeApi.getState().setTitle, titleGetter);
pageAgentRuntime.setBeforeMutateHandler(() => {
- if (!pageId) return;
- const editor = storeApi.getState().editor;
- if (!editor) return;
- try {
- const editorData = editor.getDocument('json');
- documentHistoryQueueService.enqueue({
- documentId: pageId,
- editorData: JSON.stringify(editorData),
- saveSource: 'llm_call',
- });
- } catch (error) {
- log('Failed to capture history snapshot before mutation: %o', error);
- }
+ documentHistoryQueueService.enqueueEditorSnapshot({
+ documentId: pageId,
+ editor: storeApi.getState().editor,
+ });
});
return () => {
diff --git a/src/features/Portal/components/Header.tsx b/src/features/Portal/components/Header.tsx
index 500a2920071..e4e6d93ee89 100644
--- a/src/features/Portal/components/Header.tsx
+++ b/src/features/Portal/components/Header.tsx
@@ -5,17 +5,26 @@ import { ActionIcon, Flexbox } from '@lobehub/ui';
import { ArrowLeft, X } from 'lucide-react';
import { type ReactNode } from 'react';
import { memo } from 'react';
+import { useLocation, useNavigate, useParams } from 'react-router-dom';
+import { SESSION_CHAT_TOPIC_PAGE_URL, SESSION_CHAT_TOPIC_URL } from '@/const/url';
import NavHeader from '@/features/NavHeader';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
const Header = memo<{ title: ReactNode }>(({ title }) => {
+ const location = useLocation();
+ const navigate = useNavigate();
+ const params = useParams<{ aid?: string; topicId?: string }>();
const [canGoBack, goBack, clearPortalStack] = useChatStore((s) => [
chatPortalSelectors.canGoBack(s),
s.goBack,
s.clearPortalStack,
]);
+ const isTopicPageRoute =
+ !!params.aid &&
+ !!params.topicId &&
+ location.pathname.startsWith(SESSION_CHAT_TOPIC_PAGE_URL(params.aid, params.topicId));
return (
<NavHeader
@@ -34,6 +43,11 @@ const Header = memo<{ title: ReactNode }>(({ title }) => {
icon={X}
size={DESKTOP_HEADER_ICON_SIZE}
onClick={() => {
+ if (params.aid && params.topicId && isTopicPageRoute) {
+ navigate(SESSION_CHAT_TOPIC_URL(params.aid, params.topicId));
+ return;
+ }
+
clearPortalStack();
}}
/>
diff --git a/src/features/TopicCanvas/TitleSection.tsx b/src/features/TopicCanvas/TitleSection.tsx
new file mode 100644
index 00000000000..8df384fd35d
--- /dev/null
+++ b/src/features/TopicCanvas/TitleSection.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import { Flexbox, TextArea } from '@lobehub/ui';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { truncateByWeightedLength } from '@/utils/textLength';
+
+export interface TitleSectionProps {
+ onTitleChange?: (title: string) => void;
+ title?: string;
+}
+
+const TitleSection = memo<TitleSectionProps>(({ title: titleProp, onTitleChange }) => {
+ const { t } = useTranslation('file');
+
+ const isTitleControlled = titleProp !== undefined;
+
+ const [innerTitle, setInnerTitle] = useState('');
+
+ const title = isTitleControlled ? titleProp : innerTitle;
+
+ const setTitle = (value: string) => {
+ if (!isTitleControlled) setInnerTitle(value);
+ onTitleChange?.(value);
+ };
+
+ return (
+ <Flexbox
+ gap={16}
+ paddingBlock={16}
+ style={{ cursor: 'default' }}
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ >
+ <TextArea
+ autoSize={{ minRows: 1 }}
+ placeholder={t('pageEditor.titlePlaceholder')}
+ value={title}
+ variant={'borderless'}
+ style={{
+ fontSize: 36,
+ fontWeight: 600,
+ padding: 0,
+ resize: 'none',
+ width: '100%',
+ }}
+ onChange={(e) => {
+ const truncated = truncateByWeightedLength(e.target.value, 100);
+ setTitle(truncated);
+ }}
+ />
+ </Flexbox>
+ );
+});
+
+TitleSection.displayName = 'TopicCanvasTitleSection';
+
+export default TitleSection;
diff --git a/src/features/TopicCanvas/index.test.tsx b/src/features/TopicCanvas/index.test.tsx
new file mode 100644
index 00000000000..500180b3682
--- /dev/null
+++ b/src/features/TopicCanvas/index.test.tsx
@@ -0,0 +1,151 @@
+import { render, screen, waitFor } from '@testing-library/react';
+import type * as React from 'react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { documentHistoryQueueService } from '@/services/documentHistoryQueue';
+
+import TopicCanvas from './index';
+
+const mockEditor = {
+ dataTypeMap: new Map([
+ ['json', {}],
+ ['litexml', {}],
+ ['markdown', {}],
+ ]),
+ focus: vi.fn(),
+ getDocument: vi.fn(() => ({ root: true })),
+ getLexicalEditor: vi.fn(() => ({})),
+} as const;
+
+const runtimeSpies = vi.hoisted(() => ({
+ setBeforeMutateHandler: vi.fn(),
+ setCurrentDocId: vi.fn(),
+ setEditor: vi.fn(),
+ setTitleHandlers: vi.fn(),
+}));
+
+const useEditorMock = vi.hoisted(() => vi.fn(() => mockEditor));
+
+vi.mock('@lobehub/editor/react', () => ({
+ EditorProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useEditor: useEditorMock,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ TextArea: ({
+ value,
+ onChange,
+ }: {
+ onChange?: (event: { target: { value: string } }) => void;
+ value?: string;
+ }) => (
+ <textarea
+ data-testid="topic-title-input"
+ value={value ?? ''}
+ onChange={(event) => onChange?.({ target: { value: event.target.value } })}
+ />
+ ),
+}));
+
+vi.mock('@/features/EditorCanvas', async () => {
+ const ReactActual = (await vi.importActual('react')) as typeof React;
+
+ return {
+ DiffAllToolbar: ({ documentId, editor }: { documentId: string; editor: typeof mockEditor }) => (
+ <div
+ data-document-id={documentId}
+ data-editor={editor === mockEditor ? 'shared' : 'other'}
+ data-testid="diff-toolbar"
+ />
+ ),
+ EditorCanvas: ({
+ documentId,
+ editor,
+ onInit,
+ }: {
+ documentId?: string;
+ editor?: typeof mockEditor;
+ onInit?: (editor: typeof mockEditor) => void;
+ }) => {
+ ReactActual.useEffect(() => {
+ if (editor) onInit?.(editor);
+ }, [editor, onInit]);
+
+ return (
+ <div
+ data-document-id={documentId ?? ''}
+ data-editor={editor === mockEditor ? 'shared' : 'other'}
+ data-testid="editor-canvas"
+ />
+ );
+ },
+ };
+});
+
+vi.mock('@/features/WideScreenContainer', () => ({
+ default: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock('@/hooks/useHotkeys', () => ({
+ useRegisterFilesHotkeys: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/services/documentHistoryQueue', () => ({
+ documentHistoryQueueService: {
+ enqueue: vi.fn(),
+ enqueueEditorSnapshot: vi.fn(),
+ flush: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/tool/slices/builtin/executors/lobe-page-agent', () => ({
+ pageAgentRuntime: runtimeSpies,
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('TopicCanvas', () => {
+ it('mounts diff toolbar and page-agent runtime bridge for the current document', async () => {
+ const { unmount } = render(
+ <TopicCanvas documentId="doc-1" title="Topic Title" onTitleChange={vi.fn()} />,
+ );
+
+ expect(screen.getByTestId('editor-canvas')).toHaveAttribute('data-document-id', 'doc-1');
+ expect(screen.getByTestId('diff-toolbar')).toHaveAttribute('data-document-id', 'doc-1');
+ expect(screen.getByTestId('diff-toolbar')).toHaveAttribute('data-editor', 'shared');
+
+ await waitFor(() => {
+ expect(runtimeSpies.setEditor).toHaveBeenCalledWith(mockEditor);
+ expect(runtimeSpies.setCurrentDocId).toHaveBeenCalledWith('doc-1');
+ expect(runtimeSpies.setTitleHandlers).toHaveBeenCalledTimes(1);
+ expect(runtimeSpies.setBeforeMutateHandler).toHaveBeenCalledWith(expect.any(Function));
+ });
+
+ const beforeMutateHandler = runtimeSpies.setBeforeMutateHandler.mock.calls.find(
+ ([handler]) => typeof handler === 'function',
+ )?.[0] as (() => void) | undefined;
+ beforeMutateHandler?.();
+
+ expect(documentHistoryQueueService.enqueueEditorSnapshot).toHaveBeenCalledWith({
+ documentId: 'doc-1',
+ editor: mockEditor,
+ });
+
+ unmount();
+
+ expect(runtimeSpies.setCurrentDocId).toHaveBeenLastCalledWith(undefined);
+ expect(runtimeSpies.setTitleHandlers).toHaveBeenLastCalledWith(null, null);
+ expect(runtimeSpies.setBeforeMutateHandler).toHaveBeenLastCalledWith(null);
+ expect(runtimeSpies.setEditor).toHaveBeenLastCalledWith(null);
+ });
+});
diff --git a/src/features/TopicCanvas/index.tsx b/src/features/TopicCanvas/index.tsx
new file mode 100644
index 00000000000..00cb1bc5740
--- /dev/null
+++ b/src/features/TopicCanvas/index.tsx
@@ -0,0 +1,293 @@
+'use client';
+
+import type { IEditor } from '@lobehub/editor';
+import { EditorProvider, useEditor } from '@lobehub/editor/react';
+import { Flexbox } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import debug from 'debug';
+import type { CSSProperties } from 'react';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
+
+import { DiffAllToolbar, EditorCanvas as SharedEditorCanvas } from '@/features/EditorCanvas';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useRegisterFilesHotkeys } from '@/hooks/useHotkeys';
+import { documentHistoryQueueService } from '@/services/documentHistoryQueue';
+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
+import { StyleSheet } from '@/utils/styles';
+
+import TitleSection, { type TitleSectionProps } from './TitleSection';
+
+const log = debug('lobe-client:topic-canvas');
+
+const styles = StyleSheet.create({
+ contentWrapper: {
+ display: 'flex',
+ position: 'relative',
+ },
+ editorContainer: {
+ minWidth: 0,
+ position: 'relative',
+ },
+ editorContent: {
+ paddingBlock: 16,
+ position: 'relative',
+ },
+ root: {
+ background: cssVar.colorBgContainer,
+ borderRadius: 12,
+ overflow: 'hidden',
+ },
+});
+
+export interface TopicCanvasProps extends TitleSectionProps {
+ agentId?: string;
+ documentId?: string;
+ placeholder?: string;
+ style?: CSSProperties;
+ topicId?: string | null;
+}
+
+type PageAgentEditor = NonNullable<Parameters<typeof pageAgentRuntime.setEditor>[0]>;
+
+const PAGE_AGENT_DATA_SOURCE_TYPES = ['json', 'litexml', 'markdown'] as const;
+const PAGE_AGENT_READY_RETRY_LIMIT = 30;
+const PAGE_AGENT_READY_RETRY_INTERVAL = 16;
+
+interface InspectableEditor extends IEditor {
+ dataTypeMap?: Map<string, unknown> | Record<string, unknown>;
+}
+
+const getEditorDataSourceTypes = (editor: InspectableEditor): string[] => {
+ const dataTypeMap = editor.dataTypeMap;
+
+ if (!dataTypeMap) return [];
+
+ if (dataTypeMap instanceof Map) {
+ return [...dataTypeMap.keys()].sort();
+ }
+
+ return Object.keys(dataTypeMap).sort();
+};
+
+const getPageAgentEditorSnapshot = (editor: IEditor | undefined) => {
+ if (!editor) {
+ return {
+ dataSourceTypes: [],
+ hasLexicalEditor: false,
+ isReady: false,
+ };
+ }
+
+ const dataSourceTypes = getEditorDataSourceTypes(editor as InspectableEditor);
+ const hasLexicalEditor = !!editor.getLexicalEditor?.();
+
+ return {
+ dataSourceTypes,
+ hasLexicalEditor,
+ isReady:
+ hasLexicalEditor &&
+ PAGE_AGENT_DATA_SOURCE_TYPES.every((type) => dataSourceTypes.includes(type)),
+ };
+};
+
+const TopicCanvasPageAgentBridge = memo<
+ Pick<TopicCanvasProps, 'documentId' | 'onTitleChange' | 'title'> & {
+ editor: IEditor | undefined;
+ editorReady: boolean;
+ }
+>(({ documentId, editor, editorReady, onTitleChange, title }) => {
+ const pageAgentEditor = editor as unknown as PageAgentEditor | undefined;
+ const titleRef = useRef(title ?? '');
+ const onTitleChangeRef = useRef(onTitleChange);
+
+ useEffect(() => {
+ titleRef.current = title ?? '';
+ }, [title]);
+
+ useEffect(() => {
+ onTitleChangeRef.current = onTitleChange;
+ }, [onTitleChange]);
+
+ useEffect(() => {
+ if (editorReady && pageAgentEditor) {
+ log('[TopicCanvas/PageAgentBridge] setEditor', {
+ dataSourceTypes: getPageAgentEditorSnapshot(editor).dataSourceTypes,
+ documentId,
+ editorReady,
+ hasLexicalEditor: !!pageAgentEditor.getLexicalEditor?.(),
+ });
+ pageAgentRuntime.setEditor(pageAgentEditor);
+ }
+
+ return () => {
+ log('[TopicCanvas/PageAgentBridge] clearEditor', { documentId });
+ pageAgentRuntime.setEditor(null);
+ };
+ }, [documentId, editor, editorReady, pageAgentEditor]);
+
+ useEffect(() => {
+ log('[TopicCanvas/PageAgentBridge] bindDocumentContext', {
+ dataSourceTypes: getPageAgentEditorSnapshot(editor).dataSourceTypes,
+ documentId,
+ hasEditor: !!editor,
+ });
+ pageAgentRuntime.setCurrentDocId(documentId);
+ pageAgentRuntime.setTitleHandlers(
+ (nextTitle) => {
+ titleRef.current = nextTitle;
+ onTitleChangeRef.current?.(nextTitle);
+ },
+ () => titleRef.current,
+ );
+ pageAgentRuntime.setBeforeMutateHandler(() => {
+ log('[TopicCanvas/PageAgentBridge] beforeMutate', {
+ dataSourceTypes: getPageAgentEditorSnapshot(editor).dataSourceTypes,
+ documentId,
+ hasEditor: !!editor,
+ });
+ documentHistoryQueueService.enqueueEditorSnapshot({ documentId, editor });
+ });
+
+ return () => {
+ log('[TopicCanvas/PageAgentBridge] clearDocumentContext', { documentId });
+ pageAgentRuntime.setCurrentDocId(undefined);
+ pageAgentRuntime.setTitleHandlers(null, null);
+ pageAgentRuntime.setBeforeMutateHandler(null);
+ void documentHistoryQueueService.flush();
+ };
+ }, [documentId, editor]);
+
+ return null;
+});
+
+TopicCanvasPageAgentBridge.displayName = 'TopicCanvasPageAgentBridge';
+
+const TopicCanvasBody = memo<TopicCanvasProps>(
+ ({ placeholder, style, title, documentId, onTitleChange, topicId }) => {
+ const editor = useEditor();
+ const [editorReady, setEditorReady] = useState(false);
+ const readyTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
+ const previousEditorContextRef = useRef<{ documentId?: string; editor?: IEditor } | undefined>(
+ undefined,
+ );
+
+ useRegisterFilesHotkeys();
+
+ useEffect(() => {
+ const previous = previousEditorContextRef.current;
+
+ if (previous && (previous.documentId !== documentId || previous.editor !== editor)) {
+ setEditorReady(false);
+ if (readyTimerRef.current) clearTimeout(readyTimerRef.current);
+ }
+
+ previousEditorContextRef.current = { documentId, editor };
+ }, [documentId, editor]);
+
+ useEffect(() => {
+ return () => {
+ if (readyTimerRef.current) clearTimeout(readyTimerRef.current);
+ };
+ }, []);
+
+ const handleEditorInit = useCallback(
+ (editorInstance: IEditor) => {
+ let retryCount = 0;
+
+ if (readyTimerRef.current) clearTimeout(readyTimerRef.current);
+
+ const markReadyWhenAvailable = () => {
+ const snapshot = getPageAgentEditorSnapshot(editorInstance);
+
+ log('[TopicCanvas] editor:onInit', {
+ ...snapshot,
+ documentId,
+ retryCount,
+ });
+
+ if (snapshot.isReady) {
+ setEditorReady(true);
+ return;
+ }
+
+ if (retryCount >= PAGE_AGENT_READY_RETRY_LIMIT) {
+ console.warn('[TopicCanvas] Page agent editor is not ready:', {
+ ...snapshot,
+ documentId,
+ });
+ return;
+ }
+
+ retryCount += 1;
+ readyTimerRef.current = setTimeout(
+ markReadyWhenAvailable,
+ PAGE_AGENT_READY_RETRY_INTERVAL,
+ );
+ };
+
+ markReadyWhenAvailable();
+ },
+ [documentId],
+ );
+
+ return (
+ <>
+ <TopicCanvasPageAgentBridge
+ documentId={documentId}
+ editor={editor}
+ editorReady={editorReady}
+ title={title}
+ onTitleChange={onTitleChange}
+ />
+ <Flexbox
+ horizontal
+ style={styles.contentWrapper}
+ width={'100%'}
+ onClick={() => editor?.focus()}
+ >
+ <Flexbox flex={1} style={styles.editorContainer}>
+ <WideScreenContainer wrapperStyle={{ cursor: 'text' }}>
+ <Flexbox flex={1} style={styles.editorContent}>
+ <TitleSection title={title} onTitleChange={onTitleChange} />
+ <SharedEditorCanvas
+ documentId={documentId}
+ editor={editor}
+ placeholder={placeholder}
+ sourceType={'notebook'}
+ style={style}
+ topicId={topicId}
+ onInit={handleEditorInit}
+ />
+ </Flexbox>
+ </WideScreenContainer>
+ {documentId && editor && <DiffAllToolbar documentId={documentId} editor={editor} />}
+ </Flexbox>
+ </Flexbox>
+ </>
+ );
+ },
+);
+
+TopicCanvasBody.displayName = 'TopicCanvasBody';
+
+/**
+ * TopicCanvas
+ *
+ * Document canvas for a Topic. Mirrors PageEditor's editor-region layout but
+ * without the page chrome (header, title, right panel). Renders an empty
+ * editor; topic-document data wiring (fetch/auto-save) is intentionally
+ * deferred.
+ */
+const TopicCanvas = memo<TopicCanvasProps>((props) => {
+ return (
+ <Flexbox style={styles.root} width={'100%'}>
+ <EditorProvider>
+ <TopicCanvasBody {...props} />
+ </EditorProvider>
+ </Flexbox>
+ );
+});
+
+TopicCanvas.displayName = 'TopicCanvas';
+
+export default TopicCanvas;
diff --git a/src/features/TopicCanvas/useAutoCreateTopicDocument.test.tsx b/src/features/TopicCanvas/useAutoCreateTopicDocument.test.tsx
new file mode 100644
index 00000000000..167a8c58921
--- /dev/null
+++ b/src/features/TopicCanvas/useAutoCreateTopicDocument.test.tsx
@@ -0,0 +1,101 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useAutoCreateTopicDocument } from './useAutoCreateTopicDocument';
+
+const createForTopicMock = vi.hoisted(() => vi.fn());
+const notebookMock = vi.hoisted(() => ({
+ documents: [] as Array<{ id: string }>,
+ isLoading: false,
+ useFetchDocuments: vi.fn(),
+}));
+const chatMock = vi.hoisted(() => ({
+ topicTitle: 'Research Topic',
+}));
+
+interface MockNotebookState {
+ notebookMap: Record<string, Array<{ id: string }>>;
+ useFetchDocuments: typeof notebookMock.useFetchDocuments;
+}
+
+interface MockChatState {
+ topicDataMap: Record<string, { items: Array<{ id: string; title: string }> }>;
+}
+
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentService: {
+ createForTopic: createForTopicMock,
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: MockChatState) => unknown) =>
+ selector({
+ topicDataMap: {
+ 'agent:agt_test': { items: [{ id: 'tpc_test', title: chatMock.topicTitle }] },
+ },
+ }),
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ getTopicById: (id: string) => (state: MockChatState) =>
+ Object.values(state.topicDataMap)
+ .flatMap((data) => data.items)
+ .find((topic) => topic.id === id),
+ },
+}));
+
+vi.mock('@/store/notebook', () => ({
+ notebookSelectors: {
+ getDocumentsByTopicId: (topicId: string | undefined) => (state: MockNotebookState) => {
+ if (!topicId) return [];
+
+ return state.notebookMap[topicId] ?? [];
+ },
+ },
+ useNotebookStore: (selector: (state: MockNotebookState) => unknown) =>
+ selector({
+ notebookMap: { tpc_test: notebookMock.documents },
+ useFetchDocuments: notebookMock.useFetchDocuments,
+ }),
+}));
+
+describe('useAutoCreateTopicDocument', () => {
+ beforeEach(() => {
+ createForTopicMock.mockReset();
+ chatMock.topicTitle = 'Research Topic';
+ notebookMock.documents = [];
+ notebookMock.isLoading = false;
+ notebookMock.useFetchDocuments.mockReset();
+ notebookMock.useFetchDocuments.mockImplementation(() => ({
+ isLoading: notebookMock.isLoading,
+ }));
+ });
+
+ it('returns an existing topic document id without creating a new page', () => {
+ notebookMock.documents = [{ id: 'doc_existing' }];
+
+ const { result } = renderHook(() => useAutoCreateTopicDocument('tpc_test', 'agt_test'));
+
+ expect(result.current.documentId).toBe('doc_existing');
+ expect(createForTopicMock).not.toHaveBeenCalled();
+ });
+
+ it('creates a topic page and exposes the created document id before the list refresh is observed', async () => {
+ createForTopicMock.mockResolvedValue({ documentId: 'doc_created' });
+
+ const { result } = renderHook(() => useAutoCreateTopicDocument('tpc_test', 'agt_test'));
+
+ await waitFor(() => expect(result.current.documentId).toBe('doc_created'));
+ expect(createForTopicMock).toHaveBeenCalledWith({
+ agentId: 'agt_test',
+ content: '',
+ title: 'Research Topic',
+ topicId: 'tpc_test',
+ });
+ });
+});
diff --git a/src/features/TopicCanvas/useAutoCreateTopicDocument.ts b/src/features/TopicCanvas/useAutoCreateTopicDocument.ts
new file mode 100644
index 00000000000..ebba3bba27b
--- /dev/null
+++ b/src/features/TopicCanvas/useAutoCreateTopicDocument.ts
@@ -0,0 +1,88 @@
+'use client';
+
+import type { NotebookDocument } from '@lobechat/types';
+import { useEffect, useState } from 'react';
+
+import { agentDocumentService } from '@/services/agentDocument';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { notebookSelectors, useNotebookStore } from '@/store/notebook';
+
+interface UseAutoCreateTopicDocumentResult {
+ document: NotebookDocument | undefined;
+ documentId: string | undefined;
+ isLoading: boolean;
+}
+
+const inflight = new Map<string, Promise<string | undefined>>();
+
+/**
+ * Fetch the topic-scoped document for a topic; auto-create one via the
+ * agent-document pipeline when the list is empty, then associate it with the
+ * topic through `topic_documents`. Returns the first document (topic → page is
+ * 1:1 in practice).
+ *
+ * Deduplicates concurrent creations across component instances via a
+ * module-level promise map keyed by topicId.
+ */
+export const useAutoCreateTopicDocument = (
+ topicId: string | undefined,
+ agentId: string | undefined,
+): UseAutoCreateTopicDocumentResult => {
+ const useFetchDocuments = useNotebookStore((s) => s.useFetchDocuments);
+ const topicTitle = useChatStore((s) =>
+ topicId ? topicSelectors.getTopicById(topicId)(s)?.title : undefined,
+ );
+ const [createdDocument, setCreatedDocument] = useState<
+ { documentId: string; topicId: string } | undefined
+ >();
+
+ const { isLoading } = useFetchDocuments(topicId);
+ const documents = useNotebookStore(notebookSelectors.getDocumentsByTopicId(topicId));
+
+ useEffect(() => {
+ if (!topicId || !agentId || isLoading) return;
+ if (documents.length > 0) return;
+
+ let ignore = false;
+ const promise =
+ inflight.get(topicId) ??
+ agentDocumentService
+ .createForTopic({
+ agentId,
+ content: '',
+ title: topicTitle?.trim() || '',
+ topicId,
+ })
+ .then((document) => document.documentId)
+ .catch((error) => {
+ console.error('[TopicCanvas] Failed to auto-create topic document:', error);
+
+ return undefined;
+ })
+ .finally(() => {
+ inflight.delete(topicId);
+ });
+
+ if (!inflight.has(topicId)) inflight.set(topicId, promise);
+
+ void promise.then((documentId) => {
+ if (ignore || !documentId) return;
+ setCreatedDocument({ documentId, topicId });
+ });
+
+ return () => {
+ ignore = true;
+ };
+ }, [topicId, agentId, topicTitle, isLoading, documents.length]);
+
+ const document = documents[0];
+ const createdDocumentId =
+ createdDocument && createdDocument.topicId === topicId ? createdDocument.documentId : undefined;
+
+ return {
+ document,
+ documentId: document?.id ?? createdDocumentId,
+ isLoading,
+ };
+};
diff --git a/src/hooks/useOperationState.test.ts b/src/hooks/useOperationState.test.ts
index b5a4a221fe5..9ef106b056b 100644
--- a/src/hooks/useOperationState.test.ts
+++ b/src/hooks/useOperationState.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';
import { useChatStore } from '@/store/chat';
import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useOperationState } from './useOperationState';
@@ -269,6 +270,31 @@ describe('useOperationState', () => {
});
describe('isInputLoading', () => {
+ it('should detect loading for a page-scoped floating chat panel context', () => {
+ const context = {
+ agentId: 'test-agent-id',
+ scope: 'page',
+ threadId: null,
+ topicId: 'test-topic-id',
+ } as const;
+
+ const { result } = renderHook(() => useOperationState(context));
+
+ expect(result.current.isInputLoading).toBe(false);
+ expect(result.current.isAIGenerating).toBe(false);
+
+ act(() => {
+ useChatStore.getState().startOperation({
+ context,
+ type: 'execAgentRuntime',
+ });
+ });
+
+ expect(useChatStore.getState().operationsByContext[messageMapKey(context)]).toHaveLength(1);
+ expect(result.current.isInputLoading).toBe(true);
+ expect(result.current.isAIGenerating).toBe(true);
+ });
+
it('should clear loading after cancelling an operation in a null-topic context', () => {
const context = {
agentId: 'test-agent-id',
diff --git a/src/hooks/usePrefetchPage.ts b/src/hooks/usePrefetchPage.ts
index 9508ee19ce2..2cdd1f2d054 100644
--- a/src/hooks/usePrefetchPage.ts
+++ b/src/hooks/usePrefetchPage.ts
@@ -2,6 +2,7 @@ import { useCallback } from 'react';
import { mutate } from '@/libs/swr';
import { documentService } from '@/services/document';
+import { documentSWRKeys } from '@/services/document/swrKeys';
/**
* Returns a callback to prefetch page/document data into the SWR cache.
@@ -12,12 +13,12 @@ export const usePrefetchPage = () => {
if (!documentId) return;
// Prefetch individual document content (for the editor)
- mutate(['document/editor', documentId], documentService.getDocumentById(documentId), {
+ mutate(documentSWRKeys.editor(documentId), documentService.getDocumentById(documentId), {
revalidate: false,
});
// Prefetch page documents list (for the sidebar)
- mutate(['pageDocuments'], documentService.getPageDocuments(), {
+ mutate(documentSWRKeys.pageDocuments(), documentService.getPageDocuments(), {
revalidate: false,
});
}, []);
diff --git a/src/libs/editor/isValidEditorData.test.ts b/src/libs/editor/isValidEditorData.test.ts
new file mode 100644
index 00000000000..bce059c39e0
--- /dev/null
+++ b/src/libs/editor/isValidEditorData.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+
+import { isValidEditorData } from './isValidEditorData';
+
+describe('isValidEditorData', () => {
+ it('should reject empty or incomplete editor data', () => {
+ expect(isValidEditorData(null)).toBe(false);
+ expect(isValidEditorData({})).toBe(false);
+ expect(isValidEditorData({ root: { children: [] } })).toBe(false);
+ expect(
+ isValidEditorData({
+ root: {
+ children: [],
+ direction: 'ltr',
+ format: '',
+ indent: 0,
+ type: 'root',
+ version: 1,
+ },
+ }),
+ ).toBe(false);
+ });
+
+ it('should accept non-empty Lexical editor data', () => {
+ expect(
+ isValidEditorData({
+ root: {
+ children: [
+ {
+ children: [
+ {
+ detail: 0,
+ format: 0,
+ mode: 'normal',
+ style: '',
+ text: 'hello',
+ type: 'text',
+ version: 1,
+ },
+ ],
+ direction: 'ltr',
+ format: '',
+ indent: 0,
+ type: 'paragraph',
+ version: 1,
+ },
+ ],
+ direction: 'ltr',
+ format: '',
+ indent: 0,
+ type: 'root',
+ version: 1,
+ },
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/src/libs/editor/isValidEditorData.ts b/src/libs/editor/isValidEditorData.ts
index 02adf4153b5..95980170d01 100644
--- a/src/libs/editor/isValidEditorData.ts
+++ b/src/libs/editor/isValidEditorData.ts
@@ -2,5 +2,10 @@ const isObject = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null;
export const isValidEditorData = (value: unknown): value is Record<string, unknown> => {
- return isObject(value) && Object.keys(value).length > 0;
+ if (!isObject(value)) return false;
+
+ const root = value.root;
+ if (!isObject(root)) return false;
+
+ return root.type === 'root' && Array.isArray(root.children) && root.children.length > 0;
};
diff --git a/src/libs/editor/normalizeDiffNodes.test.ts b/src/libs/editor/normalizeDiffNodes.test.ts
new file mode 100644
index 00000000000..feaba65ed3f
--- /dev/null
+++ b/src/libs/editor/normalizeDiffNodes.test.ts
@@ -0,0 +1,154 @@
+import { describe, expect, it } from 'vitest';
+
+import { normalizeEditorDataDiffNodes } from './normalizeDiffNodes';
+
+describe('normalizeEditorDataDiffNodes', () => {
+ it('should replace block diff nodes with their origin content', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ { text: 'before', type: 'text' },
+ { text: 'after', type: 'text' },
+ ],
+ diffType: 'modify',
+ type: 'diff',
+ },
+ {
+ children: [{ children: [{ text: 'new', type: 'text' }], type: 'paragraph' }],
+ diffType: 'add',
+ type: 'diff',
+ },
+ {
+ children: [{ children: [{ text: 'deleted', type: 'text' }], type: 'paragraph' }],
+ diffType: 'remove',
+ type: 'diff',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(normalizeEditorDataDiffNodes(editorData)).toEqual({
+ root: {
+ children: [
+ { text: 'before', type: 'text' },
+ { children: [{ text: 'deleted', type: 'text' }], type: 'paragraph' },
+ ],
+ type: 'root',
+ },
+ });
+ });
+
+ it('should flatten list item diff nodes to the rejected list item state', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ children: [
+ {
+ children: [
+ { children: [{ text: 'origin item', type: 'text' }], type: 'listitem' },
+ { children: [{ text: 'modified item', type: 'text' }], type: 'listitem' },
+ ],
+ diffType: 'listItemModify',
+ type: 'diff',
+ },
+ ],
+ type: 'listitem',
+ },
+ {
+ children: [
+ {
+ children: [{ text: 'removed item', type: 'text' }],
+ diffType: 'listItemRemove',
+ type: 'diff',
+ },
+ ],
+ type: 'listitem',
+ },
+ {
+ children: [
+ {
+ children: [{ text: 'added item', type: 'text' }],
+ diffType: 'listItemAdd',
+ type: 'diff',
+ },
+ ],
+ type: 'listitem',
+ },
+ ],
+ type: 'list',
+ },
+ ],
+ type: 'root',
+ },
+ };
+
+ expect(normalizeEditorDataDiffNodes(editorData)).toEqual({
+ root: {
+ children: [
+ {
+ children: [
+ {
+ children: [{ text: 'origin item', type: 'text' }],
+ type: 'listitem',
+ },
+ {
+ children: [{ text: 'removed item', type: 'text' }],
+ type: 'listitem',
+ },
+ {
+ children: [],
+ type: 'listitem',
+ },
+ ],
+ type: 'list',
+ },
+ ],
+ type: 'root',
+ },
+ });
+ });
+
+ it('should recursively normalize nested diff nodes without mutating the input', () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ children: [
+ { children: [{ text: 'nested origin', type: 'text' }], type: 'paragraph' },
+ { children: [{ text: 'nested modified', type: 'text' }], type: 'paragraph' },
+ ],
+ diffType: 'modify',
+ type: 'diff',
+ },
+ ],
+ diffType: 'remove',
+ type: 'diff',
+ },
+ ],
+ type: 'root',
+ },
+ };
+ const original = structuredClone(editorData);
+
+ expect(normalizeEditorDataDiffNodes(editorData)).toEqual({
+ root: {
+ children: [
+ {
+ children: [{ text: 'nested origin', type: 'text' }],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ });
+ expect(editorData).toEqual(original);
+ });
+});
diff --git a/src/libs/editor/normalizeDiffNodes.ts b/src/libs/editor/normalizeDiffNodes.ts
new file mode 100644
index 00000000000..e93c3c416c9
--- /dev/null
+++ b/src/libs/editor/normalizeDiffNodes.ts
@@ -0,0 +1,112 @@
+type DiffType =
+ | 'add'
+ | 'listItemAdd'
+ | 'listItemModify'
+ | 'listItemRemove'
+ | 'modify'
+ | 'remove'
+ | 'unchanged';
+
+const REMOVED_NODE = Symbol('removed-diff-origin');
+
+type RemovedNode = typeof REMOVED_NODE;
+type NormalizedNode =
+ | RemovedNode
+ | Record<string, unknown>
+ | unknown[]
+ | boolean
+ | null
+ | number
+ | string
+ | undefined;
+
+interface SerializedDiffNodeLike extends Record<string, unknown> {
+ children?: unknown[];
+ diffType?: DiffType;
+ type: 'diff';
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const isDiffNode = (value: unknown): value is SerializedDiffNodeLike =>
+ isRecord(value) && value.type === 'diff';
+
+const getChildren = (node: Record<string, unknown>): unknown[] =>
+ Array.isArray(node.children) ? node.children : [];
+
+const normalizeChildren = (children: unknown[]): unknown[] =>
+ children.flatMap((child) => {
+ const normalized = normalizeNode(child);
+
+ if (normalized === REMOVED_NODE) return [];
+
+ return Array.isArray(normalized) ? normalized : [normalized];
+ });
+
+const normalizeFirstChild = (node: SerializedDiffNodeLike): NormalizedNode => {
+ const [origin] = getChildren(node);
+
+ return origin === undefined ? REMOVED_NODE : normalizeNode(origin);
+};
+
+const normalizeFirstChildChildren = (node: SerializedDiffNodeLike): NormalizedNode => {
+ const [origin] = getChildren(node);
+
+ if (origin === undefined) return REMOVED_NODE;
+
+ return isRecord(origin) && Array.isArray(origin.children)
+ ? normalizeChildren(origin.children)
+ : normalizeNode(origin);
+};
+
+const normalizeDiffNodeOrigin = (node: SerializedDiffNodeLike): NormalizedNode => {
+ switch (node.diffType) {
+ case 'add':
+ case 'listItemAdd': {
+ return REMOVED_NODE;
+ }
+
+ case 'listItemModify': {
+ return normalizeFirstChildChildren(node);
+ }
+
+ case 'listItemRemove':
+ case 'unchanged': {
+ return normalizeChildren(getChildren(node));
+ }
+
+ default: {
+ return normalizeFirstChild(node);
+ }
+ }
+};
+
+const normalizeNode = (value: unknown): NormalizedNode => {
+ if (Array.isArray(value)) return normalizeChildren(value);
+
+ if (!isRecord(value)) return value as NormalizedNode;
+
+ if (isDiffNode(value)) return normalizeDiffNodeOrigin(value);
+
+ const normalized: Record<string, unknown> = {};
+
+ for (const [key, child] of Object.entries(value)) {
+ const normalizedChild =
+ key === 'children' && Array.isArray(child) ? normalizeChildren(child) : normalizeNode(child);
+
+ if (normalizedChild !== REMOVED_NODE) {
+ normalized[key] = normalizedChild;
+ }
+ }
+
+ return normalized;
+};
+
+export const normalizeEditorDataDiffNodes = <T extends Record<string, unknown>>(
+ editorData: T,
+): T => {
+ const normalized = normalizeNode(editorData);
+
+ return isRecord(normalized) ? (normalized as T) : ({} as T);
+};
diff --git a/src/libs/next/config/define-config.ts b/src/libs/next/config/define-config.ts
index 48c0a7d897d..413438f728a 100644
--- a/src/libs/next/config/define-config.ts
+++ b/src/libs/next/config/define-config.ts
@@ -355,6 +355,7 @@ export function defineConfig(config: CustomNextConfig) {
serverExternalPackages: config.serverExternalPackages ?? [
'pdfkit',
'@napi-rs/canvas',
+ '@lobehub/editor',
'discord.js',
'ffmpeg-static',
'pdfjs-dist',
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index cd20d37b2ef..2829d8661d7 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -733,6 +733,9 @@ export default {
'viewMode.fullWidth': 'Full Width',
'viewMode.normal': 'Standard',
'viewMode.wideScreen': 'Widescreen',
+ 'viewSwitcher.chat': 'Chat',
+ 'viewSwitcher.page': 'Page',
+ 'viewSwitcher.task': 'Task',
'workflow.failedSuffix': '(failed)',
'workflow.summaryFailed': '{{count}} failed',
'workflow.summaryMoreTools': '{{count}} tool kinds',
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index 948f1e4c333..f513408adad 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -154,7 +154,7 @@ export default {
'builtins.lobe-agent-documents.apiName.createDocument': 'Create document',
'builtins.lobe-agent-documents.apiName.editDocument': 'Edit document',
'builtins.lobe-agent-documents.apiName.listDocuments': 'List documents',
- 'builtins.lobe-agent-documents.apiName.patchDocument': 'Patch document',
+ 'builtins.lobe-agent-documents.apiName.modifyNodes': 'Modify document',
'builtins.lobe-agent-documents.apiName.readDocument': 'Read document',
'builtins.lobe-agent-documents.apiName.readDocumentByFilename': 'Read document by filename',
'builtins.lobe-agent-documents.apiName.removeDocument': 'Remove document',
diff --git a/src/routes/(main)/agent/(chat)/_layout/HeaderSlot.tsx b/src/routes/(main)/agent/(chat)/_layout/HeaderSlot.tsx
new file mode 100644
index 00000000000..8c3fc7420d4
--- /dev/null
+++ b/src/routes/(main)/agent/(chat)/_layout/HeaderSlot.tsx
@@ -0,0 +1,39 @@
+'use client';
+
+import { createContext, memo, type ReactNode, use, useMemo, useState } from 'react';
+import { createPortal } from 'react-dom';
+
+interface HeaderSlotContextValue {
+ el: HTMLElement | null;
+ setEl: (el: HTMLElement | null) => void;
+}
+
+const HeaderSlotContext = createContext<HeaderSlotContextValue>({
+ el: null,
+ setEl: () => {},
+});
+
+const Provider = memo<{ children: ReactNode }>(({ children }) => {
+ const [el, setEl] = useState<HTMLElement | null>(null);
+ const value = useMemo<HeaderSlotContextValue>(() => ({ el, setEl }), [el]);
+ return <HeaderSlotContext value={value}>{children}</HeaderSlotContext>;
+});
+
+Provider.displayName = 'HeaderSlotProvider';
+
+const Outlet = memo(() => {
+ const { setEl } = use(HeaderSlotContext);
+ return <span ref={setEl} />;
+});
+
+Outlet.displayName = 'HeaderSlotOutlet';
+
+const HeaderSlot = memo<{ children: ReactNode }>(({ children }) => {
+ const { el } = use(HeaderSlotContext);
+ if (!el) return null;
+ return createPortal(children, el);
+});
+
+HeaderSlot.displayName = 'HeaderSlot';
+
+export default Object.assign(HeaderSlot, { Outlet, Provider });
diff --git a/src/routes/(main)/agent/(chat)/_layout/index.tsx b/src/routes/(main)/agent/(chat)/_layout/index.tsx
new file mode 100644
index 00000000000..a28ac0d4f1f
--- /dev/null
+++ b/src/routes/(main)/agent/(chat)/_layout/index.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { memo } from 'react';
+import { Outlet } from 'react-router-dom';
+
+import ChatHeader from '@/routes/(main)/agent/features/Conversation/Header';
+import AgentWorkingSidebar from '@/routes/(main)/agent/features/Conversation/WorkingSidebar';
+import Portal from '@/routes/(main)/agent/features/Portal';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+
+import HeaderSlot from './HeaderSlot';
+
+const ChatLayout = memo(() => {
+ const showHeader = useGlobalStore(systemStatusSelectors.showChatHeader);
+
+ return (
+ <HeaderSlot.Provider>
+ <Flexbox
+ horizontal
+ flex={1}
+ height={'100%'}
+ style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}
+ width={'100%'}
+ >
+ <Flexbox flex={1} style={{ minHeight: 0, minWidth: 0 }}>
+ {showHeader && <ChatHeader />}
+ <Flexbox flex={1} style={{ minHeight: 0, position: 'relative' }}>
+ <Outlet />
+ </Flexbox>
+ </Flexbox>
+ <Portal />
+ <AgentWorkingSidebar />
+ </Flexbox>
+ </HeaderSlot.Provider>
+ );
+});
+
+ChatLayout.displayName = 'ChatLayout';
+
+export default ChatLayout;
diff --git a/src/routes/(main)/agent/[topicId]/index.tsx b/src/routes/(main)/agent/[topicId]/index.tsx
new file mode 100644
index 00000000000..111c05ccfb2
--- /dev/null
+++ b/src/routes/(main)/agent/[topicId]/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/routes/(main)/agent';
diff --git a/src/routes/(main)/agent/[topicId]/page/[docId]/index.tsx b/src/routes/(main)/agent/[topicId]/page/[docId]/index.tsx
new file mode 100644
index 00000000000..6ddb411b336
--- /dev/null
+++ b/src/routes/(main)/agent/[topicId]/page/[docId]/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/routes/(main)/agent/features/Page';
diff --git a/src/routes/(main)/agent/[topicId]/page/index.tsx b/src/routes/(main)/agent/[topicId]/page/index.tsx
new file mode 100644
index 00000000000..02324f3a945
--- /dev/null
+++ b/src/routes/(main)/agent/[topicId]/page/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/routes/(main)/agent/features/Page/PageRedirect';
diff --git a/src/routes/(main)/agent/_layout/AgentIdSync.test.tsx b/src/routes/(main)/agent/_layout/AgentIdSync.test.tsx
index 81dda8048aa..df192a3dc53 100644
--- a/src/routes/(main)/agent/_layout/AgentIdSync.test.tsx
+++ b/src/routes/(main)/agent/_layout/AgentIdSync.test.tsx
@@ -77,5 +77,20 @@ describe('AgentIdSync', () => {
expect(useChatStore.getState().portalStack).toEqual([]);
expect(useChatStore.getState().showPortal).toBe(false);
+ expect(useChatStore.getState().activeTopicId).toBe('topic-1');
+ });
+
+ it('preserves the active topic when the destination route carries a topic path segment', () => {
+ useParamsMock.mockReturnValue({ aid: 'agent-1', topicId: 'topic-1' });
+ useSearchParamsMock.mockReturnValue([new URLSearchParams(''), vi.fn()]);
+
+ const { rerender } = render(<AgentIdSync />);
+
+ useParamsMock.mockReturnValue({ aid: 'agent-2', topicId: 'topic-2' });
+ rerender(<AgentIdSync />);
+
+ expect(useChatStore.getState().portalStack).toEqual([]);
+ expect(useChatStore.getState().showPortal).toBe(false);
+ expect(useChatStore.getState().activeTopicId).toBe('topic-1');
});
});
diff --git a/src/routes/(main)/agent/_layout/AgentIdSync.tsx b/src/routes/(main)/agent/_layout/AgentIdSync.tsx
index f404edbb91d..2c9b80507e5 100644
--- a/src/routes/(main)/agent/_layout/AgentIdSync.tsx
+++ b/src/routes/(main)/agent/_layout/AgentIdSync.tsx
@@ -13,7 +13,7 @@ const BUILTIN_SLUG_SET = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));
const AgentIdSync = () => {
const useStoreUpdater = createStoreUpdater(useAgentStore);
const useChatStoreUpdater = createStoreUpdater(useChatStore);
- const params = useParams<{ aid?: string }>();
+ const params = useParams<{ aid?: string; topicId?: string }>();
const [searchParams] = useSearchParams();
const searchParamsRef = useRef(searchParams);
searchParamsRef.current = searchParams;
@@ -54,7 +54,7 @@ const AgentIdSync = () => {
useChatStore.getState().clearPortalStack();
// Preserve topic if the URL already carries one (e.g. tab navigation)
- const topicFromUrl = searchParamsRef.current.get('topic');
+ const topicFromUrl = params.topicId ?? searchParamsRef.current.get('topic');
if (!topicFromUrl) {
useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
new file mode 100644
index 00000000000..d5d5bc4f7df
--- /dev/null
+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
@@ -0,0 +1,158 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import Nav from './Nav';
+
+const mutateMock = vi.hoisted(() => vi.fn());
+const openNewTopicOrSaveTopicMock = vi.hoisted(() => vi.fn());
+const pushMock = vi.hoisted(() => vi.fn());
+const switchTopicMock = vi.hoisted(() => vi.fn());
+const toggleCommandMenuMock = vi.hoisted(() => vi.fn());
+const useParamsMock = vi.hoisted(() => vi.fn());
+const usePathnameMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+}));
+
+vi.mock('@lobehub/ui/icons', () => ({
+ BotPromptIcon: () => null,
+}));
+
+vi.mock('lucide-react', () => ({
+ MessageSquarePlusIcon: () => null,
+ RadioTowerIcon: () => null,
+ SearchIcon: () => null,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('react-router-dom', async () => {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
+ const actual = (await vi.importActual('react-router-dom')) as typeof import('react-router-dom');
+
+ return {
+ ...actual,
+ useParams: useParamsMock,
+ };
+});
+
+vi.mock('@/const/url', () => ({
+ SESSION_CHAT_URL: (agentId: string) => `/agent/${agentId}`,
+}));
+
+vi.mock('@/features/NavPanel/components/NavItem', () => ({
+ default: ({
+ active,
+ onClick,
+ title,
+ }: {
+ active?: boolean;
+ onClick?: () => void;
+ title: ReactNode;
+ }) => (
+ <button data-active={String(active)} type="button" onClick={onClick}>
+ {title}
+ </button>
+ ),
+}));
+
+vi.mock('@/hooks/useQueryRoute', () => ({
+ useQueryRoute: () => ({
+ push: pushMock,
+ }),
+}));
+
+vi.mock('@/libs/router/navigation', () => ({
+ usePathname: usePathnameMock,
+}));
+
+vi.mock('@/libs/swr', () => ({
+ useActionSWR: () => ({
+ mutate: mutateMock,
+ }),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: {
+ isCurrentAgentHeterogeneous: () => false,
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (
+ selector: (state: {
+ openNewTopicOrSaveTopic: () => void;
+ switchTopic: (topicId: string | null, options?: unknown) => void;
+ }) => unknown,
+ ) =>
+ selector({
+ openNewTopicOrSaveTopic: openNewTopicOrSaveTopicMock,
+ switchTopic: switchTopicMock,
+ }),
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: { toggleCommandMenu: (open: boolean) => void }) => unknown) =>
+ selector({ toggleCommandMenu: toggleCommandMenuMock }),
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ featureFlagsSelectors: (state: { featureFlags: { isAgentEditable: boolean } }) =>
+ state.featureFlags,
+ useServerConfigStore: (
+ selector: (state: { featureFlags: { isAgentEditable: boolean } }) => unknown,
+ ) => selector({ featureFlags: { isAgentEditable: true } }),
+}));
+
+describe('Agent sidebar header nav', () => {
+ beforeEach(() => {
+ mutateMock.mockReset();
+ openNewTopicOrSaveTopicMock.mockReset();
+ pushMock.mockReset();
+ switchTopicMock.mockReset();
+ toggleCommandMenuMock.mockReset();
+ useParamsMock.mockReset();
+ usePathnameMock.mockReset();
+
+ useParamsMock.mockReturnValue({ aid: 'agt_eH4zL98zBx5u', topicId: 'tpc_2FCHvjS7d4CA' });
+ });
+
+ it('returns to the agent chat route before opening a new topic from a topic page document route', () => {
+ usePathnameMock.mockReturnValue(
+ '/agent/agt_eH4zL98zBx5u/tpc_2FCHvjS7d4CA/page/docs_9B8hFkmEOZyPZb60',
+ );
+
+ render(<Nav />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopic' }));
+
+ expect(pushMock).toHaveBeenCalledWith('/agent/agt_eH4zL98zBx5u');
+ expect(mutateMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('pushes the agent chat route even when already on it', () => {
+ usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u');
+
+ render(<Nav />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopic' }));
+
+ expect(pushMock).toHaveBeenCalledWith('/agent/agt_eH4zL98zBx5u');
+ expect(mutateMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
index 4f8bbcc44a3..1f6585287bc 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
@@ -2,12 +2,13 @@
import { Flexbox } from '@lobehub/ui';
import { BotPromptIcon } from '@lobehub/ui/icons';
-import { MessageSquarePlusIcon, RadioTowerIcon, SearchIcon } from 'lucide-react';
+import { ListTodoIcon, MessageSquarePlusIcon, RadioTowerIcon, SearchIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
import urlJoin from 'url-join';
+import { SESSION_CHAT_URL } from '@/const/url';
import NavItem from '@/features/NavPanel/components/NavItem';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { usePathname } from '@/libs/router/navigation';
@@ -26,8 +27,9 @@ const Nav = memo(() => {
const pathname = usePathname();
const isProfileActive = pathname.includes('/profile');
const isChannelActive = pathname.includes('/channel');
+ const isTasksActive = pathname.includes('/tasks');
const router = useQueryRoute();
- const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
+ const { isAgentEditable, enableAgentTask } = useServerConfigStore(featureFlagsSelectors);
const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
const isHeterogeneousAgent = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const hideProfile = !isAgentEditable;
@@ -37,10 +39,15 @@ const Nav = memo(() => {
const { mutate } = useActionSWR('openNewTopicOrSaveTopic', openNewTopicOrSaveTopic);
const handleNewTopic = () => {
- // If in agent sub-route, navigate back to agent chat first
- if ((isProfileActive || isChannelActive) && agentId) {
- router.push(urlJoin('/agent', agentId));
+ if (agentId) {
+ // If in agent sub-route, navigate back to agent chat first.
+ if (isProfileActive || isChannelActive || isTasksActive) {
+ router.push(urlJoin('/agent', agentId));
+ } else {
+ router.push(SESSION_CHAT_URL(agentId));
+ }
}
+
mutate();
};
@@ -80,6 +87,17 @@ const Nav = memo(() => {
}}
/>
)}
+ {enableAgentTask && (
+ <NavItem
+ active={isTasksActive}
+ icon={ListTodoIcon}
+ title={t('tab.tasks')}
+ onClick={() => {
+ switchTopic(null, { skipRefreshMessage: true });
+ router.push(urlJoin('/agent', agentId!, 'tasks'));
+ }}
+ />
+ )}
</Flexbox>
);
});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
new file mode 100644
index 00000000000..c11aaa7794d
--- /dev/null
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
@@ -0,0 +1,141 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import TopicItem from './index';
+
+const useTopicNavigationMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ Icon: () => <div data-testid="topic-item-icon" />,
+ Skeleton: {
+ Button: (props: Record<string, unknown>) => <div {...props} />,
+ },
+ Tag: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: () => ({
+ dotContainer: 'dotContainer',
+ neonDot: 'neonDot',
+ neonDotWrapper: 'neonDotWrapper',
+ }),
+ createStyles: () => () => ({
+ cx: (...classNames: Array<false | string | undefined>) => classNames.filter(Boolean).join(' '),
+ styles: {
+ container: 'container',
+ dot: 'dot',
+ },
+ }),
+ cssVar: {
+ colorInfo: '#00f',
+ colorTextDescription: '#999',
+ },
+ keyframes: () => 'keyframes',
+ useTheme: () => ({ isDarkMode: false }),
+}));
+
+vi.mock('motion/react', () => ({
+ AnimatePresence: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ m: {
+ div: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ span: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <span {...props}>{children}</span>
+ ),
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/const/version', () => ({ isDesktop: false }));
+vi.mock('@/const/url', () => ({
+ SESSION_CHAT_TOPIC_URL: (agentId: string, topicId: string) => `/agent/${agentId}/${topicId}`,
+}));
+vi.mock('@/features/Electron/titlebar/RecentlyViewed/plugins', () => ({
+ pluginRegistry: { parseUrl: vi.fn() },
+}));
+vi.mock('@/features/NavPanel/components/NavItem', () => ({
+ default: ({ active, title }: { active?: boolean; title?: ReactNode }) => (
+ <div data-active={String(active)} data-testid="nav-item">
+ {title}
+ </div>
+ ),
+}));
+vi.mock('@/routes/(main)/agent/channel/const', () => ({
+ getPlatformIcon: () => null,
+}));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: { activeAgentId: string }) => unknown) =>
+ selector({ activeAgentId: 'agt_test' }),
+}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (
+ selector: (state: { topicLoadingIds: string[]; topicRenamingId: string }) => unknown,
+ ) => selector({ topicLoadingIds: [], topicRenamingId: '' }),
+}));
+vi.mock('@/store/chat/selectors', () => ({
+ operationSelectors: {
+ isTopicUnreadCompleted: () => () => false,
+ },
+}));
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (state: { addTab: () => void }) => unknown) =>
+ selector({ addTab: vi.fn() }),
+}));
+vi.mock('../../hooks/useTopicNavigation', () => ({
+ useTopicNavigation: () => useTopicNavigationMock(),
+}));
+vi.mock('./Actions', () => ({
+ default: () => null,
+}));
+vi.mock('./Editing', () => ({
+ default: () => null,
+}));
+vi.mock('./useDropdownMenu', () => ({
+ useTopicItemDropdownMenu: () => ({ dropdownMenu: [] }),
+}));
+vi.mock('../../TopicListContent/ThreadList', () => ({
+ default: () => <div data-testid="topic-thread-list" />,
+}));
+
+describe('TopicItem active state', () => {
+ it('keeps the current topic highlighted on topic page sub-routes', () => {
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: true,
+ isInTopicContextRoute: true,
+ navigateToTopic: vi.fn(),
+ routeTopicId: 'tpc_test',
+ });
+
+ render(<TopicItem active={false} id="tpc_test" title="Topic" />);
+
+ expect(screen.getByTestId('nav-item')).toHaveAttribute('data-active', 'true');
+ expect(screen.getByTestId('topic-thread-list')).toBeInTheDocument();
+ });
+
+ it('does not highlight a stale topic while visiting non-topic agent sub-routes', () => {
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: true,
+ isInTopicContextRoute: false,
+ navigateToTopic: vi.fn(),
+ routeTopicId: undefined,
+ });
+
+ render(<TopicItem active id="tpc_test" title="Topic" />);
+
+ expect(screen.getByTestId('nav-item')).toHaveAttribute('data-active', 'false');
+ expect(screen.queryByTestId('topic-thread-list')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
index 95118991d51..1dc090a4fd5 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';
import DotsLoading from '@/components/DotsLoading';
import RingLoadingIcon from '@/components/RingLoading';
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { isDesktop } from '@/const/version';
import { pluginRegistry } from '@/features/Electron/titlebar/RecentlyViewed/plugins';
import NavItem from '@/features/NavPanel/components/NavItem';
@@ -93,7 +94,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta
// Construct href for cmd+click support
const href = useMemo(() => {
if (!activeAgentId || !id) return undefined;
- return `/agent/${activeAgentId}?topic=${id}`;
+ return SESSION_CHAT_TOPIC_URL(activeAgentId, id);
}, [activeAgentId, id]);
const [editing, isLoading] = useChatStore((s) => [
@@ -105,7 +106,17 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta
id ? operationSelectors.isTopicUnreadCompleted(id) : () => false,
);
- const { focusTopicPopup, navigateToTopic, isInAgentSubRoute } = useTopicNavigation();
+ const {
+ focusTopicPopup,
+ navigateToTopic,
+ isInAgentSubRoute,
+ isInTopicContextRoute,
+ routeTopicId,
+ } = useTopicNavigation();
+ const isRouteTopicActive = Boolean(id && routeTopicId === id && isInTopicContextRoute);
+ const isTopicActive = Boolean(
+ (active || isRouteTopicActive) && !threadId && (!isInAgentSubRoute || isRouteTopicActive),
+ );
const toggleEditing = useCallback(
(visible?: boolean) => {
@@ -138,7 +149,8 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta
void navigateToTopic(id, { skipPopupFocus: true });
return;
}
- const reference = pluginRegistry.parseUrl(`/agent/${activeAgentId}`, `topic=${id}`);
+ const url = SESSION_CHAT_TOPIC_URL(activeAgentId, id);
+ const reference = pluginRegistry.parseUrl(url, '');
if (reference) {
addTab(reference);
void navigateToTopic(id);
@@ -166,7 +178,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta
if (!id) {
return (
<NavItem
- active={active && !isInAgentSubRoute}
+ active={Boolean(active && !isInAgentSubRoute && !isInTopicContextRoute)}
icon={
isLoading ? (
<RingLoadingIcon
@@ -201,7 +213,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta
<Flexbox data-testid="topic-item" style={{ position: 'relative' }}>
<NavItem
actions={<Actions dropdownMenu={dropdownMenu} />}
- active={active && !threadId && !isInAgentSubRoute}
+ active={isTopicActive}
contextMenuItems={dropdownMenu}
disabled={editing}
href={href}
@@ -240,7 +252,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta
onDoubleClick={() => void handleDoubleClick()}
/>
<Editing id={id} title={title} toggleEditing={toggleEditing} />
- {active && (
+ {isTopicActive && (
<Suspense
fallback={
<Flexbox gap={8} paddingBlock={8} paddingInline={24} width={'100%'}>
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
index f908fa873fc..e4a9afb6e98 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -20,6 +20,7 @@ import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { openRenameModal } from '@/components/RenameModal';
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { isDesktop } from '@/const/version';
import { pluginRegistry } from '@/features/Electron/titlebar/RecentlyViewed/plugins';
import { openShareModal } from '@/features/ShareModal';
@@ -140,8 +141,8 @@ export const useTopicItemDropdownMenu = ({
label: t('actions.openInNewTab'),
onClick: () => {
if (!activeAgentId) return;
- const url = `/agent/${activeAgentId}?topic=${id}`;
- const reference = pluginRegistry.parseUrl(`/agent/${activeAgentId}`, `topic=${id}`);
+ const url = SESSION_CHAT_TOPIC_URL(activeAgentId, id);
+ const reference = pluginRegistry.parseUrl(url, '');
if (reference) {
addTab(reference);
navigate(url);
@@ -167,7 +168,7 @@ export const useTopicItemDropdownMenu = ({
label: t('actions.copyLink'),
onClick: () => {
if (!activeAgentId) return;
- const url = `${appOrigin}/agent/${activeAgentId}?topic=${id}`;
+ const url = `${appOrigin}${SESSION_CHAT_TOPIC_URL(activeAgentId, id)}`;
navigator.clipboard.writeText(url);
message.success(t('actions.copyLinkSuccess'));
},
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
index ba38916982d..481e1da5d1a 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
@@ -1,7 +1,7 @@
import { useCallback } from 'react';
import { useParams } from 'react-router-dom';
-import urlJoin from 'url-join';
+import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@/const/url';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { usePathname } from '@/libs/router/navigation';
import { useChatStore } from '@/store/chat';
@@ -13,14 +13,17 @@ import { useGlobalStore } from '@/store/global';
*/
export const useThreadNavigation = () => {
const pathname = usePathname();
- const params = useParams();
+ const params = useParams<{ aid?: string; topicId?: string }>();
const router = useQueryRoute();
const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);
const switchThread = useChatStore((s) => s.switchThread);
const isInAgentSubRoute = useCallback(() => {
if (!params.aid) return false;
- const agentBasePath = `/agent/${params.aid}`;
+ const agentBasePath = params.topicId
+ ? SESSION_CHAT_TOPIC_URL(params.aid, params.topicId)
+ : SESSION_CHAT_URL(params.aid);
+
// If pathname has more segments after /agent/:aid, it's a sub-route
return (
pathname.startsWith(agentBasePath) &&
@@ -33,7 +36,11 @@ export const useThreadNavigation = () => {
(threadId: string) => {
// If in agent sub-route, navigate back to agent chat first
if (isInAgentSubRoute() && params.aid) {
- router.push(urlJoin('/agent', params.aid as string));
+ router.push(
+ params.topicId
+ ? SESSION_CHAT_TOPIC_URL(params.aid, params.topicId)
+ : SESSION_CHAT_URL(params.aid),
+ );
}
switchThread(threadId);
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx
index c43cd08e4a9..5f309c796a8 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx
@@ -11,6 +11,11 @@ const toggleMobileTopicMock = vi.hoisted(() => vi.fn());
const pushMock = vi.hoisted(() => vi.fn());
const pathnameMock = vi.hoisted(() => vi.fn());
const focusTopicPopupMock = vi.hoisted(() => vi.fn());
+const chatStoreStateMock = vi.hoisted(() => ({
+ activeAgentId: 'agent-1' as string | undefined,
+ activeTopicId: undefined as string | undefined,
+ switchTopic: undefined as unknown,
+}));
vi.mock('@/features/TopicPopupGuard/useTopicPopupsRegistry', () => ({
useFocusTopicPopup: () => focusTopicPopupMock,
@@ -28,10 +33,7 @@ vi.mock('@/libs/router/navigation', () => ({
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({
- activeAgentId: 'agent-1',
- switchTopic: switchTopicMock,
- }),
+ selector(chatStoreStateMock as unknown as Record<string, unknown>),
}));
vi.mock('@/store/global', () => ({
@@ -48,6 +50,9 @@ describe('useTopicNavigation', () => {
pushMock.mockReset();
switchTopicMock.mockReset();
toggleMobileTopicMock.mockReset();
+ chatStoreStateMock.activeAgentId = 'agent-1';
+ chatStoreStateMock.activeTopicId = undefined;
+ chatStoreStateMock.switchTopic = switchTopicMock;
});
it('focuses the popup and still navigates back to the chat route when the topic is detached', async () => {
@@ -61,7 +66,7 @@ describe('useTopicNavigation', () => {
});
expect(focusTopicPopupMock).toHaveBeenCalledWith('topic-in-popup');
- expect(pushMock).toHaveBeenCalledWith('/agent/agent-1?topic=topic-in-popup');
+ expect(pushMock).toHaveBeenCalledWith('/agent/agent-1/topic-in-popup');
expect(switchTopicMock).not.toHaveBeenCalled();
expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);
});
@@ -77,7 +82,7 @@ describe('useTopicNavigation', () => {
});
expect(focusTopicPopupMock).toHaveBeenCalledWith('topic-2');
- expect(pushMock).toHaveBeenCalledWith('/agent/agent-1?topic=topic-2');
+ expect(pushMock).toHaveBeenCalledWith('/agent/agent-1/topic-2');
expect(switchTopicMock).not.toHaveBeenCalled();
expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);
});
@@ -97,4 +102,22 @@ describe('useTopicNavigation', () => {
expect(switchTopicMock).toHaveBeenCalledWith('topic-3');
expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);
});
+
+ it('still routes back to chat from a profile sub-route even when activeTopicId is cached', async () => {
+ // regression: cached activeTopicId should not make profile look like a topic route
+ pathnameMock.mockReturnValue('/agent/agent-1/profile');
+ chatStoreStateMock.activeTopicId = 'cached-topic';
+ focusTopicPopupMock.mockResolvedValue(false);
+
+ const { result } = renderHook(() => useTopicNavigation());
+
+ expect(result.current.isInAgentSubRoute).toBe(true);
+
+ await act(async () => {
+ await result.current.navigateToTopic('topic-click');
+ });
+
+ expect(pushMock).toHaveBeenCalledWith('/agent/agent-1/topic-click');
+ expect(switchTopicMock).not.toHaveBeenCalled();
+ });
});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
index c6f3f8a71f2..15c153b66d6 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
@@ -1,6 +1,7 @@
import { useCallback } from 'react';
-import urlJoin from 'url-join';
+import { useParams } from 'react-router-dom';
+import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@/const/url';
import { useFocusTopicPopup } from '@/features/TopicPopupGuard/useTopicPopupsRegistry';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { usePathname } from '@/libs/router/navigation';
@@ -17,22 +18,44 @@ interface NavigateToTopicOptions {
export const useTopicNavigation = () => {
const pathname = usePathname();
- const activeAgentId = useChatStore((s) => s.activeAgentId);
+ const params = useParams<{ aid?: string; topicId?: string }>();
+ const [activeAgentId, activeTopicId] = useChatStore((s) => [s.activeAgentId, s.activeTopicId]);
const router = useQueryRoute();
const toggleConfig = useGlobalStore((s) => s.toggleMobileTopic);
const switchTopic = useChatStore((s) => s.switchTopic);
+ const routeAgentId = params.aid ?? activeAgentId;
+ const routeTopicId = params.topicId ?? activeTopicId ?? undefined;
+ const topicBasePath =
+ routeAgentId && routeTopicId ? SESSION_CHAT_TOPIC_URL(routeAgentId, routeTopicId) : undefined;
+ // URL-derived topic path (no store fallback) — used for sub-route detection so a cached
+ // activeTopicId cannot mask a non-topic page like /agent/:aid/profile.
+ const urlTopicBasePath =
+ routeAgentId && params.topicId
+ ? SESSION_CHAT_TOPIC_URL(routeAgentId, params.topicId)
+ : undefined;
const focusTopicPopup = useFocusTopicPopup({ agentId: activeAgentId });
+ const isInTopicContextRoute = useCallback(() => {
+ if (!topicBasePath) return false;
+
+ return (
+ pathname === topicBasePath ||
+ pathname === `${topicBasePath}/` ||
+ pathname.startsWith(`${topicBasePath}/`)
+ );
+ }, [pathname, topicBasePath]);
+
const isInAgentSubRoute = useCallback(() => {
- if (!activeAgentId) return false;
- const agentBasePath = `/agent/${activeAgentId}`;
- // If pathname has more segments after /agent/:aid, it's a sub-route
+ if (!routeAgentId) return false;
+ const agentBasePath = urlTopicBasePath ?? SESSION_CHAT_URL(routeAgentId);
+
+ // If pathname has more segments after /agent/:aid (or the active topic), it's a sub-route
return (
pathname.startsWith(agentBasePath) &&
pathname !== agentBasePath &&
pathname !== `${agentBasePath}/`
);
- }, [pathname, activeAgentId]);
+ }, [pathname, routeAgentId, urlTopicBasePath]);
const navigateToTopic = useCallback(
async (topicId?: string, options?: NavigateToTopicOptions) => {
@@ -41,10 +64,13 @@ export const useTopicNavigation = () => {
}
// If in agent sub-route, navigate back to agent chat first
- if (isInAgentSubRoute() && activeAgentId) {
- const basePath = urlJoin('/agent', activeAgentId as string);
+ if (isInAgentSubRoute() && routeAgentId) {
+ const basePath = topicId
+ ? SESSION_CHAT_TOPIC_URL(routeAgentId, topicId)
+ : SESSION_CHAT_URL(routeAgentId);
+
// Include topicId in URL when navigating from sub-route
- router.push(topicId ? `${basePath}?topic=${topicId}` : basePath);
+ router.push(basePath);
toggleConfig(false);
return;
}
@@ -52,12 +78,14 @@ export const useTopicNavigation = () => {
switchTopic(topicId);
toggleConfig(false);
},
- [activeAgentId, focusTopicPopup, router, switchTopic, toggleConfig, isInAgentSubRoute],
+ [focusTopicPopup, isInAgentSubRoute, routeAgentId, router, switchTopic, toggleConfig],
);
return {
focusTopicPopup,
isInAgentSubRoute: isInAgentSubRoute(),
+ isInTopicContextRoute: isInTopicContextRoute(),
navigateToTopic,
+ routeTopicId,
};
};
diff --git a/src/routes/(main)/agent/_layout/index.test.tsx b/src/routes/(main)/agent/_layout/index.test.tsx
new file mode 100644
index 00000000000..fbbd6c2c3fd
--- /dev/null
+++ b/src/routes/(main)/agent/_layout/index.test.tsx
@@ -0,0 +1,49 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import Layout from './index';
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ ShikiLobeTheme: {},
+}));
+
+vi.mock('react-router-dom', async () => {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
+ const actual = (await vi.importActual('react-router-dom')) as typeof import('react-router-dom');
+
+ return {
+ ...actual,
+ Outlet: () => <div data-testid="agent-layout-outlet">outlet</div>,
+ };
+});
+
+vi.mock('@/const/version', () => ({ isDesktop: false }));
+vi.mock('@/hooks/useInitAgentConfig', () => ({ useInitAgentConfig: vi.fn() }));
+vi.mock('@/features/ProtocolUrlHandler', () => ({ default: () => null }));
+vi.mock('./RegisterHotkeys', () => ({ default: () => null }));
+vi.mock('./Sidebar', () => ({ default: () => <div data-testid="agent-layout-sidebar" /> }));
+vi.mock('@/routes/(main)/agent/_layout/AgentIdSync', () => ({
+ default: () => <div data-testid="agent-layout-agent-id-sync" />,
+}));
+
+describe('Agent layout', () => {
+ it('renders sidebar and outlet', () => {
+ render(<Layout />);
+
+ expect(screen.getByTestId('agent-layout-sidebar')).toBeInTheDocument();
+ expect(screen.getByTestId('agent-layout-outlet')).toBeInTheDocument();
+ });
+
+ it('mounts AgentIdSync in layout', () => {
+ render(<Layout />);
+
+ expect(screen.getByTestId('agent-layout-agent-id-sync')).toBeInTheDocument();
+ });
+});
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
new file mode 100644
index 00000000000..d3393fbfb1e
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
@@ -0,0 +1,123 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, render, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { initialState as initialChatState } from '@/store/chat/initialState';
+import { useChatStore } from '@/store/chat/store';
+
+import ChatHydration from './index';
+
+const navigateMock = vi.hoisted(() => vi.fn());
+const setSearchParamsMock = vi.hoisted(() => vi.fn());
+const useLocationMock = vi.hoisted(() => vi.fn());
+const useParamsMock = vi.hoisted(() => vi.fn());
+const useSearchParamsMock = vi.hoisted(() => vi.fn());
+
+vi.mock('react-router-dom', async () => {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
+ const actual = (await vi.importActual('react-router-dom')) as typeof import('react-router-dom');
+
+ return {
+ ...actual,
+ useLocation: useLocationMock,
+ useNavigate: () => navigateMock,
+ useParams: useParamsMock,
+ useSearchParams: useSearchParamsMock,
+ };
+});
+
+describe('ChatHydration', () => {
+ beforeEach(() => {
+ navigateMock.mockReset();
+ setSearchParamsMock.mockReset();
+ useLocationMock.mockReset();
+ useParamsMock.mockReset();
+ useSearchParamsMock.mockReset();
+
+ useChatStore.setState(
+ {
+ ...initialChatState,
+ activeAgentId: 'agt_test',
+ activeThreadId: undefined,
+ activeTopicId: undefined,
+ },
+ false,
+ );
+ });
+
+ it('hydrates legacy topic query params into the store and rewrites them to the topic path', async () => {
+ useParamsMock.mockReturnValue({ aid: 'agt_test' });
+ useLocationMock.mockReturnValue({
+ hash: '#msg_1',
+ pathname: '/agent/agt_test',
+ search: '?topic=tpc_123&thread=thd_456&mode=single',
+ });
+ useSearchParamsMock.mockReturnValue([
+ new URLSearchParams('topic=tpc_123&thread=thd_456&mode=single'),
+ setSearchParamsMock,
+ ]);
+
+ render(<ChatHydration />);
+
+ await waitFor(() => {
+ expect(useChatStore.getState().activeTopicId).toBe('tpc_123');
+ expect(useChatStore.getState().activeThreadId).toBe('thd_456');
+ expect(navigateMock).toHaveBeenCalledWith(
+ '/agent/agt_test/tpc_123?thread=thd_456&mode=single#msg_1',
+ { replace: true },
+ );
+ });
+ });
+
+ it('removes duplicate legacy topic query params when the path already carries topicId', async () => {
+ useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_123' });
+ useLocationMock.mockReturnValue({
+ hash: '',
+ pathname: '/agent/agt_test/tpc_123',
+ search: '?topic=tpc_999&thread=thd_456',
+ });
+ useSearchParamsMock.mockReturnValue([
+ new URLSearchParams('topic=tpc_999&thread=thd_456'),
+ setSearchParamsMock,
+ ]);
+
+ render(<ChatHydration />);
+
+ await waitFor(() => {
+ expect(useChatStore.getState().activeTopicId).toBe('tpc_123');
+ expect(useChatStore.getState().activeThreadId).toBe('thd_456');
+ expect(navigateMock).toHaveBeenCalledWith('/agent/agt_test/tpc_123?thread=thd_456', {
+ replace: true,
+ });
+ });
+ });
+
+ it('rewrites the pathname when the active topic changes in the chat store', async () => {
+ useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_123' });
+ useLocationMock.mockReturnValue({
+ hash: '',
+ pathname: '/agent/agt_test/tpc_123',
+ search: '?thread=thd_456',
+ });
+ useSearchParamsMock.mockReturnValue([
+ new URLSearchParams('thread=thd_456'),
+ setSearchParamsMock,
+ ]);
+
+ render(<ChatHydration />);
+
+ navigateMock.mockClear();
+
+ await act(async () => {
+ useChatStore.setState({ activeTopicId: 'tpc_789' }, false);
+ });
+
+ await waitFor(() => {
+ expect(navigateMock).toHaveBeenCalledWith('/agent/agt_test/tpc_789?thread=thd_456', {
+ replace: true,
+ });
+ });
+ });
+});
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
index 002e1b4cc94..5df4deb3fc2 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
@@ -1,26 +1,84 @@
'use client';
-import { memo, useLayoutEffect } from 'react';
+import { memo, useLayoutEffect, useRef } from 'react';
+import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { createStoreUpdater } from 'zustand-utils';
+import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@/const/url';
import { useQueryState } from '@/hooks/useQueryParam';
import { useChatStore } from '@/store/chat';
+const getSearchSuffix = (searchParams: URLSearchParams) => {
+ const search = searchParams.toString();
+
+ return search ? `?${search}` : '';
+};
+
// sync outside state to useChatStore
const ChatHydration = memo(() => {
const useStoreUpdater = createStoreUpdater(useChatStore);
+ const location = useLocation();
+ const navigate = useNavigate();
+ const params = useParams<{ aid?: string; topicId?: string }>();
+ const [searchParams] = useSearchParams();
- // two-way bindings the topic params to chat store
- const [topic, setTopic] = useQueryState('topic', { history: 'replace', throttleMs: 500 });
const [thread, setThread] = useQueryState('thread', { history: 'replace', throttleMs: 500 });
- useStoreUpdater('activeTopicId', topic!);
+ const routeTopicId = params.topicId ?? searchParams.get('topic');
+
+ useStoreUpdater('activeTopicId', routeTopicId ?? undefined);
useStoreUpdater('activeThreadId', thread!);
+ const locationRef = useRef(location);
+ const paramsRef = useRef(params);
+ const searchParamsRef = useRef(searchParams);
+
+ locationRef.current = location;
+ paramsRef.current = params;
+ searchParamsRef.current = searchParams;
+
+ useLayoutEffect(() => {
+ const legacyTopicId = searchParams.get('topic');
+
+ if (!params.aid || !legacyTopicId) return;
+
+ const normalizedTopicId = params.topicId ?? legacyTopicId;
+ const nextSearchParams = new URLSearchParams(searchParams);
+ nextSearchParams.delete('topic');
+
+ const nextUrl = `${SESSION_CHAT_TOPIC_URL(params.aid, normalizedTopicId)}${getSearchSuffix(nextSearchParams)}${location.hash}`;
+ const currentUrl = `${location.pathname}${location.search}${location.hash}`;
+
+ if (currentUrl !== nextUrl) {
+ navigate(nextUrl, { replace: true });
+ }
+ }, [
+ location.hash,
+ location.pathname,
+ location.search,
+ navigate,
+ params.aid,
+ params.topicId,
+ searchParams,
+ ]);
+
useLayoutEffect(() => {
const unsubscribeTopic = useChatStore.subscribe(
(s) => s.activeTopicId,
(state) => {
- setTopic(!state ? null : state);
+ const { aid } = paramsRef.current;
+
+ if (!aid) return;
+
+ const nextSearchParams = new URLSearchParams(searchParamsRef.current);
+ nextSearchParams.delete('topic');
+
+ const nextPath = state ? SESSION_CHAT_TOPIC_URL(aid, state) : SESSION_CHAT_URL(aid);
+ const nextUrl = `${nextPath}${getSearchSuffix(nextSearchParams)}${locationRef.current.hash}`;
+ const currentUrl = `${locationRef.current.pathname}${locationRef.current.search}${locationRef.current.hash}`;
+
+ if (currentUrl !== nextUrl) {
+ navigate(nextUrl, { replace: true });
+ }
},
);
const unsubscribeThread = useChatStore.subscribe(
@@ -34,7 +92,7 @@ const ChatHydration = memo(() => {
unsubscribeTopic();
unsubscribeThread();
};
- }, [setTopic, setThread]); // ✅ Now setValue is stable and can be safely added to the dependency array
+ }, [navigate, setThread]);
return null;
});
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index 617e609dace..537394bfd39 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -14,7 +14,6 @@ import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import ChatHydration from './ChatHydration';
import HeterogeneousChatInput from './HeterogeneousChatInput';
import MainChatInput from './MainChatInput';
import MessageFromUrl from './MainChatInput/MessageFromUrl';
@@ -83,7 +82,6 @@ const Conversation = memo(() => {
</Flexbox>
<TodoProgress />
{isHeterogeneousAgent ? <HeterogeneousChatInput /> : <MainChatInput />}
- <ChatHydration />
<ThreadHydration />
<ChatMiniMap />
<Suspense>
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx
index 20e737cc33b..787a08c65a8 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.tsx
@@ -4,15 +4,20 @@ import { ActionIcon, DropdownMenu } from '@lobehub/ui';
import { MoreHorizontal } from 'lucide-react';
import { memo } from 'react';
+import HeaderSlot from '@/routes/(main)/agent/(chat)/_layout/HeaderSlot';
+
import { useMenu } from './useMenu';
const HeaderActions = memo(() => {
const { menuItems } = useMenu();
return (
- <DropdownMenu items={menuItems}>
- <ActionIcon icon={MoreHorizontal} size={'small'} />
- </DropdownMenu>
+ <>
+ <HeaderSlot.Outlet />
+ <DropdownMenu items={menuItems}>
+ <ActionIcon icon={MoreHorizontal} size={'small'} />
+ </DropdownMenu>
+ </>
);
});
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
index 93b59f8b8cf..8a02f209249 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
@@ -45,6 +45,7 @@ vi.mock('react-i18next', () => ({
vi.mock('react-router-dom', () => ({
useLocation: useLocationMock,
+ useParams: () => ({}),
}));
vi.mock('@/store/chat/selectors', () => ({
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
index 58bb3203c24..474fcb19e34 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
@@ -1,21 +1,41 @@
'use client';
import { type DropdownItem, Icon } from '@lobehub/ui';
+import { confirmModal, type ModalInstance } from '@lobehub/ui/base-ui';
import { App } from 'antd';
-import { Copy, ExternalLink, Hash, Maximize2, PencilLine, Star, Trash, Wand2 } from 'lucide-react';
-import { useMemo } from 'react';
+import {
+ Clock3Icon,
+ Copy,
+ ExternalLink,
+ Hash,
+ Maximize2,
+ PencilLine,
+ Star,
+ Trash,
+ Wand2,
+} from 'lucide-react';
+import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocation } from 'react-router-dom';
+import { useLocation, useParams } from 'react-router-dom';
import { openRenameModal } from '@/components/RenameModal';
+import { DOCUMENT_HISTORY_QUERY_LIST_LIMIT } from '@/const/documentHistory';
import { isDesktop } from '@/const/version';
+import { openDocumentCompareModal } from '@/features/PageEditor/History/CompareModal';
+import { formatHistoryAbsoluteTime } from '@/features/PageEditor/History/formatHistoryDate';
+import type {
+ DocumentHistoryListItem,
+ DocumentHistorySaveSource,
+} from '@/server/routers/lambda/_schema/documentHistory';
+import { documentService } from '@/services/document';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import { useDocumentStore } from '@/store/document';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
export const useMenu = (): { menuItems: DropdownItem[] } => {
- const { t } = useTranslation(['chat', 'topic', 'common']);
+ const { t } = useTranslation(['chat', 'topic', 'common', 'file']);
const { modal, message } = App.useApp();
const { pathname } = useLocation();
@@ -35,6 +55,98 @@ export const useMenu = (): { menuItems: DropdownItem[] } => {
s.updateTopicTitle,
]);
+ const { docId } = useParams<{ docId?: string }>();
+ const compareInstanceRef = useRef<ModalInstance | null>(null);
+
+ const saveSourceLabels = useMemo<Record<DocumentHistorySaveSource, string>>(
+ () => ({
+ autosave: t('pageEditor.history.saveSource.autosave', { ns: 'file' }),
+ llm_call: t('pageEditor.history.saveSource.llm_call', { ns: 'file' }),
+ manual: t('pageEditor.history.saveSource.manual', { ns: 'file' }),
+ restore: t('pageEditor.history.saveSource.restore', { ns: 'file' }),
+ system: t('pageEditor.history.saveSource.system', { ns: 'file' }),
+ }),
+ [t],
+ );
+
+ const handleRestoreHistory = useCallback(
+ async (item: DocumentHistoryListItem, onSuccess?: () => void): Promise<void> => {
+ if (!docId || item.isCurrent) return;
+
+ const { editor, markDirty, performSave } = useDocumentStore.getState();
+ if (!editor) {
+ message.error(t('pageEditor.history.restoreError', { ns: 'file' }));
+ return;
+ }
+
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('pageEditor.history.restoreConfirm.content', {
+ ns: 'file',
+ savedAt: formatHistoryAbsoluteTime(item.savedAt),
+ }),
+ okText: t('pageEditor.history.restore', { ns: 'file' }),
+ onOk: async () => {
+ try {
+ const result = await documentService.getDocumentHistoryItem(
+ { documentId: docId, historyId: item.id },
+ `header-actions-history-${docId}`,
+ );
+
+ editor.setDocument('json', JSON.stringify(result.editorData));
+ markDirty(docId);
+ await performSave(docId, undefined, {
+ restoreFromHistoryId: item.id,
+ saveSource: 'restore',
+ });
+ onSuccess?.();
+ } catch (error) {
+ console.error('[HeaderActions] Failed to restore history item:', error);
+ message.error(t('pageEditor.history.restoreError', { ns: 'file' }));
+ throw error;
+ }
+ },
+ title: t('pageEditor.history.restoreConfirm.title', { ns: 'file' }),
+ });
+ },
+ [docId, message, t],
+ );
+
+ const openCompareModal = useCallback(async (): Promise<void> => {
+ if (!docId) return;
+
+ try {
+ const result = await documentService.listDocumentHistory({
+ documentId: docId,
+ includeCurrent: true,
+ limit: DOCUMENT_HISTORY_QUERY_LIST_LIMIT,
+ });
+ const items = result.items ?? [];
+
+ if (items.length === 0) {
+ message.info(t('pageEditor.history.empty', { ns: 'file' }));
+ return;
+ }
+
+ const initialHistoryId = items.find((item) => !item.isCurrent)?.id ?? items[0].id;
+
+ compareInstanceRef.current?.destroy();
+ const instance = openDocumentCompareModal({
+ documentId: docId,
+ initialHistoryId,
+ items,
+ onRestore: (item) => {
+ void handleRestoreHistory(item, () => instance.close());
+ },
+ saveSourceLabels,
+ });
+ compareInstanceRef.current = instance;
+ } catch (error) {
+ console.error('[HeaderActions] Failed to open document compare modal:', error);
+ message.error(t('pageEditor.history.compareError', { ns: 'file' }));
+ }
+ }, [docId, handleRestoreHistory, message, saveSourceLabels, t]);
+
const topicId = activeTopic?.id;
const topicTitle = activeTopic?.title ?? '';
const isFavorite = !!activeTopic?.favorite;
@@ -116,6 +228,20 @@ export const useMenu = (): { menuItems: DropdownItem[] } => {
);
}
+ if (docId) {
+ items.push(
+ {
+ icon: <Icon icon={Clock3Icon} />,
+ key: 'open-document-compare',
+ label: t('pageEditor.history.compareTitle', { ns: 'file' }),
+ onClick: () => {
+ void openCompareModal();
+ },
+ },
+ { type: 'divider' as const },
+ );
+ }
+
items.push({
checked: wideScreen,
icon: <Icon icon={Maximize2} />,
@@ -156,12 +282,14 @@ export const useMenu = (): { menuItems: DropdownItem[] } => {
pathname,
workingDirectory,
wideScreen,
+ docId,
autoRenameTopicTitle,
favoriteTopic,
openTopicInNewWindow,
removeTopic,
updateTopicTitle,
toggleWideScreen,
+ openCompareModal,
t,
modal,
message,
diff --git a/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx
index 2c9ac47255c..930b80002f2 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/Tags/index.tsx
@@ -18,20 +18,29 @@ const TitleTags = memo(() => {
if (isGroupSession) {
return (
- <Flexbox horizontal align={'center'} gap={12}>
+ <Flexbox allowShrink horizontal align={'center'} gap={12} style={{ minWidth: 0 }}>
<MemberCountTag />
</Flexbox>
);
}
return (
- <Flexbox horizontal align={'center'} gap={8}>
+ <Flexbox
+ allowShrink
+ horizontal
+ align={'center'}
+ gap={8}
+ style={{ flex: '1 1 auto', minWidth: 0, overflow: 'hidden' }}
+ >
<span
style={{
color: cssVar.colorText,
+ display: 'block',
+ flex: '1 1 auto',
fontSize: 14,
fontWeight: 600,
marginLeft: 8,
+ minWidth: 0,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
diff --git a/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx
new file mode 100644
index 00000000000..a0efe3a31b7
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/Header/ViewSwitcher/index.tsx
@@ -0,0 +1,64 @@
+'use client';
+
+import { Segmented } from '@lobehub/ui';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useLocation, useNavigate, useParams } from 'react-router-dom';
+
+import { SESSION_CHAT_TOPIC_PAGE_URL, SESSION_CHAT_TOPIC_URL } from '@/const/url';
+import { useChatStore } from '@/store/chat';
+
+type ViewTab = 'chat' | 'page' | 'task';
+
+const ViewSwitcher = memo(() => {
+ const { t } = useTranslation('chat');
+ const navigate = useNavigate();
+ const location = useLocation();
+ const params = useParams<{ aid?: string; topicId?: string }>();
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+
+ const aid = params.aid;
+ const topicId = params.topicId ?? activeTopicId ?? undefined;
+
+ const currentTab = useMemo((): ViewTab => {
+ if (!aid || !topicId) return 'chat';
+ if (location.pathname.startsWith(SESSION_CHAT_TOPIC_PAGE_URL(aid, topicId))) return 'page';
+ return 'chat';
+ }, [aid, topicId, location.pathname]);
+
+ const options = useMemo(
+ () => [
+ { label: t('viewSwitcher.chat'), value: 'chat' },
+ { label: t('viewSwitcher.page'), value: 'page' },
+ // { label: t('viewSwitcher.task'), value: 'task' },
+ ],
+ [t],
+ );
+
+ const handleChange = (value: number | string) => {
+ if (!aid) return;
+
+ switch (String(value) as ViewTab) {
+ case 'chat': {
+ if (topicId) navigate(SESSION_CHAT_TOPIC_URL(aid, topicId));
+ break;
+ }
+ case 'page': {
+ if (topicId) navigate(SESSION_CHAT_TOPIC_PAGE_URL(aid, topicId));
+ break;
+ }
+ case 'task': {
+ navigate(`/agent/${aid}/channel`);
+ break;
+ }
+ }
+ };
+
+ if (!topicId) return null;
+
+ return <Segmented options={options} size={'small'} value={currentTab} onChange={handleChange} />;
+});
+
+ViewSwitcher.displayName = 'ViewSwitcher';
+
+export default ViewSwitcher;
diff --git a/src/routes/(main)/agent/features/Conversation/Header/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
index 7fca6dfb85c..57404a27c4b 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { cssVar } from 'antd-style';
+import { createStaticStyles, cssVar } from 'antd-style';
import { memo } from 'react';
import NavHeader from '@/features/NavHeader';
@@ -9,29 +9,77 @@ import NavHeader from '@/features/NavHeader';
import HeaderActions from './HeaderActions';
import ShareButton from './ShareButton';
import Tags from './Tags';
+import ViewSwitcher from './ViewSwitcher';
import WorkingPanelToggle from './WorkingPanelToggle';
+const headerStyles = createStaticStyles(({ css }) => ({
+ container: css`
+ position: relative;
+ container-name: agent-conv-header;
+ container-type: inline-size;
+ `,
+ leftContent: css`
+ overflow: hidden;
+ flex: 1 1 auto;
+ min-width: 0;
+ `,
+ slotCenter: css`
+ flex: 0 0 auto !important;
+ align-items: center;
+ justify-content: center;
+ min-width: 0;
+ `,
+ slotLeft: css`
+ overflow: hidden;
+ flex: 1 1 0;
+ min-width: 0;
+
+ @container agent-conv-header (max-width: 719px) {
+ flex: 1 1 auto;
+ }
+ `,
+ slotRight: css`
+ flex: 1 1 0;
+ min-width: 0;
+
+ @container agent-conv-header (max-width: 719px) {
+ flex: 0 0 auto;
+ }
+ `,
+}));
+
const Header = memo(() => {
return (
- <NavHeader
- left={
- <Flexbox
- horizontal
- align={'center'}
- gap={4}
- style={{ backgroundColor: cssVar.colorBgContainer }}
- >
- <Tags />
- <HeaderActions />
- </Flexbox>
- }
- right={
- <Flexbox horizontal align={'center'} style={{ backgroundColor: cssVar.colorBgContainer }}>
- <ShareButton />
- <WorkingPanelToggle />
- </Flexbox>
- }
- />
+ <div className={headerStyles.container}>
+ <NavHeader
+ left={
+ <Flexbox
+ allowShrink
+ horizontal
+ align={'center'}
+ className={headerStyles.leftContent}
+ gap={4}
+ style={{ backgroundColor: cssVar.colorBgContainer }}
+ >
+ <Tags />
+ <HeaderActions />
+ </Flexbox>
+ }
+ right={
+ <Flexbox horizontal align={'center'} style={{ backgroundColor: cssVar.colorBgContainer }}>
+ <ShareButton />
+ <WorkingPanelToggle />
+ </Flexbox>
+ }
+ slotClassNames={{
+ center: headerStyles.slotCenter,
+ left: headerStyles.slotLeft,
+ right: headerStyles.slotRight,
+ }}
+ >
+ <ViewSwitcher />
+ </NavHeader>
+ </div>
);
});
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
index 0dec5d14caa..428b98f9ea9 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
@@ -5,6 +5,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import AgentDocumentsGroup from './AgentDocumentsGroup';
const useClientDataSWR = vi.fn();
+const modalConfirm = vi.hoisted(() => vi.fn());
+const messageError = vi.hoisted(() => vi.fn());
+const messageSuccess = vi.hoisted(() => vi.fn());
+const removeDocumentMock = vi.hoisted(() => vi.fn());
+const useMatchMock = vi.hoisted(() => vi.fn());
+const useNavigateMock = vi.hoisted(() => vi.fn());
vi.mock('@lobehub/ui', () => ({
ActionIcon: ({ onClick, title }: { onClick?: (e: React.MouseEvent) => void; title?: string }) => (
@@ -33,8 +39,8 @@ vi.mock('@lobehub/ui', () => ({
vi.mock('antd', () => ({
App: {
useApp: () => ({
- message: { error: vi.fn(), success: vi.fn() },
- modal: { confirm: vi.fn() },
+ message: { error: messageError, success: messageSuccess },
+ modal: { confirm: modalConfirm },
}),
},
Spin: () => <div data-testid="spin" />,
@@ -59,6 +65,11 @@ vi.mock('react-i18next', () => ({
}),
}));
+vi.mock('react-router-dom', () => ({
+ useMatch: () => useMatchMock(),
+ useNavigate: () => useNavigateMock,
+}));
+
vi.mock('@/services/agentDocument', () => ({
agentDocumentSWRKeys: {
documents: (agentId: string) => ['agent-documents', agentId],
@@ -66,7 +77,7 @@ vi.mock('@/services/agentDocument', () => ({
},
agentDocumentService: {
getDocuments: vi.fn(),
- removeDocument: vi.fn(),
+ removeDocument: removeDocumentMock,
},
}));
@@ -92,6 +103,16 @@ vi.mock('@/store/chat/selectors', () => ({
describe('AgentDocumentsGroup', () => {
beforeEach(() => {
useClientDataSWR.mockReset();
+ closeDocument.mockReset();
+ modalConfirm.mockReset();
+ messageError.mockReset();
+ messageSuccess.mockReset();
+ openDocument.mockReset();
+ removeDocumentMock.mockReset();
+ useMatchMock.mockReset();
+ useNavigateMock.mockReset();
+ useMatchMock.mockReturnValue(null);
+ removeDocumentMock.mockResolvedValue({ deleted: true, id: 'doc-1' });
});
it('renders documents and opens via openDocument', async () => {
@@ -174,6 +195,48 @@ describe('AgentDocumentsGroup', () => {
expect(screen.queryByText('Example')).not.toBeInTheDocument();
});
+ it('passes page document and topic context when deleting from a topic page route', async () => {
+ const mutate = vi.fn().mockResolvedValue(undefined);
+ useMatchMock.mockReturnValue({
+ params: { aid: 'agent-1', docId: 'doc-content-1', topicId: 'topic-1' },
+ });
+ useClientDataSWR.mockReturnValue({
+ data: [
+ {
+ createdAt: new Date('2026-04-16T00:00:00Z'),
+ description: 'File doc',
+ documentId: 'doc-content-1',
+ filename: 'brief.md',
+ id: 'doc-1',
+ sourceType: 'file',
+ templateId: 'claw',
+ title: 'Brief',
+ },
+ ],
+ error: undefined,
+ isLoading: false,
+ mutate,
+ });
+
+ render(<AgentDocumentsGroup />);
+
+ fireEvent.click(screen.getByLabelText('delete'));
+
+ const [firstConfirmCall] = modalConfirm.mock.calls;
+ const [{ onOk }] = firstConfirmCall;
+ await onOk();
+
+ expect(closeDocument).toHaveBeenCalled();
+ expect(removeDocumentMock).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ documentId: 'doc-content-1',
+ id: 'doc-1',
+ topicId: 'topic-1',
+ });
+ expect(mutate).toHaveBeenCalled();
+ expect(messageSuccess).toHaveBeenCalledWith('workingPanel.resources.deleteSuccess');
+ });
+
it('renders empty state when no documents', () => {
useClientDataSWR.mockReturnValue({
data: [],
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
index d478aa1ce60..08727db680e 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -6,6 +6,7 @@ import relativeTime from 'dayjs/plugin/relativeTime';
import { FileTextIcon, GlobeIcon, type LucideIcon, Trash2Icon } from 'lucide-react';
import { memo, type MouseEvent, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useMatch, useNavigate } from 'react-router-dom';
import { useClientDataSWR } from '@/libs/swr';
import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';
@@ -13,6 +14,8 @@ import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+const PAGE_ROUTE_PATTERN = '/agent/:aid/:topicId/page/:docId?';
+
dayjs.extend(relativeTime);
type ResourceFilter = 'all' | 'documents' | 'web';
@@ -96,16 +99,18 @@ type AgentDocumentListItem = Awaited<ReturnType<typeof agentDocumentService.getD
interface DocumentItemProps {
agentId: string;
document: AgentDocumentListItem;
- isActive: boolean;
mutate: () => Promise<unknown>;
}
-const DocumentItem = memo<DocumentItemProps>(({ agentId, document, isActive, mutate }) => {
+const DocumentItem = memo<DocumentItemProps>(({ agentId, document, mutate }) => {
const { t } = useTranslation(['chat', 'common']);
const { message, modal } = App.useApp();
const [deleting, setDeleting] = useState(false);
const openDocument = useChatStore((s) => s.openDocument);
const closeDocument = useChatStore((s) => s.closeDocument);
+ const portalDocumentId = useChatStore(chatPortalSelectors.portalDocumentId);
+ const navigate = useNavigate();
+ const pageMatch = useMatch(PAGE_ROUTE_PATTERN);
const title = document.title || document.filename || '';
const description = document.description ?? undefined;
@@ -113,8 +118,17 @@ const DocumentItem = memo<DocumentItemProps>(({ agentId, document, isActive, mut
const IconComponent: LucideIcon = isWeb ? GlobeIcon : FileTextIcon;
const createdAtLabel = document.createdAt ? dayjs(document.createdAt).fromNow() : null;
+ const activeDocumentId = pageMatch ? pageMatch.params.docId : portalDocumentId;
+ const isActive = activeDocumentId === document.documentId;
+
const handleOpen = () => {
if (!document.documentId) return;
+ if (pageMatch?.params.aid && pageMatch.params.topicId) {
+ navigate(
+ `/agent/${pageMatch.params.aid}/${pageMatch.params.topicId}/page/${document.documentId}`,
+ );
+ return;
+ }
openDocument(document.documentId);
};
@@ -127,7 +141,12 @@ const DocumentItem = memo<DocumentItemProps>(({ agentId, document, isActive, mut
setDeleting(true);
try {
if (isActive) closeDocument();
- await agentDocumentService.removeDocument({ agentId, id: document.id });
+ await agentDocumentService.removeDocument({
+ agentId,
+ documentId: document.documentId,
+ id: document.id,
+ topicId: pageMatch?.params.topicId,
+ });
await mutate();
message.success(t('workingPanel.resources.deleteSuccess', { ns: 'chat' }));
} catch (error) {
@@ -186,7 +205,6 @@ interface AgentDocumentsGroupProps {
const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ viewMode = 'list' }) => {
const { t } = useTranslation('chat');
const agentId = useAgentStore((s) => s.activeAgentId);
- const activeDocumentId = useChatStore(chatPortalSelectors.portalDocumentId);
const [filter, setFilter] = useState<ResourceFilter>('all');
const {
@@ -251,13 +269,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ viewMode = 'list'
</Text>
<Flexbox gap={8}>
{group.items.map((doc) => (
- <DocumentItem
- agentId={agentId}
- document={doc}
- isActive={activeDocumentId === doc.documentId}
- key={doc.id}
- mutate={mutate}
- />
+ <DocumentItem agentId={agentId} document={doc} key={doc.id} mutate={mutate} />
))}
</Flexbox>
</Flexbox>
@@ -294,13 +306,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ viewMode = 'list'
) : (
<Flexbox gap={8}>
{filteredData.map((doc) => (
- <DocumentItem
- agentId={agentId}
- document={doc}
- isActive={activeDocumentId === doc.documentId}
- key={doc.id}
- mutate={mutate}
- />
+ <DocumentItem agentId={agentId} document={doc} key={doc.id} mutate={mutate} />
))}
</Flexbox>
)}
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.test.tsx
index b03fa287fdb..b580807e2f4 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.test.tsx
@@ -16,10 +16,12 @@ vi.mock('@/libs/swr', async (importOriginal) => {
});
vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ ...props }: { [key: string]: unknown }) => <button {...props} />,
Accordion: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<div {...props}>{children}</div>
),
+ ActionIcon: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <button {...props}>{children}</button>
+ ),
AccordionItem: ({
children,
title,
diff --git a/src/routes/(main)/agent/features/Conversation/index.tsx b/src/routes/(main)/agent/features/Conversation/index.tsx
index 41f2c8603e4..85b6543b3cd 100644
--- a/src/routes/(main)/agent/features/Conversation/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/index.tsx
@@ -9,16 +9,15 @@ import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import ConversationArea from './ConversationArea';
-import ChatHeader from './Header';
const wrapperStyle: React.CSSProperties = {
+ flex: 1,
height: '100%',
minWidth: 300,
width: '100%',
};
const ChatConversation = memo(() => {
- const showHeader = useGlobalStore(systemStatusSelectors.showChatHeader);
const isStatusInit = useGlobalStore(systemStatusSelectors.isStatusInit);
// Get current agent's model info for vision support check
@@ -35,7 +34,6 @@ const ChatConversation = memo(() => {
<Suspense fallback={<Loading debugId="Agent > ChatConversation" />}>
<DragUploadZone style={wrapperStyle} onUploadFiles={handleUploadFiles}>
<Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}>
- {showHeader && <ChatHeader />}
<TooltipGroup>
<ConversationArea />
</TooltipGroup>
diff --git a/src/routes/(main)/agent/features/Conversation/useAgentContext.test.tsx b/src/routes/(main)/agent/features/Conversation/useAgentContext.test.tsx
new file mode 100644
index 00000000000..d5e76d6a251
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/useAgentContext.test.tsx
@@ -0,0 +1,101 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { initialState as initialChatState } from '@/store/chat/initialState';
+import { useChatStore } from '@/store/chat/store';
+import { createInitialEditorContentState, useDocumentStore } from '@/store/document';
+import { initialEditorState } from '@/store/document/slices/editor';
+
+import { useAgentContext } from './useAgentContext';
+
+describe('useAgentContext', () => {
+ beforeEach(() => {
+ useChatStore.setState(
+ {
+ ...initialChatState,
+ activeAgentId: 'agt_1',
+ activeThreadId: undefined,
+ activeTopicId: 'tpc_1',
+ },
+ false,
+ );
+ useDocumentStore.setState({ ...initialEditorState }, false);
+ });
+
+ it('carries the active notebook document for the current topic in main scope', () => {
+ useDocumentStore.setState(
+ {
+ activeDocumentId: 'docs_1',
+ documents: {
+ docs_1: createInitialEditorContentState('notebook', { topicId: 'tpc_1' }),
+ },
+ },
+ false,
+ );
+
+ const { result } = renderHook(() => useAgentContext());
+
+ expect(result.current).toEqual({
+ agentId: 'agt_1',
+ documentId: 'docs_1',
+ scope: 'main',
+ threadId: null,
+ topicId: 'tpc_1',
+ });
+ });
+
+ it('falls back to the last opened topic document after leaving the page route', () => {
+ useDocumentStore.setState(
+ {
+ activeDocumentId: undefined,
+ documents: {
+ docs_1: createInitialEditorContentState('notebook', { topicId: 'tpc_1' }),
+ },
+ lastActiveTopicDocumentIdByTopicId: {
+ tpc_1: 'docs_1',
+ },
+ },
+ false,
+ );
+
+ const { result } = renderHook(() => useAgentContext());
+
+ expect(result.current.documentId).toBe('docs_1');
+ });
+
+ it('can carry the last topic document id even when editor document state has been cleared', () => {
+ useDocumentStore.setState(
+ {
+ activeDocumentId: undefined,
+ documents: {},
+ lastActiveTopicDocumentIdByTopicId: {
+ tpc_1: 'docs_1',
+ },
+ },
+ false,
+ );
+
+ const { result } = renderHook(() => useAgentContext());
+
+ expect(result.current.documentId).toBe('docs_1');
+ });
+
+ it('does not carry a stale notebook document from another topic', () => {
+ useDocumentStore.setState(
+ {
+ activeDocumentId: 'docs_1',
+ documents: {
+ docs_1: createInitialEditorContentState('notebook', { topicId: 'tpc_other' }),
+ },
+ },
+ false,
+ );
+
+ const { result } = renderHook(() => useAgentContext());
+
+ expect(result.current.documentId).toBeUndefined();
+ });
+});
diff --git a/src/routes/(main)/agent/features/Conversation/useAgentContext.ts b/src/routes/(main)/agent/features/Conversation/useAgentContext.ts
index 0952833d607..11137af8275 100644
--- a/src/routes/(main)/agent/features/Conversation/useAgentContext.ts
+++ b/src/routes/(main)/agent/features/Conversation/useAgentContext.ts
@@ -3,6 +3,7 @@
import { type ConversationContext } from '@lobechat/types';
import { useChatStore } from '@/store/chat';
+import { useDocumentStore } from '@/store/document';
/**
* Hook to get agent conversation context
@@ -16,9 +17,25 @@ export function useAgentContext(): ConversationContext {
s.activeTopicId ?? null,
s.activeThreadId ?? null,
]);
+ const activeTopicDocumentId = useDocumentStore((s) => {
+ if (!topicId || threadId) return undefined;
+
+ const lastTopicDocumentId = s.lastActiveTopicDocumentIdByTopicId[topicId];
+ const documentIds = [s.activeDocumentId, lastTopicDocumentId].filter(Boolean) as string[];
+
+ for (const documentId of documentIds) {
+ const document = s.documents[documentId];
+ if (!document) {
+ if (documentId === lastTopicDocumentId) return documentId;
+ continue;
+ }
+ if (document.sourceType === 'notebook' && document.topicId === topicId) return documentId;
+ }
+ });
return {
agentId,
+ documentId: activeTopicDocumentId,
scope: threadId ? 'thread' : 'main',
threadId,
topicId,
diff --git a/src/routes/(main)/agent/features/Page/PageRedirect.test.tsx b/src/routes/(main)/agent/features/Page/PageRedirect.test.tsx
new file mode 100644
index 00000000000..67d1a0c92a8
--- /dev/null
+++ b/src/routes/(main)/agent/features/Page/PageRedirect.test.tsx
@@ -0,0 +1,68 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import PageRedirect from './PageRedirect';
+
+const navigateMock = vi.hoisted(() => vi.fn());
+const useAutoCreateTopicDocumentMock = vi.hoisted(() => vi.fn());
+const useParamsMock = vi.hoisted(() => vi.fn());
+
+vi.mock('react-router-dom', async () => {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
+ const actual = (await vi.importActual('react-router-dom')) as typeof import('react-router-dom');
+
+ return {
+ ...actual,
+ useNavigate: () => navigateMock,
+ useParams: useParamsMock,
+ };
+});
+
+vi.mock('@/components/Loading/BrandTextLoading', () => ({
+ default: ({ debugId }: { debugId: string }) => <div data-testid={debugId} />,
+}));
+
+vi.mock('@/features/TopicCanvas/useAutoCreateTopicDocument', () => ({
+ useAutoCreateTopicDocument: useAutoCreateTopicDocumentMock,
+}));
+
+describe('PageRedirect', () => {
+ beforeEach(() => {
+ navigateMock.mockReset();
+ useAutoCreateTopicDocumentMock.mockReset();
+ useParamsMock.mockReset();
+ });
+
+ it('redirects to the page created for an empty topic', async () => {
+ useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_test' });
+ useAutoCreateTopicDocumentMock.mockReturnValue({
+ document: undefined,
+ documentId: 'doc_created',
+ isLoading: false,
+ });
+
+ render(<PageRedirect />);
+
+ await waitFor(() =>
+ expect(navigateMock).toHaveBeenCalledWith('/agent/agt_test/tpc_test/page/doc_created', {
+ replace: true,
+ }),
+ );
+ });
+
+ it('keeps the loading state while the topic document id is not available', () => {
+ useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_test' });
+ useAutoCreateTopicDocumentMock.mockReturnValue({
+ document: undefined,
+ documentId: undefined,
+ isLoading: true,
+ });
+
+ render(<PageRedirect />);
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/routes/(main)/agent/features/Page/PageRedirect.tsx b/src/routes/(main)/agent/features/Page/PageRedirect.tsx
new file mode 100644
index 00000000000..57bb24d548a
--- /dev/null
+++ b/src/routes/(main)/agent/features/Page/PageRedirect.tsx
@@ -0,0 +1,25 @@
+'use client';
+
+import { memo, useEffect } from 'react';
+import { useNavigate, useParams } from 'react-router-dom';
+
+import BrandTextLoading from '@/components/Loading/BrandTextLoading';
+import { useAutoCreateTopicDocument } from '@/features/TopicCanvas/useAutoCreateTopicDocument';
+
+const PageRedirect = memo(() => {
+ const { aid, topicId } = useParams<{ aid?: string; topicId?: string }>();
+ const navigate = useNavigate();
+
+ const { documentId } = useAutoCreateTopicDocument(topicId, aid);
+
+ useEffect(() => {
+ if (!aid || !topicId || !documentId) return;
+ navigate(`/agent/${aid}/${topicId}/page/${documentId}`, { replace: true });
+ }, [aid, topicId, documentId, navigate]);
+
+ return <BrandTextLoading debugId={'PageRedirect'} />;
+});
+
+PageRedirect.displayName = 'PageRedirect';
+
+export default PageRedirect;
diff --git a/src/routes/(main)/agent/features/Page/index.test.tsx b/src/routes/(main)/agent/features/Page/index.test.tsx
new file mode 100644
index 00000000000..e90e8d3f818
--- /dev/null
+++ b/src/routes/(main)/agent/features/Page/index.test.tsx
@@ -0,0 +1,188 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import TopicPage from './index';
+
+const useParamsMock = vi.hoisted(() => vi.fn());
+const useNavigateMock = vi.hoisted(() => vi.fn());
+const useClientDataSWRMock = vi.hoisted(() => vi.fn());
+const useAutoCreateTopicDocumentMock = vi.hoisted(() => vi.fn());
+
+vi.mock('react-router-dom', async () => {
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
+ const actual = (await vi.importActual('react-router-dom')) as typeof import('react-router-dom');
+
+ return {
+ ...actual,
+ useNavigate: () => useNavigateMock,
+ useParams: useParamsMock,
+ };
+});
+
+vi.mock('swr', () => ({
+ mutate: vi.fn(),
+}));
+
+vi.mock('@/features/EditorCanvas', () => ({
+ AutoSaveHint: ({ documentId }: { documentId: string }) => (
+ <div data-document-id={documentId} data-testid="autosave-hint" />
+ ),
+}));
+
+vi.mock('@/libs/swr', () => ({
+ useClientDataSWR: (...args: unknown[]) => useClientDataSWRMock(...args),
+}));
+
+vi.mock('@/services/document', () => ({
+ documentService: {
+ getDocumentById: vi.fn(),
+ updateDocument: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentSWRKeys: { documentsList: (id: string) => ['agent-documents-list', id] },
+}));
+
+vi.mock('@/store/notebook/action', () => ({
+ SWR_USE_FETCH_NOTEBOOK_DOCUMENTS: 'SWR_USE_FETCH_NOTEBOOK_DOCUMENTS',
+}));
+
+vi.mock('@/features/TopicCanvas/useAutoCreateTopicDocument', () => ({
+ useAutoCreateTopicDocument: (...args: unknown[]) => useAutoCreateTopicDocumentMock(...args),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+}));
+
+vi.mock('@/features/FloatingChatPanel', () => ({
+ default: ({
+ agentId,
+ documentId,
+ open,
+ scope,
+ title,
+ topicId,
+ variant,
+ }: {
+ agentId: string;
+ documentId?: string;
+ open?: boolean;
+ scope?: string;
+ title?: string;
+ topicId: string | null;
+ variant?: string;
+ }) => (
+ <div
+ data-agent-id={agentId}
+ data-document-id={documentId ?? ''}
+ data-open={String(open)}
+ data-scope={scope ?? ''}
+ data-testid="floating-chat-panel"
+ data-title={title ?? ''}
+ data-topic-id={topicId ?? 'null'}
+ data-variant={variant ?? ''}
+ />
+ ),
+}));
+
+vi.mock('@/features/TopicCanvas', () => ({
+ default: ({
+ agentId,
+ documentId,
+ topicId,
+ }: {
+ agentId?: string;
+ documentId?: string;
+ topicId?: string | null;
+ }) => (
+ <div
+ data-agent-id={agentId ?? ''}
+ data-document-id={documentId ?? ''}
+ data-testid="topic-canvas"
+ data-topic-id={topicId ?? 'null'}
+ />
+ ),
+}));
+
+describe('Topic page route', () => {
+ beforeEach(() => {
+ useClientDataSWRMock.mockReset();
+ useAutoCreateTopicDocumentMock.mockReset();
+ useNavigateMock.mockReset();
+ useParamsMock.mockReset();
+
+ useClientDataSWRMock.mockReturnValue({ data: null, error: undefined, isLoading: false });
+ useAutoCreateTopicDocumentMock.mockReturnValue({
+ document: undefined,
+ documentId: undefined,
+ isLoading: false,
+ });
+ });
+
+ it('renders FloatingChatPanel with route topic context', () => {
+ useParamsMock.mockReturnValue({
+ aid: 'agt_test',
+ docId: 'doc_test',
+ topicId: 'tpc_test',
+ });
+
+ render(<TopicPage />);
+
+ expect(screen.getByTestId('agent-page-container')).toBeInTheDocument();
+ expect(screen.getByTestId('topic-canvas')).toHaveAttribute('data-agent-id', 'agt_test');
+ expect(screen.getByTestId('topic-canvas')).toHaveAttribute('data-topic-id', 'tpc_test');
+ expect(screen.getByTestId('topic-canvas')).toHaveAttribute('data-document-id', 'doc_test');
+ expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute('data-agent-id', 'agt_test');
+ expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute(
+ 'data-document-id',
+ 'doc_test',
+ );
+ expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute('data-scope', 'page');
+
+ expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute('data-topic-id', 'tpc_test');
+ expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute('data-variant', 'embedded');
+ expect(useAutoCreateTopicDocumentMock).toHaveBeenCalledWith('tpc_test', 'agt_test');
+ });
+
+ it('redirects to the topic page document when the current doc id is invalid', async () => {
+ useParamsMock.mockReturnValue({
+ aid: 'agt_test',
+ docId: 'doc_deleted',
+ topicId: 'tpc_test',
+ });
+ useClientDataSWRMock.mockReturnValue({
+ data: undefined,
+ error: undefined,
+ isLoading: false,
+ });
+ useAutoCreateTopicDocumentMock.mockReturnValue({
+ document: undefined,
+ documentId: 'doc_created',
+ isLoading: false,
+ });
+
+ render(<TopicPage />);
+
+ await waitFor(() =>
+ expect(useNavigateMock).toHaveBeenCalledWith('/agent/agt_test/tpc_test/page/doc_created', {
+ replace: true,
+ }),
+ );
+ });
+
+ it('returns null when aid or topicId is missing', () => {
+ useParamsMock.mockReturnValue({ aid: 'agt_test' });
+
+ const { container } = render(<TopicPage />);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/src/routes/(main)/agent/features/Page/index.tsx b/src/routes/(main)/agent/features/Page/index.tsx
new file mode 100644
index 00000000000..8cf5048d0c4
--- /dev/null
+++ b/src/routes/(main)/agent/features/Page/index.tsx
@@ -0,0 +1,130 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { debounce } from 'es-toolkit/compat';
+import { memo, useEffect, useMemo, useState } from 'react';
+import { useNavigate, useParams } from 'react-router-dom';
+
+import { AutoSaveHint } from '@/features/EditorCanvas';
+import FloatingChatPanel from '@/features/FloatingChatPanel';
+import TopicCanvas from '@/features/TopicCanvas';
+import { useAutoCreateTopicDocument } from '@/features/TopicCanvas/useAutoCreateTopicDocument';
+import { useClientDataSWR } from '@/libs/swr';
+import HeaderSlot from '@/routes/(main)/agent/(chat)/_layout/HeaderSlot';
+import { documentService } from '@/services/document';
+import { invalidateDocumentMutation } from '@/services/document/invalidation';
+import { documentSWRKeys } from '@/services/document/swrKeys';
+
+const MAX_PANEL_WIDTH = 1024;
+const TITLE_SAVE_DEBOUNCE = 500;
+
+const TopicPage = memo(() => {
+ const { aid, topicId, docId } = useParams<{ aid?: string; docId?: string; topicId?: string }>();
+ const navigate = useNavigate();
+
+ const { documentId: topicDocumentId } = useAutoCreateTopicDocument(topicId, aid);
+
+ const [titleDraft, setTitleDraft] = useState<string | undefined>();
+
+ const {
+ data: documentMeta,
+ error: documentError,
+ isLoading: isDocLoading,
+ } = useClientDataSWR(docId ? documentSWRKeys.pageMeta(docId) : null, () =>
+ documentService.getDocumentById(docId!),
+ );
+
+ const isInvalidDoc = Boolean(docId && !isDocLoading && (documentError || documentMeta == null));
+
+ useEffect(() => {
+ if (!aid || !topicId) return;
+ if (!isInvalidDoc) return;
+ if (!topicDocumentId) return;
+ if (topicDocumentId === docId) return;
+ navigate(`/agent/${aid}/${topicId}/page/${topicDocumentId}`, { replace: true });
+ }, [aid, topicId, docId, isInvalidDoc, topicDocumentId, navigate]);
+
+ useEffect(() => {
+ setTitleDraft(undefined);
+ }, [docId]);
+
+ const debouncedSaveTitle = useMemo(
+ () =>
+ debounce(
+ async (
+ id: string,
+ nextTitle: string,
+ ctx: { agentId: string | undefined; topicId: string | undefined },
+ ) => {
+ await documentService.updateDocument({
+ id,
+ saveSource: 'autosave',
+ title: nextTitle,
+ });
+ await invalidateDocumentMutation({
+ agentId: ctx.agentId,
+ cause: 'page-title',
+ documentId: id,
+ refreshDocumentEditor: false,
+ topicId: ctx.topicId,
+ });
+ },
+ TITLE_SAVE_DEBOUNCE,
+ ),
+ [],
+ );
+
+ const handleTitleChange = (next: string) => {
+ setTitleDraft(next);
+ if (docId) debouncedSaveTitle(docId, next, { agentId: aid, topicId });
+ };
+
+ if (!aid || !topicId) return null;
+
+ const displayTitle = titleDraft ?? documentMeta?.title ?? '';
+
+ return (
+ <Flexbox
+ align={'center'}
+ data-testid="agent-page-container"
+ height={'100%'}
+ style={{ minHeight: 0, minWidth: 0, position: 'relative' }}
+ width={'100%'}
+ >
+ {docId && (
+ <HeaderSlot>
+ <AutoSaveHint documentId={docId} />
+ </HeaderSlot>
+ )}
+ <Flexbox
+ align={'center'}
+ flex={1}
+ style={{ minHeight: 0, overflowX: 'hidden', overflowY: 'auto' }}
+ width={'100%'}
+ >
+ <Flexbox style={{ maxWidth: MAX_PANEL_WIDTH, paddingBlockEnd: 16 }} width={'100%'}>
+ <TopicCanvas
+ agentId={aid}
+ documentId={docId}
+ title={displayTitle}
+ topicId={topicId}
+ onTitleChange={handleTitleChange}
+ />
+ </Flexbox>
+ </Flexbox>
+ <Flexbox style={{ maxWidth: MAX_PANEL_WIDTH, zIndex: 19 }} width={'100%'}>
+ <FloatingChatPanel
+ agentId={aid}
+ documentId={docId}
+ maxHeight={0.92}
+ minHeight={320}
+ scope={'page'}
+ topicId={topicId}
+ variant={'embedded'}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default TopicPage;
diff --git a/src/routes/(main)/agent/index.desktop.test.tsx b/src/routes/(main)/agent/index.desktop.test.tsx
index 5d3bd32060c..e9d5f57c222 100644
--- a/src/routes/(main)/agent/index.desktop.test.tsx
+++ b/src/routes/(main)/agent/index.desktop.test.tsx
@@ -3,7 +3,7 @@
*/
import { act, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
-import { MemoryRouter, useLocation } from 'react-router-dom';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { initialState as initialChatState } from '@/store/chat/initialState';
@@ -78,10 +78,10 @@ vi.mock('./features/TelemetryNotification', () => ({
default: () => <div data-testid="telemetry-notification" />,
}));
-const SearchProbe = () => {
+const LocationProbe = () => {
const location = useLocation();
- return <div data-testid="search-probe">{location.search}</div>;
+ return <div data-testid="location-probe">{`${location.pathname}${location.search}`}</div>;
};
describe('Agent desktop topic popup guard', () => {
@@ -99,21 +99,32 @@ describe('Agent desktop topic popup guard', () => {
});
afterEach(() => {
- useChatStore.setState(initialChatState, false);
- vi.runOnlyPendingTimers();
+ act(() => {
+ useChatStore.setState(initialChatState, false);
+ vi.runOnlyPendingTimers();
+ });
vi.useRealTimers();
});
- it('keeps the topic query synchronized while the popup guard is visible', async () => {
+ it('keeps the topic route synchronized while the popup guard is visible', async () => {
render(
- <MemoryRouter initialEntries={['/agent/agent-1?topic=popup-topic']}>
- <SearchProbe />
- <ChatPage />
+ <MemoryRouter initialEntries={['/agent/agent-1/popup-topic']}>
+ <Routes>
+ <Route
+ path="/agent/:aid/:topicId"
+ element={
+ <>
+ <LocationProbe />
+ <ChatPage />
+ </>
+ }
+ />
+ </Routes>
</MemoryRouter>,
);
expect(screen.getByTestId('topic-popup-guard')).toBeInTheDocument();
- expect(screen.getByTestId('search-probe')).toHaveTextContent('?topic=popup-topic');
+ expect(screen.getByTestId('location-probe')).toHaveTextContent('/agent/agent-1/popup-topic');
act(() => {
useChatStore.setState({ activeTopicId: 'other-topic' });
@@ -127,6 +138,6 @@ describe('Agent desktop topic popup guard', () => {
await Promise.resolve();
});
- expect(screen.getByTestId('search-probe')).toHaveTextContent('?topic=other-topic');
+ expect(screen.getByTestId('location-probe')).toHaveTextContent('/agent/agent-1/other-topic');
});
});
diff --git a/src/routes/(main)/agent/index.desktop.tsx b/src/routes/(main)/agent/index.desktop.tsx
index 26d5143c5a3..ec79b6bc63d 100644
--- a/src/routes/(main)/agent/index.desktop.tsx
+++ b/src/routes/(main)/agent/index.desktop.tsx
@@ -25,30 +25,33 @@ const ChatPage = memo(() => {
// When the same topic is already hosted in a popup window, avoid
// rendering a second (out-of-sync) instance here — guide the user back
// to the popup instead.
- if (activeTopicId && popup) {
- return (
+ const pageContent =
+ activeTopicId && popup ? (
<>
- <ChatHydration />
<PageTitle />
<TopicInPopupGuard popup={popup} />
</>
+ ) : (
+ <>
+ <PageTitle />
+ <Flexbox
+ horizontal
+ height={'100%'}
+ style={{ overflow: 'hidden', position: 'relative' }}
+ width={'100%'}
+ >
+ <Conversation />
+ <Portal />
+ <AgentWorkingSidebar />
+ </Flexbox>
+ <TelemetryNotification mobile={false} />
+ </>
);
- }
return (
<>
- <PageTitle />
- <Flexbox
- horizontal
- height={'100%'}
- style={{ overflow: 'hidden', position: 'relative' }}
- width={'100%'}
- >
- <Conversation />
- <Portal />
- <AgentWorkingSidebar />
- </Flexbox>
- <TelemetryNotification mobile={false} />
+ <ChatHydration />
+ {pageContent}
</>
);
});
diff --git a/src/routes/(main)/agent/index.tsx b/src/routes/(main)/agent/index.tsx
index b949bdf165e..1b50ccca176 100644
--- a/src/routes/(main)/agent/index.tsx
+++ b/src/routes/(main)/agent/index.tsx
@@ -4,24 +4,21 @@ import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import Conversation from './features/Conversation';
-import AgentWorkingSidebar from './features/Conversation/WorkingSidebar';
+import ChatHydration from './features/Conversation/ChatHydration';
import PageTitle from './features/PageTitle';
-import Portal from './features/Portal';
import TelemetryNotification from './features/TelemetryNotification';
const ChatPage = memo(() => {
return (
<>
+ <ChatHydration />
<PageTitle />
<Flexbox
- horizontal
height={'100%'}
- style={{ overflow: 'hidden', position: 'relative' }}
+ style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}
width={'100%'}
>
<Conversation />
- <Portal />
- <AgentWorkingSidebar />
</Flexbox>
<TelemetryNotification mobile={false} />
</>
diff --git a/src/routes/(main)/agent/page/index.tsx b/src/routes/(main)/agent/page/index.tsx
new file mode 100644
index 00000000000..09093b9f69b
--- /dev/null
+++ b/src/routes/(main)/agent/page/index.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { memo } from 'react';
+import { Navigate, useParams } from 'react-router-dom';
+
+import { SESSION_CHAT_URL } from '@/const/url';
+
+const PageRedirect = memo(() => {
+ const params = useParams<{ aid?: string }>();
+
+ return <Navigate replace to={params.aid ? SESSION_CHAT_URL(params.aid) : '/agent'} />;
+});
+
+export default PageRedirect;
diff --git a/src/routes/(main)/agent/tasks/[taskId]/index.tsx b/src/routes/(main)/agent/tasks/[taskId]/index.tsx
new file mode 100644
index 00000000000..2dea9adb08e
--- /dev/null
+++ b/src/routes/(main)/agent/tasks/[taskId]/index.tsx
@@ -0,0 +1,16 @@
+'use client';
+
+import { memo } from 'react';
+import { useParams } from 'react-router-dom';
+
+import { TaskDetailPage } from '@/features/AgentTasks';
+
+const TaskDetailRoute = memo(() => {
+ const { aid, taskId } = useParams<{ aid?: string; taskId?: string }>();
+
+ if (!aid || !taskId) return null;
+
+ return <TaskDetailPage agentId={aid} taskId={taskId} />;
+});
+
+export default TaskDetailRoute;
diff --git a/src/routes/(main)/agent/tasks/_layout/index.tsx b/src/routes/(main)/agent/tasks/_layout/index.tsx
new file mode 100644
index 00000000000..ddc822daab9
--- /dev/null
+++ b/src/routes/(main)/agent/tasks/_layout/index.tsx
@@ -0,0 +1,46 @@
+'use client';
+
+import { TaskIdentifier } from '@lobechat/builtin-tool-task';
+import { Flexbox } from '@lobehub/ui';
+import { memo } from 'react';
+import { Navigate, Outlet, useParams } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import AgentTaskManager from '@/features/AgentTaskManager';
+import { useScenarioEnabledTools } from '@/hooks/useScenarioEnabledTools';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
+
+/**
+ * Tasks pages layout.
+ *
+ * - Horizontal split: task content on the left (list / detail), main-conversation
+ * chat panel on the right. Right panel reuses the same agentId + activeTopicId
+ * as the `/agent/:aid` page via `useAgentContext()` inside ConversationArea.
+ *
+ * - Enables `lobe-task` for every LLM step while the user is on any tasks
+ * sub-page via the page-level `scenarioEnabledToolIds` chat state.
+ */
+const TasksLayout = memo(() => {
+ useScenarioEnabledTools(TaskIdentifier);
+ const params = useParams();
+ const agentId = params.aid;
+ const serverConfigInit = useServerConfigStore((s) => s.serverConfigInit);
+ const { enableAgentTask } = useServerConfigStore(featureFlagsSelectors);
+
+ if (serverConfigInit && !enableAgentTask) {
+ return <Navigate replace to={agentId ? urlJoin('/agent', agentId) : '/'} />;
+ }
+
+ return (
+ <Flexbox horizontal flex={1} height={'100%'} width={'100%'}>
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <Outlet />
+ </Flexbox>
+ <AgentTaskManager />
+ </Flexbox>
+ );
+});
+
+TasksLayout.displayName = 'TasksLayout';
+
+export default TasksLayout;
diff --git a/src/routes/(main)/agent/tasks/index.tsx b/src/routes/(main)/agent/tasks/index.tsx
new file mode 100644
index 00000000000..a2cac70bcc2
--- /dev/null
+++ b/src/routes/(main)/agent/tasks/index.tsx
@@ -0,0 +1,16 @@
+'use client';
+
+import { memo } from 'react';
+import { useParams } from 'react-router-dom';
+
+import { AgentTasksPage } from '@/features/AgentTasks';
+
+const TasksRoute = memo(() => {
+ const { aid } = useParams<{ aid?: string }>();
+
+ if (!aid) return null;
+
+ return <AgentTasksPage agentId={aid} />;
+});
+
+export default TasksRoute;
diff --git a/src/routes/(main)/memory/features/SourceLink.tsx b/src/routes/(main)/memory/features/SourceLink.tsx
index aef4a5716a2..f1e3dc34bb7 100644
--- a/src/routes/(main)/memory/features/SourceLink.tsx
+++ b/src/routes/(main)/memory/features/SourceLink.tsx
@@ -3,17 +3,18 @@ import { cssVar } from 'antd-style';
import { Link2 } from 'lucide-react';
import { memo } from 'react';
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { type MemorySource } from '@/database/repositories/userMemory';
import Link from '@/libs/router/Link';
const SourceLink = memo<{ source?: MemorySource | null }>(({ source }) => {
- if (!source) return;
+ if (!source?.agentId || !source.id) return;
const title = source.title || source.id?.replace('tpc_', '').slice(0, 8);
return (
<Link
- href={`/agent/${source.agentId}?topic=${source.id}`}
+ href={SESSION_CHAT_TOPIC_URL(source.agentId, source.id)}
style={{
flex: 1,
maxWidth: '100%',
diff --git a/src/routes/(mobile)/chat/index.tsx b/src/routes/(mobile)/chat/index.tsx
index 93ecfd8b2a4..ebaae0f8c15 100644
--- a/src/routes/(mobile)/chat/index.tsx
+++ b/src/routes/(mobile)/chat/index.tsx
@@ -2,6 +2,7 @@
import { memo } from 'react';
+import ChatHydration from '@/routes/(main)/agent/features/Conversation/ChatHydration';
import ConversationArea from '@/routes/(main)/agent/features/Conversation/ConversationArea';
import PageTitle from '@/routes/(main)/agent/features/PageTitle';
import PortalPanel from '@/routes/(main)/agent/features/Portal/features/PortalPanel';
@@ -12,6 +13,7 @@ import Topic from './features/Topic';
const MobileChatPage = memo(() => {
return (
<>
+ <ChatHydration />
<PageTitle />
<ConversationArea />
<Topic />
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index 19a94ce5277..48141451136 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -544,6 +544,7 @@ export const createRuntimeExecutors = (
evalContext: ctx.evalContext,
forceFinish: state.forceFinish,
historyCount: agentConfig.chatConfig?.historyCount ?? undefined,
+ initialContext: (state as any).initialContext?.initialContext,
knowledge: {
fileContents: agentConfig.files
?.filter((f: { enabled?: boolean | null }) => f.enabled === true)
@@ -1526,7 +1527,9 @@ export const createRuntimeExecutors = (
toolExecutionService.executeTool(chatToolPayload, {
activeDeviceId: state.metadata?.activeDeviceId,
agentId: state.metadata?.agentId,
+ documentId: state.metadata?.documentId,
memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,
+ scope: state.metadata?.scope,
serverDB: ctx.serverDB,
taskId: state.metadata?.taskId,
toolManifestMap: effectiveManifestMap,
@@ -1958,7 +1961,9 @@ export const createRuntimeExecutors = (
toolExecutionService.executeTool(chatToolPayload, {
activeDeviceId: state.metadata?.activeDeviceId,
agentId: state.metadata?.agentId,
+ documentId: state.metadata?.documentId,
memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,
+ scope: state.metadata?.scope,
serverDB: ctx.serverDB,
taskId: state.metadata?.taskId,
toolManifestMap: batchManifestMap,
diff --git a/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
index d073470c817..fa57c7dd043 100644
--- a/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
+++ b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
@@ -80,6 +80,34 @@ describe('serverMessagesEngine', () => {
// SystemDateProvider injects a system date message even with empty input
expect(result).toEqual([{ content: getCurrentDateContent(), role: 'system' }]);
});
+
+ it('should pass active topic document initial context into MessagesEngine', async () => {
+ const result = await serverMessagesEngine({
+ initialContext: {
+ activeTopicDocument: {
+ agentDocumentId: 'agd_1',
+ documentId: 'docs_1',
+ title: 'Topic Doc',
+ },
+ },
+ messages: [
+ {
+ content: '继续修改',
+ createdAt: Date.now(),
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ],
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ const userMessage = result.find((message) => message.role === 'user');
+
+ expect(userMessage?.content).toContain('<active_topic_document>');
+ expect(userMessage?.content).toContain('agent_document_id="agd_1"');
+ });
});
describe('knowledge injection', () => {
diff --git a/src/server/modules/Mecha/ContextEngineering/index.ts b/src/server/modules/Mecha/ContextEngineering/index.ts
index 5a8139e344a..f91efc6c7fc 100644
--- a/src/server/modules/Mecha/ContextEngineering/index.ts
+++ b/src/server/modules/Mecha/ContextEngineering/index.ts
@@ -1,3 +1,4 @@
+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import { MessagesEngine } from '@lobechat/context-engine';
import { type OpenAIChatMessage } from '@lobechat/types';
@@ -58,6 +59,7 @@ export const serverMessagesEngine = async ({
historyCount,
historySummary,
formatHistorySummary,
+ initialContext,
knowledge,
agentDocuments,
skillsConfig,
@@ -101,6 +103,8 @@ export const serverMessagesEngine = async ({
inputTemplate,
+ initialContext,
+
// Knowledge injection
knowledge: {
fileContents: knowledge?.fileContents,
@@ -123,6 +127,9 @@ export const serverMessagesEngine = async ({
// Tools configuration
toolDiscoveryConfig,
toolsConfig: {
+ disabledToolIdentifiers:
+ toolsConfig?.disabledToolIdentifiers ??
+ (toolsConfig?.tools?.includes(PageAgentIdentifier) ? undefined : [PageAgentIdentifier]),
manifests: toolsConfig?.manifests,
tools: toolsConfig?.tools,
},
diff --git a/src/server/modules/Mecha/ContextEngineering/types.ts b/src/server/modules/Mecha/ContextEngineering/types.ts
index cdfd87a4196..169b2df9bc9 100644
--- a/src/server/modules/Mecha/ContextEngineering/types.ts
+++ b/src/server/modules/Mecha/ContextEngineering/types.ts
@@ -16,7 +16,7 @@ import type {
UserMemoryData,
} from '@lobechat/context-engine';
import type { PageContentContext } from '@lobechat/prompts';
-import type { UIChatMessage } from '@lobechat/types';
+import type { RuntimeInitialContext, UIChatMessage } from '@lobechat/types';
/**
* Model capability checker functions for server-side
@@ -44,6 +44,8 @@ export interface ServerKnowledgeConfig {
* Tools configuration for server context engineering
*/
export interface ServerToolsConfig {
+ /** Tool identifiers that must be removed from historical tool calls in this runtime scope */
+ disabledToolIdentifiers?: string[];
/** Tool manifests with systemRole and API definitions */
manifests?: LobeToolManifest[];
/** Enabled tool IDs (kept for compatibility) */
@@ -107,6 +109,8 @@ export interface ServerMessagesEngineParams {
historySummary?: string;
/** Input template */
inputTemplate?: string;
+ /** Initial runtime context captured at operation start */
+ initialContext?: RuntimeInitialContext;
// ========== Knowledge ==========
/** Knowledge configuration */
knowledge?: ServerKnowledgeConfig;
diff --git a/src/server/routers/lambda/agentDocument.ts b/src/server/routers/lambda/agentDocument.ts
index 29c1647545a..d1702319166 100644
--- a/src/server/routers/lambda/agentDocument.ts
+++ b/src/server/routers/lambda/agentDocument.ts
@@ -6,6 +6,8 @@ import {
import { z } from 'zod';
import { AgentDocumentModel } from '@/database/models/agentDocuments';
+import { TopicModel } from '@/database/models/topic';
+import { TopicDocumentModel } from '@/database/models/topicDocument';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
@@ -30,6 +32,29 @@ const toolLoadRuleSchema = z.object({
timeRange: z.object({ from: z.string().optional(), to: z.string().optional() }).optional(),
});
+const readFormatSchema = z.enum(['xml', 'markdown', 'both']).optional();
+
+const liteXMLOperationSchema = z.union([
+ z.object({
+ action: z.literal('insert'),
+ beforeId: z.string(),
+ litexml: z.string(),
+ }),
+ z.object({
+ action: z.literal('insert'),
+ afterId: z.string(),
+ litexml: z.string(),
+ }),
+ z.object({
+ action: z.literal('modify'),
+ litexml: z.union([z.string(), z.array(z.string())]),
+ }),
+ z.object({
+ action: z.literal('remove'),
+ id: z.string(),
+ }),
+]);
+
const agentDocumentProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -37,6 +62,8 @@ const agentDocumentProcedure = authedProcedure.use(serverDatabase).use(async (op
ctx: {
agentDocumentModel: new AgentDocumentModel(ctx.serverDB, ctx.userId),
agentDocumentService: new AgentDocumentsService(ctx.serverDB, ctx.userId),
+ topicModel: new TopicModel(ctx.serverDB, ctx.userId),
+ topicDocumentModel: new TopicDocumentModel(ctx.serverDB, ctx.userId),
},
});
});
@@ -192,8 +219,20 @@ export const agentDocumentRouter = router({
* Tool-oriented: list documents for an agent
*/
listDocuments: agentDocumentProcedure
- .input(z.object({ agentId: z.string() }))
+ .input(
+ z.object({
+ agentId: z.string(),
+ target: z.enum(['agent', 'currentTopic']).optional().default('agent'),
+ topicId: z.string().optional(),
+ }),
+ )
.query(async ({ ctx, input }) => {
+ if (input.target === 'currentTopic') {
+ if (!input.topicId) throw new Error('topicId is required to list current topic documents');
+
+ return ctx.agentDocumentService.listDocumentsForTopic(input.agentId, input.topicId);
+ }
+
return ctx.agentDocumentService.listDocuments(input.agentId);
}),
@@ -204,11 +243,14 @@ export const agentDocumentRouter = router({
.input(
z.object({
agentId: z.string(),
+ format: readFormatSchema,
filename: z.string(),
}),
)
.query(async ({ ctx, input }) => {
- return ctx.agentDocumentService.getDocumentByFilename(input.agentId, input.filename);
+ return input.format
+ ? ctx.agentDocumentService.getDocumentSnapshotByFilename(input.agentId, input.filename)
+ : ctx.agentDocumentService.getDocumentByFilename(input.agentId, input.filename);
}),
/**
@@ -259,6 +301,32 @@ export const agentDocumentRouter = router({
return ctx.agentDocumentService.createDocument(input.agentId, input.title, input.content);
}),
+ /**
+ * Create an agent document and associate it with a topic in one call.
+ * Used by the topic → page flow to replace the legacy notebook entry point.
+ */
+ createForTopic: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ content: z.string(),
+ title: z.string(),
+ topicId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const topic = input.title.trim() ? undefined : await ctx.topicModel.findById(input.topicId);
+ const title = input.title.trim() || topic?.title || '';
+ const doc = await ctx.agentDocumentService.createForTopic(
+ input.agentId,
+ title,
+ input.content,
+ input.topicId,
+ );
+
+ return doc;
+ }),
+
/**
* Tool-oriented: read document by id
*/
@@ -266,11 +334,33 @@ export const agentDocumentRouter = router({
.input(
z.object({
agentId: z.string(),
+ format: readFormatSchema,
id: z.string(),
}),
)
.query(async ({ ctx, input }) => {
- return ctx.agentDocumentService.getDocumentById(input.id, input.agentId);
+ return input.format
+ ? ctx.agentDocumentService.getDocumentSnapshotById(input.id, input.agentId)
+ : ctx.agentDocumentService.getDocumentById(input.id, input.agentId);
+ }),
+
+ /**
+ * Tool-oriented: modify document nodes by id through LiteXML.
+ */
+ modifyNodes: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ id: z.string(),
+ operations: z.array(liteXMLOperationSchema).min(1),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.modifyDocumentNodesById(
+ input.id,
+ input.operations,
+ input.agentId,
+ );
}),
/**
diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.ts
index 5e1c17ef3dc..47a032a4fcb 100644
--- a/src/server/routers/lambda/aiAgent.ts
+++ b/src/server/routers/lambda/aiAgent.ts
@@ -137,6 +137,7 @@ const ExecAgentSchema = z
/** Application context for message storage */
appContext: z
.object({
+ documentId: z.string().optional().nullable(),
groupId: z.string().optional().nullable(),
scope: z.string().optional().nullable(),
sessionId: z.string().optional(),
diff --git a/src/server/routers/lambda/recent.ts b/src/server/routers/lambda/recent.ts
index 1730c868a40..3395ab8488e 100644
--- a/src/server/routers/lambda/recent.ts
+++ b/src/server/routers/lambda/recent.ts
@@ -1,5 +1,6 @@
import { z } from 'zod';
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { RecentModel } from '@/database/models/recent';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -41,7 +42,7 @@ export const recentRouter = router({
if (item.routeGroupId) {
routePath = `/group/${item.routeGroupId}?topic=${item.id}`;
} else if (item.routeId) {
- routePath = `/agent/${item.routeId}?topic=${item.id}`;
+ routePath = SESSION_CHAT_TOPIC_URL(item.routeId, item.id);
} else {
routePath = '/';
}
diff --git a/src/server/routers/lambda/task.ts b/src/server/routers/lambda/task.ts
index d7dbe9d1fd7..2018b181d9c 100644
--- a/src/server/routers/lambda/task.ts
+++ b/src/server/routers/lambda/task.ts
@@ -1,6 +1,5 @@
import { TaskIdentifier as TaskSkillIdentifier } from '@lobechat/builtin-skills';
import { BriefIdentifier } from '@lobechat/builtin-tool-brief';
-import { NotebookIdentifier } from '@lobechat/builtin-tool-notebook';
import { TASK_STATUSES } from '@lobechat/builtin-tool-task';
import { buildTaskRunPrompt } from '@lobechat/prompts';
import type {
@@ -887,11 +886,14 @@ export const taskRouter = router({
const db = ctx.serverDB;
const userId = ctx.userId;
- // Task execution always injects: Task skill (auto-activated) + Notebook tool (for document output)
- // Conditionally inject Brief tool based on checkpoint/review config
+ // Task execution auto-injects the Task skill. The legacy Notebook tool
+ // has been deprecated and is no longer injected — document output now
+ // flows through the agent-documents tool, which is enabled via the
+ // agent config (see INBOX runtime / createEnableChecker).
+ // Conditionally inject Brief tool based on checkpoint/review config.
const checkpoint = model.getCheckpointConfig(task);
const reviewConfig = model.getReviewConfig(task);
- const pluginIds = [TaskSkillIdentifier, NotebookIdentifier];
+ const pluginIds = [TaskSkillIdentifier];
if (!reviewConfig?.enabled && checkpoint.onAgentRequest !== false) {
pluginIds.push(BriefIdentifier);
}
diff --git a/src/server/runtimeConfig/providers/CompositeRuntimeConfigProvider.ts b/src/server/runtimeConfig/providers/CompositeRuntimeConfigProvider.ts
index 50fa33b5b53..1bd4d68e1e9 100644
--- a/src/server/runtimeConfig/providers/CompositeRuntimeConfigProvider.ts
+++ b/src/server/runtimeConfig/providers/CompositeRuntimeConfigProvider.ts
@@ -1,8 +1,4 @@
-import type {
- RuntimeConfigProvider,
- RuntimeConfigSelector,
- VersionedSnapshot,
-} from '../types';
+import type { RuntimeConfigProvider, RuntimeConfigSelector, VersionedSnapshot } from '../types';
export class CompositeRuntimeConfigProvider<T> implements RuntimeConfigProvider<T> {
domain: RuntimeConfigProvider<T>['domain'];
diff --git a/src/server/services/agentDocuments.test.ts b/src/server/services/agentDocuments.test.ts
index 2d7e5de88ee..b0655fd15d8 100644
--- a/src/server/services/agentDocuments.test.ts
+++ b/src/server/services/agentDocuments.test.ts
@@ -6,9 +6,16 @@ import {
buildDocumentFilename,
extractMarkdownH1Title,
} from '@/database/models/agentDocuments';
+import { TopicDocumentModel } from '@/database/models/topicDocument';
import type { LobeChatDatabase } from '@/database/type';
import { AgentDocumentsService } from './agentDocuments';
+import { DocumentService } from './document';
+
+const headlessEditorMocks = vi.hoisted(() => ({
+ applyLiteXML: vi.fn(),
+ applyLiteXMLBatch: vi.fn(),
+}));
vi.mock('@/database/models/agentDocuments', () => ({
AgentDocumentModel: vi.fn(),
@@ -19,6 +26,46 @@ vi.mock('@/database/models/agentDocuments', () => ({
extractMarkdownH1Title: vi.fn((content: string) => ({ content })),
}));
+vi.mock('@/database/models/topicDocument', () => ({
+ TopicDocumentModel: vi.fn(),
+}));
+
+vi.mock('./document', () => ({
+ DocumentService: vi.fn(),
+}));
+
+vi.mock('@lobehub/editor/headless', () => ({
+ createHeadlessEditor: vi.fn(() => {
+ let markdown = '';
+ let litexml = '<p id="node-1">content</p>';
+
+ return {
+ applyLiteXML: vi.fn(async (operations) => {
+ headlessEditorMocks.applyLiteXML(operations);
+ markdown = 'xml updated';
+ litexml = '<p id="node-1">xml updated</p>';
+ }),
+ applyLiteXMLBatch: vi.fn(async (operations) => {
+ headlessEditorMocks.applyLiteXMLBatch(operations);
+ markdown = 'xml updated';
+ litexml = '<p id="node-1">xml updated</p>';
+ }),
+ destroy: vi.fn(),
+ export: vi.fn((options?: { litexml?: boolean }) => ({
+ editorData: { root: { children: [] } },
+ litexml: options?.litexml ? litexml : undefined,
+ markdown,
+ })),
+ hydrateEditorData: vi.fn(() => {
+ markdown = 'projected';
+ }),
+ hydrateMarkdown: vi.fn((content: string) => {
+ markdown = content;
+ }),
+ };
+ }),
+}));
+
describe('AgentDocumentsService', () => {
const db = {} as LobeChatDatabase;
const userId = 'user-1';
@@ -26,15 +73,28 @@ describe('AgentDocumentsService', () => {
const mockModel = {
associate: vi.fn(),
create: vi.fn(),
+ findById: vi.fn(),
findByAgent: vi.fn(),
+ findByDocumentIds: vi.fn(),
findByFilename: vi.fn(),
hasByAgent: vi.fn(),
+ rename: vi.fn(),
+ update: vi.fn(),
upsert: vi.fn(),
};
+ const mockDocumentService = {
+ trySaveCurrentDocumentHistory: vi.fn(),
+ };
+ const mockTopicDocumentModel = {
+ associate: vi.fn(),
+ findByTopicId: vi.fn(),
+ };
beforeEach(() => {
vi.clearAllMocks();
(AgentDocumentModel as any).mockImplementation(() => mockModel);
+ (DocumentService as any).mockImplementation(() => mockDocumentService);
+ (TopicDocumentModel as any).mockImplementation(() => mockTopicDocumentModel);
vi.mocked(buildDocumentFilename).mockImplementation((title: string) => title);
vi.mocked(extractMarkdownH1Title).mockImplementation((content: string) => ({ content }));
});
@@ -52,6 +112,7 @@ describe('AgentDocumentsService', () => {
expect(mockModel.findByFilename).toHaveBeenNthCalledWith(1, 'agent-1', 'note');
expect(mockModel.findByFilename).toHaveBeenNthCalledWith(2, 'agent-1', 'note-2');
expect(mockModel.create).toHaveBeenCalledWith('agent-1', 'note-2', 'content', {
+ editorData: { root: { children: [] } },
title: 'note',
});
expect(result).toEqual({ id: 'new-doc', filename: 'note-2' });
@@ -81,16 +142,57 @@ describe('AgentDocumentsService', () => {
expect(vi.mocked(buildDocumentFilename)).toHaveBeenCalledWith('My Title');
expect(mockModel.create).toHaveBeenCalledWith('agent-1', 'My Title', 'body', {
+ editorData: { root: { children: [] } },
title: 'My Title',
});
});
});
+ describe('createForTopic', () => {
+ it('should create an agent document and associate the underlying document with the topic', async () => {
+ mockModel.findByFilename.mockResolvedValue(undefined);
+ mockModel.create.mockResolvedValue({
+ documentId: 'documents-1',
+ filename: 'note',
+ id: 'agent-doc-1',
+ title: 'note',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+ const result = await service.createForTopic('agent-1', 'note', 'content', 'topic-1');
+
+ expect(result).toEqual({
+ documentId: 'documents-1',
+ filename: 'note',
+ id: 'agent-doc-1',
+ title: 'note',
+ });
+ expect(mockTopicDocumentModel.associate).toHaveBeenCalledWith({
+ documentId: 'documents-1',
+ topicId: 'topic-1',
+ });
+ });
+ });
+
describe('listDocuments', () => {
- it('should return a list of documents with filename, id, and title', async () => {
+ it('should return a list of documents with documentId, filename, id, and title', async () => {
mockModel.findByAgent.mockResolvedValue([
- { content: 'c1', filename: 'a.md', id: 'doc-1', policy: null, title: 'A' },
- { content: 'c2', filename: 'b.md', id: 'doc-2', policy: null, title: 'B' },
+ {
+ content: 'c1',
+ documentId: 'documents-1',
+ filename: 'a.md',
+ id: 'doc-1',
+ policy: null,
+ title: 'A',
+ },
+ {
+ content: 'c2',
+ documentId: 'documents-2',
+ filename: 'b.md',
+ id: 'doc-2',
+ policy: null,
+ title: 'B',
+ },
]);
const service = new AgentDocumentsService(db, userId);
@@ -98,8 +200,70 @@ describe('AgentDocumentsService', () => {
expect(mockModel.findByAgent).toHaveBeenCalledWith('agent-1');
expect(result).toEqual([
- { filename: 'a.md', id: 'doc-1', loadPosition: undefined, title: 'A' },
- { filename: 'b.md', id: 'doc-2', loadPosition: undefined, title: 'B' },
+ {
+ documentId: 'documents-1',
+ filename: 'a.md',
+ id: 'doc-1',
+ loadPosition: undefined,
+ title: 'A',
+ },
+ {
+ documentId: 'documents-2',
+ filename: 'b.md',
+ id: 'doc-2',
+ loadPosition: undefined,
+ title: 'B',
+ },
+ ]);
+ });
+ });
+
+ describe('listDocumentsForTopic', () => {
+ it('should list only agent documents associated with the topic and preserve topic order', async () => {
+ mockTopicDocumentModel.findByTopicId.mockResolvedValue([
+ { id: 'documents-2', title: 'B' },
+ { id: 'documents-1', title: 'A' },
+ ]);
+ mockModel.findByDocumentIds.mockResolvedValue([
+ {
+ documentId: 'documents-1',
+ filename: 'a.md',
+ id: 'agent-doc-1',
+ policy: null,
+ title: 'A',
+ },
+ {
+ documentId: 'documents-2',
+ filename: 'b.md',
+ id: 'agent-doc-2',
+ policy: null,
+ title: 'B',
+ },
+ ]);
+
+ const service = new AgentDocumentsService(db, userId);
+ const result = await service.listDocumentsForTopic('agent-1', 'topic-1');
+
+ expect(mockTopicDocumentModel.findByTopicId).toHaveBeenCalledWith('topic-1');
+ expect(mockModel.findByDocumentIds).toHaveBeenCalledWith('agent-1', [
+ 'documents-2',
+ 'documents-1',
+ ]);
+ expect(result).toEqual([
+ {
+ documentId: 'documents-2',
+ filename: 'b.md',
+ id: 'agent-doc-2',
+ loadPosition: undefined,
+ title: 'B',
+ },
+ {
+ documentId: 'documents-1',
+ filename: 'a.md',
+ id: 'agent-doc-1',
+ loadPosition: undefined,
+ title: 'A',
+ },
]);
});
});
@@ -135,8 +299,33 @@ describe('AgentDocumentsService', () => {
});
});
+ describe('getDocumentSnapshotById', () => {
+ it('should fall back to markdown content when editor data is empty', async () => {
+ mockModel.findById.mockResolvedValue({
+ agentId: 'agent-1',
+ content: 'fallback content',
+ editorData: { root: { children: [] } },
+ id: 'agent-doc-1',
+ title: 'Doc',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+ const result = await service.getDocumentSnapshotById('agent-doc-1', 'agent-1');
+
+ expect(result).toEqual({
+ agentId: 'agent-1',
+ content: 'fallback content',
+ editorData: { root: { children: [] } },
+ id: 'agent-doc-1',
+ litexml: '<p id="node-1">content</p>',
+ title: 'Doc',
+ });
+ });
+ });
+
describe('upsertDocumentByFilename', () => {
it('should create or update a document by filename', async () => {
+ mockModel.findByFilename.mockResolvedValue(undefined);
mockModel.upsert.mockResolvedValue({ content: 'new', filename: 'f.md', id: 'doc-1' });
const service = new AgentDocumentsService(db, userId);
@@ -146,9 +335,201 @@ describe('AgentDocumentsService', () => {
filename: 'f.md',
});
- expect(mockModel.upsert).toHaveBeenCalledWith('agent-1', 'f.md', 'new');
+ expect(mockModel.upsert).toHaveBeenCalledWith('agent-1', 'f.md', 'new', {
+ editorData: { root: { children: [] } },
+ });
expect(result).toEqual({ content: 'new', filename: 'f.md', id: 'doc-1' });
});
+
+ it('should save history before updating an existing document by filename', async () => {
+ mockModel.findByFilename.mockResolvedValue({
+ agentId: 'agent-1',
+ content: 'old',
+ documentId: 'documents-1',
+ filename: 'f.md',
+ id: 'agent-doc-1',
+ });
+ mockModel.upsert.mockResolvedValue({ content: 'new', filename: 'f.md', id: 'agent-doc-1' });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.upsertDocumentByFilename({
+ agentId: 'agent-1',
+ content: 'new',
+ filename: 'f.md',
+ });
+
+ expect(mockDocumentService.trySaveCurrentDocumentHistory).toHaveBeenCalledWith(
+ 'documents-1',
+ 'llm_call',
+ );
+ expect(
+ mockDocumentService.trySaveCurrentDocumentHistory.mock.invocationCallOrder[0],
+ ).toBeLessThan(mockModel.upsert.mock.invocationCallOrder[0]);
+ });
+
+ it('should skip history when upsert content is unchanged', async () => {
+ mockModel.findByFilename.mockResolvedValue({
+ agentId: 'agent-1',
+ content: 'same',
+ documentId: 'documents-1',
+ filename: 'f.md',
+ id: 'agent-doc-1',
+ });
+ mockModel.upsert.mockResolvedValue({ content: 'same', filename: 'f.md', id: 'agent-doc-1' });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.upsertDocumentByFilename({
+ agentId: 'agent-1',
+ content: 'same',
+ filename: 'f.md',
+ });
+
+ expect(mockDocumentService.trySaveCurrentDocumentHistory).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('editDocumentById', () => {
+ it('should save history before editing document content', async () => {
+ mockModel.findById
+ .mockResolvedValueOnce({
+ agentId: 'agent-1',
+ content: 'old',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ title: 'Doc',
+ })
+ .mockResolvedValueOnce({
+ agentId: 'agent-1',
+ content: 'new',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ title: 'Doc',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+ const result = await service.editDocumentById('agent-doc-1', 'new', 'agent-1');
+
+ expect(mockDocumentService.trySaveCurrentDocumentHistory).toHaveBeenCalledWith(
+ 'documents-1',
+ 'llm_call',
+ );
+ expect(mockModel.update).toHaveBeenCalledWith('agent-doc-1', {
+ content: 'new',
+ editorData: { root: { children: [] } },
+ });
+ expect(
+ mockDocumentService.trySaveCurrentDocumentHistory.mock.invocationCallOrder[0],
+ ).toBeLessThan(mockModel.update.mock.invocationCallOrder[0]);
+ expect(result).toEqual({
+ agentId: 'agent-1',
+ content: 'new',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ title: 'Doc',
+ });
+ });
+
+ it('should skip history when edited content is unchanged', async () => {
+ mockModel.findById
+ .mockResolvedValueOnce({
+ agentId: 'agent-1',
+ content: 'same',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ title: 'Doc',
+ })
+ .mockResolvedValueOnce({
+ agentId: 'agent-1',
+ content: 'same',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ title: 'Doc',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.editDocumentById('agent-doc-1', 'same', 'agent-1');
+
+ expect(mockDocumentService.trySaveCurrentDocumentHistory).not.toHaveBeenCalled();
+ expect(mockModel.update).toHaveBeenCalledWith('agent-doc-1', {
+ content: 'same',
+ editorData: { root: { children: [] } },
+ });
+ });
+
+ it('should apply LiteXML operations against editor data', async () => {
+ mockModel.findById
+ .mockResolvedValueOnce({
+ agentId: 'agent-1',
+ content: 'old',
+ documentId: 'documents-1',
+ editorData: { root: { children: [{ text: 'old' }] } },
+ id: 'agent-doc-1',
+ title: 'Doc',
+ })
+ .mockResolvedValueOnce({
+ agentId: 'agent-1',
+ content: 'xml updated',
+ documentId: 'documents-1',
+ editorData: { root: { children: [] } },
+ id: 'agent-doc-1',
+ title: 'Doc',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+ const result = await service.modifyDocumentNodesById(
+ 'agent-doc-1',
+ [{ action: 'modify', litexml: '<p id="node-1">xml updated</p>' }],
+ 'agent-1',
+ );
+
+ expect(mockDocumentService.trySaveCurrentDocumentHistory).toHaveBeenCalledWith(
+ 'documents-1',
+ 'llm_call',
+ );
+ expect(mockModel.update).toHaveBeenCalledWith('agent-doc-1', {
+ content: 'xml updated',
+ editorData: { root: { children: [] } },
+ });
+ expect(headlessEditorMocks.applyLiteXML).toHaveBeenCalledWith([
+ {
+ action: 'replace',
+ delay: true,
+ litexml: '<p id="node-1">xml updated</p>',
+ },
+ ]);
+ expect(headlessEditorMocks.applyLiteXMLBatch).not.toHaveBeenCalled();
+ expect(result?.content).toBe('xml updated');
+ });
+ });
+
+ describe('renameDocumentById', () => {
+ it('should save history before renaming a document', async () => {
+ mockModel.findById.mockResolvedValue({
+ agentId: 'agent-1',
+ content: 'content',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ title: 'Old title',
+ });
+ mockModel.rename.mockResolvedValue({
+ agentId: 'agent-1',
+ content: 'content',
+ documentId: 'documents-1',
+ id: 'agent-doc-1',
+ title: 'New title',
+ });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.renameDocumentById('agent-doc-1', 'New title', 'agent-1');
+
+ expect(mockDocumentService.trySaveCurrentDocumentHistory).toHaveBeenCalledWith(
+ 'documents-1',
+ 'llm_call',
+ );
+ expect(
+ mockDocumentService.trySaveCurrentDocumentHistory.mock.invocationCallOrder[0],
+ ).toBeLessThan(mockModel.rename.mock.invocationCallOrder[0]);
+ });
});
describe('hasDocuments', () => {
diff --git a/src/server/services/agentDocuments.ts b/src/server/services/agentDocuments.ts
index 2c6cd03e284..4f07fb17a76 100644
--- a/src/server/services/agentDocuments.ts
+++ b/src/server/services/agentDocuments.ts
@@ -1,20 +1,32 @@
-import {
- type AgentDocumentPolicy,
- type DOCUMENT_TEMPLATES,
- DocumentLoadPosition,
- type DocumentLoadRules,
- type DocumentTemplateSet,
- getDocumentTemplate,
- type PolicyLoad,
+import type {
+ AgentDocumentPolicy,
+ DOCUMENT_TEMPLATES,
+ DocumentLoadRules,
+ DocumentTemplateSet,
+ PolicyLoad,
} from '@lobechat/agent-templates';
+import { DocumentLoadPosition, getDocumentTemplate } from '@lobechat/agent-templates';
import type { LobeChatDatabase } from '@lobechat/database';
+import type {
+ AgentDocument,
+ AgentDocumentWithRules,
+ ToolUpdateLoadRule,
+} from '@/database/models/agentDocuments';
import {
AgentDocumentModel,
- type AgentDocumentWithRules,
- type ToolUpdateLoadRule,
+ buildDocumentFilename,
+ extractMarkdownH1Title,
} from '@/database/models/agentDocuments';
-import { buildDocumentFilename, extractMarkdownH1Title } from '@/database/models/agentDocuments';
+import { TopicDocumentModel } from '@/database/models/topicDocument';
+
+import {
+ type AgentDocumentLiteXMLOperation,
+ applyLiteXMLOperations,
+ createMarkdownEditorSnapshot,
+ exportEditorDataSnapshot,
+} from './agentDocuments/headlessEditor';
+import { DocumentService } from './document';
const MAX_UNIQUE_FILENAME_ATTEMPTS = 1000;
@@ -32,15 +44,61 @@ interface UpsertDocumentParams {
updatedAt?: Date;
}
+type AgentDocumentWithLiteXML = AgentDocument & { litexml?: string };
+
/**
* Service for managing agent documents with reusable template sets.
* Document-level policy controls runtime behavior (context rendering/retrieval).
*/
export class AgentDocumentsService {
private agentDocumentModel: AgentDocumentModel;
+ private documentService: DocumentService;
+ private topicDocumentModel: TopicDocumentModel;
constructor(db: LobeChatDatabase, userId: string) {
this.agentDocumentModel = new AgentDocumentModel(db, userId);
+ this.documentService = new DocumentService(db, userId);
+ this.topicDocumentModel = new TopicDocumentModel(db, userId);
+ }
+
+ private async projectDocumentContent<T extends AgentDocument | AgentDocumentWithRules>(
+ doc: T,
+ ): Promise<T>;
+ private async projectDocumentContent<T extends AgentDocument | AgentDocumentWithRules>(
+ doc: T | undefined,
+ ): Promise<T | undefined>;
+ private async projectDocumentContent<T extends AgentDocument | AgentDocumentWithRules>(
+ doc: T | undefined,
+ ): Promise<T | undefined> {
+ if (!doc?.editorData) return doc;
+
+ try {
+ const snapshot = await exportEditorDataSnapshot({
+ editorData: doc.editorData,
+ fallbackContent: doc.content,
+ });
+
+ return { ...doc, content: snapshot.content };
+ } catch (error) {
+ console.error('[AgentDocumentsService] Failed to project editorData to Markdown:', error);
+ return doc;
+ }
+ }
+
+ private async projectDocuments<T extends AgentDocument | AgentDocumentWithRules>(
+ docs: T[],
+ ): Promise<T[]> {
+ return Promise.all(docs.map((doc) => this.projectDocumentContent(doc)));
+ }
+
+ private async attachLiteXML(doc: AgentDocument): Promise<AgentDocumentWithLiteXML> {
+ const snapshot = await exportEditorDataSnapshot({
+ editorData: doc.editorData,
+ fallbackContent: doc.content,
+ litexml: true,
+ });
+
+ return { ...doc, content: snapshot.content, litexml: snapshot.litexml };
}
private async createWithUniqueFilename(
@@ -71,7 +129,13 @@ export class AgentDocumentsService {
suffix += 1;
}
- return this.agentDocumentModel.create(agentId, filename, content, { ...params, title });
+ const snapshot = await createMarkdownEditorSnapshot(content);
+
+ return this.agentDocumentModel.create(agentId, filename, snapshot.content, {
+ ...params,
+ editorData: snapshot.editorData,
+ title,
+ });
}
/**
@@ -84,7 +148,10 @@ export class AgentDocumentsService {
const templateSet = getDocumentTemplate(templateId);
for (const template of templateSet.templates) {
- await this.agentDocumentModel.upsert(agentId, template.filename, template.content, {
+ await this.upsertDocument({
+ agentId,
+ content: template.content,
+ filename: template.filename,
loadPosition: template.loadPosition,
loadRules: template.loadRules,
metadata: template.metadata,
@@ -102,7 +169,10 @@ export class AgentDocumentsService {
*/
async initializeFromCustomTemplate(agentId: string, templateSet: DocumentTemplateSet) {
for (const template of templateSet.templates) {
- await this.agentDocumentModel.upsert(agentId, template.filename, template.content, {
+ await this.upsertDocument({
+ agentId,
+ content: template.content,
+ filename: template.filename,
loadPosition: template.loadPosition,
loadRules: template.loadRules,
metadata: template.metadata,
@@ -149,14 +219,16 @@ export class AgentDocumentsService {
}
async getAgentDocuments(agentId: string): Promise<AgentDocumentWithRules[]> {
- return this.agentDocumentModel.findByAgent(agentId);
+ const docs = await this.agentDocumentModel.findByAgent(agentId);
+ return this.projectDocuments(docs);
}
async getDocumentsByTemplate(
agentId: string,
templateId: string,
): Promise<AgentDocumentWithRules[]> {
- return this.agentDocumentModel.findByTemplate(agentId, templateId);
+ const docs = await this.agentDocumentModel.findByTemplate(agentId, templateId);
+ return this.projectDocuments(docs);
}
async getDocumentsByPolicy(agentId: string, policyId: string): Promise<AgentDocumentWithRules[]> {
@@ -164,20 +236,37 @@ export class AgentDocumentsService {
}
async getDocument(agentId: string, filename: string) {
- return this.agentDocumentModel.findByFilename(agentId, filename);
+ const doc = await this.agentDocumentModel.findByFilename(agentId, filename);
+ return this.projectDocumentContent(doc);
}
async getDocumentById(id: string, expectedAgentId?: string) {
return this.getDocumentByIdInAgent(id, expectedAgentId);
}
+ async getDocumentSnapshotById(id: string, expectedAgentId?: string) {
+ const doc = await this.agentDocumentModel.findById(id);
+
+ if (!doc) return undefined;
+ if (expectedAgentId && doc.agentId !== expectedAgentId) return undefined;
+
+ return this.attachLiteXML(doc);
+ }
+
+ async getDocumentSnapshotByFilename(agentId: string, filename: string) {
+ const doc = await this.agentDocumentModel.findByFilename(agentId, filename);
+ if (!doc) return undefined;
+
+ return this.attachLiteXML(doc);
+ }
+
private async getDocumentByIdInAgent(documentId: string, expectedAgentId?: string) {
const doc = await this.agentDocumentModel.findById(documentId);
if (!doc) return undefined;
if (expectedAgentId && doc.agentId !== expectedAgentId) return undefined;
- return doc;
+ return this.projectDocumentContent(doc);
}
async upsertDocument({
@@ -193,8 +282,11 @@ export class AgentDocumentsService {
createdAt,
updatedAt,
}: UpsertDocumentParams) {
- return this.agentDocumentModel.upsert(agentId, filename, content, {
+ const snapshot = await createMarkdownEditorSnapshot(content);
+
+ return this.agentDocumentModel.upsert(agentId, filename, snapshot.content, {
createdAt,
+ editorData: snapshot.editorData,
loadPosition,
loadRules,
metadata,
@@ -215,6 +307,17 @@ export class AgentDocumentsService {
return this.createWithUniqueFilename(agentId, finalTitle, strippedContent);
}
+ async createForTopic(agentId: string, title: string, content: string, topicId: string) {
+ const doc = await this.createDocument(agentId, title, content);
+
+ await this.topicDocumentModel.associate({
+ documentId: doc.documentId,
+ topicId,
+ });
+
+ return doc;
+ }
+
async deleteDocument(documentId: string) {
return this.agentDocumentModel.delete(documentId);
}
@@ -246,19 +349,40 @@ export class AgentDocumentsService {
currentTime?: Date;
},
): Promise<AgentDocumentWithRules[]> {
- return this.agentDocumentModel.getInjectableDocuments(agentId, context);
+ const docs = await this.agentDocumentModel.getInjectableDocuments(agentId, context);
+ return this.projectDocuments(docs);
}
async getDocumentsByPosition(agentId: string) {
- return this.agentDocumentModel.getDocumentsByPosition(agentId);
+ const grouped = await this.agentDocumentModel.getDocumentsByPosition(agentId);
+ const projected = new Map<DocumentLoadPosition, AgentDocumentWithRules[]>();
+
+ for (const [position, docs] of grouped.entries()) {
+ projected.set(position, await this.projectDocuments(docs));
+ }
+
+ return projected;
}
async getAgentContext(agentId: string): Promise<string> {
- return this.agentDocumentModel.getAgentContext(agentId);
+ const docs = await this.getInjectableDocuments(agentId, {});
+
+ if (docs.length === 0) return '';
+
+ const contextParts: string[] = [];
+ for (const doc of docs) {
+ if (doc.content) {
+ contextParts.push(`--- ${doc.filename} ---`);
+ contextParts.push(doc.content);
+ contextParts.push('');
+ }
+ }
+
+ return contextParts.join('\n').trim();
}
async getDocumentsMap(agentId: string) {
- const docs = await this.agentDocumentModel.findByAgent(agentId);
+ const docs = await this.getAgentDocuments(agentId);
return new Map(docs.map((doc) => [doc.filename, doc.content]));
}
@@ -315,6 +439,7 @@ export class AgentDocumentsService {
async listDocuments(agentId: string) {
const docs = await this.agentDocumentModel.findByAgent(agentId);
return docs.map((d) => ({
+ documentId: d.documentId,
filename: d.filename,
id: d.id,
loadPosition: d.policy?.context?.position,
@@ -322,8 +447,27 @@ export class AgentDocumentsService {
}));
}
+ async listDocumentsForTopic(agentId: string, topicId: string) {
+ const topicDocs = await this.topicDocumentModel.findByTopicId(topicId);
+ const documentIds = topicDocs.map((doc) => doc.id);
+ const docs = await this.agentDocumentModel.findByDocumentIds(agentId, documentIds);
+ const docsByDocumentId = new Map(docs.map((doc) => [doc.documentId, doc]));
+
+ return topicDocs
+ .map((topicDoc) => docsByDocumentId.get(topicDoc.id))
+ .filter((doc): doc is AgentDocumentWithRules => Boolean(doc))
+ .map((doc) => ({
+ documentId: doc.documentId,
+ filename: doc.filename,
+ id: doc.id,
+ loadPosition: doc.policy?.context?.position,
+ title: doc.title,
+ }));
+ }
+
async getDocumentByFilename(agentId: string, filename: string) {
- return this.agentDocumentModel.findByFilename(agentId, filename);
+ const doc = await this.agentDocumentModel.findByFilename(agentId, filename);
+ return this.projectDocumentContent(doc);
}
async upsertDocumentByFilename({
@@ -335,21 +479,68 @@ export class AgentDocumentsService {
content: string;
filename: string;
}) {
- return this.agentDocumentModel.upsert(agentId, filename, content);
+ const existing = await this.agentDocumentModel.findByFilename(agentId, filename);
+ const projectedExisting = await this.projectDocumentContent(existing);
+ const snapshot = await createMarkdownEditorSnapshot(content);
+
+ if (existing && projectedExisting?.content !== snapshot.content) {
+ await this.documentService.trySaveCurrentDocumentHistory(existing.documentId, 'llm_call');
+ }
+
+ return this.agentDocumentModel.upsert(agentId, filename, snapshot.content, {
+ editorData: snapshot.editorData,
+ });
}
async editDocumentById(documentId: string, content: string, expectedAgentId?: string) {
const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);
if (!doc) return undefined;
+ const snapshot = await createMarkdownEditorSnapshot(content);
+
+ if (doc.content !== snapshot.content) {
+ await this.documentService.trySaveCurrentDocumentHistory(doc.documentId, 'llm_call');
+ }
+
+ await this.agentDocumentModel.update(documentId, {
+ content: snapshot.content,
+ editorData: snapshot.editorData,
+ });
+ return this.getDocumentByIdInAgent(documentId, expectedAgentId);
+ }
+
+ async modifyDocumentNodesById(
+ documentId: string,
+ operations: AgentDocumentLiteXMLOperation[],
+ expectedAgentId?: string,
+ ) {
+ const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);
+ if (!doc) return undefined;
+
+ await this.documentService.trySaveCurrentDocumentHistory(doc.documentId, 'llm_call');
+
+ const snapshot = await applyLiteXMLOperations({
+ editorData: doc.editorData,
+ fallbackContent: doc.content,
+ operations,
+ });
- await this.agentDocumentModel.update(documentId, { content });
- return this.agentDocumentModel.findById(documentId);
+ await this.agentDocumentModel.update(documentId, {
+ content: snapshot.content,
+ editorData: snapshot.editorData,
+ });
+
+ return this.getDocumentByIdInAgent(documentId, expectedAgentId);
}
async renameDocumentById(documentId: string, newTitle: string, expectedAgentId?: string) {
const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);
if (!doc) return undefined;
+ const title = newTitle.trim();
+ if (title && title !== doc.title) {
+ await this.documentService.trySaveCurrentDocumentHistory(doc.documentId, 'llm_call');
+ }
+
return this.agentDocumentModel.rename(documentId, newTitle);
}
diff --git a/src/server/services/agentDocuments/headlessEditor.test.ts b/src/server/services/agentDocuments/headlessEditor.test.ts
new file mode 100644
index 00000000000..a9f7ad7d0eb
--- /dev/null
+++ b/src/server/services/agentDocuments/headlessEditor.test.ts
@@ -0,0 +1,56 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { applyLiteXMLOperations, exportEditorDataSnapshot } from './headlessEditor';
+
+const hasNodeType = (value: unknown, type: string): boolean => {
+ if (!value || typeof value !== 'object') return false;
+
+ if (!Array.isArray(value) && 'type' in value && value.type === type) return true;
+
+ return Object.values(value).some((child) => {
+ if (Array.isArray(child)) {
+ return child.some((item) => hasNodeType(item, type));
+ }
+
+ return hasNodeType(child, type);
+ });
+};
+
+const getSpanId = (litexml: string, text: string): string => {
+ const match = litexml.match(new RegExp(`<span id="([^"]+)">${text}</span>`));
+ expect(match).not.toBeNull();
+
+ return match![1];
+};
+
+describe('agent document headless editor', () => {
+ it('should apply LiteXML operations and persist diff nodes for later human review', async () => {
+ const initial = await exportEditorDataSnapshot({
+ fallbackContent: 'Original',
+ litexml: true,
+ });
+ const textId = getSpanId(initial.litexml!, 'Original');
+
+ const snapshot = await applyLiteXMLOperations({
+ editorData: initial.editorData,
+ fallbackContent: initial.content,
+ operations: [
+ {
+ action: 'modify',
+ litexml: `<span id="${textId}">Updated</span>`,
+ },
+ ],
+ });
+
+ // Markdown and LiteXML exports are auto-normalized by the headless editor,
+ // so they show the accepted view — this is what Context Engine injects and
+ // what LLMs see when reading the document.
+ expect(snapshot.content).toBe('Updated\n');
+ expect(snapshot.litexml).toContain('Updated');
+
+ // editorData (the persisted form) retains the diff node so the page editor
+ // can render a review UI when the user next opens the document.
+ expect(hasNodeType(snapshot.editorData, 'diff')).toBe(true);
+ });
+});
diff --git a/src/server/services/agentDocuments/headlessEditor.ts b/src/server/services/agentDocuments/headlessEditor.ts
new file mode 100644
index 00000000000..b47b869a5a7
--- /dev/null
+++ b/src/server/services/agentDocuments/headlessEditor.ts
@@ -0,0 +1,169 @@
+/* eslint-disable @typescript-eslint/consistent-type-imports */
+import type { HeadlessLiteXMLOperation } from '@lobehub/editor/headless';
+import type { SerializedEditorState, SerializedLexicalNode } from 'lexical';
+
+import { isValidEditorData } from '@/libs/editor/isValidEditorData';
+
+export type AgentDocumentEditorData = Record<string, any>;
+
+export type AgentDocumentLiteXMLOperation =
+ | {
+ action: 'insert';
+ afterId: string;
+ litexml: string;
+ }
+ | {
+ action: 'insert';
+ beforeId: string;
+ litexml: string;
+ }
+ | {
+ action: 'modify';
+ litexml: string | string[];
+ }
+ | {
+ action: 'remove';
+ id: string;
+ };
+
+const orderLiteXMLOperations = (
+ operations: AgentDocumentLiteXMLOperation[],
+): AgentDocumentLiteXMLOperation[] => {
+ const orderedOperations: AgentDocumentLiteXMLOperation[] = [];
+
+ for (const operation of operations) {
+ if (operation.action === 'insert') {
+ orderedOperations.unshift(operation);
+ } else {
+ orderedOperations.push(operation);
+ }
+ }
+
+ return orderedOperations;
+};
+
+const toHeadlessLiteXMLOperation = (
+ operation: AgentDocumentLiteXMLOperation,
+): HeadlessLiteXMLOperation => {
+ switch (operation.action) {
+ case 'insert': {
+ return 'beforeId' in operation
+ ? {
+ action: 'insert',
+ beforeId: operation.beforeId,
+ delay: true,
+ litexml: operation.litexml,
+ }
+ : {
+ action: 'insert',
+ afterId: operation.afterId,
+ delay: true,
+ litexml: operation.litexml,
+ };
+ }
+
+ case 'modify': {
+ return {
+ action: 'replace',
+ delay: true,
+ litexml: operation.litexml,
+ };
+ }
+
+ case 'remove': {
+ return {
+ action: 'remove',
+ delay: true,
+ id: operation.id,
+ };
+ }
+ }
+};
+
+export interface AgentDocumentEditorSnapshot {
+ content: string;
+ editorData: AgentDocumentEditorData;
+ litexml?: string;
+}
+
+interface LoadEditorStateParams {
+ editorData?: AgentDocumentEditorData | null;
+ fallbackContent?: string;
+}
+
+const exportSnapshot = (
+ editor: ReturnType<(typeof import('@lobehub/editor/headless'))['createHeadlessEditor']>,
+ litexml = false,
+): AgentDocumentEditorSnapshot => {
+ const snapshot = editor.export({ litexml });
+
+ return {
+ content: snapshot.markdown,
+ editorData: snapshot.editorData as SerializedEditorState<SerializedLexicalNode>,
+ litexml: snapshot.litexml,
+ };
+};
+
+const loadEditorState = (
+ editor: ReturnType<(typeof import('@lobehub/editor/headless'))['createHeadlessEditor']>,
+ { editorData, fallbackContent = '' }: LoadEditorStateParams,
+) => {
+ if (isValidEditorData(editorData)) {
+ editor.hydrateEditorData(
+ editorData as unknown as SerializedEditorState<SerializedLexicalNode>,
+ {
+ keepId: true,
+ },
+ );
+ return;
+ }
+
+ editor.hydrateMarkdown(fallbackContent, { keepId: true });
+};
+
+export const createMarkdownEditorSnapshot = async (
+ content: string,
+): Promise<AgentDocumentEditorSnapshot> => {
+ const { createHeadlessEditor } = await import('@lobehub/editor/headless');
+ const editor = createHeadlessEditor();
+
+ try {
+ editor.hydrateMarkdown(content);
+ return exportSnapshot(editor);
+ } finally {
+ editor.destroy();
+ }
+};
+
+export const exportEditorDataSnapshot = async (
+ params: LoadEditorStateParams & { litexml?: boolean },
+): Promise<AgentDocumentEditorSnapshot> => {
+ const { createHeadlessEditor } = await import('@lobehub/editor/headless');
+ const editor = createHeadlessEditor();
+
+ try {
+ loadEditorState(editor, params);
+ return exportSnapshot(editor, params.litexml);
+ } finally {
+ editor.destroy();
+ }
+};
+
+export const applyLiteXMLOperations = async ({
+ editorData,
+ fallbackContent,
+ operations,
+}: LoadEditorStateParams & {
+ operations: AgentDocumentLiteXMLOperation[];
+}): Promise<AgentDocumentEditorSnapshot> => {
+ const { createHeadlessEditor } = await import('@lobehub/editor/headless');
+ const editor = createHeadlessEditor();
+
+ try {
+ loadEditorState(editor, { editorData, fallbackContent });
+ await editor.applyLiteXML(orderLiteXMLOperations(operations).map(toHeadlessLiteXMLOperation));
+ return exportSnapshot(editor, true);
+ } finally {
+ editor.destroy();
+ }
+};
diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.ts
index fc81735b30f..25a64893ecc 100644
--- a/src/server/services/agentRuntime/types.ts
+++ b/src/server/services/agentRuntime/types.ts
@@ -149,7 +149,9 @@ export interface OperationCreationParams {
agentConfig?: any;
appContext: {
agentId?: string;
+ documentId?: string | null;
groupId?: string | null;
+ scope?: string | null;
taskId?: string;
threadId?: string | null;
topicId?: string | null;
diff --git a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index 15c875d56ce..b103d914ffd 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -1,6 +1,9 @@
+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
+
import { AiAgentService } from '../index';
const { mockCreateOperation, mockGetAgentConfig, mockMessageCreate } = vi.hoisted(() => ({
@@ -210,4 +213,46 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
const callArgs = mockCreateOperation.mock.calls[0][0];
expect(callArgs.agentConfig.systemRole).toBe('');
});
+
+ it('should inject page-agent runtime for regular agents in page scope', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: { enableHistoryCount: true },
+ id: 'agent-custom',
+ model: 'gpt-4',
+ plugins: ['lobe-agent-documents'],
+ provider: 'openai',
+ systemRole: 'Custom role.',
+ });
+
+ await service.execAgent({
+ agentId: 'agent-custom',
+ appContext: {
+ documentId: 'docs-1',
+ scope: 'page',
+ topicId: 'topic-1',
+ },
+ prompt: 'Rewrite this page',
+ });
+
+ const callArgs = mockCreateOperation.mock.calls[0][0];
+ expect(callArgs.appContext).toMatchObject({
+ documentId: 'docs-1',
+ scope: 'page',
+ });
+ expect(callArgs.agentConfig.plugins).toEqual([PageAgentIdentifier, 'lobe-agent-documents']);
+ expect(callArgs.agentConfig.chatConfig.enableHistoryCount).toBe(false);
+ expect(callArgs.agentConfig.systemRole).toContain('Custom role.');
+ expect(callArgs.agentConfig.systemRole).toContain(
+ 'You are a helpful document (page) editing assistant',
+ );
+
+ expect(createServerAgentToolsEngine).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ agentConfig: expect.objectContaining({
+ plugins: [PageAgentIdentifier, 'lobe-agent-documents'],
+ }),
+ }),
+ );
+ });
});
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index a1ff4b849d7..de863ae4547 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -3,6 +3,7 @@ import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-ag
import { builtinSkills } from '@lobechat/builtin-skills';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';
+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import {
type DeviceAttachment,
generateSystemPrompt,
@@ -356,6 +357,33 @@ export class AiAgentService {
}
}
+ if (appContext?.scope !== 'page') {
+ agentConfig.plugins = agentConfig.plugins?.filter((id) => id !== PageAgentIdentifier);
+ }
+
+ if (appContext?.scope === 'page' && agentSlug !== BUILTIN_AGENT_SLUGS.pageAgent) {
+ const pageAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.pageAgent, {
+ model: agentConfig.model,
+ plugins: agentConfig.plugins ?? [],
+ });
+ const pageAgentSystemRole = pageAgentRuntime?.systemRole || '';
+
+ if (pageAgentSystemRole) {
+ agentConfig.systemRole = agentConfig.systemRole
+ ? `${agentConfig.systemRole}\n\n${pageAgentSystemRole}`
+ : pageAgentSystemRole;
+ }
+
+ agentConfig.plugins = agentConfig.plugins?.includes(PageAgentIdentifier)
+ ? agentConfig.plugins
+ : [PageAgentIdentifier, ...(agentConfig.plugins ?? [])];
+ agentConfig.chatConfig = {
+ ...agentConfig.chatConfig,
+ enableHistoryCount: false,
+ };
+ log('execAgent: injected page-agent runtime for page scope');
+ }
+
await throwIfExecutionAborted('agent configuration');
// 2.5. Append additional instructions to agent's systemRole
@@ -1326,6 +1354,39 @@ export class AiAgentService {
},
};
+ if (appContext?.scope !== 'page' && appContext?.documentId && topicId) {
+ try {
+ const topicDocuments = await this.agentDocumentsService.listDocumentsForTopic(
+ resolvedAgentId,
+ topicId,
+ );
+ const activeTopicDocument = topicDocuments.find(
+ (document) => document.documentId === appContext.documentId,
+ );
+
+ initialContext = {
+ ...initialContext,
+ initialContext: {
+ activeTopicDocument: {
+ agentDocumentId: activeTopicDocument?.id,
+ documentId: appContext.documentId,
+ title: activeTopicDocument?.title,
+ },
+ },
+ };
+ } catch (error) {
+ log('execAgent: failed to resolve active topic document context: %O', error);
+ initialContext = {
+ ...initialContext,
+ initialContext: {
+ activeTopicDocument: {
+ documentId: appContext.documentId,
+ },
+ },
+ };
+ }
+ }
+
// 16b. Human-approval resume — override initialContext based on the
// user's decision. The DB write above has already persisted the
// intervention status, so `allMessages` reflects the decision for the
@@ -1347,6 +1408,7 @@ export class AiAgentService {
// the plugin row fetched above; missing any of identifier/apiName
// breaks the server-side tool executor dispatch.
initialContext = {
+ initialContext: initialContext.initialContext,
payload: {
approvedToolCall: {
apiName: resumeApprovalPlugin.apiName,
@@ -1439,7 +1501,9 @@ export class AiAgentService {
userTimezone,
appContext: {
agentId: resolvedAgentId,
+ documentId: appContext?.documentId,
groupId: appContext?.groupId,
+ scope: appContext?.scope,
taskId,
threadId: appContext?.threadId,
topicId,
diff --git a/src/server/services/document/__tests__/history.integration.test.ts b/src/server/services/document/__tests__/history.integration.test.ts
index f2b6daa48e3..d0657efb3b0 100644
--- a/src/server/services/document/__tests__/history.integration.test.ts
+++ b/src/server/services/document/__tests__/history.integration.test.ts
@@ -57,6 +57,36 @@ const createTestDocument = async (content: string, editorData?: Record<string, a
return doc;
};
+const createValidEditorData = (text: string) => ({
+ root: {
+ children: [
+ {
+ children: [
+ {
+ detail: 0,
+ format: 0,
+ mode: 'normal',
+ style: '',
+ text,
+ type: 'text',
+ version: 1,
+ },
+ ],
+ direction: 'ltr',
+ format: '',
+ indent: 0,
+ type: 'paragraph',
+ version: 1,
+ },
+ ],
+ direction: 'ltr',
+ format: '',
+ indent: 0,
+ type: 'root',
+ version: 1,
+ },
+});
+
describe('DocumentHistoryService', () => {
describe('createHistory & listDocumentHistory', () => {
it('should create history entries and list them with head included', async () => {
@@ -435,7 +465,8 @@ describe('DocumentHistoryService', () => {
describe('getDocumentHistoryItem', () => {
it('should resolve head as current document state', async () => {
- const doc = await createTestDocument('Head content', { blocks: [] });
+ const editorData = createValidEditorData('Head content');
+ const doc = await createTestDocument('Head content', editorData);
const result = await historyService.getDocumentHistoryItem({
documentId: doc.id,
@@ -444,7 +475,7 @@ describe('DocumentHistoryService', () => {
expect(result.id).toBe('head');
expect(result.isCurrent).toBe(true);
- expect(result.editorData).toEqual({ blocks: [] });
+ expect(result.editorData).toEqual(editorData);
expect(result.saveSource).toBe('system');
});
@@ -538,7 +569,8 @@ describe('DocumentHistoryService', () => {
describe('compareDocumentHistoryItems', () => {
it('should compare a history item against head', async () => {
- const doc = await createTestDocument('Current', { current: true });
+ const currentEditorData = createValidEditorData('Current');
+ const doc = await createTestDocument('Current', currentEditorData);
await historyService.createHistory({
documentId: doc.id,
@@ -559,7 +591,7 @@ describe('DocumentHistoryService', () => {
});
expect(result.from.editorData).toEqual({ old: true });
- expect(result.to.editorData).toEqual({ current: true });
+ expect(result.to.editorData).toEqual(currentEditorData);
expect(result.to.isCurrent).toBe(true);
});
});
diff --git a/src/server/services/document/__tests__/index.test.ts b/src/server/services/document/__tests__/index.test.ts
index db367fc0842..08a66f09141 100644
--- a/src/server/services/document/__tests__/index.test.ts
+++ b/src/server/services/document/__tests__/index.test.ts
@@ -21,6 +21,42 @@ vi.mock('debug', () => ({
const { loadFile } = await import('@lobechat/file-loaders');
+const createEditorDataWithDiffNode = () => ({
+ root: {
+ children: [
+ {
+ children: [
+ { children: [{ text: 'origin', type: 'text' }], type: 'paragraph' },
+ { children: [{ text: 'modified', type: 'text' }], type: 'paragraph' },
+ ],
+ diffType: 'modify',
+ type: 'diff',
+ },
+ {
+ children: [{ children: [{ text: 'added', type: 'text' }], type: 'paragraph' }],
+ diffType: 'add',
+ type: 'diff',
+ },
+ {
+ children: [{ children: [{ text: 'removed', type: 'text' }], type: 'paragraph' }],
+ diffType: 'remove',
+ type: 'diff',
+ },
+ ],
+ type: 'root',
+ },
+});
+
+const normalizedEditorDataFromDiffNode = {
+ root: {
+ children: [
+ { children: [{ text: 'origin', type: 'text' }], type: 'paragraph' },
+ { children: [{ text: 'removed', type: 'text' }], type: 'paragraph' },
+ ],
+ type: 'root',
+ },
+};
+
describe('DocumentService', () => {
let service: DocumentService;
let mockDb: LobeChatDatabase;
@@ -568,6 +604,50 @@ describe('DocumentService', () => {
expect(result.savedAt).toBeInstanceOf(Date);
});
+ it('should persist raw editorData with diff nodes and normalize only the history snapshot', async () => {
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ { children: [{ text: 'next origin', type: 'text' }], type: 'paragraph' },
+ { children: [{ text: 'next modified', type: 'text' }], type: 'paragraph' },
+ ],
+ diffType: 'modify',
+ type: 'diff',
+ },
+ {
+ children: [{ children: [{ text: 'next added', type: 'text' }], type: 'paragraph' }],
+ diffType: 'add',
+ type: 'diff',
+ },
+ ],
+ },
+ };
+ mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });
+ mockDocumentModel.findById.mockResolvedValue(
+ createCurrentDocument({ editorData: createEditorDataWithDiffNode() }),
+ );
+
+ const result = await service.updateDocument('doc-1', { editorData, saveSource: 'manual' });
+
+ // Persisted editorData keeps the diff nodes — DiffAllToolbar can render
+ // them for human review on next open.
+ expect(mockDocumentModel.update).toHaveBeenCalledWith(
+ 'doc-1',
+ expect.objectContaining({ editorData }),
+ );
+ // History snapshot still captures the pre-update accepted view.
+ expect(mockDocumentHistoryService.createHistory).toHaveBeenCalledWith(
+ expect.objectContaining({
+ documentId: 'doc-1',
+ editorData: normalizedEditorDataFromDiffNode,
+ saveSource: 'manual',
+ }),
+ );
+ expect(result.historyAppended).toBe(true);
+ });
+
it('should skip history when editorData is unchanged', async () => {
const editorData = { blocks: [] };
mockDocumentModel.update.mockResolvedValue({ id: 'doc-1' });
@@ -702,6 +782,21 @@ describe('DocumentService', () => {
expect(result.savedAt).toBeInstanceOf(Date);
});
+ it('should create history with diff nodes normalized to their origin content', async () => {
+ mockDocumentModel.findById.mockResolvedValue({ id: 'doc-1', editorData: { blocks: [] } });
+ mockDocumentHistoryService.createHistory.mockResolvedValue(undefined);
+
+ await service.saveDocumentHistory('doc-1', createEditorDataWithDiffNode(), 'llm_call');
+
+ expect(mockDocumentHistoryService.createHistory).toHaveBeenCalledWith(
+ expect.objectContaining({
+ documentId: 'doc-1',
+ editorData: normalizedEditorDataFromDiffNode,
+ saveSource: 'llm_call',
+ }),
+ );
+ });
+
it('should throw when document does not exist', async () => {
mockDocumentModel.findById.mockResolvedValue(undefined);
@@ -712,6 +807,75 @@ describe('DocumentService', () => {
});
});
+ describe('trySaveCurrentDocumentHistory', () => {
+ it('should create a history entry from the current document editor data', async () => {
+ const editorData = {
+ root: { children: [{ children: [], type: 'paragraph' }], type: 'root' },
+ };
+ mockDocumentModel.findById.mockResolvedValue({ editorData, id: 'doc-1' });
+ mockDocumentHistoryService.createHistory.mockResolvedValue(undefined);
+
+ const result = await service.trySaveCurrentDocumentHistory('doc-1', 'llm_call');
+
+ expect(mockDocumentHistoryService.createHistory).toHaveBeenCalledWith(
+ expect.objectContaining({
+ documentId: 'doc-1',
+ editorData,
+ saveSource: 'llm_call',
+ savedAt: expect.any(Date),
+ }),
+ );
+ expect(result?.savedAt).toBeInstanceOf(Date);
+ });
+
+ it('should snapshot current document history with diff nodes normalized to origin content', async () => {
+ mockDocumentModel.findById.mockResolvedValue({
+ editorData: createEditorDataWithDiffNode(),
+ id: 'doc-1',
+ });
+ mockDocumentHistoryService.createHistory.mockResolvedValue(undefined);
+
+ const result = await service.trySaveCurrentDocumentHistory('doc-1', 'llm_call');
+
+ expect(mockDocumentHistoryService.createHistory).toHaveBeenCalledWith(
+ expect.objectContaining({
+ documentId: 'doc-1',
+ editorData: normalizedEditorDataFromDiffNode,
+ saveSource: 'llm_call',
+ }),
+ );
+ expect(result?.savedAt).toBeInstanceOf(Date);
+ });
+
+ it('should skip history when the current editor data is empty', async () => {
+ mockDocumentModel.findById.mockResolvedValue({ editorData: {}, id: 'doc-1' });
+
+ const result = await service.trySaveCurrentDocumentHistory('doc-1', 'llm_call');
+
+ expect(result).toBeUndefined();
+ expect(mockDocumentHistoryService.createHistory).not.toHaveBeenCalled();
+ });
+
+ it('should not block the caller when history creation fails', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockDocumentModel.findById.mockResolvedValue({
+ editorData: { root: { children: [{ children: [], type: 'paragraph' }], type: 'root' } },
+ id: 'doc-1',
+ });
+ mockDocumentHistoryService.createHistory.mockRejectedValueOnce(new Error('history failed'));
+
+ await expect(
+ service.trySaveCurrentDocumentHistory('doc-1', 'llm_call'),
+ ).resolves.toBeUndefined();
+
+ expect(consoleError).toHaveBeenCalledWith(
+ '[DocumentService] Failed to save current document history:',
+ expect.any(Error),
+ );
+ consoleError.mockRestore();
+ });
+ });
+
describe('parseDocument', () => {
const mockCleanup = vi.fn();
diff --git a/src/server/services/document/index.ts b/src/server/services/document/index.ts
index 207327b72d7..34ea5f4fb3a 100644
--- a/src/server/services/document/index.ts
+++ b/src/server/services/document/index.ts
@@ -8,6 +8,8 @@ import isEqual from 'fast-deep-equal';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
+import { isValidEditorData } from '@/libs/editor/isValidEditorData';
+import { normalizeEditorDataDiffNodes } from '@/libs/editor/normalizeDiffNodes';
import { type LobeDocument } from '@/types/document';
import { FileService } from '../file';
@@ -203,10 +205,11 @@ export class DocumentService {
throw new Error(`Document not found: ${documentId}`);
}
+ const normalizedEditorData = normalizeEditorDataDiffNodes(editorData);
const savedAt = new Date();
await this.documentHistoryService.createHistory({
documentId,
- editorData,
+ editorData: normalizedEditorData,
saveSource,
savedAt,
});
@@ -214,6 +217,34 @@ export class DocumentService {
return { savedAt };
}
+ /**
+ * Best-effort snapshot of the current document editor state before an automated mutation.
+ */
+ async trySaveCurrentDocumentHistory(
+ documentId: string,
+ saveSource: DocumentHistorySaveSource,
+ ): Promise<SaveDocumentHistoryResult | undefined> {
+ try {
+ const currentDocument = await this.documentModel.findById(documentId);
+ const editorData = currentDocument?.editorData;
+ if (!isValidEditorData(editorData)) return undefined;
+
+ const normalizedEditorData = normalizeEditorDataDiffNodes(editorData);
+ const savedAt = new Date();
+ await this.documentHistoryService.createHistory({
+ documentId,
+ editorData: normalizedEditorData,
+ saveSource,
+ savedAt,
+ });
+
+ return { savedAt };
+ } catch (error) {
+ console.error('[DocumentService] Failed to save current document history:', error);
+ return undefined;
+ }
+ }
+
/**
* Delete document (recursively deletes children if it's a folder)
*/
@@ -274,10 +305,20 @@ export class DocumentService {
throw new Error(`Document not found: ${id}`);
}
- const currentEditorData = (currentDocument.editorData ?? {}) as Record<string, any>;
- const nextEditorData = params.editorData;
+ // Accepted-view projections used only for historyAppended comparison and
+ // for the "before" snapshot written into history. The persisted editorData
+ // keeps any pending diff nodes — they're only normalized when the user
+ // explicitly accepts/rejects via DiffAllToolbar.
+ const currentEditorDataAccepted = normalizeEditorDataDiffNodes(
+ (currentDocument.editorData ?? {}) as Record<string, any>,
+ );
+ const nextEditorDataAccepted =
+ params.editorData === undefined
+ ? undefined
+ : normalizeEditorDataDiffNodes(params.editorData);
const historyAppended =
- nextEditorData !== undefined && !isEqual(nextEditorData, currentEditorData);
+ nextEditorDataAccepted !== undefined &&
+ !isEqual(nextEditorDataAccepted, currentEditorDataAccepted);
const updates: Record<string, unknown> = {};
@@ -314,7 +355,7 @@ export class DocumentService {
savedAt = new Date();
await documentHistoryService.createHistory({
documentId: id,
- editorData: currentEditorData,
+ editorData: currentEditorDataAccepted,
saveSource: params.saveSource ?? 'autosave',
savedAt,
});
diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts
index b031ad2c383..2e774530cd6 100644
--- a/src/server/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts
+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts
@@ -27,8 +27,11 @@ describe('AgentDocumentsExecutionRuntime.createDocument', () => {
const makeStub = () => ({
copyDocument: vi.fn(),
createDocument: vi.fn(),
+ createTopicDocument: vi.fn(),
editDocument: vi.fn(),
listDocuments: vi.fn(),
+ listTopicDocuments: vi.fn(),
+ modifyNodes: vi.fn(),
readDocument: vi.fn(),
readDocumentByFilename: vi.fn(),
removeDocument: vi.fn(),
@@ -65,4 +68,192 @@ describe('AgentDocumentsExecutionRuntime.createDocument', () => {
expect(result.success).toBe(false);
expect(stub.createDocument).not.toHaveBeenCalled();
});
+
+ it('creates a document in the current topic when target is currentTopic', async () => {
+ const stub = makeStub();
+ stub.createTopicDocument.mockResolvedValue({
+ documentId: 'documents-row-id',
+ filename: 'topic-note',
+ id: 'agent-doc-assoc-id',
+ title: 'Topic Note',
+ });
+
+ const runtime = new AgentDocumentsExecutionRuntime(stub);
+ const result = await runtime.createDocument(
+ { content: 'body', target: 'currentTopic', title: 'Topic Note' },
+ { agentId: 'agent-1', topicId: 'topic-1' },
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.state).toEqual({ documentId: 'documents-row-id' });
+ expect(stub.createTopicDocument).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ content: 'body',
+ target: 'currentTopic',
+ title: 'Topic Note',
+ topicId: 'topic-1',
+ });
+ expect(stub.createDocument).not.toHaveBeenCalled();
+ });
+
+ it('refuses current topic creation without topicId', async () => {
+ const stub = makeStub();
+ const runtime = new AgentDocumentsExecutionRuntime(stub);
+
+ const result = await runtime.createDocument(
+ { content: 'body', target: 'currentTopic', title: 'Topic Note' },
+ { agentId: 'agent-1' },
+ );
+
+ expect(result).toMatchObject({
+ content: 'Cannot create current topic document without topicId context.',
+ success: false,
+ });
+ expect(stub.createTopicDocument).not.toHaveBeenCalled();
+ });
+
+ it('blocks editDocument for the current page document', async () => {
+ const stub = makeStub();
+ stub.readDocument.mockResolvedValue({
+ content: 'body',
+ documentId: 'documents-row-id',
+ id: 'agent-doc-assoc-id',
+ title: 'Daily Brief',
+ });
+
+ const runtime = new AgentDocumentsExecutionRuntime(stub);
+ const result = await runtime.editDocument(
+ { content: 'updated', id: 'agent-doc-assoc-id' },
+ {
+ agentId: 'agent-1',
+ currentDocumentId: 'documents-row-id',
+ scope: 'page',
+ },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({
+ code: 'CURRENT_PAGE_DOCUMENT_WRITE_FORBIDDEN',
+ kind: 'replan',
+ });
+ expect(stub.editDocument).not.toHaveBeenCalled();
+ });
+
+ it('blocks upsertDocumentByFilename when the filename resolves to the current page document', async () => {
+ const stub = makeStub();
+ stub.listDocuments.mockResolvedValue([
+ {
+ documentId: 'documents-row-id',
+ filename: 'current-doc.md',
+ id: 'agent-doc-assoc-id',
+ title: 'Current Doc',
+ },
+ ]);
+
+ const runtime = new AgentDocumentsExecutionRuntime(stub);
+ const result = await runtime.upsertDocumentByFilename(
+ { content: 'updated', filename: 'current-doc.md' },
+ {
+ agentId: 'agent-1',
+ currentDocumentId: 'documents-row-id',
+ scope: 'page',
+ },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({
+ code: 'CURRENT_PAGE_DOCUMENT_WRITE_FORBIDDEN',
+ kind: 'replan',
+ });
+ expect(stub.upsertDocumentByFilename).not.toHaveBeenCalled();
+ });
+
+ it('still allows editing a different agent document in page scope', async () => {
+ const stub = makeStub();
+ stub.readDocument.mockResolvedValue({
+ content: 'body',
+ documentId: 'documents-row-id-2',
+ id: 'agent-doc-assoc-id-2',
+ title: 'Other Doc',
+ });
+ stub.editDocument.mockResolvedValue({
+ content: 'updated',
+ documentId: 'documents-row-id-2',
+ id: 'agent-doc-assoc-id-2',
+ title: 'Other Doc',
+ });
+
+ const runtime = new AgentDocumentsExecutionRuntime(stub);
+ const result = await runtime.editDocument(
+ { content: 'updated', id: 'agent-doc-assoc-id-2' },
+ {
+ agentId: 'agent-1',
+ currentDocumentId: 'documents-row-id',
+ scope: 'page',
+ },
+ );
+
+ expect(result.success).toBe(true);
+ expect(stub.editDocument).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ content: 'updated',
+ id: 'agent-doc-assoc-id-2',
+ });
+ });
+});
+
+describe('AgentDocumentsExecutionRuntime.listDocuments', () => {
+ const makeStub = () => ({
+ copyDocument: vi.fn(),
+ createDocument: vi.fn(),
+ createTopicDocument: vi.fn(),
+ editDocument: vi.fn(),
+ listDocuments: vi.fn(),
+ listTopicDocuments: vi.fn(),
+ modifyNodes: vi.fn(),
+ readDocument: vi.fn(),
+ readDocumentByFilename: vi.fn(),
+ removeDocument: vi.fn(),
+ renameDocument: vi.fn(),
+ updateLoadRule: vi.fn(),
+ upsertDocumentByFilename: vi.fn(),
+ });
+
+ it('lists current topic documents while preserving agent document ids', async () => {
+ const stub = makeStub();
+ stub.listTopicDocuments.mockResolvedValue([
+ {
+ documentId: 'documents-row-id',
+ filename: 'topic-note',
+ id: 'agent-doc-assoc-id',
+ title: 'Topic Note',
+ },
+ ]);
+
+ const runtime = new AgentDocumentsExecutionRuntime(stub);
+ const result = await runtime.listDocuments(
+ { target: 'currentTopic' },
+ { agentId: 'agent-1', topicId: 'topic-1' },
+ );
+
+ const documents = [
+ {
+ documentId: 'documents-row-id',
+ filename: 'topic-note',
+ id: 'agent-doc-assoc-id',
+ title: 'Topic Note',
+ },
+ ];
+ expect(result).toEqual({
+ content: JSON.stringify(documents),
+ state: { documents },
+ success: true,
+ });
+ expect(stub.listTopicDocuments).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ target: 'currentTopic',
+ topicId: 'topic-1',
+ });
+ expect(stub.listDocuments).not.toHaveBeenCalled();
+ });
});
diff --git a/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts b/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts
index 1f8228c58c1..12b7e6cea4d 100644
--- a/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts
+++ b/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts
@@ -18,14 +18,32 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {
copyDocument: ({ agentId, id, newTitle }) => service.copyDocumentById(id, newTitle, agentId),
createDocument: ({ agentId, content, title }) =>
service.createDocument(agentId, title, content),
+ createTopicDocument: ({ agentId, content, title, topicId }) =>
+ service.createForTopic(agentId, title, content, topicId),
editDocument: ({ agentId, content, id }) => service.editDocumentById(id, content, agentId),
listDocuments: async ({ agentId }) => {
const docs = await service.listDocuments(agentId);
- return docs.map((d) => ({ filename: d.filename, id: d.id, title: d.title }));
+ return docs.map((d) => ({
+ documentId: d.documentId,
+ filename: d.filename,
+ id: d.id,
+ title: d.title,
+ }));
},
- readDocument: ({ agentId, id }) => service.getDocumentById(id, agentId),
+ listTopicDocuments: async ({ agentId, topicId }) => {
+ const docs = await service.listDocumentsForTopic(agentId, topicId);
+ return docs.map((d) => ({
+ documentId: d.documentId,
+ filename: d.filename,
+ id: d.id,
+ title: d.title,
+ }));
+ },
+ modifyNodes: ({ agentId, id, operations }) =>
+ service.modifyDocumentNodesById(id, operations, agentId),
+ readDocument: ({ agentId, id }) => service.getDocumentSnapshotById(id, agentId),
readDocumentByFilename: ({ agentId, filename }) =>
- service.getDocumentByFilename(agentId, filename),
+ service.getDocumentSnapshotByFilename(agentId, filename),
removeDocument: ({ agentId, id }) => service.removeDocumentById(id, agentId),
renameDocument: ({ agentId, id, newTitle }) =>
service.renameDocumentById(id, newTitle, agentId),
diff --git a/src/server/services/toolExecution/types.ts b/src/server/services/toolExecution/types.ts
index aac2e000789..f71b7b7e55c 100644
--- a/src/server/services/toolExecution/types.ts
+++ b/src/server/services/toolExecution/types.ts
@@ -7,8 +7,12 @@ export interface ToolExecutionContext {
activeDeviceId?: string;
/** Agent ID executing the tool call */
agentId?: string;
+ /** Current page document ID for page-scoped conversations */
+ documentId?: string | null;
/** Memory tool permission from agent chat config */
memoryToolPermission?: 'read-only' | 'read-write';
+ /** Conversation scope captured when the operation was created */
+ scope?: string | null;
/** Server database for LobeHub Skills execution */
serverDB?: LobeChatDatabase;
/** Task ID when executing within the Task system */
diff --git a/src/services/agentDocument.test.ts b/src/services/agentDocument.test.ts
index 8b1b2b1512f..00d1d0fd519 100644
--- a/src/services/agentDocument.test.ts
+++ b/src/services/agentDocument.test.ts
@@ -60,10 +60,18 @@ describe('AgentDocumentService', () => {
it('should revalidate agent documents after removeDocument', async () => {
await agentDocumentService.removeDocument({
agentId: 'agent-1',
+ documentId: 'page-doc-1',
id: 'doc-1',
+ topicId: 'topic-1',
});
expect(mutate).toHaveBeenCalledWith(['agent-documents', 'agent-1']);
+ expect(mutate).toHaveBeenCalledWith(['agent-documents-list', 'agent-1']);
+ expect(mutate).toHaveBeenCalledWith(['workspace-agent-document-editor', 'agent-1', 'doc-1']);
+ expect(mutate).toHaveBeenCalledWith(['page-document-meta', 'page-doc-1']);
+ expect(mutate).toHaveBeenCalledWith(['pageDetail', 'page-doc-1']);
+ expect(mutate).toHaveBeenCalledWith(['pageDocuments']);
+ expect(mutate).toHaveBeenCalledWith(['SWR_USE_FETCH_NOTEBOOK_DOCUMENTS', 'topic-1']);
});
it('should revalidate agent documents after updateLoadRule', async () => {
diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.ts
index 6ba7a4506bc..b3e7228279b 100644
--- a/src/services/agentDocument.ts
+++ b/src/services/agentDocument.ts
@@ -4,20 +4,10 @@ import {
type AgentContextDocument,
} from '@lobechat/context-engine';
-import { mutate } from '@/libs/swr';
import { lambdaClient } from '@/libs/trpc/client';
+import { invalidateDocumentMutation } from '@/services/document/invalidation';
-export const agentDocumentSWRKeys = {
- documents: (agentId: string) => ['agent-documents', agentId] as const,
- /**
- * UI-side list: raw AgentDocumentWithRules (includes documentId, sourceType, createdAt).
- * Kept separate from `documents` because the agent store writes mapAgentDocumentsToContext(...)
- * under that key, which drops those fields.
- */
- documentsList: (agentId: string) => ['agent-documents-list', agentId] as const,
- readDocument: (agentId: string, id: string) =>
- ['workspace-agent-document-editor', agentId, id] as const,
-};
+export { agentDocumentSWRKeys } from '@/services/document/swrKeys';
const VALID_DOCUMENT_POSITIONS = new Set<AgentContextDocument['loadPosition']>(
AGENT_DOCUMENT_INJECTION_POSITIONS,
@@ -34,14 +24,21 @@ export const normalizeAgentDocumentPosition = (
};
const revalidateAgentDocuments = async (agentId: string) => {
- await mutate(agentDocumentSWRKeys.documents(agentId));
- await mutate(agentDocumentSWRKeys.documentsList(agentId));
+ await invalidateDocumentMutation({ agentId, cause: 'agent-document' });
};
-const revalidateReadDocument = async (agentId: string, id: string) => {
- await mutate(agentDocumentSWRKeys.readDocument(agentId, id));
+const getStringField = (value: unknown, field: 'documentId' | 'id') => {
+ if (!value || typeof value !== 'object' || !(field in value)) return undefined;
+
+ const fieldValue = (value as Record<string, unknown>)[field];
+
+ return typeof fieldValue === 'string' ? fieldValue : undefined;
};
+const getAgentDocumentId = (value: unknown) => getStringField(value, 'id');
+
+const getDocumentId = (value: unknown) => getStringField(value, 'documentId');
+
class AgentDocumentService {
getTemplates = async () => {
return lambdaClient.agentDocument.getTemplates.query();
@@ -58,11 +55,19 @@ class AgentDocumentService {
return result;
};
- listDocuments = async (params: { agentId: string }) => {
+ listDocuments = async (params: {
+ agentId: string;
+ target?: 'agent' | 'currentTopic';
+ topicId?: string;
+ }) => {
return lambdaClient.agentDocument.listDocuments.query(params);
};
- readDocumentByFilename = async (params: { agentId: string; filename: string }) => {
+ readDocumentByFilename = async (params: {
+ agentId: string;
+ filename: string;
+ format?: 'xml' | 'markdown' | 'both';
+ }) => {
return lambdaClient.agentDocument.readDocumentByFilename.query(params);
};
@@ -72,54 +77,152 @@ class AgentDocumentService {
filename: string;
}) => {
const result = await lambdaClient.agentDocument.upsertDocumentByFilename.mutate(params);
- await revalidateAgentDocuments(params.agentId);
+ await invalidateDocumentMutation({
+ agentDocumentId: getAgentDocumentId(result),
+ agentId: params.agentId,
+ cause: 'agent-document',
+ documentId: getDocumentId(result),
+ });
return result;
};
associateDocument = async (params: { agentId: string; documentId: string }) => {
const result = await lambdaClient.agentDocument.associateDocument.mutate(params);
- await revalidateAgentDocuments(params.agentId);
+ await invalidateDocumentMutation({
+ agentDocumentId: getAgentDocumentId(result),
+ agentId: params.agentId,
+ cause: 'agent-document',
+ documentId: params.documentId,
+ });
return result;
};
createDocument = async (params: { agentId: string; content: string; title: string }) => {
const result = await lambdaClient.agentDocument.createDocument.mutate(params);
- await revalidateAgentDocuments(params.agentId);
+ await invalidateDocumentMutation({
+ agentDocumentId: getAgentDocumentId(result),
+ agentId: params.agentId,
+ cause: 'agent-document',
+ documentId: getDocumentId(result),
+ });
return result;
};
- readDocument = async (params: { agentId: string; id: string }) => {
+ createForTopic = async (params: {
+ agentId: string;
+ content: string;
+ title: string;
+ topicId: string;
+ }) => {
+ const result = await lambdaClient.agentDocument.createForTopic.mutate(params);
+ await invalidateDocumentMutation({
+ agentDocumentId: getAgentDocumentId(result),
+ agentId: params.agentId,
+ cause: 'agent-document',
+ documentId: getDocumentId(result),
+ topicId: params.topicId,
+ });
+
+ return result;
+ };
+
+ readDocument = async (params: {
+ agentId: string;
+ format?: 'xml' | 'markdown' | 'both';
+ id: string;
+ }) => {
return lambdaClient.agentDocument.readDocument.query(params);
};
editDocument = async (params: { agentId: string; content: string; id: string }) => {
const result = await lambdaClient.agentDocument.editDocument.mutate(params);
- await revalidateAgentDocuments(params.agentId);
+ await invalidateDocumentMutation({
+ agentDocumentId: params.id,
+ agentId: params.agentId,
+ cause: 'agent-document',
+ documentId: getDocumentId(result),
+ });
return result;
};
- removeDocument = async (params: { agentId: string; id: string }) => {
- const result = await lambdaClient.agentDocument.removeDocument.mutate(params);
- await revalidateAgentDocuments(params.agentId);
+ modifyNodes = async (params: {
+ agentId: string;
+ id: string;
+ operations: Array<
+ | {
+ action: 'insert';
+ afterId: string;
+ litexml: string;
+ }
+ | {
+ action: 'insert';
+ beforeId: string;
+ litexml: string;
+ }
+ | {
+ action: 'modify';
+ litexml: string | string[];
+ }
+ | {
+ action: 'remove';
+ id: string;
+ }
+ >;
+ }) => {
+ const result = await lambdaClient.agentDocument.modifyNodes.mutate(params);
+ await invalidateDocumentMutation({
+ agentDocumentId: params.id,
+ agentId: params.agentId,
+ cause: 'agent-document',
+ documentId: getDocumentId(result),
+ });
+
+ return result;
+ };
+
+ removeDocument = async (params: {
+ agentId: string;
+ documentId?: string;
+ id: string;
+ topicId?: string;
+ }) => {
+ const { agentId, documentId, id, topicId } = params;
+ const result = await lambdaClient.agentDocument.removeDocument.mutate({ agentId, id });
+ await invalidateDocumentMutation({
+ agentDocumentId: id,
+ agentId,
+ cause: 'agent-document',
+ documentId,
+ topicId,
+ });
return result;
};
copyDocument = async (params: { agentId: string; id: string; newTitle?: string }) => {
const result = await lambdaClient.agentDocument.copyDocument.mutate(params);
- await revalidateAgentDocuments(params.agentId);
+ await invalidateDocumentMutation({
+ agentDocumentId: getAgentDocumentId(result),
+ agentId: params.agentId,
+ cause: 'agent-document',
+ documentId: getDocumentId(result),
+ });
return result;
};
renameDocument = async (params: { agentId: string; id: string; newTitle: string }) => {
const result = await lambdaClient.agentDocument.renameDocument.mutate(params);
- await revalidateAgentDocuments(params.agentId);
- await revalidateReadDocument(params.agentId, params.id);
+ await invalidateDocumentMutation({
+ agentDocumentId: params.id,
+ agentId: params.agentId,
+ cause: 'agent-document',
+ documentId: getDocumentId(result),
+ });
return result;
};
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index a27f9907b4f..5c8d7b7a66b 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -27,6 +27,7 @@ export interface ResumeApprovalParam {
export interface ExecAgentTaskParams {
agentId?: string;
appContext?: {
+ documentId?: string | null;
groupId?: string | null;
scope?: string | null;
sessionId?: string;
diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.ts
index ac7bef7680d..be2ce7d5ae9 100644
--- a/src/services/chat/mecha/agentConfigResolver.test.ts
+++ b/src/services/chat/mecha/agentConfigResolver.test.ts
@@ -621,6 +621,17 @@ describe('resolveAgentConfig', () => {
expect(result.plugins).toEqual([PageAgentIdentifier, 'other-plugin']);
});
+ it('should strip page-agent from explicit plugins outside page scope', () => {
+ const result = resolveAgentConfig({
+ agentId: 'custom-agent',
+ plugins: [PageAgentIdentifier, 'other-plugin'],
+ scope: 'main',
+ });
+
+ expect(result.plugins).toEqual(['other-plugin']);
+ expect(result.plugins).not.toContain(PageAgentIdentifier);
+ });
+
it('should apply chatConfig overrides for page editor', () => {
vi.spyOn(agentSelectors.chatConfigByIdSelectors, 'getChatConfigById').mockReturnValue(
() =>
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index a7ecc938122..69758084354 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -161,7 +161,14 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
log('disableTools is true, returning empty plugins');
return [];
}
- return isSubTask ? pluginIds.filter((id) => id !== 'lobe-gtd') : pluginIds;
+
+ let nextPluginIds = pluginIds;
+
+ if (ctx.scope !== 'page') {
+ nextPluginIds = nextPluginIds.filter((id) => id !== PageAgentIdentifier);
+ }
+
+ return isSubTask ? nextPluginIds.filter((id) => id !== 'lobe-gtd') : nextPluginIds;
};
const agentStoreState = getAgentStoreState();
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 76e5cbdfb43..7c09cd91160 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -15,6 +15,7 @@ import {
} from '@lobechat/builtin-tool-cron';
import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import { WebOnboardingIdentifier } from '@lobechat/builtin-tool-web-onboarding';
import { isDesktop, KLAVIS_SERVER_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';
import type {
@@ -763,6 +764,9 @@ export const contextEngineering = async ({
// Tools configuration
toolsConfig: {
+ disabledToolIdentifiers: tools?.includes(PageAgentIdentifier)
+ ? undefined
+ : [PageAgentIdentifier],
manifests,
tools,
},
diff --git a/src/services/chat/mecha/index.ts b/src/services/chat/mecha/index.ts
index 38a42a02921..22e3b844060 100644
--- a/src/services/chat/mecha/index.ts
+++ b/src/services/chat/mecha/index.ts
@@ -23,3 +23,11 @@ export { resolveModelExtendParams } from './modelParamsResolver';
// Memory management
export type { TopicMemoryResolverContext } from './memoryManager';
export { combineUserMemoryData, resolveTopicMemories, resolveUserPersona } from './memoryManager';
+
+// Tool set composition
+export type {
+ ComposedToolSet,
+ ToolSetComposerContext,
+ ToolSetComposerInput,
+} from './toolSetComposer';
+export { composeEnabledTools } from './toolSetComposer';
diff --git a/src/services/chat/mecha/toolSetComposer.test.ts b/src/services/chat/mecha/toolSetComposer.test.ts
new file mode 100644
index 00000000000..be336307d18
--- /dev/null
+++ b/src/services/chat/mecha/toolSetComposer.test.ts
@@ -0,0 +1,155 @@
+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
+import type { LobeToolManifest, ToolsGenerationResult } from '@lobechat/context-engine';
+import { generateToolsFromManifest } from '@lobechat/context-engine';
+import { describe, expect, it } from 'vitest';
+
+import { composeEnabledTools } from './toolSetComposer';
+
+const makeManifest = (identifier: string, apiName: string): LobeToolManifest => ({
+ api: [
+ {
+ description: `${identifier}.${apiName}`,
+ name: apiName,
+ parameters: { properties: {}, type: 'object' },
+ },
+ ],
+ identifier,
+ meta: { avatar: '🔧', description: identifier, title: identifier },
+ systemRole: '',
+ type: 'builtin',
+});
+
+const makeToolsDetailed = (manifests: LobeToolManifest[]): ToolsGenerationResult => ({
+ enabledManifests: manifests,
+ enabledToolIds: manifests.map((m) => m.identifier),
+ filteredTools: [],
+ tools: manifests.length > 0 ? manifests.flatMap((m) => generateToolsFromManifest(m)) : undefined,
+});
+
+const PAGE_AGENT_MANIFEST = makeManifest(PageAgentIdentifier, 'initPage');
+const OTHER_MANIFEST = makeManifest('lobe-agent-documents', 'readDocument');
+
+describe('composeEnabledTools', () => {
+ describe('mergeInjectedManifests', () => {
+ it('returns base unchanged when no injection and no filter triggers', () => {
+ const toolsDetailed = makeToolsDetailed([OTHER_MANIFEST]);
+
+ const result = composeEnabledTools({
+ context: {},
+ toolsDetailed,
+ });
+
+ expect(result.enabledToolIds).toEqual(['lobe-agent-documents']);
+ expect(result.enabledManifests).toEqual([OTHER_MANIFEST]);
+ expect(result.tools).toEqual(toolsDetailed.tools);
+ });
+
+ it('dedupes injected manifests by identifier', () => {
+ const duplicate = makeManifest('lobe-agent-documents', 'editDocument');
+
+ const result = composeEnabledTools({
+ context: {},
+ injectedManifests: [duplicate],
+ toolsDetailed: makeToolsDetailed([OTHER_MANIFEST]),
+ });
+
+ expect(result.enabledToolIds).toEqual(['lobe-agent-documents']);
+ expect(result.enabledManifests).toEqual([OTHER_MANIFEST]);
+ expect(result.tools?.some((t) => t.function?.name?.includes('editDocument'))).toBe(false);
+ });
+
+ it('appends new injected manifest and adds its tools', () => {
+ const extra = makeManifest('lobe-calculator', 'calc');
+
+ const result = composeEnabledTools({
+ context: {},
+ injectedManifests: [extra],
+ toolsDetailed: makeToolsDetailed([OTHER_MANIFEST]),
+ });
+
+ expect(result.enabledToolIds).toEqual(['lobe-agent-documents', 'lobe-calculator']);
+ expect(result.enabledManifests).toEqual([OTHER_MANIFEST, extra]);
+ expect(result.tools?.some((t) => t.function?.name?.startsWith('lobe-calculator____'))).toBe(
+ true,
+ );
+ });
+
+ it('produces a tools array when base has none but injection brings some', () => {
+ const extra = makeManifest('lobe-calculator', 'calc');
+
+ const result = composeEnabledTools({
+ context: {},
+ injectedManifests: [extra],
+ toolsDetailed: makeToolsDetailed([]),
+ });
+
+ expect(result.enabledToolIds).toEqual(['lobe-calculator']);
+ expect(result.tools).toBeDefined();
+ expect(result.tools).toHaveLength(1);
+ });
+ });
+
+ describe('dropPageAgentIfEditorNotMounted', () => {
+ it('keeps PageAgent when scope is not page', () => {
+ const result = composeEnabledTools({
+ context: { isPageEditorReady: false, scope: undefined },
+ toolsDetailed: makeToolsDetailed([PAGE_AGENT_MANIFEST, OTHER_MANIFEST]),
+ });
+
+ expect(result.enabledToolIds).toContain(PageAgentIdentifier);
+ });
+
+ it('keeps PageAgent when scope is page and editor is ready', () => {
+ const result = composeEnabledTools({
+ context: { isPageEditorReady: true, scope: 'page' },
+ toolsDetailed: makeToolsDetailed([PAGE_AGENT_MANIFEST, OTHER_MANIFEST]),
+ });
+
+ expect(result.enabledToolIds).toContain(PageAgentIdentifier);
+ expect(result.enabledManifests).toContainEqual(PAGE_AGENT_MANIFEST);
+ expect(
+ result.tools?.some((t) => t.function?.name?.startsWith(`${PageAgentIdentifier}____`)),
+ ).toBe(true);
+ });
+
+ it('drops PageAgent from all three outputs when scope is page and editor is not ready', () => {
+ const toolsDetailed = makeToolsDetailed([PAGE_AGENT_MANIFEST, OTHER_MANIFEST]);
+
+ const result = composeEnabledTools({
+ context: { isPageEditorReady: false, scope: 'page' },
+ toolsDetailed,
+ });
+
+ expect(result.enabledToolIds).toEqual(['lobe-agent-documents']);
+ expect(result.enabledManifests).toEqual([OTHER_MANIFEST]);
+ expect(
+ result.tools?.every((t) => !t.function?.name?.startsWith(`${PageAgentIdentifier}____`)),
+ ).toBe(true);
+ expect(result.tools).toHaveLength(1);
+ });
+
+ it('sets tools to undefined when dropping PageAgent leaves no tools', () => {
+ const result = composeEnabledTools({
+ context: { isPageEditorReady: false, scope: 'page' },
+ toolsDetailed: makeToolsDetailed([PAGE_AGENT_MANIFEST]),
+ });
+
+ expect(result.enabledToolIds).toEqual([]);
+ expect(result.enabledManifests).toEqual([]);
+ expect(result.tools).toBeUndefined();
+ });
+
+ it('is a no-op when scope is page but PageAgent is not enabled', () => {
+ const toolsDetailed = makeToolsDetailed([OTHER_MANIFEST]);
+
+ const result = composeEnabledTools({
+ context: { isPageEditorReady: false, scope: 'page' },
+ toolsDetailed,
+ });
+
+ expect(result.enabledToolIds).toEqual(['lobe-agent-documents']);
+ expect(result.enabledManifests).toEqual([OTHER_MANIFEST]);
+ expect(result.tools).toEqual(toolsDetailed.tools);
+ });
+ });
+});
diff --git a/src/services/chat/mecha/toolSetComposer.ts b/src/services/chat/mecha/toolSetComposer.ts
new file mode 100644
index 00000000000..54c913dbfbf
--- /dev/null
+++ b/src/services/chat/mecha/toolSetComposer.ts
@@ -0,0 +1,90 @@
+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
+import type { LobeToolManifest, ToolsGenerationResult } from '@lobechat/context-engine';
+import { generateToolsFromManifest } from '@lobechat/context-engine';
+import debug from 'debug';
+
+type UniformToolArray = NonNullable<ToolsGenerationResult['tools']>;
+type UniformTool = UniformToolArray[number];
+
+const log = debug('lobe-mecha:tool-set-composer');
+
+export interface ToolSetComposerContext {
+ isPageEditorReady?: boolean;
+ scope?: string;
+}
+
+export interface ToolSetComposerInput {
+ context: ToolSetComposerContext;
+ injectedManifests?: LobeToolManifest[];
+ toolsDetailed: ToolsGenerationResult;
+}
+
+export interface ComposedToolSet {
+ enabledManifests: LobeToolManifest[];
+ enabledToolIds: string[];
+ tools?: UniformTool[];
+}
+
+const mergeInjectedManifests = (
+ base: ComposedToolSet,
+ injectedManifests: LobeToolManifest[] | undefined,
+): ComposedToolSet => {
+ if (!injectedManifests?.length) return base;
+
+ const existingIds = new Set(base.enabledToolIds);
+ const newManifests = injectedManifests.filter((m) => !existingIds.has(m.identifier));
+ if (newManifests.length === 0) return base;
+
+ const newTools = newManifests.flatMap((m) => generateToolsFromManifest(m));
+ const mergedTools = base.tools
+ ? [...base.tools, ...newTools]
+ : newTools.length > 0
+ ? newTools
+ : undefined;
+
+ return {
+ enabledManifests: [...base.enabledManifests, ...newManifests],
+ enabledToolIds: [...base.enabledToolIds, ...newManifests.map((m) => m.identifier)],
+ tools: mergedTools,
+ };
+};
+
+// `scope` is bound to the topic, not the route: navigating away from the page
+// editor keeps `scope === 'page'` on the same topic. Without this drop the LLM
+// still sees page-agent tools and can call them against a stale editor ref.
+const dropPageAgentIfEditorNotMounted = (
+ set: ComposedToolSet,
+ context: ToolSetComposerContext,
+): ComposedToolSet => {
+ if (context.scope !== 'page') return set;
+ if (!set.enabledToolIds.includes(PageAgentIdentifier)) return set;
+ if (context.isPageEditorReady) return set;
+
+ log('dropping %s: editor not mounted', PageAgentIdentifier);
+
+ const toolNamePrefix = `${PageAgentIdentifier}____`;
+ const nextTools = set.tools?.filter((t) => !t.function?.name?.startsWith(toolNamePrefix));
+
+ return {
+ enabledManifests: set.enabledManifests.filter((m) => m.identifier !== PageAgentIdentifier),
+ enabledToolIds: set.enabledToolIds.filter((id) => id !== PageAgentIdentifier),
+ tools: nextTools && nextTools.length > 0 ? nextTools : undefined,
+ };
+};
+
+export const composeEnabledTools = ({
+ toolsDetailed,
+ injectedManifests,
+ context,
+}: ToolSetComposerInput): ComposedToolSet => {
+ const initial: ComposedToolSet = {
+ enabledManifests: toolsDetailed.enabledManifests,
+ enabledToolIds: toolsDetailed.enabledToolIds,
+ tools: toolsDetailed.tools,
+ };
+
+ return dropPageAgentIfEditorNotMounted(
+ mergeInjectedManifests(initial, injectedManifests),
+ context,
+ );
+};
diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.ts
new file mode 100644
index 00000000000..328596840de
--- /dev/null
+++ b/src/services/document/invalidation.ts
@@ -0,0 +1,66 @@
+import { mutate } from '@/libs/swr';
+
+import { agentDocumentSWRKeys, documentSWRKeys, notebookSWRKeys } from './swrKeys';
+
+export type DocumentMutationCause =
+ | 'agent-document'
+ | 'document-service'
+ | 'notebook'
+ | 'page-title';
+
+export interface InvalidateDocumentMutationParams {
+ agentDocumentId?: string;
+ agentId?: string;
+ cause?: DocumentMutationCause;
+ documentId?: string;
+ refreshDocumentEditor?: boolean;
+ refreshPageDocuments?: boolean;
+ topicId?: string;
+}
+
+export const invalidateDocumentMutation = async (
+ params: InvalidateDocumentMutationParams,
+): Promise<void> => {
+ const {
+ agentDocumentId,
+ agentId,
+ documentId,
+ refreshDocumentEditor,
+ refreshPageDocuments,
+ topicId,
+ } = params;
+ const revalidations: Promise<unknown>[] = [];
+
+ if (documentId) {
+ if (refreshDocumentEditor !== false) {
+ revalidations.push(mutate(documentSWRKeys.editor(documentId)));
+ }
+ revalidations.push(mutate(documentSWRKeys.pageDetail(documentId)));
+ revalidations.push(mutate(documentSWRKeys.pageMeta(documentId)));
+ }
+
+ if (documentId || refreshPageDocuments) {
+ revalidations.push(mutate(documentSWRKeys.pageDocuments()));
+ }
+
+ if (topicId) {
+ revalidations.push(mutate(notebookSWRKeys.documents(topicId)));
+ }
+
+ if (agentId) {
+ revalidations.push(mutate(agentDocumentSWRKeys.documents(agentId)));
+ revalidations.push(mutate(agentDocumentSWRKeys.documentsList(agentId)));
+ }
+
+ if (agentId && agentDocumentId) {
+ revalidations.push(mutate(agentDocumentSWRKeys.readDocument(agentId, agentDocumentId)));
+ }
+
+ const results = await Promise.allSettled(revalidations);
+
+ for (const result of results) {
+ if (result.status === 'rejected') {
+ console.error('[DocumentInvalidation] Failed to revalidate document cache:', result.reason);
+ }
+ }
+};
diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.ts
new file mode 100644
index 00000000000..5e5f9bd88b8
--- /dev/null
+++ b/src/services/document/swrKeys.ts
@@ -0,0 +1,24 @@
+export const SWR_USE_FETCH_NOTEBOOK_DOCUMENTS = 'SWR_USE_FETCH_NOTEBOOK_DOCUMENTS';
+
+export const agentDocumentSWRKeys = {
+ documents: (agentId: string) => ['agent-documents', agentId] as const,
+ /**
+ * UI-side list: raw AgentDocumentWithRules (includes documentId, sourceType, createdAt).
+ * Kept separate from `documents` because the agent store writes mapAgentDocumentsToContext(...)
+ * under that key, which drops those fields.
+ */
+ documentsList: (agentId: string) => ['agent-documents-list', agentId] as const,
+ readDocument: (agentId: string, id: string) =>
+ ['workspace-agent-document-editor', agentId, id] as const,
+};
+
+export const documentSWRKeys = {
+ editor: (documentId: string) => ['document/editor', documentId] as const,
+ pageDetail: (documentId: string) => ['pageDetail', documentId] as const,
+ pageDocuments: () => ['pageDocuments'] as const,
+ pageMeta: (documentId: string) => ['page-document-meta', documentId] as const,
+};
+
+export const notebookSWRKeys = {
+ documents: (topicId: string) => [SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId] as const,
+};
diff --git a/src/services/documentHistoryQueue.test.ts b/src/services/documentHistoryQueue.test.ts
new file mode 100644
index 00000000000..15b19e39584
--- /dev/null
+++ b/src/services/documentHistoryQueue.test.ts
@@ -0,0 +1,129 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { documentService } from '@/services/document';
+
+import { documentHistoryQueueService } from './documentHistoryQueue';
+
+vi.mock('@/services/document', () => ({
+ documentService: {
+ saveDocumentHistory: vi.fn(),
+ },
+}));
+
+describe('DocumentHistoryQueueService', () => {
+ afterEach(async () => {
+ await Promise.resolve();
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+ });
+
+ describe('enqueueEditorSnapshot', () => {
+ it('should capture editor JSON and enqueue an llm_call history save', async () => {
+ vi.mocked(documentService.saveDocumentHistory).mockResolvedValue({
+ savedAt: new Date().toISOString(),
+ });
+ const editor = {
+ getDocument: vi.fn(() => ({ root: true })),
+ };
+
+ const result = documentHistoryQueueService.enqueueEditorSnapshot({
+ documentId: 'doc-1',
+ editor,
+ });
+ await Promise.resolve();
+
+ expect(result).toBe(true);
+ expect(editor.getDocument).toHaveBeenCalledWith('json');
+ expect(documentService.saveDocumentHistory).toHaveBeenCalledWith({
+ documentId: 'doc-1',
+ editorData: JSON.stringify({ root: true }),
+ saveSource: 'llm_call',
+ });
+ });
+
+ it('should save the origin content when the editor snapshot contains diff nodes', async () => {
+ vi.mocked(documentService.saveDocumentHistory).mockResolvedValue({
+ savedAt: new Date().toISOString(),
+ });
+ const editor = {
+ getDocument: vi.fn(() => ({
+ root: {
+ children: [
+ {
+ children: [
+ { children: [{ text: 'origin', type: 'text' }], type: 'paragraph' },
+ { children: [{ text: 'modified', type: 'text' }], type: 'paragraph' },
+ ],
+ diffType: 'modify',
+ type: 'diff',
+ },
+ {
+ children: [{ children: [{ text: 'added', type: 'text' }], type: 'paragraph' }],
+ diffType: 'add',
+ type: 'diff',
+ },
+ {
+ children: [{ children: [{ text: 'removed', type: 'text' }], type: 'paragraph' }],
+ diffType: 'remove',
+ type: 'diff',
+ },
+ ],
+ },
+ })),
+ };
+
+ const result = documentHistoryQueueService.enqueueEditorSnapshot({
+ documentId: 'doc-1',
+ editor,
+ });
+ await Promise.resolve();
+
+ expect(result).toBe(true);
+ expect(documentService.saveDocumentHistory).toHaveBeenCalledWith({
+ documentId: 'doc-1',
+ editorData: JSON.stringify({
+ root: {
+ children: [
+ { children: [{ text: 'origin', type: 'text' }], type: 'paragraph' },
+ { children: [{ text: 'removed', type: 'text' }], type: 'paragraph' },
+ ],
+ },
+ }),
+ saveSource: 'llm_call',
+ });
+ });
+
+ it('should skip capture when document id or editor is missing', () => {
+ expect(documentHistoryQueueService.enqueueEditorSnapshot({ editor: undefined })).toBe(false);
+ expect(
+ documentHistoryQueueService.enqueueEditorSnapshot({
+ documentId: 'doc-1',
+ editor: undefined,
+ }),
+ ).toBe(false);
+ expect(documentService.saveDocumentHistory).not.toHaveBeenCalled();
+ });
+
+ it('should not enqueue history when editor snapshot capture fails', () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const error = new Error('snapshot failed');
+ const editor = {
+ getDocument: vi.fn(() => {
+ throw error;
+ }),
+ };
+
+ const result = documentHistoryQueueService.enqueueEditorSnapshot({
+ documentId: 'doc-1',
+ editor,
+ });
+
+ expect(result).toBe(false);
+ expect(documentService.saveDocumentHistory).not.toHaveBeenCalled();
+ expect(consoleError).toHaveBeenCalledWith(
+ '[DocumentHistoryQueueService] Failed to capture editor history snapshot:',
+ error,
+ );
+ });
+ });
+});
diff --git a/src/services/documentHistoryQueue.ts b/src/services/documentHistoryQueue.ts
index 4f038897d34..39201665c61 100644
--- a/src/services/documentHistoryQueue.ts
+++ b/src/services/documentHistoryQueue.ts
@@ -1,5 +1,6 @@
import debug from 'debug';
+import { normalizeEditorDataDiffNodes } from '@/libs/editor/normalizeDiffNodes';
import { documentService } from '@/services/document';
const log = debug('page:editor:history-queue');
@@ -10,6 +11,16 @@ interface QueueItem {
saveSource: 'llm_call';
}
+interface EditorSnapshotSource {
+ getDocument: (type: 'json') => unknown;
+}
+
+interface EnqueueEditorSnapshotParams {
+ documentId?: string;
+ editor?: EditorSnapshotSource;
+ saveSource?: 'llm_call';
+}
+
class DocumentHistoryQueueService {
private queue: QueueItem[] = [];
private isProcessing = false;
@@ -19,6 +30,33 @@ class DocumentHistoryQueueService {
void this.drain();
};
+ enqueueEditorSnapshot = ({
+ documentId,
+ editor,
+ saveSource = 'llm_call',
+ }: EnqueueEditorSnapshotParams) => {
+ if (!documentId || !editor) return false;
+
+ try {
+ const editorData = normalizeEditorDataDiffNodes(
+ editor.getDocument('json') as Record<string, unknown>,
+ );
+ this.enqueue({
+ documentId,
+ editorData: JSON.stringify(editorData),
+ saveSource,
+ });
+
+ return true;
+ } catch (error) {
+ console.error(
+ '[DocumentHistoryQueueService] Failed to capture editor history snapshot:',
+ error,
+ );
+ return false;
+ }
+ };
+
drain = async () => {
if (this.isProcessing) return;
this.isProcessing = true;
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index 6cc84a93ddb..00e6edc0e14 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -16,9 +16,16 @@ import DesktopVideoLayout from '@/routes/(main)/(create)/video/_layout';
// Pages — sync import
import AgentPage from '@/routes/(main)/agent';
import DesktopChatLayout from '@/routes/(main)/agent/_layout';
+import DesktopAgentChatLayout from '@/routes/(main)/agent/(chat)/_layout';
+import AgentTopicNotebookRedirectPage from '@/routes/(main)/agent/[topicId]/page';
+import AgentTopicNotebookDocPage from '@/routes/(main)/agent/[topicId]/page/[docId]';
import AgentChannelPage from '@/routes/(main)/agent/channel';
import AgentCronDetailPage from '@/routes/(main)/agent/cron/[cronId]';
+import AgentPageRedirectPage from '@/routes/(main)/agent/page';
import AgentProfilePage from '@/routes/(main)/agent/profile';
+import AgentTasksPage from '@/routes/(main)/agent/tasks';
+import AgentTasksLayout from '@/routes/(main)/agent/tasks/_layout';
+import AgentTaskDetailPage from '@/routes/(main)/agent/tasks/[taskId]';
import CommunityLayout from '@/routes/(main)/community/_layout';
import CommunityDetailLayout from '@/routes/(main)/community/(detail)/_layout';
import CommunityDetailAgentPage from '@/routes/(main)/community/(detail)/agent';
@@ -94,8 +101,39 @@ export const desktopRoutes: RouteObject[] = [
{
children: [
{
- element: <AgentPage />,
- index: true,
+ children: [
+ {
+ element: <AgentPage />,
+ index: true,
+ },
+ {
+ children: [
+ {
+ element: <AgentPage />,
+ index: true,
+ },
+ {
+ children: [
+ {
+ element: <AgentTopicNotebookRedirectPage />,
+ index: true,
+ },
+ {
+ element: <AgentTopicNotebookDocPage />,
+ path: ':docId',
+ },
+ ],
+ path: 'page',
+ },
+ ],
+ path: ':topicId',
+ },
+ ],
+ element: <DesktopAgentChatLayout />,
+ },
+ {
+ element: <AgentPageRedirectPage />,
+ path: 'page',
},
{
element: <AgentProfilePage />,
@@ -109,6 +147,20 @@ export const desktopRoutes: RouteObject[] = [
element: <AgentChannelPage />,
path: 'channel',
},
+ {
+ children: [
+ {
+ element: <AgentTasksPage />,
+ index: true,
+ },
+ {
+ element: <AgentTaskDetailPage />,
+ path: ':taskId',
+ },
+ ],
+ element: <AgentTasksLayout />,
+ path: 'tasks',
+ },
],
element: <DesktopChatLayout />,
errorElement: <ErrorBoundary />,
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index dcc0f1afba8..8fe8b0f9bae 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -8,8 +8,8 @@ import {
} from '@/business/client/BusinessDesktopRoutes';
import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
+const agentChatElement = dynamicElement(() => import('@/routes/(main)/agent'), 'Desktop > Chat');
const isDev = process.env.NODE_ENV === 'development';
-
// Desktop router configuration (declarative mode)
export const desktopRoutes: RouteObject[] = [
{
@@ -24,8 +24,51 @@ export const desktopRoutes: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(main)/agent'), 'Desktop > Chat'),
- index: true,
+ children: [
+ {
+ element: agentChatElement,
+ index: true,
+ },
+ {
+ children: [
+ {
+ element: agentChatElement,
+ index: true,
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/[topicId]/page'),
+ 'Desktop > Chat > Topic > Page > Redirect',
+ ),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/[topicId]/page/[docId]'),
+ 'Desktop > Chat > Topic > Page > Doc',
+ ),
+ path: ':docId',
+ },
+ ],
+ path: 'page',
+ },
+ ],
+ path: ':topicId',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/agent/(chat)/_layout'),
+ 'Desktop > Chat > ChatLayout',
+ ),
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/page'),
+ 'Desktop > Chat > Invalid Page Redirect',
+ ),
+ path: 'page',
},
{
element: dynamicElement(
@@ -48,6 +91,29 @@ export const desktopRoutes: RouteObject[] = [
),
path: 'channel',
},
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/tasks'),
+ 'Desktop > Chat > Tasks',
+ ),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/tasks/[taskId]'),
+ 'Desktop > Chat > Task Detail',
+ ),
+ path: ':taskId',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/agent/tasks/_layout'),
+ 'Desktop > Chat > Tasks > Layout',
+ ),
+ path: 'tasks',
+ },
],
element: dynamicLayout(
() => import('@/routes/(main)/agent/_layout'),
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts
index 818537986a2..ae5f96add98 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/clientToolExecution.test.ts
@@ -58,7 +58,12 @@ function setup(options: { hasConnection?: boolean; sendReturns?: boolean } = {})
operations: {
'op-1': {
abortController: { signal: { aborted: false } },
- context: { agentId: 'agent-1', topicId: 'topic-1' },
+ context: {
+ agentId: 'agent-1',
+ documentId: 'documents-row-id',
+ scope: 'page',
+ topicId: 'topic-1',
+ },
},
},
pendingClientToolExecutions: {},
@@ -101,8 +106,10 @@ describe('internal_executeClientTool', () => {
{ path: '/tmp/a.txt' },
expect.objectContaining({
agentId: 'agent-1',
+ documentId: 'documents-row-id',
messageId: 'call_1',
operationId: 'op-1',
+ scope: 'page',
topicId: 'topic-1',
}),
);
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 52d32ec37e5..056a2093062 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
@@ -818,17 +818,27 @@ describe('StreamingExecutor actions', () => {
tools: [],
}),
} as any);
+ vi.spyOn(pageAgentRuntime, 'isReady').mockReturnValue(true);
vi.spyOn(pageAgentRuntime, 'getPageContentContext').mockReturnValue({
markdown: '# Test Document',
xml: '<root><h1>Test</h1></root>',
metadata: { title: 'Test Doc', charCount: 15, lineCount: 1 },
});
+ const { operationId } = result.current.startOperation({
+ context: {
+ agentId: TEST_IDS.SESSION_ID,
+ scope: 'page',
+ topicId: TEST_IDS.TOPIC_ID,
+ },
+ type: 'execAgentRuntime',
+ });
const { context } = result.current.internal_createAgentState({
messages: [userMessage],
parentMessageId: userMessage.id,
agentId: TEST_IDS.SESSION_ID,
topicId: TEST_IDS.TOPIC_ID,
+ operationId,
initialContext: {
phase: 'init',
initialContext: {
@@ -849,6 +859,55 @@ describe('StreamingExecutor actions', () => {
});
});
+ it('should not inject page editor context outside page scope', () => {
+ 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);
+ const pageContextSpy = vi.spyOn(pageAgentRuntime, 'getPageContentContext');
+ const { operationId } = result.current.startOperation({
+ context: {
+ agentId: TEST_IDS.SESSION_ID,
+ scope: 'main',
+ topicId: TEST_IDS.TOPIC_ID,
+ },
+ type: 'execAgentRuntime',
+ });
+
+ const { context } = result.current.internal_createAgentState({
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ agentId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ operationId,
+ });
+
+ expect(context.initialContext?.pageEditor).toBeUndefined();
+ expect(pageContextSpy).not.toHaveBeenCalled();
+ });
+
it('should merge selectedTools into generated tools when provided', () => {
act(() => {
useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
diff --git a/src/store/chat/slices/aiChat/actions/clientToolExecution.ts b/src/store/chat/slices/aiChat/actions/clientToolExecution.ts
index fa9e32338a5..eefb772c565 100644
--- a/src/store/chat/slices/aiChat/actions/clientToolExecution.ts
+++ b/src/store/chat/slices/aiChat/actions/clientToolExecution.ts
@@ -94,17 +94,39 @@ export class ClientToolExecutionActionImpl {
const operation = this.#get().operations[operationId];
const ctx: BuiltinToolContext = {
agentId: operation?.context?.agentId,
+ documentId: operation?.context?.documentId,
groupId: operation?.context?.groupId,
// Gateway-side tool messages are persisted on the server; the client
// has no local message id, so reuse toolCallId as the context key.
messageId: toolCallId,
operationId,
+ scope: operation?.context?.scope,
signal: operation?.abortController?.signal,
topicId: operation?.context?.topicId ?? undefined,
};
+ log('[ClientToolCall] execute:start', {
+ agentId: ctx.agentId,
+ apiName,
+ documentId: ctx.documentId,
+ identifier,
+ operationId,
+ scope: ctx.scope,
+ toolCallId,
+ topicId: ctx.topicId,
+ });
+
const result = await invokeExecutor(identifier, apiName, params, ctx);
+ log('[ClientToolCall] execute:end', {
+ apiName,
+ errorType: result.error?.type,
+ identifier,
+ operationId,
+ success: result.success,
+ toolCallId,
+ });
+
if (result.error) {
send({
content: result.content ?? result.error.message ?? null,
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 41fbc89116a..65b7bb16165 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -29,6 +29,10 @@ import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';
import { resolveHeteroResume } from '@/store/chat/slices/aiChat/actions/heteroResume';
import { type ChatStore } from '@/store/chat/store';
+import {
+ mergeAgentRuntimeInitialContexts,
+ resolveActiveTopicDocumentInitialContext,
+} from '@/store/chat/utils/activeTopicDocumentContext';
import {
createPendingCompressedGroup,
getCompressionCandidateMessageIds,
@@ -837,6 +841,8 @@ export class ConversationLifecycleActionImpl {
// When agents are @mentioned, inject a slim callAgent-only manifest
// so the AI can delegate directly without activating the full agent-management tool
const injectedManifests = hasMentionedAgents ? [createCallAgentManifest()] : undefined;
+ const activeTopicDocumentInitialContext =
+ await resolveActiveTopicDocumentInitialContext(execContext);
const hasInitialContext = hasMentionedAgents || !!injectedManifests;
@@ -854,10 +860,14 @@ export class ConversationLifecycleActionImpl {
phase: 'init' as const,
}
: undefined;
+ const mergedAgentRuntimeInitialContext = mergeAgentRuntimeInitialContexts(
+ activeTopicDocumentInitialContext,
+ agentRuntimeInitialContext,
+ );
await internal_execAgentRuntime({
context: execContext,
- initialContext: agentRuntimeInitialContext,
+ initialContext: mergedAgentRuntimeInitialContext,
messages: displayMessages,
parentMessageId: data.assistantMessageId,
parentMessageType: 'assistant',
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index e45402b45a4..6f892a13b9c 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -235,6 +235,7 @@ export class GatewayActionImpl {
const result = await aiAgentService.execAgentTask({
agentId: context.agentId,
appContext: {
+ documentId: context.documentId,
groupId: context.groupId,
scope: context.scope,
threadId: context.threadId,
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index e7825ac8f1c..183ede1c0f5 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -10,7 +10,7 @@ import { createPathScopeAudit } from '@lobechat/builtin-tool-local-system';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';
import { isDesktop } from '@lobechat/const';
-import { generateToolsFromManifest, type ToolsEngine } from '@lobechat/context-engine';
+import { type ToolsEngine } from '@lobechat/context-engine';
import { buildTaskDetailPrompt, buildTaskListPrompt } from '@lobechat/prompts';
import {
type ConversationContext,
@@ -22,7 +22,7 @@ import { t } from 'i18next';
import { createAgentToolsEngine } from '@/helpers/toolEngineering';
import { type ResolvedAgentConfig } from '@/services/chat/mecha';
-import { resolveAgentConfig } from '@/services/chat/mecha';
+import { composeEnabledTools, resolveAgentConfig } from '@/services/chat/mecha';
import { localFileService } from '@/services/electron/localFileService';
import { messageService } from '@/services/message';
import { getAgentStoreState } from '@/store/agent';
@@ -201,23 +201,14 @@ export class StreamingExecutorActionImpl {
toolIds: mergedToolIds,
});
- // --- Merge injected manifests (generic, caller-driven) ---
- const injectedManifests = initialContext?.initialContext?.injectedManifests;
- const existingIdSet = new Set(toolsDetailed.enabledToolIds);
- // Skip manifests whose identifier is already enabled (dedup)
- const newInjected = injectedManifests?.filter((m) => !existingIdSet.has(m.identifier)) ?? [];
-
- const enabledToolIds = [
- ...toolsDetailed.enabledToolIds,
- ...newInjected.map((m) => m.identifier),
- ];
- const enabledManifests = [...toolsDetailed.enabledManifests, ...newInjected];
- const injectedTools = newInjected.flatMap((m) => generateToolsFromManifest(m));
- const tools = toolsDetailed.tools
- ? [...toolsDetailed.tools, ...injectedTools]
- : injectedTools.length > 0
- ? injectedTools
- : undefined;
+ const { enabledToolIds, enabledManifests, tools } = composeEnabledTools({
+ context: {
+ isPageEditorReady: pageAgentRuntime.isReady(),
+ scope,
+ },
+ injectedManifests: initialContext?.initialContext?.injectedManifests,
+ toolsDetailed,
+ });
// Use enabledManifests directly to avoid getEnabledPluginManifests adding default tools again
const toolManifestMap = Object.fromEntries(
@@ -286,7 +277,7 @@ export class StreamingExecutorActionImpl {
// Build initialContext for page editor if lobe-page-agent is enabled
let runtimeInitialContext: RuntimeInitialContext | undefined;
- if (enabledToolIds.includes(PageAgentIdentifier)) {
+ if (scope === 'page' && enabledToolIds.includes(PageAgentIdentifier)) {
try {
// Get page content context from page agent runtime
const pageContentContext = pageAgentRuntime.getPageContentContext('both');
@@ -569,7 +560,9 @@ export class StreamingExecutorActionImpl {
// Use selectTodosFromMessages selector (shared with UI display)
const todos = selectTodosFromMessages(currentDBMessages);
// Accumulate activated tool IDs from lobe-activator messages
- const activatedToolIds = selectActivatedToolIdsFromMessages(currentDBMessages);
+ const activatedToolIds = selectActivatedToolIdsFromMessages(currentDBMessages)?.filter(
+ (id) => scope === 'page' || id !== PageAgentIdentifier,
+ );
// Accumulate activated skills from activateSkill messages
const activatedSkills = selectActivatedSkillsFromMessages(currentDBMessages);
const hasQueuedMessages = (this.#get().queuedMessages[contextKey]?.length ?? 0) > 0;
@@ -581,7 +574,7 @@ export class StreamingExecutorActionImpl {
});
// If page agent is enabled, get the latest XML for stepPageEditor
- if (nextContext.initialContext?.pageEditor) {
+ if (scope === 'page' && nextContext.initialContext?.pageEditor) {
try {
const pageContentContext = pageAgentRuntime.getPageContentContext('xml');
stepContext.stepPageEditor = {
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
index 5911d2d0908..982f369f08b 100644
--- a/src/store/chat/slices/operation/selectors.ts
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -206,31 +206,11 @@ const hasRunningOperationByContext =
* Checks all AI runtime operation types (see AI_RUNTIME_OPERATION_TYPES)
*/
const isAgentRuntimeRunningByContext =
- (context: {
- agentId?: string;
- groupId?: string;
- threadId?: string | null;
- topicId?: string | null;
- }) =>
+ (context: MessageMapKeyInput) =>
(s: ChatStoreState): boolean => {
if (!context.agentId) return false;
- const contextKey = messageMapKey({
- agentId: context.agentId,
- groupId: context.groupId,
- topicId: context.topicId,
- });
-
- const operationIds = s.operationsByContext[contextKey] || [];
- const operations = operationIds
- .map((id) => s.operations[id])
- .filter((op): op is Operation => {
- if (!op) return false;
- // Also filter by threadId if provided
- const opThreadId = op.context.threadId ?? null;
- const contextThreadId = context.threadId ?? null;
- return opThreadId === contextThreadId;
- });
+ const operations = getOperationsByContext(context)(s);
return operations.some(
(op) =>
@@ -246,30 +226,11 @@ const isAgentRuntimeRunningByContext =
* so the input stays in loading state from the moment user sends until AI finishes
*/
const isInputLoadingByContext =
- (context: {
- agentId?: string;
- groupId?: string;
- threadId?: string | null;
- topicId?: string | null;
- }) =>
+ (context: MessageMapKeyInput) =>
(s: ChatStoreState): boolean => {
if (!context.agentId) return false;
- const contextKey = messageMapKey({
- agentId: context.agentId,
- groupId: context.groupId,
- topicId: context.topicId,
- });
-
- const operationIds = s.operationsByContext[contextKey] || [];
- const operations = operationIds
- .map((id) => s.operations[id])
- .filter((op): op is Operation => {
- if (!op) return false;
- const opThreadId = op.context.threadId ?? null;
- const contextThreadId = context.threadId ?? null;
- return opThreadId === contextThreadId;
- });
+ const operations = getOperationsByContext(context)(s);
return operations.some(
(op) =>
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index c8956432ffe..da3c0c9015b 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -392,6 +392,61 @@ describe('ChatPluginAction', () => {
expect(returnValue).toEqual({ error: 'Invalid arguments', success: false });
});
+ it('should pass page document context to Tool Store executor', async () => {
+ const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+
+ const { result } = renderHook(() => useChatStore());
+ const messageId = 'page-tool-message-id';
+
+ act(() => {
+ const rootOperationId = result.current.startOperation({
+ type: 'execAgentRuntime',
+ context: {
+ agentId: 'agent-1',
+ documentId: 'docs-current',
+ scope: 'page',
+ topicId: 'topic-1',
+ },
+ }).operationId;
+
+ const toolOperationId = result.current.startOperation({
+ type: 'executeToolCall',
+ context: { messageId },
+ parentOperationId: rootOperationId,
+ }).operationId;
+
+ result.current.associateMessageWithOperation(messageId, toolOperationId);
+ });
+
+ let capturedContext: any;
+ vi.spyOn(useToolStore.getState(), 'invokeBuiltinTool').mockImplementation(
+ async (_id, _api, _params, ctx) => {
+ capturedContext = ctx;
+ return { success: true };
+ },
+ );
+
+ const payload = {
+ identifier: 'lobe-agent-documents',
+ apiName: 'editDocument',
+ arguments: JSON.stringify({ content: 'test', id: 'agent-document-id' }),
+ type: 'builtin',
+ } as ChatToolPayload;
+
+ await act(async () => {
+ await result.current.invokeBuiltinTool(messageId, payload);
+ });
+
+ expect(capturedContext).toMatchObject({
+ agentId: 'agent-1',
+ documentId: 'docs-current',
+ messageId,
+ scope: 'page',
+ topicId: 'topic-1',
+ });
+ });
+
describe('registerAfterCompletion with Tool Store executor', () => {
it('should create registerAfterCompletion when root execAgentRuntime operation exists', async () => {
// Mock hasExecutor to return true
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index 3cca58ba0cb..091ef879642 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -63,10 +63,30 @@ export class PluginTypesActionImpl {
const operation = operationId ? this.#get().operations[operationId] : undefined;
const context = operationId ? { operationId } : undefined;
- // Get agent ID, group ID, and topic ID from operation context
- let agentId = operation?.context?.agentId;
- let groupId = operation?.context?.groupId;
- const topicId = operation?.context?.topicId;
+ let rootRuntimeOperationId: string | undefined;
+ let rootRuntimeOperationContext = operation?.context;
+ if (operationId) {
+ let currentOp = operation;
+ while (currentOp) {
+ if (AI_RUNTIME_OPERATION_TYPES.includes(currentOp.type)) {
+ rootRuntimeOperationId = currentOp.id;
+ rootRuntimeOperationContext = currentOp.context;
+ break;
+ }
+ // Move up to parent operation
+ const parentId = currentOp.parentOperationId;
+ currentOp = parentId ? this.#get().operations[parentId] : undefined;
+ }
+ }
+
+ // Get agent ID, group ID, topic ID, and page scope from operation context.
+ // Prefer the concrete tool operation; fall back to the runtime root for
+ // legacy operations created before child context inheritance was complete.
+ let agentId = operation?.context?.agentId ?? rootRuntimeOperationContext?.agentId;
+ let groupId = operation?.context?.groupId ?? rootRuntimeOperationContext?.groupId;
+ const documentId = operation?.context?.documentId ?? rootRuntimeOperationContext?.documentId;
+ const scope = operation?.context?.scope ?? rootRuntimeOperationContext?.scope;
+ const topicId = operation?.context?.topicId ?? rootRuntimeOperationContext?.topicId;
// For agent-builder tools, inject activeAgentId from store if not in context
// This is needed because AgentBuilderProvider uses a separate scope for messages
@@ -89,22 +109,6 @@ export class PluginTypesActionImpl {
// Get group orchestration callbacks if available (for group management tools)
const groupOrchestration = this.#get().getGroupOrchestrationCallbacks?.();
- // Find root execAgentRuntime operation for registering afterCompletion callbacks
- // Navigate up the operation tree to find the root runtime operation
- let rootRuntimeOperationId: string | undefined;
- if (operationId) {
- let currentOp = operation;
- while (currentOp) {
- if (AI_RUNTIME_OPERATION_TYPES.includes(currentOp.type)) {
- rootRuntimeOperationId = currentOp.id;
- break;
- }
- // Move up to parent operation
- const parentId = currentOp.parentOperationId;
- currentOp = parentId ? this.#get().operations[parentId] : undefined;
- }
- }
-
// Create registerAfterCompletion function that registers callback to root runtime operation
const registerAfterCompletion = rootRuntimeOperationId
? (callback: Parameters<typeof registerAfterCompletionCallback>[1]) => {
@@ -125,20 +129,43 @@ export class PluginTypesActionImpl {
);
// Call Tool Store's invokeBuiltinTool
+ log('[BuiltinToolCall] invoke:start', {
+ agentId,
+ apiName: payload.apiName,
+ documentId,
+ identifier: payload.identifier,
+ messageId: id,
+ operationId,
+ rootRuntimeOperationId,
+ scope,
+ topicId,
+ });
+
const result = await useToolStore
.getState()
.invokeBuiltinTool(payload.identifier, payload.apiName, params, {
agentId,
+ documentId,
groupId,
groupOrchestration,
messageId: id,
operationId,
registerAfterCompletion,
+ scope,
signal: operation?.abortController?.signal,
stepContext,
topicId,
});
+ log('[BuiltinToolCall] invoke:end', {
+ apiName: payload.apiName,
+ errorType: result.error?.type,
+ identifier: payload.identifier,
+ messageId: id,
+ operationId,
+ success: result.success,
+ });
+
// When error exists but content is empty, backfill error message into content
const content = result.content || result.error?.message || '';
diff --git a/src/store/chat/utils/activeTopicDocumentContext.test.ts b/src/store/chat/utils/activeTopicDocumentContext.test.ts
new file mode 100644
index 00000000000..e1a59e32e8b
--- /dev/null
+++ b/src/store/chat/utils/activeTopicDocumentContext.test.ts
@@ -0,0 +1,89 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentDocumentService } from '@/services/agentDocument';
+
+import {
+ mergeAgentRuntimeInitialContexts,
+ resolveActiveTopicDocumentInitialContext,
+} from './activeTopicDocumentContext';
+
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentService: {
+ listDocuments: vi.fn(),
+ },
+}));
+
+describe('activeTopicDocumentContext', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('resolves active topic document context from current topic documents', async () => {
+ vi.mocked(agentDocumentService.listDocuments).mockResolvedValue([
+ {
+ documentId: 'docs_1',
+ filename: 'doc-1.md',
+ id: 'agd_1',
+ title: 'Doc 1',
+ },
+ ] as any);
+
+ const context = await resolveActiveTopicDocumentInitialContext({
+ agentId: 'agt_1',
+ documentId: 'docs_1',
+ scope: 'main',
+ topicId: 'tpc_1',
+ });
+
+ expect(agentDocumentService.listDocuments).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ target: 'currentTopic',
+ topicId: 'tpc_1',
+ });
+ expect(context?.initialContext?.activeTopicDocument).toEqual({
+ agentDocumentId: 'agd_1',
+ documentId: 'docs_1',
+ title: 'Doc 1',
+ });
+ });
+
+ it('does not resolve active topic document context in page scope', async () => {
+ const context = await resolveActiveTopicDocumentInitialContext({
+ agentId: 'agt_1',
+ documentId: 'docs_1',
+ scope: 'page',
+ topicId: 'tpc_1',
+ });
+
+ expect(context).toBeUndefined();
+ expect(agentDocumentService.listDocuments).not.toHaveBeenCalled();
+ });
+
+ it('merges initial contexts without losing nested runtime context', () => {
+ const context = mergeAgentRuntimeInitialContexts(
+ {
+ initialContext: {
+ activeTopicDocument: {
+ agentDocumentId: 'agd_1',
+ documentId: 'docs_1',
+ },
+ },
+ phase: 'init',
+ },
+ {
+ initialContext: {
+ mentionedAgents: [{ id: 'agt_2', name: 'Agent 2' }],
+ },
+ phase: 'init',
+ },
+ );
+
+ expect(context?.initialContext).toEqual({
+ activeTopicDocument: {
+ agentDocumentId: 'agd_1',
+ documentId: 'docs_1',
+ },
+ mentionedAgents: [{ id: 'agt_2', name: 'Agent 2' }],
+ });
+ });
+});
diff --git a/src/store/chat/utils/activeTopicDocumentContext.ts b/src/store/chat/utils/activeTopicDocumentContext.ts
new file mode 100644
index 00000000000..08191809da9
--- /dev/null
+++ b/src/store/chat/utils/activeTopicDocumentContext.ts
@@ -0,0 +1,79 @@
+import type { AgentRuntimeContext } from '@lobechat/agent-runtime';
+import type { ConversationContext, RuntimeActiveTopicDocumentContext } from '@lobechat/types';
+
+import { agentDocumentService } from '@/services/agentDocument';
+
+export const mergeAgentRuntimeInitialContexts = (
+ ...contexts: Array<AgentRuntimeContext | undefined>
+): AgentRuntimeContext | undefined => {
+ const validContexts = contexts.filter(Boolean) as AgentRuntimeContext[];
+ if (validContexts.length === 0) return undefined;
+
+ const firstContext = validContexts[0]!;
+
+ return validContexts.reduce<AgentRuntimeContext>(
+ (acc, context) => ({
+ ...acc,
+ ...context,
+ initialContext: {
+ ...acc.initialContext,
+ ...context.initialContext,
+ },
+ payload:
+ acc.payload &&
+ context.payload &&
+ typeof acc.payload === 'object' &&
+ typeof context.payload === 'object'
+ ? {
+ ...(acc.payload as Record<string, unknown>),
+ ...(context.payload as Record<string, unknown>),
+ }
+ : (context.payload ?? acc.payload),
+ }),
+ { phase: firstContext.phase },
+ );
+};
+
+const resolveActiveTopicDocument = async (
+ context: ConversationContext,
+): Promise<RuntimeActiveTopicDocumentContext | undefined> => {
+ if (context.scope === 'page') return;
+ if (!context.agentId || !context.topicId || !context.documentId) return;
+
+ try {
+ const documents = await agentDocumentService.listDocuments({
+ agentId: context.agentId,
+ target: 'currentTopic',
+ topicId: context.topicId,
+ });
+ const matchedDocument = documents.find(
+ (document) => document.documentId === context.documentId,
+ );
+
+ return {
+ agentDocumentId: matchedDocument?.id,
+ documentId: context.documentId,
+ title: matchedDocument?.title,
+ };
+ } catch (error) {
+ console.error('[activeTopicDocumentContext] Failed to resolve topic document context:', error);
+
+ return {
+ documentId: context.documentId,
+ };
+ }
+};
+
+export const resolveActiveTopicDocumentInitialContext = async (
+ context: ConversationContext,
+): Promise<AgentRuntimeContext | undefined> => {
+ const activeTopicDocument = await resolveActiveTopicDocument(context);
+ if (!activeTopicDocument) return;
+
+ return {
+ initialContext: {
+ activeTopicDocument,
+ },
+ phase: 'init',
+ };
+};
diff --git a/src/store/chat/utils/messageMapKey.ts b/src/store/chat/utils/messageMapKey.ts
index 0bf056ae8be..601c5ac691a 100644
--- a/src/store/chat/utils/messageMapKey.ts
+++ b/src/store/chat/utils/messageMapKey.ts
@@ -41,7 +41,7 @@ export interface MessageMapKeyInput {
* Handles mapping from agentId/threadId to scopeId/subTopicId format
*/
const toMessageMapContext = (input: MessageMapKeyInput): MessageMapContext => {
- const { agentId, topicId, threadId, isNew, scope, groupId, subAgentId } = input;
+ const { agentId, topicId, threadId, isNew, groupId, subAgentId, scope } = input;
// If threadId is present and scope is explicitly 'thread', use thread scope
// Thread scope takes priority when explicitly requested, even with groupId
diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.ts
index 7901c2e3170..d09b2b835f5 100644
--- a/src/store/document/slices/document/action.ts
+++ b/src/store/document/slices/document/action.ts
@@ -8,6 +8,7 @@ import { type SWRResponse } from 'swr';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { documentService } from '@/services/document';
+import { documentSWRKeys } from '@/services/document/swrKeys';
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
@@ -50,6 +51,10 @@ export interface UseFetchDocumentOptions {
* Source type for the document. Defaults to 'page'.
*/
sourceType?: DocumentSourceType;
+ /**
+ * Topic ID for notebook documents.
+ */
+ topicId?: string | null;
}
type Setter = StoreSetter<DocumentStore>;
@@ -153,7 +158,18 @@ export class DocumentActionImpl {
// Update activeDocumentId and editor
this.#set(
- { activeDocumentId: documentId, editor },
+ {
+ activeDocumentId: documentId,
+ editor,
+ ...(sourceType === 'notebook' && topicId
+ ? {
+ lastActiveTopicDocumentIdByTopicId: {
+ ...this.#get().lastActiveTopicDocumentIdByTopicId,
+ [topicId]: documentId,
+ },
+ }
+ : {}),
+ },
false,
n('initDocumentWithEditor:setActive'),
);
@@ -174,8 +190,8 @@ export class DocumentActionImpl {
documentId: string | undefined,
options: UseFetchDocumentOptions = {},
): SWRResponse<DocumentItem | null> => {
- const { autoSave = true, editor, sourceType = 'page' } = options;
- const swrKey = documentId && editor ? ['document/editor', documentId] : null;
+ const { autoSave = true, editor, sourceType = 'page', topicId } = options;
+ const swrKey = documentId && editor ? documentSWRKeys.editor(documentId) : null;
return useClientDataSWRWithSync<DocumentItem | null>(
swrKey,
@@ -213,6 +229,7 @@ export class DocumentActionImpl {
editorData: document.editorData,
sourceType,
+ topicId: topicId ?? undefined,
});
},
revalidateOnFocus: true,
diff --git a/src/store/document/slices/editor/action.test.ts b/src/store/document/slices/editor/action.test.ts
index 75fb5e7ebcc..df9d47380e6 100644
--- a/src/store/document/slices/editor/action.test.ts
+++ b/src/store/document/slices/editor/action.test.ts
@@ -29,6 +29,17 @@ const createMockEditor = () => ({
setDocument: vi.fn(),
});
+const createValidMockEditor = () => ({
+ getDocument: vi.fn((type: string) => {
+ if (type === 'markdown') return '# Test';
+ if (type === 'json') {
+ return { root: { children: [{ children: [], type: 'paragraph' }], type: 'root' } };
+ }
+ return null;
+ }),
+ setDocument: vi.fn(),
+});
+
describe('DocumentStore - Editor Actions', () => {
beforeEach(() => {
vi.mocked(documentService.updateDocument).mockResolvedValue({
@@ -73,6 +84,9 @@ describe('DocumentStore - Editor Actions', () => {
sourceType: 'notebook',
topicId: 'topic-1',
});
+ expect(result.current.lastActiveTopicDocumentIdByTopicId).toEqual({
+ 'topic-1': 'doc-1',
+ });
// Should NOT call setDocument - that happens in onEditorInit
expect(mockEditor.setDocument).not.toHaveBeenCalled();
});
@@ -449,7 +463,7 @@ describe('DocumentStore - Editor Actions', () => {
it('should save metadata-only updates when history is not appended', async () => {
const { result } = renderHook(() => useDocumentStore());
- const mockEditor = createMockEditor() as any;
+ const mockEditor = createValidMockEditor() as any;
vi.mocked(documentService.updateDocument).mockResolvedValue({
historyAppended: false,
@@ -483,9 +497,66 @@ describe('DocumentStore - Editor Actions', () => {
expect(result.current.documents['doc-1'].isDirty).toBe(false);
});
+ it('should save and persist raw editorData with diff nodes (pending human review)', async () => {
+ const { result } = renderHook(() => useDocumentStore());
+ const editorData = {
+ root: {
+ children: [
+ {
+ children: [
+ { children: [{ text: 'origin', type: 'text' }], type: 'paragraph' },
+ { children: [{ text: 'modified', type: 'text' }], type: 'paragraph' },
+ ],
+ diffType: 'modify',
+ type: 'diff',
+ },
+ {
+ children: [{ children: [{ text: 'added', type: 'text' }], type: 'paragraph' }],
+ diffType: 'add',
+ type: 'diff',
+ },
+ ],
+ type: 'root',
+ },
+ };
+ const mockEditor = {
+ getDocument: vi.fn((type: string) => {
+ if (type === 'markdown') return '# Test';
+ if (type === 'json') return editorData;
+ return null;
+ }),
+ setDocument: vi.fn(),
+ } as any;
+
+ act(() => {
+ result.current.initDocumentWithEditor({
+ content: '# Test',
+ documentId: 'doc-1',
+ editor: mockEditor,
+ sourceType: 'page',
+ });
+ result.current.markDirty('doc-1');
+ });
+
+ await act(async () => {
+ await result.current.performSave('doc-1');
+ });
+
+ // Autosave preserves diff nodes; DiffAllToolbar surfaces Accept/Reject
+ // on the next render and only then does the editor normalize the state.
+ expect(documentService.updateDocument).toHaveBeenCalledWith(
+ expect.objectContaining({
+ editorData: JSON.stringify(editorData),
+ id: 'doc-1',
+ }),
+ );
+ expect(result.current.documents['doc-1'].editorData).toEqual(editorData);
+ expect(result.current.documents['doc-1'].lastSavedEditorData).toEqual(editorData);
+ });
+
it('should pass restore metadata through updateDocument', async () => {
const { result } = renderHook(() => useDocumentStore());
- const mockEditor = createMockEditor() as any;
+ const mockEditor = createValidMockEditor() as any;
vi.mocked(documentService.updateDocument).mockResolvedValue({
historyAppended: true,
diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.ts
index 659df2b82bf..e51011e062f 100644
--- a/src/store/document/slices/editor/action.ts
+++ b/src/store/document/slices/editor/action.ts
@@ -180,7 +180,9 @@ export class EditorActionImpl {
return;
}
- // Save document
+ // Preserve diff nodes (pending review) through the save path.
+ // Normalization only happens when the user explicitly clicks Accept/Reject
+ // in DiffAllToolbar, which mutates editor state before calling performSave.
const result = await documentService.updateDocument({
content: currentContent,
editorData: JSON.stringify(currentEditorData),
diff --git a/src/store/document/slices/editor/initialState.ts b/src/store/document/slices/editor/initialState.ts
index 262c2619299..004b20426ef 100644
--- a/src/store/document/slices/editor/initialState.ts
+++ b/src/store/document/slices/editor/initialState.ts
@@ -77,6 +77,10 @@ export interface EditorState {
* Editor state from useEditorState hook
*/
editorState: LobehubEditorState | undefined;
+ /**
+ * Last notebook document opened from each topic.
+ */
+ lastActiveTopicDocumentIdByTopicId: Record<string, string>;
}
/**
@@ -103,4 +107,5 @@ export const initialEditorState: EditorState = {
documents: {},
editor: undefined,
editorState: undefined,
+ lastActiveTopicDocumentIdByTopicId: {},
};
diff --git a/src/store/global/actions/general.ts b/src/store/global/actions/general.ts
index e555ccc8b61..f0c13b34788 100644
--- a/src/store/global/actions/general.ts
+++ b/src/store/global/actions/general.ts
@@ -2,6 +2,7 @@ import isEqual from 'fast-deep-equal';
import { gt, parse, valid } from 'semver';
import { type SWRResponse } from 'swr';
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
import { CURRENT_VERSION, isDesktop } from '@/const/version';
import { useOnlyFetchOnceSWR } from '@/libs/swr';
import { globalService } from '@/services/global';
@@ -66,7 +67,7 @@ export class GlobalGeneralActionImpl {
openTopicInNewWindow = async (agentId: string, topicId: string): Promise<void> => {
const popupPath = `/popup/agent/${agentId}/${topicId}`;
- const browserUrl = `/agent/${agentId}?topic=${topicId}`;
+ const browserUrl = SESSION_CHAT_TOPIC_URL(agentId, topicId);
if (isDesktop) {
try {
diff --git a/src/store/notebook/action.ts b/src/store/notebook/action.ts
index 5f018d12833..d9d28914b6f 100644
--- a/src/store/notebook/action.ts
+++ b/src/store/notebook/action.ts
@@ -3,9 +3,10 @@ import { type DocumentItem } from '@lobechat/database/schemas';
import { type NotebookDocument } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
-import { mutate } from 'swr';
-import { useClientDataSWR } from '@/libs/swr';
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { invalidateDocumentMutation } from '@/services/document/invalidation';
+import { notebookSWRKeys } from '@/services/document/swrKeys';
import { notebookService } from '@/services/notebook';
import { useChatStore } from '@/store/chat';
import { type StoreSetter } from '@/store/types';
@@ -15,7 +16,7 @@ import { type NotebookStore } from './store';
const n = setNamespace('notebook');
-const SWR_USE_FETCH_NOTEBOOK_DOCUMENTS = 'SWR_USE_FETCH_NOTEBOOK_DOCUMENTS';
+export { SWR_USE_FETCH_NOTEBOOK_DOCUMENTS } from '@/services/document/swrKeys';
type ExtendedDocumentType = DocumentType | 'agent/plan';
@@ -53,8 +54,11 @@ export class NotebookActionImpl {
createDocument = async (params: CreateDocumentParams): Promise<DocumentItem> => {
const document = await notebookService.createDocument(params);
- // Refresh the documents list
- await mutate([SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, params.topicId]);
+ await invalidateDocumentMutation({
+ cause: 'notebook',
+ documentId: document.id,
+ topicId: params.topicId,
+ });
return document;
};
@@ -69,12 +73,11 @@ export class NotebookActionImpl {
// Call API to delete
await notebookService.deleteDocument(id);
- // Refresh the documents list
- await mutate([SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId]);
+ await invalidateDocumentMutation({ cause: 'notebook', documentId: id, topicId });
};
refreshDocuments = async (topicId: string): Promise<void> => {
- await mutate([SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId]);
+ await mutate(notebookSWRKeys.documents(topicId));
};
updateDocument = async (
@@ -83,15 +86,14 @@ export class NotebookActionImpl {
): Promise<DocumentItem | undefined> => {
const document = await notebookService.updateDocument(params);
- // Refresh the documents list
- await mutate([SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId]);
+ await invalidateDocumentMutation({ cause: 'notebook', documentId: params.id, topicId });
return document;
};
useFetchDocuments = (topicId: string | undefined): SWRResponse<NotebookDocument[]> => {
return useClientDataSWR<NotebookDocument[]>(
- topicId ? [SWR_USE_FETCH_NOTEBOOK_DOCUMENTS, topicId] : null,
+ topicId ? notebookSWRKeys.documents(topicId) : null,
async () => {
if (!topicId) return [];
diff --git a/src/store/page/slices/crud/action.ts b/src/store/page/slices/crud/action.ts
index 2eebd960fff..ce095dd59c9 100644
--- a/src/store/page/slices/crud/action.ts
+++ b/src/store/page/slices/crud/action.ts
@@ -2,6 +2,7 @@ import { type SWRResponse } from 'swr';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { documentService } from '@/services/document';
+import { documentSWRKeys } from '@/services/document/swrKeys';
import { type StoreSetter } from '@/store/types';
import { type LobeDocument } from '@/types/document';
import { DocumentSourceType } from '@/types/document';
@@ -350,7 +351,7 @@ export class CrudActionImpl {
};
useFetchPageDetail = (pageId: string | undefined): SWRResponse<LobeDocument | null> => {
- const swrKey = pageId ? ['pageDetail', pageId] : null;
+ const swrKey = pageId ? documentSWRKeys.pageDetail(pageId) : null;
return useClientDataSWRWithSync<LobeDocument | null>(
swrKey,
diff --git a/src/store/page/slices/list/action.ts b/src/store/page/slices/list/action.ts
index 563eada7070..6071f1f2cfc 100644
--- a/src/store/page/slices/list/action.ts
+++ b/src/store/page/slices/list/action.ts
@@ -2,6 +2,7 @@ import { type SWRResponse } from 'swr';
import { useClientDataSWRWithSync } from '@/libs/swr';
import { documentService } from '@/services/document';
+import { documentSWRKeys } from '@/services/document/swrKeys';
import { useGlobalStore } from '@/store/global';
import { type StoreSetter } from '@/store/types';
import { type LobeDocument } from '@/types/document';
@@ -124,7 +125,7 @@ export class ListActionImpl {
useFetchDocuments = (): SWRResponse<LobeDocument[]> => {
return useClientDataSWRWithSync<LobeDocument[]>(
- ['pageDocuments'],
+ documentSWRKeys.pageDocuments(),
async () => {
const pageSize = useGlobalStore.getState().status.pagePageSize || 20;
return (await documentService.getPageDocuments(pageSize)) as LobeDocument[];
diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
index 45538353860..e2dad4ab4c5 100644
--- a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
@@ -9,15 +9,38 @@ const runtime = new AgentDocumentsExecutionRuntime({
agentDocumentService.copyDocument({ agentId, id, newTitle }),
createDocument: ({ agentId, content, title }) =>
agentDocumentService.createDocument({ agentId, content, title }),
+ createTopicDocument: ({ agentId, content, title, topicId }) =>
+ agentDocumentService.createForTopic({ agentId, content, title, topicId }),
editDocument: ({ agentId, content, id }) =>
agentDocumentService.editDocument({ agentId, content, id }),
listDocuments: async ({ agentId }) => {
const docs = await agentDocumentService.listDocuments({ agentId });
- return docs.map((d) => ({ filename: d.filename, id: d.id, title: d.title }));
+ return docs.map((d) => ({
+ documentId: d.documentId,
+ filename: d.filename,
+ id: d.id,
+ title: d.title,
+ }));
},
- readDocument: ({ agentId, id }) => agentDocumentService.readDocument({ agentId, id }),
- readDocumentByFilename: ({ agentId, filename }) =>
- agentDocumentService.readDocumentByFilename({ agentId, filename }),
+ listTopicDocuments: async ({ agentId, topicId }) => {
+ const docs = await agentDocumentService.listDocuments({
+ agentId,
+ target: 'currentTopic',
+ topicId,
+ });
+ return docs.map((d) => ({
+ documentId: d.documentId,
+ filename: d.filename,
+ id: d.id,
+ title: d.title,
+ }));
+ },
+ modifyNodes: ({ agentId, id, operations }) =>
+ agentDocumentService.modifyNodes({ agentId, id, operations }),
+ readDocument: ({ agentId, format, id }) =>
+ agentDocumentService.readDocument({ agentId, format: format ?? 'xml', id }),
+ readDocumentByFilename: ({ agentId, filename, format }) =>
+ agentDocumentService.readDocumentByFilename({ agentId, filename, format: format ?? 'xml' }),
removeDocument: async ({ agentId, id }) =>
(await agentDocumentService.removeDocument({ agentId, id })).deleted,
renameDocument: ({ agentId, id, newTitle }) =>