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.

⚑️ perf: make SPA startup demand-aware (#17577)

Innei93213a51fb67
diff --git a/apps/desktop/vite.renderer.config.ts b/apps/desktop/vite.renderer.config.ts
index 5b5b4d337f1..611c344c8d5 100644
--- a/apps/desktop/vite.renderer.config.ts
+++ b/apps/desktop/vite.renderer.config.ts
@@ -11,7 +11,6 @@ import {
sharedOptimizeDeps,
sharedRendererDefine,
sharedRendererPlugins,
- sharedRollupOutput,
} from '../../plugins/vite/sharedRendererConfig';
import {
applyDesktopViteConfigExtension,
@@ -230,7 +229,6 @@ export default defineConfig(async (env) => {
overlay: path.resolve(__dirname, 'overlay.html'),
popup: path.resolve(__dirname, 'popup.html'),
},
- output: sharedRollupOutput,
},
sourcemap: false,
target: RENDERER_CHROME_TARGET,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
index 206ef1806c3..89ead0973d8 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts
@@ -1,7 +1,5 @@
-import {
- RemoteDeviceExecutionRuntime,
- RemoteDeviceIdentifier,
-} from '@lobechat/builtin-tool-remote-device';
+import { RemoteDeviceIdentifier } from '@lobechat/builtin-tool-remote-device';
+import { RemoteDeviceExecutionRuntime } from '@lobechat/builtin-tool-remote-device/executionRuntime';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type ToolExecutionContext } from '../../types';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillManagement.test.ts
index 2a4672a10d8..a58c93f1ed2 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillManagement.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skillManagement.test.ts
@@ -1,4 +1,4 @@
-import { SkillMaintainerExecutionRuntime } from '@lobechat/builtin-tool-skill-maintainer';
+import { SkillMaintainerExecutionRuntime } from '@lobechat/builtin-tool-skill-maintainer/executionRuntime';
import { describe, expect, it, vi } from 'vitest';
import { SkillManagementDocumentService } from '@/server/services/skillManagement';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalFeedbackIntent.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalFeedbackIntent.ts
index c69a538f107..5b61e4d7e44 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalFeedbackIntent.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalFeedbackIntent.ts
@@ -1,8 +1,8 @@
import {
AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER,
AGENT_SIGNAL_REFLECTION_TOOL_API_NAMES,
- AgentSignalToolExecutionRuntime,
} from '@lobechat/builtin-tool-agent-signal';
+import { AgentSignalToolExecutionRuntime } from '@lobechat/builtin-tool-agent-signal/executionRuntime';
import { createResourceRuntimePrimitives } from '@/server/services/agentSignal/services/selfIteration/tools/runtimePrimitives';
import { SkillManagementDocumentService } from '@/server/services/skillManagement';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReflection.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReflection.ts
index 3247231e252..9b97853c5f8 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReflection.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReflection.ts
@@ -1,8 +1,8 @@
import {
AGENT_SIGNAL_REFLECTION_IDENTIFIER,
AGENT_SIGNAL_REFLECTION_TOOL_API_NAMES,
- AgentSignalToolExecutionRuntime,
} from '@lobechat/builtin-tool-agent-signal';
+import { AgentSignalToolExecutionRuntime } from '@lobechat/builtin-tool-agent-signal/executionRuntime';
import { createResourceRuntimePrimitives } from '@/server/services/agentSignal/services/selfIteration/tools/runtimePrimitives';
import { SkillManagementDocumentService } from '@/server/services/skillManagement';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts
index 7b4a662698b..34269c56bfb 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalReview.ts
@@ -1,8 +1,8 @@
import {
AGENT_SIGNAL_REVIEW_IDENTIFIER,
AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,
- AgentSignalToolExecutionRuntime,
} from '@lobechat/builtin-tool-agent-signal';
+import { AgentSignalToolExecutionRuntime } from '@lobechat/builtin-tool-agent-signal/executionRuntime';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { BriefModel } from '@/database/models/brief';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalSkillManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalSkillManagement.ts
index c9be07e7b6f..8ce8f586e56 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentSignalSkillManagement.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentSignalSkillManagement.ts
@@ -1,8 +1,8 @@
import {
AGENT_SIGNAL_SKILL_MANAGEMENT_IDENTIFIER,
AGENT_SIGNAL_SKILL_MANAGEMENT_TOOL_API_NAMES,
- AgentSignalToolExecutionRuntime,
} from '@lobechat/builtin-tool-agent-signal';
+import { AgentSignalToolExecutionRuntime } from '@lobechat/builtin-tool-agent-signal/executionRuntime';
import { createResourceRuntimePrimitives } from '@/server/services/agentSignal/services/selfIteration/tools/runtimePrimitives';
import { SkillManagementDocumentService } from '@/server/services/skillManagement';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/calculator.ts b/apps/server/src/services/toolExecution/serverRuntimes/calculator.ts
index e1dd3ae2539..2089f440bb9 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/calculator.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/calculator.ts
@@ -1,4 +1,5 @@
-import { CalculatorExecutionRuntime, CalculatorManifest } from '@lobechat/builtin-tool-calculator';
+import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';
+import { CalculatorExecutionRuntime } from '@lobechat/builtin-tool-calculator/executionRuntime';
import { type ServerRuntimeRegistration } from './types';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
index c2eef901f4f..af0eb23ca53 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
@@ -1,7 +1,5 @@
-import {
- CloudSandboxExecutionRuntime,
- CloudSandboxIdentifier,
-} from '@lobechat/builtin-tool-cloud-sandbox';
+import { CloudSandboxIdentifier } from '@lobechat/builtin-tool-cloud-sandbox';
+import { CloudSandboxExecutionRuntime } from '@lobechat/builtin-tool-cloud-sandbox/executionRuntime';
import { FileService } from '@/server/services/file';
import { MarketService } from '@/server/services/market';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts
index 3a2469a82ed..a1319367cde 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts
@@ -1,8 +1,5 @@
-import {
- CredsExecutionRuntime,
- CredsIdentifier,
- type ICredsService,
-} from '@lobechat/builtin-tool-creds';
+import { CredsIdentifier, type ICredsService } from '@lobechat/builtin-tool-creds';
+import { CredsExecutionRuntime } from '@lobechat/builtin-tool-creds/executionRuntime';
import debug from 'debug';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
index 207a6e7a0d0..fd0cc499ee0 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
@@ -11,10 +11,10 @@ import {
hasUserVisualFiles,
LobeAgentIdentifier,
normalizeAnalyzeVisualMediaInput,
- PlanExecutionRuntime,
selectVisualFileItems,
validateVisualMediaUrls,
} from '@lobechat/builtin-tool-lobe-agent';
+import { PlanExecutionRuntime } from '@lobechat/builtin-tool-lobe-agent/planRuntime';
import { UserInteractionExecutionRuntime } from '@lobechat/builtin-tool-user-interaction/executionRuntime';
import type { LobeChatDatabase } from '@lobechat/database';
import type { ChatStreamPayload } from '@lobechat/model-runtime';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
index 8167cfb4e1e..96be36940ec 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/remoteDevice.ts
@@ -1,8 +1,8 @@
import {
type DeviceAttachment,
- RemoteDeviceExecutionRuntime,
RemoteDeviceIdentifier,
} from '@lobechat/builtin-tool-remote-device';
+import { RemoteDeviceExecutionRuntime } from '@lobechat/builtin-tool-remote-device/executionRuntime';
import debug from 'debug';
import { deviceGateway } from '@/server/services/deviceGateway';
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skillManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/skillManagement.ts
index da4cec4b190..87e7bfac468 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/skillManagement.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/skillManagement.ts
@@ -4,10 +4,10 @@ import {
type ListSkillsArgs,
type RenameSkillArgs,
type ReplaceSkillIndexArgs,
- SkillMaintainerExecutionRuntime,
SkillMaintainerIdentifier,
type SkillMaintainerRuntimeService,
} from '@lobechat/builtin-tool-skill-maintainer';
+import { SkillMaintainerExecutionRuntime } from '@lobechat/builtin-tool-skill-maintainer/executionRuntime';
import { SkillManagementDocumentService } from '@/server/services/skillManagement';
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 1546a74b372..d178b8615a5 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -6,6 +6,31 @@ import { flat as mdxFlat } from 'eslint-plugin-mdx';
const tsconfigRootDir = fileURLToPath(new URL('.', import.meta.url));
+const baseRestrictedImportOptions = restrictedImports.rules['no-restricted-imports'][1];
+
+const performanceRestrictedImportPaths = [
+ {
+ message:
+ 'Import the imperative facade from "@/features/ShareModal" so the modal implementation stays outside initial chunks.',
+ name: '@/features/ShareModal/Modal',
+ },
+];
+
+const createRestrictedImportRule = ({ paths = [], patterns } = {}) => [
+ 'error',
+ {
+ ...baseRestrictedImportOptions,
+ paths: [
+ ...(baseRestrictedImportOptions.paths ?? []),
+ ...performanceRestrictedImportPaths,
+ ...paths,
+ ],
+ ...(patterns?.length
+ ? { patterns: [...(baseRestrictedImportOptions.patterns ?? []), ...patterns] }
+ : {}),
+ },
+];
+
export default eslint(
{
ignores: [
@@ -56,6 +81,140 @@ export default eslint(
},
},
restrictedImports,
+ // Performance import boundaries. These restrictions preserve real import()
+ // seams instead of relying on component-level conditional rendering.
+ {
+ files: ['src/**/*.{ts,tsx}'],
+ rules: {
+ 'no-restricted-imports': createRestrictedImportRule(),
+ },
+ },
+ {
+ files: ['src/features/Conversation/**/*.{ts,tsx}'],
+ rules: {
+ 'no-restricted-imports': createRestrictedImportRule({
+ paths: [
+ {
+ message:
+ 'Conversation internals must use stable subpaths such as "./store", "./ConversationProvider", or "./Messages" instead of the root barrel.',
+ name: '@/features/Conversation',
+ },
+ ],
+ }),
+ },
+ },
+ {
+ files: ['src/features/NavPanel/**/*.{ts,tsx}'],
+ rules: {
+ 'no-restricted-imports': createRestrictedImportRule({
+ patterns: [
+ {
+ group: [
+ '@/routes/**/_layout/Sidebar',
+ '@/routes/**/_layout/Sidebar/**',
+ '@/routes/**/_layout/SideBar',
+ '@/routes/**/_layout/SideBar/**',
+ ],
+ message:
+ 'NavPanel must not own route Sidebar implementations. Register route content through NavPanelPortal.',
+ },
+ ],
+ }),
+ },
+ },
+ {
+ files: [
+ 'src/routes/**/_layout/Sidebar.{ts,tsx}',
+ 'src/routes/**/_layout/Sidebar/**/*.{ts,tsx}',
+ 'src/routes/**/_layout/SideBar.{ts,tsx}',
+ 'src/routes/**/_layout/SideBar/**/*.{ts,tsx}',
+ ],
+ rules: {
+ 'no-restricted-imports': createRestrictedImportRule({
+ paths: [
+ {
+ message:
+ 'Route Sidebars must import NavPanelPortal from its dedicated subpath instead of the NavPanel host barrel.',
+ name: '@/features/NavPanel',
+ },
+ ],
+ }),
+ },
+ },
+ {
+ files: ['src/features/HomeInbox/**/*.{ts,tsx}'],
+ rules: {
+ 'no-restricted-imports': createRestrictedImportRule({
+ paths: [
+ {
+ message:
+ 'Load RunReplyEditor with import() after reply intent so the editor stays outside the home static closure.',
+ name: '@/features/AgentTasks/AgentTaskDetail/RunReplyEditor',
+ },
+ {
+ message:
+ 'HomeInbox must not mount TopicChatDrawer; navigate to the topic or load an interaction-owned surface dynamically.',
+ name: '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer',
+ },
+ {
+ message:
+ 'HomeInbox must not mount TopicChatDrawer; navigate to the topic or load an interaction-owned surface dynamically.',
+ name: '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index',
+ },
+ {
+ message:
+ 'Use the imperative DocumentModal loader instead of statically importing the implementation.',
+ name: '@/features/DocumentModal',
+ },
+ {
+ message:
+ 'Use the imperative DocumentModal loader instead of statically importing the implementation.',
+ name: '@/features/DocumentModal/index',
+ },
+ ],
+ }),
+ },
+ },
+ {
+ files: ['src/routes/(main)/home/**/*.{ts,tsx}'],
+ ignores: [
+ 'src/routes/(main)/home/_layout/hooks/useCreateModal.tsx',
+ 'src/routes/(main)/home/features/InputArea/EditorInput.tsx',
+ ],
+ rules: {
+ 'no-restricted-imports': createRestrictedImportRule({
+ paths: [
+ {
+ message:
+ 'Home cold-path modules must use stable Conversation subpaths instead of the root barrel that exports ChatInput.',
+ name: '@/features/Conversation',
+ },
+ ],
+ patterns: [
+ {
+ message:
+ 'Home cold-path modules must not statically import ChatInput. Load an isolated editor entry with import().',
+ regex:
+ '^@/features/ChatInput(?:$|/(?!(?:store/initialState|utils/contextSelections)$).+)',
+ },
+ ],
+ }),
+ },
+ },
+ {
+ files: ['src/routes/(main)/home/features/InputArea/index.tsx'],
+ rules: {
+ 'no-restricted-imports': createRestrictedImportRule({
+ paths: [
+ {
+ message:
+ 'The home input must load EditorInput through useProgressiveEditor instead of adding it to the route static closure.',
+ name: './EditorInput',
+ },
+ ],
+ }),
+ },
+ },
// Global rule overrides
{
rules: {
diff --git a/eslint.config.test.mts b/eslint.config.test.mts
new file mode 100644
index 00000000000..8eeec8077be
--- /dev/null
+++ b/eslint.config.test.mts
@@ -0,0 +1,155 @@
+// @vitest-environment node
+
+import { ESLint } from 'eslint';
+import { describe, expect, it } from 'vitest';
+
+const eslint = new ESLint({ cwd: process.cwd() });
+
+const lintRestrictedImports = async (filePath: string, code: string): Promise<string[]> => {
+ const [result] = await eslint.lintText(code, { filePath });
+
+ return result.messages
+ .filter(({ ruleId }) => ruleId === 'no-restricted-imports')
+ .map(({ message }) => message);
+};
+
+const forbiddenImports = [
+ [
+ 'Conversation internal root barrel',
+ 'src/features/Conversation/ChatItem/lint-fixture.tsx',
+ `import { ChatInput } from '@/features/Conversation';\nvoid ChatInput;`,
+ 'Conversation internals must use stable subpaths',
+ ],
+ [
+ 'NavPanel route Sidebar ownership',
+ 'src/features/NavPanel/lint-fixture.tsx',
+ `import Sidebar from '@/routes/(main)/agent/_layout/Sidebar';\nvoid Sidebar;`,
+ 'NavPanel must not own route Sidebar implementations',
+ ],
+ [
+ 'NavPanel route SideBar ownership',
+ 'src/features/NavPanel/lint-fixture.tsx',
+ `import SideBar from '@/routes/(main)/settings/_layout/SideBar';\nvoid SideBar;`,
+ 'NavPanel must not own route Sidebar implementations',
+ ],
+ [
+ 'route Sidebar NavPanel host barrel',
+ 'src/routes/(main)/agent/_layout/Sidebar/lint-fixture.tsx',
+ `import NavPanel from '@/features/NavPanel';\nvoid NavPanel;`,
+ 'Route Sidebars must import NavPanelPortal from its dedicated subpath',
+ ],
+ [
+ 'HomeInbox RunReplyEditor static import',
+ 'src/features/HomeInbox/lint-fixture.tsx',
+ `import RunReplyEditor from '@/features/AgentTasks/AgentTaskDetail/RunReplyEditor';\nvoid RunReplyEditor;`,
+ 'Load RunReplyEditor with import()',
+ ],
+ [
+ 'HomeInbox TopicChatDrawer static import',
+ 'src/features/HomeInbox/lint-fixture.tsx',
+ `import TopicChatDrawer from '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer';\nvoid TopicChatDrawer;`,
+ 'HomeInbox must not mount TopicChatDrawer',
+ ],
+ [
+ 'HomeInbox DocumentModal implementation import',
+ 'src/features/HomeInbox/lint-fixture.tsx',
+ `import DocumentModal from '@/features/DocumentModal';\nvoid DocumentModal;`,
+ 'imperative DocumentModal loader',
+ ],
+ [
+ 'home cold-path ChatInput static import',
+ 'src/routes/(main)/home/features/lint-fixture.tsx',
+ `import { ChatInput } from '@/features/ChatInput';\nvoid ChatInput;`,
+ 'Home cold-path modules must not statically import ChatInput',
+ ],
+ [
+ 'home cold-path ChatInput subpath import',
+ 'src/routes/(main)/home/features/lint-fixture.tsx',
+ `import ChatInputDesktop from '@/features/ChatInput/Desktop';\nvoid ChatInputDesktop;`,
+ 'Home cold-path modules must not statically import ChatInput',
+ ],
+ [
+ 'home cold-path Conversation root barrel',
+ 'src/routes/(main)/home/features/lint-fixture.tsx',
+ `import { ChatInput } from '@/features/Conversation';\nvoid ChatInput;`,
+ 'Home cold-path modules must use stable Conversation subpaths',
+ ],
+ [
+ 'home input direct EditorInput import',
+ 'src/routes/(main)/home/features/InputArea/index.tsx',
+ `import EditorInput from './EditorInput';\nvoid EditorInput;`,
+ 'load EditorInput through useProgressiveEditor',
+ ],
+ [
+ 'ShareModal implementation bypass',
+ 'src/features/PageEditor/lint-fixture.tsx',
+ `import openShareModal from '@/features/ShareModal/Modal';\nvoid openShareModal;`,
+ 'Import the imperative facade from "@/features/ShareModal"',
+ ],
+ [
+ 'existing UI restriction remains active',
+ 'src/features/HomeInbox/lint-fixture.tsx',
+ `import { Button } from '@lobehub/ui';\nvoid Button;`,
+ 'Import from "@lobehub/ui/base-ui" instead',
+ ],
+] as const;
+
+const allowedImports = [
+ [
+ 'Conversation stable store subpath',
+ 'src/features/Conversation/ChatItem/lint-fixture.tsx',
+ `import { useConversationStore } from '@/features/Conversation/store';\nvoid useConversationStore;`,
+ ],
+ [
+ 'route Sidebar dedicated Portal subpath',
+ 'src/routes/(main)/agent/_layout/Sidebar/lint-fixture.tsx',
+ `import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';\nvoid NavPanelPortal;`,
+ ],
+ [
+ 'HomeInbox interaction-triggered editor import',
+ 'src/features/HomeInbox/lint-fixture.tsx',
+ `void import('@/features/AgentTasks/AgentTaskDetail/RunReplyEditor');`,
+ ],
+ [
+ 'HomeInbox imperative DocumentModal loader',
+ 'src/features/HomeInbox/lint-fixture.tsx',
+ `import { openDocumentModal } from '@/features/DocumentModal/loader';\nvoid openDocumentModal;`,
+ ],
+ [
+ 'home interaction-triggered ChatInput import',
+ 'src/routes/(main)/home/features/lint-fixture.tsx',
+ `void import('@/features/ChatInput');`,
+ ],
+ [
+ 'home lightweight ChatInput initial-state utility',
+ 'src/routes/(main)/home/features/lint-fixture.tsx',
+ `import { initialState } from '@/features/ChatInput/store/initialState';\nvoid initialState;`,
+ ],
+ [
+ 'home lightweight ChatInput context-selection utility',
+ 'src/routes/(main)/home/features/lint-fixture.tsx',
+ `import { resolveContextSelections } from '@/features/ChatInput/utils/contextSelections';\nvoid resolveContextSelections;`,
+ ],
+ [
+ 'isolated home EditorInput entry',
+ 'src/routes/(main)/home/features/InputArea/EditorInput.tsx',
+ `import { ChatInput } from '@/features/ChatInput';\nvoid ChatInput;`,
+ ],
+ [
+ 'ShareModal imperative facade',
+ 'src/features/PageEditor/lint-fixture.tsx',
+ `import { openShareModal } from '@/features/ShareModal';\nvoid openShareModal;`,
+ ],
+] as const;
+
+describe('performance import boundaries', () => {
+ it.each(forbiddenImports)('rejects %s', async (_name, filePath, code, message) => {
+ await expect(lintRestrictedImports(filePath, code)).resolves.toEqual([
+ expect.stringContaining(message),
+ ]);
+ });
+
+ it.each(allowedImports)('allows %s', async (_name, filePath, code) => {
+ await expect(lintRestrictedImports(filePath, code)).resolves.toEqual([]);
+ });
+});
diff --git a/package.json b/package.json
index 314a2d280e8..ce796a1078e 100644
--- a/package.json
+++ b/package.json
@@ -295,7 +295,7 @@
"@lobehub/analytics": "^1.6.3",
"@lobehub/charts": "^5.4.0",
"@lobehub/desktop-ipc-typings": "workspace:*",
- "@lobehub/editor": "^4.19.1",
+ "@lobehub/editor": "^4.23.0",
"@lobehub/icons": "^5.11.0",
"@lobehub/market-sdk": "0.39.2",
"@lobehub/tts": "^5.1.2",
@@ -438,7 +438,7 @@
"rtl-detect": "^1.1.2",
"semver": "^7.8.5",
"sharp": "^0.34.5",
- "shiki": "^3.23.0",
+ "shiki": "^4.3.1",
"stripe": "^17.7.0",
"superjson": "^2.2.6",
"svix": "^1.96.1",
@@ -476,6 +476,7 @@
"@peculiar/webcrypto": "^1.7.1",
"@playwright/test": "^1.61.1",
"@prettier/sync": "^0.6.1",
+ "@rolldown/plugin-transform-imports": "0.1.1",
"@semantic-release/exec": "^6.0.3",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
diff --git a/packages/builtin-tool-agent-documents/src/index.ts b/packages/builtin-tool-agent-documents/src/index.ts
index 8ad6b713bdc..18123a6f5b3 100644
--- a/packages/builtin-tool-agent-documents/src/index.ts
+++ b/packages/builtin-tool-agent-documents/src/index.ts
@@ -1,4 +1,3 @@
-export * from './ExecutionRuntime';
export { AgentDocumentsManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
diff --git a/packages/builtin-tool-agent-signal/src/index.ts b/packages/builtin-tool-agent-signal/src/index.ts
index 2d5bfb973d9..2ae3179583b 100644
--- a/packages/builtin-tool-agent-signal/src/index.ts
+++ b/packages/builtin-tool-agent-signal/src/index.ts
@@ -14,13 +14,12 @@ export {
AGENT_SIGNAL_TOOL_RESULT_KIND,
type AgentSignalToolApiName,
} from './shared/apiNames';
-export {
- type AgentSignalRuntimePrimitive,
- type AgentSignalRuntimeService,
- type AgentSignalToolContext,
- AgentSignalToolExecutionRuntime,
- type AgentSignalToolExecutionRuntimeOptions,
- type ToolResultKind,
+export type {
+ AgentSignalRuntimePrimitive,
+ AgentSignalRuntimeService,
+ AgentSignalToolContext,
+ AgentSignalToolExecutionRuntimeOptions,
+ ToolResultKind,
} from './shared/ExecutionRuntime';
export {
AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER,
diff --git a/packages/builtin-tool-calculator/package.json b/packages/builtin-tool-calculator/package.json
index e0ed2a637de..c0af8f79b1a 100644
--- a/packages/builtin-tool-calculator/package.json
+++ b/packages/builtin-tool-calculator/package.json
@@ -5,7 +5,9 @@
"exports": {
".": "./src/index.ts",
"./client": "./src/client/index.ts",
- "./executor": "./src/executor/index.ts"
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts",
+ "./executor": "./src/executor/index.ts",
+ "./manifest": "./src/manifest.ts"
},
"main": "./src/index.ts",
"dependencies": {
diff --git a/packages/builtin-tool-calculator/src/client/index.ts b/packages/builtin-tool-calculator/src/client/index.ts
index 7dbe0f19cfc..a0e81f7c5d4 100644
--- a/packages/builtin-tool-calculator/src/client/index.ts
+++ b/packages/builtin-tool-calculator/src/client/index.ts
@@ -1,5 +1,2 @@
-// Client-side exports for the Calculator tool
-
-export { calculatorExecutor } from '../executor';
export { CalculatorManifest } from '../manifest';
export * from '../types';
diff --git a/packages/builtin-tool-calculator/src/index.ts b/packages/builtin-tool-calculator/src/index.ts
index 47986dd2595..bc873eb3830 100644
--- a/packages/builtin-tool-calculator/src/index.ts
+++ b/packages/builtin-tool-calculator/src/index.ts
@@ -1,4 +1,3 @@
-export * from './ExecutionRuntime';
export { CalculatorManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
diff --git a/packages/builtin-tool-cloud-sandbox/src/index.ts b/packages/builtin-tool-cloud-sandbox/src/index.ts
index f017b83bbc7..22c87a25fec 100644
--- a/packages/builtin-tool-cloud-sandbox/src/index.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/index.ts
@@ -1,4 +1,3 @@
-export * from './ExecutionRuntime';
export * from './manifest';
export * from './systemRole';
export * from './types';
diff --git a/packages/builtin-tool-creds/package.json b/packages/builtin-tool-creds/package.json
index a7a32501c82..40b113b086e 100644
--- a/packages/builtin-tool-creds/package.json
+++ b/packages/builtin-tool-creds/package.json
@@ -6,6 +6,7 @@
"exports": {
".": "./src/index.ts",
"./client": "./src/client/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts",
"./executor": "./src/executor/index.ts"
},
"main": "./src/index.ts",
diff --git a/packages/builtin-tool-creds/src/index.ts b/packages/builtin-tool-creds/src/index.ts
index 958a58afc60..00c4fef2df9 100644
--- a/packages/builtin-tool-creds/src/index.ts
+++ b/packages/builtin-tool-creds/src/index.ts
@@ -1,4 +1,4 @@
-export { CredsExecutionRuntime, type ICredsService } from './ExecutionRuntime';
+export type { ICredsService } from './ExecutionRuntime';
export {
checkCredsSatisfied,
type ComposioAppTypeLike,
diff --git a/packages/builtin-tool-image-generation/src/client/index.ts b/packages/builtin-tool-image-generation/src/client/index.ts
index 4f2421183a2..e13ceb96f00 100644
--- a/packages/builtin-tool-image-generation/src/client/index.ts
+++ b/packages/builtin-tool-image-generation/src/client/index.ts
@@ -1,6 +1,5 @@
export { ImageGenerationManifest } from '../manifest';
export * from '../types';
-export { imageGenerationExecutor } from './executor';
export { ImageGenerationInspector, ImageGenerationInspectors } from './Inspector';
export {
GenerateImageRender,
diff --git a/packages/builtin-tool-image-generation/src/index.ts b/packages/builtin-tool-image-generation/src/index.ts
index 8e475b77eb0..25a3cec44a6 100644
--- a/packages/builtin-tool-image-generation/src/index.ts
+++ b/packages/builtin-tool-image-generation/src/index.ts
@@ -1,7 +1,4 @@
-export {
- ImageGenerationExecutionRuntime,
- type ImageGenerationRuntimeService,
-} from './ExecutionRuntime';
+export type { ImageGenerationRuntimeService } from './ExecutionRuntime';
export { ImageGenerationManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
diff --git a/packages/builtin-tool-lobe-agent/package.json b/packages/builtin-tool-lobe-agent/package.json
index 91999f0c7da..cbfcc10ade2 100644
--- a/packages/builtin-tool-lobe-agent/package.json
+++ b/packages/builtin-tool-lobe-agent/package.json
@@ -5,7 +5,8 @@
"exports": {
".": "./src/index.ts",
"./client": "./src/client/index.ts",
- "./client/executor": "./src/client/executor/index.ts"
+ "./client/executor": "./src/client/executor/index.ts",
+ "./planRuntime": "./src/client/executor/PlanRuntime/index.ts"
},
"main": "./src/index.ts",
"scripts": {
diff --git a/packages/builtin-tool-lobe-agent/src/index.ts b/packages/builtin-tool-lobe-agent/src/index.ts
index 1779b0fb527..820b2f05f84 100644
--- a/packages/builtin-tool-lobe-agent/src/index.ts
+++ b/packages/builtin-tool-lobe-agent/src/index.ts
@@ -1,7 +1,6 @@
// Plan execution runtime β€” pure logic, safe to consume server-side
export {
type PlanDocument,
- PlanExecutionRuntime,
type PlanRuntimeContext,
type PlanRuntimeService,
} from './client/executor/PlanRuntime';
diff --git a/packages/builtin-tool-page-agent/package.json b/packages/builtin-tool-page-agent/package.json
index 280fa1afb08..a95dd62855c 100644
--- a/packages/builtin-tool-page-agent/package.json
+++ b/packages/builtin-tool-page-agent/package.json
@@ -5,6 +5,7 @@
"exports": {
".": "./src/index.ts",
"./client": "./src/client/index.ts",
+ "./client/executor": "./src/client/executor/index.ts",
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
diff --git a/packages/builtin-tool-page-agent/src/client/index.ts b/packages/builtin-tool-page-agent/src/client/index.ts
index 6b27dcd3cb7..027c6d2c2c5 100644
--- a/packages/builtin-tool-page-agent/src/client/index.ts
+++ b/packages/builtin-tool-page-agent/src/client/index.ts
@@ -1,4 +1,3 @@
-export { PageAgentExecutor } from './executor';
export { PageAgentInspectors } from './Inspector';
export { PageAgentPlaceholders } from './Placeholder';
export { PageAgentRenders } from './Render';
diff --git a/packages/builtin-tool-remote-device/package.json b/packages/builtin-tool-remote-device/package.json
index 25b68f68c30..7efa0158ce9 100644
--- a/packages/builtin-tool-remote-device/package.json
+++ b/packages/builtin-tool-remote-device/package.json
@@ -4,7 +4,8 @@
"private": true,
"exports": {
".": "./src/index.ts",
- "./client": "./src/client/index.ts"
+ "./client": "./src/client/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
"dependencies": {
diff --git a/packages/builtin-tool-remote-device/src/index.ts b/packages/builtin-tool-remote-device/src/index.ts
index f00153e4917..dc44d916f7c 100644
--- a/packages/builtin-tool-remote-device/src/index.ts
+++ b/packages/builtin-tool-remote-device/src/index.ts
@@ -1,4 +1,4 @@
-export { RemoteDeviceExecutionRuntime, type RemoteDeviceRuntimeService } from './ExecutionRuntime';
+export type { RemoteDeviceRuntimeService } from './ExecutionRuntime';
export type { DeviceAttachment } from './ExecutionRuntime/types';
export { RemoteDeviceManifest } from './manifest';
export { generateSystemPrompt, systemPrompt } from './systemRole';
diff --git a/packages/builtin-tool-self-iteration/src/index.test.ts b/packages/builtin-tool-self-iteration/src/index.test.ts
index 422a0c96754..4fd6cee2b9f 100644
--- a/packages/builtin-tool-self-iteration/src/index.test.ts
+++ b/packages/builtin-tool-self-iteration/src/index.test.ts
@@ -1,12 +1,12 @@
import type { LobeToolManifest, OperationToolSet, ToolSource } from '@lobechat/context-engine';
import { describe, expect, it, vi } from 'vitest';
+import { SelfFeedbackIntentExecutionRuntime } from './ExecutionRuntime';
import {
injectSelfFeedbackIntentTool,
SELF_FEEDBACK_INTENT_API_NAME,
SELF_FEEDBACK_INTENT_IDENTIFIER,
SELF_FEEDBACK_INTENT_TOOL_NAME,
- SelfFeedbackIntentExecutionRuntime,
selfFeedbackIntentManifest,
shouldExposeSelfFeedbackIntentTool,
} from './index';
diff --git a/packages/builtin-tool-self-iteration/src/index.ts b/packages/builtin-tool-self-iteration/src/index.ts
index aca3512bc56..d457ec616f4 100644
--- a/packages/builtin-tool-self-iteration/src/index.ts
+++ b/packages/builtin-tool-self-iteration/src/index.ts
@@ -1,4 +1,3 @@
-export * from './ExecutionRuntime';
export {
injectSelfFeedbackIntentTool,
type SelfFeedbackIntentToolSetParts,
@@ -15,18 +14,18 @@ export {
type DeclareSelfFeedbackIntentResult,
type DeclareSelfFeedbackIntentState,
type DeclareSelfFeedbackIntentStateReason,
- SELF_FEEDBACK_INTENT_API_NAME,
SELF_FEEDBACK_INTENT_ACTIONS,
+ SELF_FEEDBACK_INTENT_API_NAME,
SELF_FEEDBACK_INTENT_EVIDENCE_REF_TYPES,
SELF_FEEDBACK_INTENT_IDENTIFIER,
SELF_FEEDBACK_INTENT_KINDS,
SELF_FEEDBACK_INTENT_TOOL_NAME,
- type ShouldExposeSelfFeedbackIntentToolOptions,
+ type SelfFeedbackIntentAction,
SelfFeedbackIntentApiName,
type SelfFeedbackIntentApiNameType,
- type SelfFeedbackIntentAction,
type SelfFeedbackIntentEvidenceRef,
type SelfFeedbackIntentEvidenceRefType,
type SelfFeedbackIntentKind,
type SelfFeedbackIntentStrength,
+ type ShouldExposeSelfFeedbackIntentToolOptions,
} from './types';
diff --git a/packages/builtin-tool-skill-maintainer/src/index.ts b/packages/builtin-tool-skill-maintainer/src/index.ts
index 10f1d8efc4d..4fe58a91a70 100644
--- a/packages/builtin-tool-skill-maintainer/src/index.ts
+++ b/packages/builtin-tool-skill-maintainer/src/index.ts
@@ -1,5 +1,4 @@
export type { SkillMaintainerRuntimeService } from './ExecutionRuntime';
-export { SkillMaintainerExecutionRuntime } from './ExecutionRuntime';
export { SkillMaintainerManifest } from './manifest';
export {
type CreateSkillArgs,
diff --git a/packages/builtin-tool-user-interaction/src/index.ts b/packages/builtin-tool-user-interaction/src/index.ts
index 0d29756e518..385b5957ef6 100644
--- a/packages/builtin-tool-user-interaction/src/index.ts
+++ b/packages/builtin-tool-user-interaction/src/index.ts
@@ -1,4 +1,3 @@
-export * from './ExecutionRuntime';
export { UserInteractionManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.ts
index 18d0d675673..89106a7b274 100644
--- a/packages/builtin-tools/src/identifiers.ts
+++ b/packages/builtin-tools/src/identifiers.ts
@@ -9,7 +9,7 @@ import {
agentSignalSkillManagementManifest,
} from '@lobechat/builtin-tool-agent-signal';
import { BrowserManifest } from '@lobechat/builtin-tool-browser';
-import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';
+import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 8a2d0d71cf0..02e57f23e10 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -10,7 +10,7 @@ import {
} from '@lobechat/builtin-tool-agent-signal';
import { BriefManifest } from '@lobechat/builtin-tool-brief';
import { BrowserManifest } from '@lobechat/builtin-tool-browser';
-import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';
+import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';
diff --git a/packages/business/config/src/llm.ts b/packages/business/config/src/llm.ts
index 9f9894c85e0..02f297a0337 100644
--- a/packages/business/config/src/llm.ts
+++ b/packages/business/config/src/llm.ts
@@ -1,19 +1,31 @@
-import type { ModelProviderCard, UserModelProviderConfig } from '@lobechat/types';
-import { ModelProvider } from 'model-bank';
-import * as ProviderCards from 'model-bank/modelProviders';
+import type { UserModelProviderConfig } from '@lobechat/types';
+import { ModelProvider } from 'model-bank/modelProvider';
+import opencodezenModels from 'model-bank/opencodeZen';
-const genUserLLMConfig = (specificConfig: Record<any, any>): UserModelProviderConfig => {
- return Object.keys(ModelProvider).reduce((config, providerKey) => {
- const provider = ModelProvider[providerKey as keyof typeof ModelProvider];
- const providerCard = ProviderCards[
- `${providerKey}ProviderCard` as keyof typeof ProviderCards
- ] as ModelProviderCard;
- const providerConfig = specificConfig[provider as keyof typeof specificConfig] || {};
+const enabledOpenCodeZenModels = opencodezenModels
+ .filter(({ enabled }) => enabled)
+ .map(({ id }) => id);
+
+const providerDefaults: Partial<
+ Record<ModelProvider, { enabled?: boolean; enabledModels?: string[]; fetchOnClient?: boolean }>
+> = {
+ [ModelProvider.Anthropic]: { enabled: true },
+ [ModelProvider.DeepSeek]: { enabled: true },
+ [ModelProvider.Google]: { enabled: true },
+ [ModelProvider.LMStudio]: { fetchOnClient: true },
+ [ModelProvider.Ollama]: { fetchOnClient: true },
+ [ModelProvider.OpenAI]: { enabled: true },
+ [ModelProvider.OpenCodeZen]: { enabledModels: enabledOpenCodeZenModels },
+};
+
+const genUserLLMConfig = (): UserModelProviderConfig => {
+ return Object.values(ModelProvider).reduce((config, provider) => {
+ const providerConfig = providerDefaults[provider];
config[provider] = {
- enabled: providerConfig.enabled !== undefined ? providerConfig.enabled : false,
- enabledModels: providerCard ? ProviderCards.filterEnabledModels(providerCard) : [],
- ...(providerConfig.fetchOnClient !== undefined && {
+ enabled: providerConfig?.enabled ?? false,
+ enabledModels: providerConfig?.enabledModels ?? [],
+ ...(providerConfig?.fetchOnClient !== undefined && {
fetchOnClient: providerConfig.fetchOnClient,
}),
};
@@ -22,23 +34,4 @@ const genUserLLMConfig = (specificConfig: Record<any, any>): UserModelProviderCo
}, {} as UserModelProviderConfig);
};
-export const DEFAULT_LLM_CONFIG = genUserLLMConfig({
- anthropic: {
- enabled: true,
- },
- deepseek: {
- enabled: true,
- },
- google: {
- enabled: true,
- },
- lmstudio: {
- fetchOnClient: true,
- },
- ollama: {
- fetchOnClient: true,
- },
- openai: {
- enabled: true,
- },
-});
+export const DEFAULT_LLM_CONFIG = genUserLLMConfig();
diff --git a/packages/fetch-sse/src/fetchSSE.ts b/packages/fetch-sse/src/fetchSSE.ts
index c850baf0d70..ea805112f72 100644
--- a/packages/fetch-sse/src/fetchSSE.ts
+++ b/packages/fetch-sse/src/fetchSSE.ts
@@ -1,5 +1,5 @@
import { LOBE_CHAT_OBSERVATION_ID, LOBE_CHAT_TRACE_ID, MESSAGE_CANCEL_FLAT } from '@lobechat/const';
-import { parseToolCalls } from '@lobechat/model-runtime';
+import { parseToolCalls } from '@lobechat/model-runtime/helpers/parseToolCalls';
import type {
ChatImageChunk,
ChatMessageError,
diff --git a/packages/fetch-sse/vitest.config.mts b/packages/fetch-sse/vitest.config.mts
index 00bc0f9ea78..2653da26f72 100644
--- a/packages/fetch-sse/vitest.config.mts
+++ b/packages/fetch-sse/vitest.config.mts
@@ -4,10 +4,13 @@ import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
- alias: {
- // Keep this package unit-testable when a parent workspace overrides model-runtime.
- '@lobechat/model-runtime': path.resolve(__dirname, '../model-runtime/src/helpers/index.ts'),
- },
+ alias: [
+ {
+ // Keep the root import unit-testable without shadowing package subpath exports.
+ find: /^@lobechat\/model-runtime$/,
+ replacement: path.resolve(__dirname, '../model-runtime/src/helpers/index.ts'),
+ },
+ ],
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'lcov', 'text-summary'],
diff --git a/packages/locales/src/default/models.ts b/packages/locales/src/default/models.ts
index dec1dbf83bd..f5a306b54f8 100644
--- a/packages/locales/src/default/models.ts
+++ b/packages/locales/src/default/models.ts
@@ -1,5 +1,7 @@
import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';
+import { modelDescriptionOverrides } from '../modelDescriptionOverrides';
+
const locales: Record<`${string}.description`, string> = {};
LOBE_DEFAULT_MODEL_LIST.forEach((model) => {
@@ -8,28 +10,6 @@ LOBE_DEFAULT_MODEL_LIST.forEach((model) => {
locales[`${model.id}.description`] = model.description;
});
-// #region LobeHub online model descriptions
-const lobeHubOnlineModelLocales = {
- 'dreamina-seedance-2-0-260128.description':
- 'Seedance 2.0 by ByteDance is the most powerful video generation model, supporting multimodal reference video generation, video editing, video extension, text-to-video, and image-to-video with synchronized audio.',
- 'dreamina-seedance-2-0-fast-260128.description':
- 'Seedance 2.0 Fast by ByteDance offers the same capabilities as Seedance 2.0 with faster generation speeds at a more competitive price.',
- 'fal-ai/bytedance/seedream/v4.5.description':
- 'Seedream 4.5, built by ByteDance Seed team, supports multi-image editing and composition. Features enhanced subject consistency, precise instruction following, spatial logic understanding, aesthetic expression, poster layout and logo design with high-precision text-image rendering.',
- 'grok-4.20-beta-0309-non-reasoning.description': 'A non-reasoning variant for simple use cases',
- 'grok-4.20-beta-0309-reasoning.description':
- 'Intelligent, blazing-fast model that reasons before responding',
- 'lobehub-glm-5.2-fast.description':
- 'Fast variant of GLM-5.2 with substantially lower latency. Same capabilities as GLM-5.2 β€” costs more, but responds much faster.',
- 'qwen3.8-max-preview.description':
- "Qwen3.8-Max-Preview is a preview of Alibaba's next-generation 2.4T-parameter flagship model, with major gains over Qwen3.7-Max in coding and professional productivity, and leading performance on complex long-horizon tasks such as full-stack development and data analysis.",
- 'seedance-1-5-pro-251215.description':
- 'Seedance 1.5 Pro by ByteDance supports text-to-video, image-to-video (first frame, first+last frame), and audio generation synchronized with visuals.',
- 'seedream-5-0-260128.description':
- 'ByteDance-Seedream-5.0-lite by BytePlus features web-retrieval-augmented generation for real-time information, enhanced complex prompt interpretation, and improved reference consistency for professional visual creation.',
-} satisfies Record<`${string}.description`, string>;
-
-Object.assign(locales, lobeHubOnlineModelLocales);
-// #endregion
+Object.assign(locales, modelDescriptionOverrides);
export default locales;
diff --git a/packages/locales/src/default/models.vite.ts b/packages/locales/src/default/models.vite.ts
new file mode 100644
index 00000000000..ad87aee7f37
--- /dev/null
+++ b/packages/locales/src/default/models.vite.ts
@@ -0,0 +1,8 @@
+import { modelDescriptionOverrides } from '../modelDescriptionOverrides';
+
+/**
+ * The client already receives each model's English description with its model card and uses it as
+ * i18next's defaultValue. Keep only app-owned overrides in the browser namespace so loading the
+ * models locale does not import the complete model-bank catalog.
+ */
+export default modelDescriptionOverrides;
diff --git a/packages/locales/src/default/providers.vite.ts b/packages/locales/src/default/providers.vite.ts
new file mode 100644
index 00000000000..5bfb5b2eb91
--- /dev/null
+++ b/packages/locales/src/default/providers.vite.ts
@@ -0,0 +1,4 @@
+const locales: Record<`${string}.description`, string> = {};
+
+/** Provider cards already carry their English descriptions for the client-side defaultValue. */
+export default locales;
diff --git a/packages/locales/src/modelDescriptionOverrides.ts b/packages/locales/src/modelDescriptionOverrides.ts
new file mode 100644
index 00000000000..adfc221180f
--- /dev/null
+++ b/packages/locales/src/modelDescriptionOverrides.ts
@@ -0,0 +1,19 @@
+export const modelDescriptionOverrides = {
+ 'dreamina-seedance-2-0-260128.description':
+ 'Seedance 2.0 by ByteDance is the most powerful video generation model, supporting multimodal reference video generation, video editing, video extension, text-to-video, and image-to-video with synchronized audio.',
+ 'dreamina-seedance-2-0-fast-260128.description':
+ 'Seedance 2.0 Fast by ByteDance offers the same capabilities as Seedance 2.0 with faster generation speeds at a more competitive price.',
+ 'fal-ai/bytedance/seedream/v4.5.description':
+ 'Seedream 4.5, built by ByteDance Seed team, supports multi-image editing and composition. Features enhanced subject consistency, precise instruction following, spatial logic understanding, aesthetic expression, poster layout and logo design with high-precision text-image rendering.',
+ 'grok-4.20-beta-0309-non-reasoning.description': 'A non-reasoning variant for simple use cases',
+ 'grok-4.20-beta-0309-reasoning.description':
+ 'Intelligent, blazing-fast model that reasons before responding',
+ 'lobehub-glm-5.2-fast.description':
+ 'Fast variant of GLM-5.2 with substantially lower latency. Same capabilities as GLM-5.2 β€” costs more, but responds much faster.',
+ 'qwen3.8-max-preview.description':
+ "Qwen3.8-Max-Preview is a preview of Alibaba's next-generation 2.4T-parameter flagship model, with major gains over Qwen3.7-Max in coding and professional productivity, and leading performance on complex long-horizon tasks such as full-stack development and data analysis.",
+ 'seedance-1-5-pro-251215.description':
+ 'Seedance 1.5 Pro by ByteDance supports text-to-video, image-to-video (first frame, first+last frame), and audio generation synchronized with visuals.',
+ 'seedream-5-0-260128.description':
+ 'ByteDance-Seedream-5.0-lite by BytePlus features web-retrieval-augmented generation for real-time information, enhanced complex prompt interpretation, and improved reference consistency for professional visual creation.',
+} satisfies Record<`${string}.description`, string>;
diff --git a/packages/model-bank/package.json b/packages/model-bank/package.json
index cd69302da16..e5915bfe5df 100644
--- a/packages/model-bank/package.json
+++ b/packages/model-bank/package.json
@@ -4,6 +4,9 @@
"private": true,
"exports": {
".": "./src/index.ts",
+ "./aiModel": "./src/types/aiModel.ts",
+ "./aiProvider": "./src/types/aiProvider.ts",
+ "./modelProvider": "./src/const/modelProvider.ts",
"./modelProviders": "./src/modelProviders/index.ts",
"./modelProviders/lobehub": "./src/modelProviders/lobehub.ts",
"./ai21": "./src/aiModels/ai21.ts",
@@ -90,6 +93,7 @@
"./zenmux": "./src/aiModels/zenmux.ts",
"./zeroone": "./src/aiModels/zeroone.ts",
"./zhipu": "./src/aiModels/zhipu.ts",
+ "./standardParameters": "./src/standard-parameters/index.ts",
"./types": "./src/types/index.ts"
},
"scripts": {
diff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.json
index a70b2cfd506..beafd72aafa 100644
--- a/packages/model-runtime/package.json
+++ b/packages/model-runtime/package.json
@@ -4,6 +4,16 @@
"private": true,
"exports": {
".": "./src/index.ts",
+ "./errors": "./src/errors/index.ts",
+ "./getModelPropertyWithFallback": "./src/utils/getFallbackModelProperty.ts",
+ "./helpers/parseToolCalls": "./src/helpers/parseToolCalls.ts",
+ "./providers/openai/modelId": "./src/providers/openai/modelId.ts",
+ "./resolveImageSinglePrice": "./src/core/usageConverters/utils/resolveImageSinglePrice.ts",
+ "./resolveVideoSinglePrice": "./src/core/usageConverters/utils/resolveVideoSinglePrice.ts",
+ "./types/error": "./src/types/error.ts",
+ "./utils/createError": "./src/utils/createError.ts",
+ "./utils/modelExtendParams": "./src/utils/modelExtendParams.ts",
+ "./utils/uriParser": "./src/utils/uriParser.ts",
"./vertexai": "./src/providers/vertexai/index.ts"
},
"scripts": {
diff --git a/packages/types/src/aiProvider.ts b/packages/types/src/aiProvider.ts
index 83caf9dad66..31560a2bb40 100644
--- a/packages/types/src/aiProvider.ts
+++ b/packages/types/src/aiProvider.ts
@@ -28,7 +28,7 @@ export type {
ResponseAnimationStyle,
UpdateAiProviderConfigParams,
UpdateAiProviderParams,
-} from 'model-bank';
+} from 'model-bank/aiProvider';
export {
AiProviderAuthTypeEnum,
AiProviderSDKEnum,
@@ -36,4 +36,4 @@ export {
CreateAiProviderSchema,
UpdateAiProviderConfigSchema,
UpdateAiProviderSchema,
-} from 'model-bank';
+} from 'model-bank/aiProvider';
diff --git a/packages/utils/src/number.ts b/packages/utils/src/number.ts
index ad22ecdb5c5..04096bc61dd 100644
--- a/packages/utils/src/number.ts
+++ b/packages/utils/src/number.ts
@@ -1,4 +1,4 @@
-import { IMAGE_GENERATION_CONFIG, MAX_SEED } from 'model-bank';
+import { IMAGE_GENERATION_CONFIG, MAX_SEED } from 'model-bank/standardParameters';
import prand from 'pure-rand';
export function generateUniqueSeeds(seedCount: number): number[] {
diff --git a/plugins/vite/lobeIconImports.test.ts b/plugins/vite/lobeIconImports.test.ts
new file mode 100644
index 00000000000..7d59bf77d76
--- /dev/null
+++ b/plugins/vite/lobeIconImports.test.ts
@@ -0,0 +1,50 @@
+import { build, type Plugin } from 'vite';
+import { describe, expect, it } from 'vitest';
+
+import { lobeIconImports } from './lobeIconImports';
+
+const ENTRY_ID = '\0lobe-icon-imports-fixture.mjs';
+
+const fixturePlugin: Plugin = {
+ name: 'lobe-icon-imports-fixture',
+ load(id) {
+ if (id !== ENTRY_ID) return;
+
+ return `
+ import { getLobeIconCDN, MCP } from '@lobehub/icons';
+ export { getLobeIconCDN, MCP };
+ `;
+ },
+ resolveId(id) {
+ if (id === 'virtual:lobe-icon-imports-fixture') return ENTRY_ID;
+ },
+};
+
+describe('lobeIconImports', () => {
+ it('keeps icon barrel dependencies out of transformed .mjs modules', async () => {
+ const result = await build({
+ build: {
+ minify: false,
+ rolldownOptions: {
+ external: /^@lobehub\/icons\/es\//,
+ input: 'virtual:lobe-icon-imports-fixture',
+ },
+ write: false,
+ },
+ configFile: false,
+ logLevel: 'silent',
+ plugins: [fixturePlugin, ...lobeIconImports()],
+ });
+
+ const outputs = Array.isArray(result) ? result : [result];
+ const code = outputs
+ .flatMap(({ output }) => output)
+ .filter((item) => item.type === 'chunk')
+ .map((item) => item.code)
+ .join('\n');
+
+ expect(code).toContain('@lobehub/icons/es/MCP/index.js');
+ expect(code).toContain('@lobehub/icons/es/features/getLobeIconCDN/index.js');
+ expect(code).not.toMatch(/from ["']@lobehub\/icons["']/);
+ });
+});
diff --git a/plugins/vite/lobeIconImports.ts b/plugins/vite/lobeIconImports.ts
new file mode 100644
index 00000000000..dd5af0851c7
--- /dev/null
+++ b/plugins/vite/lobeIconImports.ts
@@ -0,0 +1,88 @@
+import transformImports from '@rolldown/plugin-transform-imports';
+import type { Plugin, PluginOption } from 'vite';
+
+const NAMED_EXPORT_PREFIX = 'virtual:lobe-icon-named:';
+const RESOLVED_NAMED_EXPORT_PREFIX = `\0${NAMED_EXPORT_PREFIX}`;
+
+const namedExportModules = {
+ agentMappings: '@lobehub/icons/es/features/agentConfig.js',
+ getLobeIconCDN: '@lobehub/icons/es/features/getLobeIconCDN/index.js',
+ modelMappings: '@lobehub/icons/es/features/modelConfig.js',
+ ModelProvider: '@lobehub/icons/es/features/providerEnum.js',
+ providerMappings: '@lobehub/icons/es/features/providerConfig.js',
+ toc: '@lobehub/icons/es/toc.js',
+ useFillId: '@lobehub/icons/es/hooks/useFillId.js',
+ useFillIds: '@lobehub/icons/es/hooks/useFillId.js',
+} as const;
+
+type NamedExport = keyof typeof namedExportModules;
+
+const isNamedExport = (value: string): value is NamedExport => value in namedExportModules;
+
+const namedExportProxy = (): Plugin => ({
+ name: 'lobe-icon-named-export-proxy',
+ load(id) {
+ if (!id.startsWith(RESOLVED_NAMED_EXPORT_PREFIX)) return;
+
+ const member = id.slice(RESOLVED_NAMED_EXPORT_PREFIX.length);
+ if (!isNamedExport(member)) return;
+
+ return `export { ${member} as default } from '${namedExportModules[member]}';`;
+ },
+ resolveId(id) {
+ if (!id.startsWith(NAMED_EXPORT_PREFIX)) return;
+
+ return `\0${id}`;
+ },
+});
+
+const includeModuleExtensions = (plugin: ReturnType<typeof transformImports>) => {
+ if (typeof plugin.transform !== 'object' || !plugin.transform) return plugin;
+
+ plugin.transform = {
+ ...plugin.transform,
+ filter: {
+ ...plugin.transform.filter,
+ // @lobehub/ui is published as .mjs and imports @lobehub/icons internally.
+ // The upstream plugin currently only includes .js/.jsx/.ts/.tsx by default.
+ id: /\.[cm]?[jt]sx?$/,
+ },
+ };
+
+ return plugin;
+};
+
+/**
+ * Rewrites the @lobehub/icons barrel to deep imports.
+ *
+ * The SPA entry and lazy routes otherwise share the same barrel module. Once a
+ * lazy route uses ModelIcon or ProviderIcon, their complete mapping tables are
+ * promoted into the initial shared chunk even when the first screen only needs
+ * a small standalone icon.
+ */
+export const lobeIconImports = (): PluginOption[] => {
+ const iconImports = transformImports({
+ '@lobehub/icons': {
+ preventFullImport: true,
+ transform: [
+ [
+ 'AgentIcon|IconAvatar|IconCombine|ModelIcon|ModelTag|ProviderCombine|ProviderIcon',
+ '@lobehub/icons/es/features/{{member}}/index.js',
+ ],
+ [
+ 'agentMappings|getLobeIconCDN|modelMappings|ModelProvider|providerMappings|toc|useFillId|useFillIds',
+ `${NAMED_EXPORT_PREFIX}{{member}}`,
+ ],
+ ['*', '@lobehub/icons/es/{{member}}/index.js'],
+ ],
+ },
+ });
+
+ return [namedExportProxy(), includeModuleExtensions(iconImports)];
+};
+
+export const __testing = {
+ NAMED_EXPORT_PREFIX,
+ RESOLVED_NAMED_EXPORT_PREFIX,
+ namedExportModules,
+};
diff --git a/plugins/vite/routeChunkPreload.test.ts b/plugins/vite/routeChunkPreload.test.ts
deleted file mode 100644
index 8dcf6c70a22..00000000000
--- a/plugins/vite/routeChunkPreload.test.ts
+++ /dev/null
@@ -1,577 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { __testing, routeChunkPreload } from './routeChunkPreload';
-
-interface TestOutputChunk {
- code: string;
- dynamicImports: string[];
- facadeModuleId: null | string;
- fileName: string;
- imports: string[];
- moduleIds: string[];
- type: 'chunk';
-}
-
-type TestOutputBundle = Record<string, TestOutputChunk | { type: 'asset' }>;
-
-function createChunk(overrides: Partial<TestOutputChunk>): TestOutputChunk {
- return {
- code: '',
- dynamicImports: [],
- facadeModuleId: null,
- fileName: 'assets/chunk.js',
- imports: [],
- moduleIds: [],
- type: 'chunk',
- ...overrides,
- };
-}
-
-describe('routeChunkPreload', () => {
- it('creates route preload entries from emitted route chunk filenames', () => {
- const bundle = {
- 'assets/agent-CJm8x.js': createChunk({
- dynamicImports: ['assets/MainChatInput-BwuHC6qv.js', 'assets/typescript-D20RI-Hp.js'],
- facadeModuleId: '/repo/src/routes/(main)/agent/index.desktop.tsx',
- fileName: 'assets/agent-CJm8x.js',
- imports: ['vendor/vendor-icons-Bd7x.js'],
- moduleIds: ['/repo/src/routes/(main)/agent/index.desktop.tsx'],
- }),
- 'vendor/vendor-icons-Bd7x.js': createChunk({
- facadeModuleId: null,
- fileName: 'vendor/vendor-icons-Bd7x.js',
- moduleIds: ['/repo/node_modules/lucide-react/dist/esm/icons/settings.js'],
- }),
- 'assets/MainChatInput-BwuHC6qv.js': createChunk({
- fileName: 'assets/MainChatInput-BwuHC6qv.js',
- moduleIds: ['/repo/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx'],
- }),
- 'assets/typescript-D20RI-Hp.js': createChunk({
- fileName: 'assets/typescript-D20RI-Hp.js',
- moduleIds: ['/repo/node_modules/@shikijs/langs/dist/typescript.mjs'],
- }),
- 'devtools/DevDock-B3.js': createChunk({
- fileName: 'devtools/DevDock-B3.js',
- moduleIds: ['/repo/src/features/DevDock/index.tsx'],
- }),
- } satisfies TestOutputBundle;
-
- const manifest = __testing.createRoutePreloadManifest(bundle, '/repo');
- const agentEntry = manifest.find((entry) => entry.id === 'desktop-chat-launch');
-
- expect(agentEntry?.preload).toEqual([
- 'assets/agent-CJm8x.js',
- 'vendor/vendor-icons-Bd7x.js',
- 'assets/MainChatInput-BwuHC6qv.js',
- ]);
- });
-
- it('matches route modules when built from the cloud repository root', () => {
- const bundle = {
- 'assets/agent-CJm8x.js': createChunk({
- facadeModuleId: '/repo/lobehub/src/routes/(main)/agent/index.tsx',
- fileName: 'assets/agent-CJm8x.js',
- moduleIds: ['/repo/lobehub/src/routes/(main)/agent/index.tsx'],
- }),
- } satisfies TestOutputBundle;
-
- const manifest = __testing.createRoutePreloadManifest(bundle, '/repo');
- const agentEntry = manifest.find((entry) => entry.id === 'desktop-chat-launch');
-
- expect(agentEntry?.preload).toEqual(['assets/agent-CJm8x.js']);
- });
-
- it('matches non-index platform-specific route module variants', () => {
- const bundle = {
- 'assets/settings-provider-CJm8x.js': createChunk({
- facadeModuleId: '/repo/src/routes/(main)/settings/provider.desktop.tsx',
- fileName: 'assets/settings-provider-CJm8x.js',
- moduleIds: ['/repo/src/routes/(main)/settings/provider.desktop.tsx'],
- }),
- } satisfies TestOutputBundle;
-
- const manifest = __testing.createRoutePreloadManifest(bundle, '/repo', [
- {
- id: 'custom-settings-provider',
- modules: ['src/routes/(main)/settings/provider'],
- patterns: ['^/settings/provider(/|$)'],
- },
- ]);
-
- expect(manifest[0]?.preload).toEqual(['assets/settings-provider-CJm8x.js']);
- });
-
- it('can include static imports for explicitly configured groups', () => {
- const bundle = {
- 'assets/agent-CJm8x.js': createChunk({
- facadeModuleId: '/repo/src/routes/(main)/agent/index.tsx',
- fileName: 'assets/agent-CJm8x.js',
- imports: ['vendor/vendor-icons-Bd7x.js'],
- moduleIds: ['/repo/src/routes/(main)/agent/index.tsx'],
- }),
- 'vendor/vendor-icons-Bd7x.js': createChunk({
- facadeModuleId: null,
- fileName: 'vendor/vendor-icons-Bd7x.js',
- moduleIds: ['/repo/node_modules/lucide-react/dist/esm/icons/settings.js'],
- }),
- } satisfies TestOutputBundle;
-
- const manifest = __testing.createRoutePreloadManifest(bundle, '/repo', [
- {
- id: 'custom-agent',
- includeStaticImports: true,
- modules: ['src/routes/(main)/agent'],
- patterns: ['^/agent(/|$)'],
- },
- ]);
-
- expect(manifest[0]?.preload).toEqual(['assets/agent-CJm8x.js', 'vendor/vendor-icons-Bd7x.js']);
- });
-
- it('can include dynamic imports for route warmup groups', () => {
- const bundle = {
- 'assets/settings-CJm8x.js': createChunk({
- dynamicImports: [
- 'assets/settings-provider-D8p.js',
- 'devtools/DevDock-B3.js',
- 'assets/typescript-D20RI-Hp.js',
- 'assets/pierre-dark-BVeDunhK.js',
- 'assets/mermaid.core-FQG0m7QG.js',
- ],
- facadeModuleId: '/repo/src/routes/(main)/settings/index.tsx',
- fileName: 'assets/settings-CJm8x.js',
- imports: ['vendor/vendor-icons-Bd7x.js'],
- moduleIds: ['/repo/src/routes/(main)/settings/index.tsx'],
- }),
- 'assets/settings-provider-D8p.js': createChunk({
- fileName: 'assets/settings-provider-D8p.js',
- moduleIds: ['/repo/src/routes/(main)/settings/provider/index.tsx'],
- }),
- 'devtools/DevDock-B3.js': createChunk({
- fileName: 'devtools/DevDock-B3.js',
- moduleIds: ['/repo/src/features/DevDock/index.tsx'],
- }),
- 'assets/typescript-D20RI-Hp.js': createChunk({
- fileName: 'assets/typescript-D20RI-Hp.js',
- moduleIds: ['/repo/node_modules/@shikijs/langs/dist/typescript.mjs'],
- }),
- 'assets/pierre-dark-BVeDunhK.js': createChunk({
- fileName: 'assets/pierre-dark-BVeDunhK.js',
- }),
- 'assets/mermaid.core-FQG0m7QG.js': createChunk({
- imports: ['assets/cytoscape.esm-B2pAKChx.js'],
- fileName: 'assets/mermaid.core-FQG0m7QG.js',
- }),
- 'assets/cytoscape.esm-B2pAKChx.js': createChunk({
- fileName: 'assets/cytoscape.esm-B2pAKChx.js',
- }),
- 'assets/graphlib-s-2OPgNI.js': createChunk({
- fileName: 'assets/graphlib-s-2OPgNI.js',
- moduleIds: ['/repo/node_modules/graphlib/index.js'],
- }),
- 'vendor/vendor-icons-Bd7x.js': createChunk({
- fileName: 'vendor/vendor-icons-Bd7x.js',
- moduleIds: ['/repo/node_modules/lucide-react/dist/esm/icons/settings.js'],
- }),
- } satisfies TestOutputBundle;
-
- const manifest = __testing.createRoutePreloadManifest(bundle, '/repo', [
- {
- id: 'custom-settings',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: ['src/routes/(main)/settings'],
- patterns: ['^/settings(/|$)'],
- },
- ]);
-
- expect(manifest[0]?.preload).toEqual([
- 'assets/settings-CJm8x.js',
- 'vendor/vendor-icons-Bd7x.js',
- 'assets/settings-provider-D8p.js',
- ]);
- });
-
- it('warms additional desktop secondary route families during idle time', () => {
- const bundle = {
- 'assets/group-CJm8x.js': createChunk({
- facadeModuleId: '/repo/src/routes/(main)/group/index.desktop.tsx',
- fileName: 'assets/group-CJm8x.js',
- moduleIds: ['/repo/src/routes/(main)/group/index.desktop.tsx'],
- }),
- 'assets/group-profile-D8p.js': createChunk({
- facadeModuleId: '/repo/src/routes/(main)/group/profile/index.tsx',
- fileName: 'assets/group-profile-D8p.js',
- moduleIds: ['/repo/src/routes/(main)/group/profile/index.tsx'],
- }),
- 'assets/community-detail-model-B2.js': createChunk({
- facadeModuleId: '/repo/src/routes/(main)/community/(detail)/model/index.tsx',
- fileName: 'assets/community-detail-model-B2.js',
- moduleIds: ['/repo/src/routes/(main)/community/(detail)/model/index.tsx'],
- }),
- 'assets/memory-contexts-B9.js': createChunk({
- facadeModuleId: '/repo/src/routes/(main)/memory/contexts/index.tsx',
- fileName: 'assets/memory-contexts-B9.js',
- moduleIds: ['/repo/src/routes/(main)/memory/contexts/index.tsx'],
- }),
- 'assets/image-B3.js': createChunk({
- facadeModuleId: '/repo/src/routes/(main)/(create)/image/index.tsx',
- fileName: 'assets/image-B3.js',
- moduleIds: ['/repo/src/routes/(main)/(create)/image/index.tsx'],
- }),
- 'assets/eval-run-C8.js': createChunk({
- facadeModuleId: '/repo/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx',
- fileName: 'assets/eval-run-C8.js',
- moduleIds: ['/repo/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx'],
- }),
- } satisfies TestOutputBundle;
-
- const manifest = __testing.createRoutePreloadManifest(
- bundle,
- '/repo',
- __testing.defaultIdleRoutePreloadGroups,
- );
- const preloadByGroup = new Map(manifest.map((entry) => [entry.id, entry.preload]));
-
- expect(preloadByGroup.get('desktop-group-chat')).toEqual([
- 'assets/group-CJm8x.js',
- 'assets/group-profile-D8p.js',
- ]);
- expect(preloadByGroup.get('desktop-community')).toEqual([
- 'assets/community-detail-model-B2.js',
- ]);
- expect(preloadByGroup.get('desktop-memory')).toEqual(['assets/memory-contexts-B9.js']);
- expect(preloadByGroup.get('desktop-create')).toEqual(['assets/image-B3.js']);
- expect(preloadByGroup.get('desktop-eval')).toEqual(['assets/eval-run-C8.js']);
- });
-
- it('keeps low-probability routes out of the default preload manifest', () => {
- const bundle = {
- 'assets/settings-CJm8x.js': createChunk({
- facadeModuleId: '/repo/src/routes/(main)/settings/index.tsx',
- fileName: 'assets/settings-CJm8x.js',
- moduleIds: ['/repo/src/routes/(main)/settings/index.tsx'],
- }),
- } satisfies TestOutputBundle;
-
- expect(__testing.createRoutePreloadManifest(bundle, '/repo')).toEqual([]);
- });
-
- it('creates a sorted all-JS warmup manifest from emitted chunks', () => {
- const bundle = {
- 'assets/agent-CJm8x.js': createChunk({
- fileName: 'assets/agent-CJm8x.js',
- }),
- 'assets/i18n-en-US-DjOrYbGM.js': createChunk({
- fileName: 'assets/i18n-en-US-DjOrYbGM.js',
- }),
- 'assets/style-D8p.css': createChunk({
- fileName: 'assets/style-D8p.css',
- }),
- 'i18n/i18n-default-BV0oTRYH.js': createChunk({
- fileName: 'i18n/i18n-default-BV0oTRYH.js',
- }),
- 'assets/javascript-C1Q1DjBS.js': createChunk({
- fileName: 'assets/javascript-C1Q1DjBS.js',
- moduleIds: ['/repo/node_modules/@shikijs/langs/dist/javascript.mjs'],
- }),
- 'assets/github-dark-Bo88FFvI.js': createChunk({
- fileName: 'assets/github-dark-Bo88FFvI.js',
- moduleIds: ['/repo/node_modules/@shikijs/themes/dist/github-dark.mjs'],
- }),
- 'assets/wasm-CGWTL0IK.js': createChunk({
- fileName: 'assets/wasm-CGWTL0IK.js',
- moduleIds: ['/repo/node_modules/oniguruma-to-es/dist/wasm.mjs'],
- }),
- 'assets/pierre-light-Dmd9-PaL.js': createChunk({
- fileName: 'assets/pierre-light-Dmd9-PaL.js',
- }),
- 'assets/mermaid-parser.core-BLfQKdsC.js': createChunk({
- fileName: 'assets/mermaid-parser.core-BLfQKdsC.js',
- }),
- 'assets/rough.esm-BgK9YCbF.js': createChunk({
- fileName: 'assets/rough.esm-BgK9YCbF.js',
- moduleIds: ['/repo/node_modules/roughjs/bin/rough.js'],
- }),
- 'vendor/vendor-icons-Bd7x.js': createChunk({
- fileName: 'vendor/vendor-icons-Bd7x.js',
- }),
- 'assets/image.png': { type: 'asset' },
- 'devtools/DevDock-B3.js': createChunk({
- fileName: 'devtools/DevDock-B3.js',
- }),
- } satisfies TestOutputBundle;
-
- expect(__testing.createAllJsWarmupManifest(bundle)).toEqual([
- 'assets/agent-CJm8x.js',
- 'vendor/vendor-icons-Bd7x.js',
- ]);
- });
-
- it('injects route modulepreload links into html and skips existing module assets', () => {
- const html = [
- '<html>',
- ' <head>',
- ' <script type="module" crossorigin src="/_spa/assets/index-D8p.js?dpl=dpl_test"></script>',
- ' <link rel="modulepreload" crossorigin href="/_spa/assets/existing-B2.js?dpl=dpl_test">',
- ' </head>',
- '</html>',
- ].join('\n');
-
- const result = __testing.injectRouteModulepreloadsIntoHtml(
- html,
- [
- {
- id: 'desktop-page',
- patterns: ['^/page(/|$)'],
- preload: ['assets/page-B9kLm.js', 'assets/existing-B2.js'],
- },
- ],
- '/_spa/',
- 'dpl_test',
- );
-
- expect(result).toContain(
- '<link rel="modulepreload" crossorigin href="/_spa/assets/page-B9kLm.js?dpl=dpl_test">',
- );
- expect(result.match(/assets\/existing-B2\.js/g)).toHaveLength(1);
- expect(result.match(/assets\/index-D8p\.js/g)).toHaveLength(1);
- });
-
- it('removes small existing modulepreload links from html', () => {
- const html = [
- '<html>',
- ' <head>',
- ' <link rel="modulepreload" crossorigin href="/_spa/assets/small-D8p.js?dpl=dpl_test">',
- ' <link rel="modulepreload" crossorigin href="/_spa/assets/large-D8p.js?dpl=dpl_test">',
- ' </head>',
- '</html>',
- ].join('\n');
-
- const result = __testing.removeSmallModulepreloadsFromHtml(
- html,
- '/_spa/',
- (fileName) => fileName === 'assets/large-D8p.js',
- );
-
- expect(result).not.toContain('/_spa/assets/small-D8p.js');
- expect(result).toContain('/_spa/assets/large-D8p.js?dpl=dpl_test');
- });
-
- it('appends the deployment query to emitted preload assets', () => {
- expect(__testing.createAssetHref('assets/page-B9kLm.js', '/_spa/', 'dpl_test')).toBe(
- '/_spa/assets/page-B9kLm.js?dpl=dpl_test',
- );
- expect(
- __testing.createAssetHref('assets/page-B9kLm.js?dpl=dpl_test', '/_spa/', 'dpl_test'),
- ).toBe('/_spa/assets/page-B9kLm.js?dpl=dpl_test');
- });
-
- it('injects emitted route preloads into html with the Vite html transform hook', () => {
- const plugin = routeChunkPreload({ allJsWarmup: true });
- const configResolved = plugin.configResolved as (config: {
- base: string;
- root: string;
- }) => void;
- const bundle = {
- 'assets/agent-CJm8x.js': createChunk({
- code: 'x'.repeat(2048),
- facadeModuleId: '/repo/src/routes/(main)/agent/index.tsx',
- fileName: 'assets/agent-CJm8x.js',
- moduleIds: ['/repo/src/routes/(main)/agent/index.tsx'],
- }),
- 'assets/settings-D8p.js': createChunk({
- code: 'x'.repeat(2048),
- facadeModuleId: '/repo/src/routes/(main)/settings/index.tsx',
- fileName: 'assets/settings-D8p.js',
- moduleIds: ['/repo/src/routes/(main)/settings/index.tsx'],
- }),
- } satisfies TestOutputBundle;
- const transformIndexHtml = plugin.transformIndexHtml as {
- handler: (html: string, ctx: { bundle: TestOutputBundle }) => string;
- };
-
- configResolved({ base: '/_spa/', root: '/repo' });
- const result = transformIndexHtml.handler(
- '<html><head><script type="module" crossorigin src="/_spa/assets/index-D8p.js"></script></head><body></body></html>',
- { bundle },
- );
-
- expect(result).toContain('/_spa/assets/agent-CJm8x.js');
- expect(result).toContain('/_spa/assets/settings-D8p.js');
- expect(result).toContain('/_spa/assets/js-warmup-manifest.json');
- expect(result).toContain('rel="modulepreload"');
- expect(result).not.toContain('window.__LOBE_PRELOAD_ROUTE__');
- expect(result).not.toContain("import('@/routes");
- });
-
- it('skips the auth SPA html entirely', () => {
- const plugin = routeChunkPreload();
- const configResolved = plugin.configResolved as (config: {
- base: string;
- root: string;
- }) => void;
- const bundle = {
- 'assets/agent-CJm8x.js': createChunk({
- code: 'x'.repeat(2048),
- facadeModuleId: '/repo/src/routes/(main)/agent/index.tsx',
- fileName: 'assets/agent-CJm8x.js',
- moduleIds: ['/repo/src/routes/(main)/agent/index.tsx'],
- }),
- } satisfies TestOutputBundle;
- const transformIndexHtml = plugin.transformIndexHtml as {
- handler: (html: string, ctx: { bundle: TestOutputBundle; path?: string }) => string;
- };
-
- configResolved({ base: '/_spa/', root: '/repo' });
- const html = '<html><head></head><body></body></html>';
- const result = transformIndexHtml.handler(html, { bundle, path: '/index.auth.html' });
-
- expect(result).toBe(html);
- });
-
- it('does not inject the all-JS warmup manifest by default', () => {
- const plugin = routeChunkPreload();
- const configResolved = plugin.configResolved as (config: {
- base: string;
- root: string;
- }) => void;
- const bundle = {
- 'assets/agent-CJm8x.js': createChunk({
- code: 'x'.repeat(2048),
- facadeModuleId: '/repo/src/routes/(main)/agent/index.tsx',
- fileName: 'assets/agent-CJm8x.js',
- moduleIds: ['/repo/src/routes/(main)/agent/index.tsx'],
- }),
- 'assets/settings-D8p.js': createChunk({
- code: 'x'.repeat(2048),
- facadeModuleId: '/repo/src/routes/(main)/settings/index.tsx',
- fileName: 'assets/settings-D8p.js',
- moduleIds: ['/repo/src/routes/(main)/settings/index.tsx'],
- }),
- } satisfies TestOutputBundle;
- const transformIndexHtml = plugin.transformIndexHtml as {
- handler: (html: string, ctx: { bundle: TestOutputBundle }) => string;
- };
-
- configResolved({ base: '/_spa/', root: '/repo' });
- const result = transformIndexHtml.handler('<html><head></head><body></body></html>', {
- bundle,
- });
-
- expect(result).toContain('/_spa/assets/agent-CJm8x.js');
- expect(result).toContain('/_spa/assets/settings-D8p.js');
- expect(result).not.toContain('js-warmup-manifest.json');
- });
-
- it('keeps tiny route dependencies out of initial html while preserving idle warmup coverage', () => {
- const plugin = routeChunkPreload();
- const configResolved = plugin.configResolved as (config: {
- base: string;
- root: string;
- }) => void;
- const bundle = {
- 'assets/agent-CJm8x.js': createChunk({
- code: 'x'.repeat(2048),
- dynamicImports: ['assets/HeaderSlot-D8p.js'],
- facadeModuleId: '/repo/src/routes/(main)/agent/index.tsx',
- fileName: 'assets/agent-CJm8x.js',
- moduleIds: ['/repo/src/routes/(main)/agent/index.tsx'],
- }),
- 'assets/HeaderSlot-D8p.js': createChunk({
- code: 'x'.repeat(128),
- fileName: 'assets/HeaderSlot-D8p.js',
- moduleIds: ['/repo/src/routes/(main)/agent/HeaderSlot.tsx'],
- }),
- } satisfies TestOutputBundle;
- const transformIndexHtml = plugin.transformIndexHtml as {
- handler: (html: string, ctx: { bundle: TestOutputBundle }) => string;
- };
-
- configResolved({ base: '/_spa/', root: '/repo' });
- const result = transformIndexHtml.handler('<html><head></head><body></body></html>', {
- bundle,
- });
-
- expect(result).toContain(
- '<link rel="modulepreload" crossorigin href="/_spa/assets/agent-CJm8x.js',
- );
- expect(result).not.toContain(
- '<link rel="modulepreload" crossorigin href="/_spa/assets/HeaderSlot-D8p.js',
- );
- expect(result).toContain('"idleRouteFetch":[]');
- expect(result).toContain(
- '"idleRoutePreload":["/_spa/assets/agent-CJm8x.js","/_spa/assets/HeaderSlot-D8p.js"',
- );
- expect(result).toContain('"/_spa/assets/HeaderSlot-D8p.js');
- });
-
- it('does not warm tiny low-priority idle route chunks', () => {
- const plugin = routeChunkPreload({
- groups: [],
- idleGroups: [
- {
- id: 'custom-settings',
- includeDynamicImports: true,
- modules: ['src/routes/(main)/settings'],
- patterns: ['^/settings(/|$)'],
- },
- ],
- });
- const configResolved = plugin.configResolved as (config: {
- base: string;
- root: string;
- }) => void;
- const bundle = {
- 'assets/settings-CJm8x.js': createChunk({
- code: 'x'.repeat(2048),
- dynamicImports: ['assets/tiny-D8p.js'],
- facadeModuleId: '/repo/src/routes/(main)/settings/index.tsx',
- fileName: 'assets/settings-CJm8x.js',
- moduleIds: ['/repo/src/routes/(main)/settings/index.tsx'],
- }),
- 'assets/tiny-D8p.js': createChunk({
- code: 'x'.repeat(128),
- fileName: 'assets/tiny-D8p.js',
- moduleIds: ['/repo/src/routes/(main)/settings/Tiny.tsx'],
- }),
- } satisfies TestOutputBundle;
- const transformIndexHtml = plugin.transformIndexHtml as {
- handler: (html: string, ctx: { bundle: TestOutputBundle }) => string;
- };
-
- configResolved({ base: '/_spa/', root: '/repo' });
- const result = transformIndexHtml.handler('<html><head></head><body></body></html>', {
- bundle,
- });
-
- expect(result).toContain('"idleRouteFetch":[]');
- expect(result).toContain('"idleRoutePreload":["/_spa/assets/settings-CJm8x.js"');
- expect(result).not.toContain('/_spa/assets/tiny-D8p.js');
- });
-
- it('can omit the all-JS warmup manifest while keeping idle route warmup', () => {
- const result = __testing.injectIdleWarmupScriptIntoHtml(
- '<html><body></body></html>',
- { idleRouteFetch: [], idleRoutePreload: ['assets/settings-D8p.js'] },
- '/_spa/',
- 'dpl_test',
- );
-
- expect(result).toContain('/_spa/assets/settings-D8p.js?dpl=dpl_test');
- expect(result).not.toContain('js-warmup-manifest.json');
- });
-
- it('can warm tiny route chunks through fetch without modulepreload links', () => {
- const result = __testing.injectIdleWarmupScriptIntoHtml(
- '<html><body></body></html>',
- { idleRouteFetch: ['assets/tiny-D8p.js'], idleRoutePreload: [] },
- '/_spa/',
- 'dpl_test',
- );
-
- expect(result).toContain('"idleRouteFetch":["/_spa/assets/tiny-D8p.js?dpl=dpl_test"]');
- expect(result).toContain('"idleRoutePreload":[]');
- expect(result).toContain('warmQueue(m.idleRouteFetch||[])');
- });
-});
diff --git a/plugins/vite/routeChunkPreload.ts b/plugins/vite/routeChunkPreload.ts
deleted file mode 100644
index 8f0da95d16d..00000000000
--- a/plugins/vite/routeChunkPreload.ts
+++ /dev/null
@@ -1,646 +0,0 @@
-import type { Plugin, ResolvedConfig } from 'vite';
-
-interface RouteChunkPreloadRoute {
- id: string;
- includeDynamicImports?: boolean;
- includeStaticImports?: boolean;
- modules: string[];
- patterns: string[];
-}
-
-interface RuntimeRoutePreloadEntry {
- id: string;
- patterns: string[];
- preload: string[];
-}
-
-interface IdleWarmupManifest {
- allJsManifestFileName?: string;
- idleRouteFetch: string[];
- idleRoutePreload: string[];
-}
-
-interface OutputChunkLike {
- code: string;
- dynamicImports: string[];
- facadeModuleId: null | string;
- fileName: string;
- imports: string[];
- moduleIds: string[];
- type: 'chunk';
-}
-
-type OutputBundleLike = Record<string, OutputChunkLike | { type: string }>;
-
-const minInitialRoutePreloadSize = 2048;
-
-const criticalRouteSmallChunkFileNamePatterns = [
- /^EmptyNavItem-/,
- /^HeaderSlot-/,
- /^Item-/,
- /^MainChatInput-/,
- /^Notification-/,
- /^PortalPanel-/,
- /^RenameModal-/,
- /^TokenTag-/,
- /^agent-/,
- /^router-/,
- /^useAgentContext-/,
- /^useAppOrigin-/,
- /^useFetchChatTopics-/,
- /^useFetchThreads-/,
- /^useQueryParam-/,
- /^useTokenCount-/,
- /^useTopicPopupsRegistry-/,
- /^withSuspense-/,
-];
-
-const isCriticalRouteSmallChunkFileName = (fileName: string) => {
- const basename = normalizePath(fileName).split('/').at(-1) ?? fileName;
-
- return criticalRouteSmallChunkFileNamePatterns.some((pattern) => pattern.test(basename));
-};
-
-const defaultRoutePreloadGroups = [
- {
- id: 'desktop-chat-launch',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/_layout',
- 'src/routes/(main)/agent/_layout',
- 'src/routes/(main)/agent/(chat)/_layout',
- 'src/routes/(main)/agent',
- ],
- patterns: ['^/agent(/|$)'],
- },
-] as const satisfies RouteChunkPreloadRoute[];
-
-const defaultIdleRoutePreloadGroups = [
- {
- id: 'desktop-group-chat',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/group/_layout',
- 'src/routes/(main)/group',
- 'src/routes/(main)/group/profile',
- ],
- patterns: ['^/group(/|$)'],
- },
- {
- id: 'desktop-agent-profile',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: ['src/routes/(main)/agent/profile'],
- patterns: ['^/agent/[^/]+/profile(/|$)'],
- },
- {
- id: 'desktop-agent-channel',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: ['src/routes/(main)/agent/channel'],
- patterns: ['^/agent/[^/]+/channel(/|$)'],
- },
- {
- id: 'desktop-agent-page',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/agent/page',
- 'src/routes/(main)/agent/[topicId]/page',
- 'src/routes/(main)/agent/[topicId]/page/[docId]',
- ],
- patterns: ['^/agent/[^/]+(?:/[^/]+)?/page(/|$)'],
- },
- {
- id: 'desktop-community',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/community/_layout',
- 'src/routes/(main)/community/(list)/_layout',
- 'src/routes/(main)/community/(detail)/_layout',
- 'src/routes/(main)/community/(list)/(home)',
- 'src/routes/(main)/community/(list)/agent',
- 'src/routes/(main)/community/(list)/agent/_layout',
- 'src/routes/(main)/community/(list)/mcp',
- 'src/routes/(main)/community/(list)/mcp/_layout',
- 'src/routes/(main)/community/(list)/model',
- 'src/routes/(main)/community/(list)/model/_layout',
- 'src/routes/(main)/community/(list)/provider',
- 'src/routes/(main)/community/(list)/skill',
- 'src/routes/(main)/community/(list)/skill/_layout',
- 'src/routes/(main)/community/(detail)/agent',
- 'src/routes/(main)/community/(detail)/group_agent',
- 'src/routes/(main)/community/(detail)/mcp',
- 'src/routes/(main)/community/(detail)/model',
- 'src/routes/(main)/community/(detail)/provider',
- 'src/routes/(main)/community/(detail)/skill',
- 'src/routes/(main)/community/(detail)/user',
- ],
- patterns: ['^/community(/|$)'],
- },
- {
- id: 'desktop-resource',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/resource/_layout',
- 'src/routes/(main)/resource/(home)/_layout',
- 'src/routes/(main)/resource/(home)',
- 'src/routes/(main)/resource/library/_layout',
- 'src/routes/(main)/resource/library',
- 'src/routes/(main)/resource/library/[slug]',
- ],
- patterns: ['^/resource(/|$)'],
- },
- {
- id: 'desktop-settings',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: ['src/routes/(main)/settings/_layout', 'src/routes/(main)/settings'],
- patterns: ['^/settings(/|$)'],
- },
- {
- id: 'desktop-settings-provider',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: ['src/routes/(main)/settings/provider'],
- patterns: ['^/settings/provider(/|$)'],
- },
- {
- id: 'desktop-memory',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/memory/_layout',
- 'src/routes/(main)/memory/(home)',
- 'src/routes/(main)/memory/activities',
- 'src/routes/(main)/memory/contexts',
- 'src/routes/(main)/memory/experiences',
- 'src/routes/(main)/memory/identities',
- 'src/routes/(main)/memory/preferences',
- ],
- patterns: ['^/memory(/|$)'],
- },
- {
- id: 'desktop-create',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/(create)/image/_layout',
- 'src/routes/(main)/(create)/image',
- 'src/routes/(main)/(create)/video/_layout',
- 'src/routes/(main)/(create)/video',
- ],
- patterns: ['^/(image|video)(/|$)'],
- },
- {
- id: 'desktop-eval',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/eval/_layout',
- 'src/routes/(main)/eval/(home)/_layout',
- 'src/routes/(main)/eval',
- 'src/routes/(main)/eval/bench/[benchmarkId]/_layout',
- 'src/routes/(main)/eval/bench/[benchmarkId]',
- 'src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]',
- 'src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]',
- 'src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]',
- ],
- patterns: ['^/eval(/|$)'],
- },
- {
- id: 'desktop-tasks',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/(task-workspace)/_layout',
- 'src/routes/(main)/tasks',
- 'src/routes/(main)/task/[taskId]',
- 'src/routes/(main)/agent/task/[taskId]',
- ],
- patterns: ['^/(tasks|task|agent/[^/]+/task)(/|$)'],
- },
- {
- id: 'desktop-page',
- includeDynamicImports: true,
- includeStaticImports: true,
- modules: [
- 'src/routes/(main)/page/_layout',
- 'src/routes/(main)/page',
- 'src/routes/(main)/page/[id]',
- ],
- patterns: ['^/page(/|$)'],
- },
-] as const satisfies RouteChunkPreloadRoute[];
-
-const allJsWarmupManifestFileName = 'assets/js-warmup-manifest.json';
-
-const normalizePath = (value: string) => value.split('?')[0].replaceAll('\\', '/');
-
-const isI18nChunkFileName = (fileName: string) => {
- const normalized = normalizePath(fileName);
- const basename = normalized.split('/').at(-1) ?? normalized;
-
- return normalized.startsWith('i18n/') || basename.startsWith('i18n-');
-};
-
-const isDevtoolsChunkFileName = (fileName: string) => {
- const normalized = normalizePath(fileName);
-
- return normalized.includes('/devtools/') || normalized.startsWith('devtools/');
-};
-
-const syntaxHighlightModulePatterns = [
- '/node_modules/@shikijs/',
- '/node_modules/shiki/',
- '/node_modules/oniguruma-to-es/',
- '/node_modules/vscode-oniguruma/',
- '/node_modules/vscode-textmate/',
-];
-
-const deferredRendererModulePatterns = [
- ...syntaxHighlightModulePatterns,
- '/node_modules/@mermaid-js/',
- '/node_modules/cytoscape/',
- '/node_modules/dagre/',
- '/node_modules/graphlib/',
- '/node_modules/mermaid/',
- '/node_modules/roughjs/',
-];
-
-const deferredRendererFileNamePatterns = [
- /(^|\/)(?:github-dark|catppuccin|pierre-dark|pierre-light)-[^/]+\.js$/i,
- /(^|\/)(?:javascript|typescript|tsx|jsx|wasm)-[^/]+\.js$/i,
- /(^|\/)mermaid(?:\.|-)[^/]+\.js$/i,
- /(^|\/)(?:cytoscape|dagre|graphlib|rough)(?:\.|-)[^/]+\.js$/i,
-];
-
-function isDeferredRendererChunk(chunk: OutputChunkLike) {
- if (deferredRendererFileNamePatterns.some((pattern) => pattern.test(chunk.fileName))) return true;
-
- const moduleIds = [chunk.facadeModuleId, ...chunk.moduleIds].filter(Boolean);
-
- return moduleIds.some((id) => {
- const normalized = normalizePath(id!);
-
- return deferredRendererModulePatterns.some((pattern) => normalized.includes(pattern));
- });
-}
-
-function isPrewarmExcludedChunk(chunk: OutputChunkLike) {
- return (
- isI18nChunkFileName(chunk.fileName) ||
- isDevtoolsChunkFileName(chunk.fileName) ||
- isDeferredRendererChunk(chunk)
- );
-}
-
-const stripModuleSuffix = (value: string) =>
- value
- .replace(/\.(mjs|js|jsx|ts|tsx)$/, '')
- .replace(/\.(desktop|mobile|vite|web)$/, '')
- .replace(/\/index$/, '');
-
-function normalizeComparableModuleId(id: string, root = '') {
- let normalized = normalizePath(id);
- const normalizedRoot = root ? normalizePath(root).replace(/\/$/, '') : '';
-
- if (normalizedRoot && normalized.startsWith(`${normalizedRoot}/`)) {
- normalized = normalized.slice(normalizedRoot.length + 1);
- }
-
- if (normalized.startsWith('lobehub/src/')) {
- normalized = normalized.slice('lobehub/'.length);
- }
-
- return stripModuleSuffix(normalized);
-}
-
-function isOutputChunk(item: OutputBundleLike[string]): item is OutputChunkLike {
- return item.type === 'chunk';
-}
-
-function chunkContainsModule(chunk: OutputChunkLike, moduleId: string, root: string) {
- const expected = normalizeComparableModuleId(moduleId, root);
- const chunkModuleIds = [chunk.facadeModuleId, ...chunk.moduleIds].filter(Boolean);
-
- return chunkModuleIds.some((id) => normalizeComparableModuleId(id!, root) === expected);
-}
-
-function collectChunkDependencies(
- chunk: OutputChunkLike,
- chunksByFileName: Map<string, OutputChunkLike>,
- collected: Set<string>,
- options: { includeDynamicImports?: boolean; includeStaticImports?: boolean },
-) {
- if (collected.has(chunk.fileName)) return;
- if (isPrewarmExcludedChunk(chunk)) return;
-
- collected.add(chunk.fileName);
-
- const imports = [
- ...(options.includeStaticImports ? chunk.imports : []),
- ...(options.includeDynamicImports ? chunk.dynamicImports : []),
- ];
-
- for (const importedFileName of imports) {
- const importedChunk = chunksByFileName.get(importedFileName);
- if (!importedChunk) continue;
- collectChunkDependencies(importedChunk, chunksByFileName, collected, options);
- }
-}
-
-function createRoutePreloadManifest(
- bundle: OutputBundleLike,
- root: string,
- groups: readonly RouteChunkPreloadRoute[] = defaultRoutePreloadGroups,
-): RuntimeRoutePreloadEntry[] {
- const chunks = Object.values(bundle).filter(isOutputChunk);
- const chunksByFileName = new Map(chunks.map((chunk) => [chunk.fileName, chunk]));
-
- return groups
- .map((route) => {
- const preload = new Set<string>();
-
- for (const moduleId of route.modules) {
- const matchingChunks = chunks.filter((chunk) => chunkContainsModule(chunk, moduleId, root));
-
- for (const chunk of matchingChunks) {
- if (route.includeStaticImports || route.includeDynamicImports) {
- collectChunkDependencies(chunk, chunksByFileName, preload, {
- includeDynamicImports: route.includeDynamicImports,
- includeStaticImports: route.includeStaticImports,
- });
- } else {
- preload.add(chunk.fileName);
- }
- }
- }
-
- return {
- id: route.id,
- patterns: [...route.patterns],
- preload: [...preload].filter((fileName) => {
- const chunk = chunksByFileName.get(fileName);
-
- return fileName.endsWith('.js') && (!chunk || !isPrewarmExcludedChunk(chunk));
- }),
- };
- })
- .filter((entry) => entry.preload.length > 0);
-}
-
-function appendDeploymentQuery(href: string, deploymentId = process.env.VERCEL_DEPLOYMENT_ID) {
- if (!deploymentId || href.includes('dpl=')) return href;
-
- return `${href}${href.includes('?') ? '&' : '?'}dpl=${deploymentId}`;
-}
-
-function createAssetHref(fileName: string, base: string, deploymentId?: string) {
- if (base === '' || base === './') return appendDeploymentQuery(fileName, deploymentId);
-
- const normalizedBase = base.endsWith('/') ? base : `${base}/`;
- return appendDeploymentQuery(`${normalizedBase}${fileName}`, deploymentId);
-}
-
-function createAllJsWarmupManifest(bundle: OutputBundleLike) {
- return Object.values(bundle)
- .filter(isOutputChunk)
- .filter((chunk) => chunk.fileName.endsWith('.js') && !isPrewarmExcludedChunk(chunk))
- .map((chunk) => chunk.fileName)
- .sort();
-}
-
-function collectExistingHtmlAssets(html: string, base: string) {
- const existing = new Set<string>();
- const sourcePattern = /<(?:link|script)\b[^>]+(?:href|src)="([^"]+)"/g;
-
- for (const match of html.matchAll(sourcePattern)) {
- existing.add(normalizeHtmlAssetHref(match[1], base));
- }
-
- return existing;
-}
-
-function normalizeHtmlAssetHref(href: string, base: string) {
- const cleanHref = href.split('?')[0];
- const basePrefix = base === '' || base === './' ? '' : base.endsWith('/') ? base : `${base}/`;
-
- return basePrefix && cleanHref.startsWith(basePrefix)
- ? cleanHref.slice(basePrefix.length)
- : cleanHref.replaceAll(/^\//g, '');
-}
-
-function removeSmallModulepreloadsFromHtml(
- html: string,
- base: string,
- shouldKeepFile: (fileName: string) => boolean,
-) {
- return html.replaceAll(
- /^[ \t]*<link\s+rel="modulepreload"[^>]*href="([^"]+)"[^>]*>\n?/gm,
- (match, href: string) => {
- const fileName = normalizeHtmlAssetHref(href, base);
-
- return shouldKeepFile(fileName) ? match : '';
- },
- );
-}
-
-function injectRouteModulepreloadsIntoHtml(
- html: string,
- manifest: RuntimeRoutePreloadEntry[],
- base: string,
- deploymentId?: string,
- shouldInjectFile: (fileName: string) => boolean = () => true,
-) {
- const existing = collectExistingHtmlAssets(html, base);
- const routeFiles = new Set(manifest.flatMap((entry) => entry.preload));
- const links = [...routeFiles]
- .filter(shouldInjectFile)
- .filter((fileName) => !existing.has(fileName))
- .map(
- (fileName) =>
- ` <link rel="modulepreload" crossorigin href="${createAssetHref(fileName, base, deploymentId)}">`,
- );
-
- if (links.length === 0) return html;
-
- const injection = links.join('\n');
- const lastModulepreloadMatch = [
- ...html.matchAll(/^[ \t]*<link\s+rel="modulepreload"[^>]*>$/gm),
- ].at(-1);
-
- if (lastModulepreloadMatch?.index !== undefined) {
- const insertAt = lastModulepreloadMatch.index + lastModulepreloadMatch[0].length;
- return `${html.slice(0, insertAt)}\n${injection}${html.slice(insertAt)}`;
- }
-
- return html.replace('</head>', `${injection}\n </head>`);
-}
-
-function createIdleWarmupScript(manifest: IdleWarmupManifest, base: string, deploymentId?: string) {
- const payload = {
- allJsManifest: manifest.allJsManifestFileName
- ? createAssetHref(manifest.allJsManifestFileName, base, deploymentId)
- : undefined,
- base,
- idleRouteFetch: manifest.idleRouteFetch.map((fileName) =>
- createAssetHref(fileName, base, deploymentId),
- ),
- idleRoutePreload: manifest.idleRoutePreload.map((fileName) =>
- createAssetHref(fileName, base, deploymentId),
- ),
- };
-
- return [
- ' <script>',
- ' (()=>{',
- ` const m=${JSON.stringify(payload)};`,
- ' const c=navigator.connection||navigator.mozConnection||navigator.webkitConnection;',
- ' if(c&&(c.saveData||/(^|-)2g$/.test(c.effectiveType||"")))return;',
- ' const seen=new Set([...document.querySelectorAll("link[href],script[src]")].map((n)=>n.href||n.src));',
- ' const idle=(cb)=>"requestIdleCallback"in window?requestIdleCallback(cb,{timeout:3e3}):setTimeout(()=>cb({didTimeout:true,timeRemaining:()=>16}),1200);',
- ' const visible=(cb)=>document.hidden?document.addEventListener("visibilitychange",()=>!document.hidden&&cb(),{once:true}):cb();',
- ' const run=(items,fn,batch,next)=>{let i=0;const step=(d)=>visible(()=>{let n=0;while(i<items.length&&n<batch&&(d.didTimeout||d.timeRemaining()>6)){fn(items[i++]);n++;}if(i<items.length)idle(step);else next&&idle(next);});idle(step);};',
- ' const addModulepreload=(href)=>{if(seen.has(href))return;seen.add(href);const l=document.createElement("link");l.rel="modulepreload";l.crossOrigin="";l.href=href;document.head.append(l);};',
- ' const warm=(href)=>{if(seen.has(href))return Promise.resolve();seen.add(href);return fetch(href,{cache:"force-cache",credentials:"same-origin"}).catch(()=>{});};',
- ' const warmQueue=(items)=>{let i=0,a=0;const pump=()=>visible(()=>{while(a<2&&i<items.length){a++;warm(items[i++]).finally(()=>{a--;idle(pump);});}});idle(pump);};',
- ' const toHref=(f)=>new URL(f,m.base&&m.base!=="./"?location.origin+m.base:location.href).href;',
- ' const warmAll=()=>{if(!m.allJsManifest)return;fetch(m.allJsManifest,{cache:"force-cache",credentials:"same-origin"}).then((r)=>r.ok?r.json():[]).then((files)=>warmQueue(files.map(toHref))).catch(()=>{});};',
- ' const start=()=>setTimeout(()=>idle(()=>run(m.idleRoutePreload,addModulepreload,4,()=>{warmQueue(m.idleRouteFetch||[]);setTimeout(()=>idle(warmAll),1.2e4);})),2e3);',
- ' document.readyState==="complete"?start():window.addEventListener("load",start,{once:true});',
- ' })();',
- ' </script>',
- ].join('\n');
-}
-
-function injectIdleWarmupScriptIntoHtml(
- html: string,
- manifest: IdleWarmupManifest,
- base: string,
- deploymentId?: string,
-) {
- if (
- manifest.idleRoutePreload.length === 0 &&
- manifest.idleRouteFetch.length === 0 &&
- !manifest.allJsManifestFileName
- )
- return html;
-
- return html.replace(
- '</body>',
- `${createIdleWarmupScript(manifest, base, deploymentId)}\n </body>`,
- );
-}
-
-interface RouteChunkPreloadOptions {
- allJsWarmup?: boolean;
- groups?: readonly RouteChunkPreloadRoute[];
- idleGroups?: readonly RouteChunkPreloadRoute[];
-}
-
-export function routeChunkPreload(options: RouteChunkPreloadOptions = {}): Plugin {
- let config: ResolvedConfig | undefined;
- const groups = options.groups ?? defaultRoutePreloadGroups;
- const idleGroups = options.idleGroups ?? defaultIdleRoutePreloadGroups;
- const allJsWarmup = options.allJsWarmup ?? false;
-
- return {
- name: 'lobe-route-chunk-preload',
- configResolved(resolvedConfig) {
- config = resolvedConfig;
- },
- generateBundle(_, bundle) {
- if (!allJsWarmup) return;
-
- this.emitFile({
- fileName: allJsWarmupManifestFileName,
- source: JSON.stringify(createAllJsWarmupManifest(bundle as OutputBundleLike)),
- type: 'asset',
- });
- },
- transformIndexHtml: {
- order: 'post',
- handler(html, ctx) {
- if (!config || !ctx.bundle) return html;
- // The auth SPA shares the build but must not preload main-app routes
- if (ctx.path?.includes('index.auth')) return html;
-
- const outputBundle = ctx.bundle as OutputBundleLike;
- const manifest = createRoutePreloadManifest(outputBundle, config.root, groups);
- const idleManifest = createRoutePreloadManifest(outputBundle, config.root, idleGroups);
- const deploymentId = process.env.VERCEL_DEPLOYMENT_ID;
- const chunkSizeByFileName = new Map(
- Object.values(outputBundle)
- .filter(isOutputChunk)
- .map((chunk) => [chunk.fileName, Buffer.byteLength(chunk.code)]),
- );
- const htmlWithoutSmallPreloads = removeSmallModulepreloadsFromHtml(
- html,
- config.base,
- (fileName) =>
- (chunkSizeByFileName.get(fileName) ?? minInitialRoutePreloadSize) >=
- minInitialRoutePreloadSize,
- );
- const htmlWithInitialPreloads = injectRouteModulepreloadsIntoHtml(
- htmlWithoutSmallPreloads,
- manifest,
- config.base,
- deploymentId,
- (fileName) =>
- (chunkSizeByFileName.get(fileName) ?? minInitialRoutePreloadSize) >=
- minInitialRoutePreloadSize,
- );
-
- return injectIdleWarmupScriptIntoHtml(
- htmlWithInitialPreloads,
- {
- allJsManifestFileName: allJsWarmup ? allJsWarmupManifestFileName : undefined,
- idleRouteFetch: [],
- idleRoutePreload: [
- ...new Set([
- ...manifest
- .flatMap((entry) => entry.preload)
- .filter((fileName) => {
- const size = chunkSizeByFileName.get(fileName) ?? minInitialRoutePreloadSize;
-
- return (
- size >= minInitialRoutePreloadSize ||
- isCriticalRouteSmallChunkFileName(fileName)
- );
- }),
- ...idleManifest
- .flatMap((entry) => entry.preload)
- .filter(
- (fileName) =>
- (chunkSizeByFileName.get(fileName) ?? minInitialRoutePreloadSize) >=
- minInitialRoutePreloadSize,
- ),
- ]),
- ],
- },
- config.base,
- deploymentId,
- );
- },
- },
- };
-}
-
-export const __testing = {
- appendDeploymentQuery,
- collectExistingHtmlAssets,
- createAllJsWarmupManifest,
- createAssetHref,
- createIdleWarmupScript,
- createRoutePreloadManifest,
- defaultIdleRoutePreloadGroups,
- defaultRoutePreloadGroups,
- injectIdleWarmupScriptIntoHtml,
- injectRouteModulepreloadsIntoHtml,
- removeSmallModulepreloadsFromHtml,
-};
diff --git a/plugins/vite/sharedRendererConfig.test.ts b/plugins/vite/sharedRendererConfig.test.ts
index 9da9eecbee3..8fcd4cf0cc3 100644
--- a/plugins/vite/sharedRendererConfig.test.ts
+++ b/plugins/vite/sharedRendererConfig.test.ts
@@ -1,6 +1,24 @@
import { describe, expect, it } from 'vitest';
-import { __testing, sharedModulePreload, sharedOptimizeDeps } from './sharedRendererConfig';
+import {
+ __testing,
+ sharedModulePreload,
+ sharedOptimizeDeps,
+ sharedRendererPlugins,
+} from './sharedRendererConfig';
+
+const getPluginNames = (platform: 'desktop' | 'web') =>
+ sharedRendererPlugins({ platform })
+ .flat(Number.POSITIVE_INFINITY)
+ .filter((plugin): plugin is { name: string } => Boolean(plugin) && typeof plugin === 'object')
+ .map((plugin) => plugin.name);
+
+describe('sharedRendererPlugins', () => {
+ it('keeps the icon barrel transform out of the Electron renderer', () => {
+ expect(getPluginNames('desktop')).not.toContain('lobe-icon-named-export-proxy');
+ expect(getPluginNames('web')).toContain('lobe-icon-named-export-proxy');
+ });
+});
describe('sharedOptimizeDeps', () => {
it('pre-bundles the root and base-ui entrypoints together', () => {
@@ -34,7 +52,7 @@ describe('sharedModulePreload', () => {
});
describe('sharedManualChunks', () => {
- it('splits auth SPA namespaces into their own per-locale i18n chunks', () => {
+ it('isolates synchronously bundled and heavy namespaces from deferred locale data', () => {
expect(__testing.sharedManualChunks('/repo/locales/zh-CN/auth.json')).toBe('i18n-zh-CN-auth');
expect(__testing.sharedManualChunks('/repo/locales/zh-CN/common.json')).toBe(
'i18n-zh-CN-common',
@@ -43,12 +61,36 @@ describe('sharedManualChunks', () => {
'i18n-default-oauth',
);
expect(__testing.sharedManualChunks('/repo/packages/locales/src/default/chat.ts')).toBe(
- 'i18n-src',
+ 'i18n-default-app-shell',
+ );
+ expect(__testing.sharedManualChunks('/repo/packages/locales/src/default/home.ts')).toBe(
+ 'i18n-default-app-shell',
+ );
+ expect(__testing.sharedManualChunks('/repo/packages/locales/src/default/hotkey.ts')).toBe(
+ 'i18n-default-hotkey',
+ );
+ expect(__testing.sharedManualChunks('/repo/packages/locales/src/default/models.ts')).toBe(
+ 'i18n-default-models',
+ );
+ expect(__testing.sharedManualChunks('/repo/locales/zh-CN/chat.json')).toBe(
+ 'i18n-zh-CN-app-shell',
+ );
+ expect(__testing.sharedManualChunks('/repo/locales/zh-CN/home.json')).toBe(
+ 'i18n-zh-CN-app-shell',
);
- expect(__testing.sharedManualChunks('/repo/locales/zh-CN/chat.json')).toBe('i18n-zh-CN');
expect(__testing.sharedManualChunks('/repo/locales/zh-CN/models.json')).toBe(
'i18n-zh-CN-models',
);
+ expect(__testing.sharedManualChunks('/repo/locales/zh-CN/setting.json')).toBe('i18n-zh-CN');
+ });
+
+ it('keeps UI and date locale runtimes outside deferred namespace data', () => {
+ expect(__testing.sharedManualChunks('/repo/node_modules/antd/es/locale/zh_CN.js')).toBe(
+ 'i18n-zh-CN-ui-runtime',
+ );
+ expect(__testing.sharedManualChunks('/repo/node_modules/dayjs/locale/zh-cn.js')).toBe(
+ 'i18n-zh-CN-ui-runtime',
+ );
});
it('keeps locale runtime helpers out of the default locale chunk', () => {
@@ -114,13 +156,83 @@ describe('sharedManualChunks', () => {
'/repo/node_modules/.pnpm/zustand@5/node_modules/zustand/esm/index.mjs',
),
).toBe('vendor-data-runtime');
- expect(
- __testing.sharedManualChunks('/repo/packages/model-runtime/src/providers/openai/index.ts'),
- ).toBe('vendor-ai-runtime');
expect(
__testing.sharedManualChunks(
'/repo/node_modules/.pnpm/openai@4/node_modules/openai/index.mjs',
),
).toBe('vendor-ai-runtime');
});
+
+ it('lets model-runtime follow dynamic import boundaries', () => {
+ expect(
+ __testing.sharedManualChunks('/repo/packages/model-runtime/src/providers/openai/index.ts'),
+ ).toBeUndefined();
+ expect(
+ __testing.sharedManualChunks('/repo/packages/model-runtime/src/helpers/parseToolCalls.ts'),
+ ).toBe('model-runtime-client');
+ expect(
+ __testing.sharedManualChunks('/repo/packages/model-runtime/src/types/toolsCalling.ts'),
+ ).toBe('model-runtime-client');
+ expect(
+ __testing.sharedManualChunks(
+ '/repo/packages/model-runtime/src/utils/getFallbackModelProperty.ts',
+ ),
+ ).toBeUndefined();
+ expect(__testing.sharedManualChunks('/repo/packages/model-bank/src/index.ts')).toBeUndefined();
+ });
+});
+
+describe('sharedChunkFileNames', () => {
+ it('routes only the complete deferred model catalog to on-demand assets', () => {
+ expect(
+ __testing.sharedChunkFileNames({
+ moduleIds: [
+ '/repo/packages/model-bank/src/aiModels/index.ts',
+ '/repo/packages/model-bank/src/aiModels/openai.ts',
+ ],
+ name: 'src',
+ }),
+ ).toBe('model-bank/[name]-[hash].js');
+
+ expect(
+ __testing.sharedChunkFileNames({
+ moduleIds: ['/repo/packages/model-bank/src/aiModels/opencodeZen.ts'],
+ name: 'opencodeZen',
+ }),
+ ).toBe('assets/[name]-[hash].js');
+ });
+
+ it('routes only self-contained Shiki language, theme, and WASM chunks to on-demand assets', () => {
+ expect(
+ __testing.sharedChunkFileNames({
+ moduleIds: ['/repo/node_modules/@shikijs/langs/dist/python.mjs'],
+ name: 'python',
+ }),
+ ).toBe('shiki/[name]-[hash].js');
+ expect(
+ __testing.sharedChunkFileNames({
+ moduleIds: ['/repo/node_modules/@shikijs/themes/dist/github-dark.mjs'],
+ name: 'github-dark',
+ }),
+ ).toBe('shiki/[name]-[hash].js');
+ expect(
+ __testing.sharedChunkFileNames({
+ moduleIds: [
+ '/repo/node_modules/@shikijs/engine-oniguruma/dist/wasm-inlined.mjs',
+ '/repo/node_modules/shiki/dist/wasm.mjs',
+ ],
+ name: 'wasm',
+ }),
+ ).toBe('shiki/[name]-[hash].js');
+
+ expect(
+ __testing.sharedChunkFileNames({
+ moduleIds: [
+ '/repo/node_modules/@shikijs/core/dist/index.mjs',
+ '/repo/src/features/Conversation/Markdown/index.tsx',
+ ],
+ name: 'markdown',
+ }),
+ ).toBe('assets/[name]-[hash].js');
+ });
});
diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.ts
index 2816d9b07bb..0df5cf89871 100644
--- a/plugins/vite/sharedRendererConfig.ts
+++ b/plugins/vite/sharedRendererConfig.ts
@@ -3,25 +3,39 @@ import { codeInspectorPlugin } from 'code-inspector-plugin';
import type { ModulePreloadOptions } from 'vite';
import { viteEmotionSpeedy } from './emotionSpeedy';
+import { lobeIconImports } from './lobeIconImports';
import { viteMarkdownImport } from './markdownImport';
import { viteNodeModuleStub } from './nodeModuleStub';
import { vitePlatformResolve } from './platformResolve';
-import { routeChunkPreload } from './routeChunkPreload';
/**
* Shared manual chunk naming β€” groups leaf-node modules to reduce chunk file count.
* Only targets pure data modules (no downstream dependents) to avoid facade chunk issues.
*/
-/** Large i18n namespaces that get their own per-locale chunk instead of merging into the locale bundle */
+/** Large i18n namespaces that stay on demand instead of merging into the locale bundle. */
const HEAVY_NS = new Set(['models', 'modelProvider']);
-/**
- * Namespaces loaded by the auth SPA (see createAuthI18n). They get their own
- * per-locale chunk so the auth page never pulls the merged locale bundle of the
- * main app, and both SPAs share the same chunk URLs for these namespaces.
- */
+/** Namespaces shared with the independently built auth SPA. */
const AUTH_NS = new Set(['auth', 'authError', 'common', 'error', 'marketAuth', 'oauth']);
+/** Namespaces synchronously bundled by the main SPA shell. */
+const APP_SHELL_NS = new Set(['chat', 'home']);
+
+/** Default-language metadata imported directly by an eager route component. */
+const EAGER_DEFAULT_NS = new Set(['hotkey']);
+
+const MODEL_RUNTIME_CLIENT_MODULES = [
+ '/core/usageConverters/utils/resolveImageSinglePrice.ts',
+ '/core/usageConverters/utils/resolveVideoSinglePrice.ts',
+ '/helpers/parseToolCalls.ts',
+ '/providers/openai/modelId.ts',
+ '/types/error.ts',
+ '/types/toolsCalling.ts',
+ '/utils/createError.ts',
+ '/utils/modelExtendParams.ts',
+ '/utils/uriParser.ts',
+];
+
/** antd locale filename β†’ app locale */
const ANTD_LOCALE: Record<string, string> = {
ar_EG: 'ar',
@@ -95,12 +109,15 @@ function sharedManualChunks(id: string): string | undefined {
// closure; their existing dynamic-import boundaries must remain intact.
if (isNodePackage(id, 'react-scan')) return 'devtools-react-scan';
- // default locale sources live in packages/locales/src/default β€” their chunk
- // has historically been named i18n-src by the generic locale match below
+ // Default locale sources live in packages/locales/src/default. Keep shell
+ // and heavy namespaces isolated; the remaining on-demand namespaces share a
+ // coarse fallback chunk to avoid creating hundreds of tiny files.
const defaultLocaleMatch = id.match(/\/locales\/src\/default\/([^/.]+)/);
if (defaultLocaleMatch) {
const ns = defaultLocaleMatch[1];
- if (AUTH_NS.has(ns)) return `i18n-default-${ns}`;
+ if (APP_SHELL_NS.has(ns)) return 'i18n-default-app-shell';
+ if (AUTH_NS.has(ns) || EAGER_DEFAULT_NS.has(ns) || HEAVY_NS.has(ns))
+ return `i18n-default-${ns}`;
return 'i18n-src';
}
@@ -113,36 +130,53 @@ function sharedManualChunks(id: string): string | undefined {
const localeMatch = id.match(/\/locales\/([^/]+)\/([^/.]+)/);
if (localeMatch) {
const [, locale, ns] = localeMatch;
- if (AUTH_NS.has(ns)) return `i18n-${locale}-${ns}`;
+ if (APP_SHELL_NS.has(ns)) return `i18n-${locale}-app-shell`;
+ if (AUTH_NS.has(ns) || HEAVY_NS.has(ns)) return `i18n-${locale}-${ns}`;
if (locale === 'default') return 'i18n-default';
- if (HEAVY_NS.has(ns)) return `i18n-${locale}-${ns}`;
return `i18n-${locale}`;
}
- if (id.includes('/packages/model-runtime/') || isNodePackage(id, 'openai'))
- return 'vendor-ai-runtime';
+ // These small contracts are used by the eager app shell and the deferred
+ // composer. Without an explicit boundary, Rolldown captures them inside the
+ // large ChatInput chunk and turns that otherwise-lazy chunk into an eager
+ // dependency of the home layout.
+ if (
+ id.includes('/src/business/client/hooks/useBusinessAgentMode.ts') ||
+ id.includes('/src/features/ChatInput/utils/contextSelections.ts') ||
+ id.includes('/src/routes/(main)/_layout/DesktopLayoutContainer/LayoutContainerContext.ts')
+ ) {
+ return 'chat-input-contracts';
+ }
+
+ if (isNodePackage(id, 'openai')) return 'vendor-ai-runtime';
// shared constants would otherwise be captured into vendor-ai-runtime,
// dragging the whole AI chunk into the auth SPA's static graph
if (id.includes('/packages/const/src/')) return 'app-const';
- // model-bank (monorepo package β€” split before node_modules guard)
- if (id.includes('model-bank')) return 'providerConfig';
+ if (
+ id.includes('/packages/model-runtime/src/') &&
+ (id.includes('/packages/model-runtime/src/errors/') ||
+ MODEL_RUNTIME_CLIENT_MODULES.some((moduleId) => id.endsWith(moduleId)))
+ ) {
+ return 'model-runtime-client';
+ }
if (!id.includes('node_modules')) return;
- // antd locale β†’ merge into i18n-{locale}
+ // UI/date locale modules are loaded during shell initialization. They must
+ // not share the coarse i18n-{locale} data chunk, or loading antd/dayjs pulls
+ // every deferred namespace for that locale into the bootstrap graph.
const antdMatch = id.match(/antd\/es\/locale\/([^/.]+)\.js/);
if (antdMatch) {
const locale = ANTD_LOCALE[antdMatch[1]];
- if (locale) return `i18n-${locale}`;
+ if (locale) return `i18n-${locale}-ui-runtime`;
}
- // dayjs locale β†’ merge into i18n-{locale}
const dayjsMatch = id.match(/dayjs\/locale\/([^/.]+)\.js/);
if (dayjsMatch) {
const locale = DAYJS_LOCALE[dayjsMatch[1]];
- if (locale) return `i18n-${locale}`;
+ if (locale) return `i18n-${locale}-ui-runtime`;
}
if (
@@ -177,12 +211,42 @@ function sharedManualChunks(id: string): string | undefined {
if (id.includes('lucide-react')) return 'vendor-icons';
}
-const sharedChunkFileNames = (chunkInfo: { moduleIds?: string[]; name: string }) => {
+interface SharedChunkInfo {
+ moduleIds?: string[];
+ name: string;
+}
+
+const isOnDemandShikiModule = (moduleId: string) => {
+ const normalized = moduleId.replaceAll('\\', '/');
+
+ return (
+ normalized.includes('/node_modules/@shikijs/langs/') ||
+ normalized.includes('/node_modules/@shikijs/themes/') ||
+ normalized.includes('/node_modules/@shikijs/engine-oniguruma/dist/wasm') ||
+ normalized.includes('/node_modules/shiki/dist/wasm.mjs')
+ );
+};
+
+const isModelBankModule = (moduleId: string) =>
+ moduleId.replaceAll('\\', '/').includes('/packages/model-bank/src/');
+
+const isOnDemandModelBankCatalog = (moduleIds: string[]) =>
+ moduleIds.length > 0 &&
+ moduleIds.every(isModelBankModule) &&
+ moduleIds.some((moduleId) =>
+ moduleId.replaceAll('\\', '/').endsWith('/packages/model-bank/src/aiModels/index.ts'),
+ );
+
+const sharedChunkFileNames = (chunkInfo: SharedChunkInfo) => {
const { moduleIds = [], name } = chunkInfo;
if (name.startsWith('devtools-') || moduleIds.some(isDeferredDevtoolsSource))
return 'devtools/[name]-[hash].js';
if (name.startsWith('i18n-')) return 'i18n/[name]-[hash].js';
if (name.startsWith('vendor-')) return 'vendor/[name]-[hash].js';
+ if (chunkInfo.moduleIds && isOnDemandModelBankCatalog(chunkInfo.moduleIds))
+ return 'model-bank/[name]-[hash].js';
+ if (chunkInfo.moduleIds?.length && chunkInfo.moduleIds.every(isOnDemandShikiModule))
+ return 'shiki/[name]-[hash].js';
return 'assets/[name]-[hash].js';
};
@@ -204,8 +268,41 @@ const isDevtoolsChunkFileName = (fileName: string) => {
);
};
-/** DevDock assets are authorized runtime downloads and must never enter the service-worker precache. */
-export const sharedPwaGlobIgnores = ['devtools/**'];
+/** Deferred assets must remain demand-loaded rather than entering the service-worker precache. */
+export const sharedPwaGlobIgnores = [
+ 'devtools/**',
+ 'i18n/**/*.js',
+ 'model-bank/**/*.js',
+ 'shiki/**/*.js',
+];
+
+/** Runtime caching for deferred assets excluded from the service-worker precache. */
+export const sharedPwaRuntimeCaching = [
+ {
+ handler: 'CacheFirst',
+ options: {
+ cacheName: 'on-demand-i18n',
+ expiration: { maxAgeSeconds: 60 * 60 * 24 * 30, maxEntries: 50 },
+ },
+ urlPattern: ({ url }: { url: URL }) => /\/i18n\/.*\.js$/i.test(url.pathname),
+ },
+ {
+ handler: 'CacheFirst',
+ options: {
+ cacheName: 'on-demand-shiki',
+ expiration: { maxAgeSeconds: 60 * 60 * 24 * 30, maxEntries: 150 },
+ },
+ urlPattern: ({ url }: { url: URL }) => /\/shiki\/.*\.js$/i.test(url.pathname),
+ },
+ {
+ handler: 'CacheFirst',
+ options: {
+ cacheName: 'on-demand-model-bank',
+ expiration: { maxAgeSeconds: 60 * 60 * 24 * 30, maxEntries: 5 },
+ },
+ urlPattern: ({ url }: { url: URL }) => /\/model-bank\/.*\.js$/i.test(url.pathname),
+ },
+] as const;
export const sharedModulePreload = {
resolveDependencies: (_filename, deps) =>
@@ -236,7 +333,6 @@ export const createSharedRolldownOutput = (options: SharedRolldownOutputOptions
type Platform = 'web' | 'mobile' | 'desktop' | 'auth';
const isDev = process.env.NODE_ENV !== 'production';
-const enableRouteChunkPreload = process.env.LOBE_ROUTE_CHUNK_PRELOAD !== 'false';
interface SharedRendererOptions {
platform: Platform;
@@ -249,7 +345,6 @@ export function sharedRendererPlugins(options: SharedRendererOptions) {
viteMarkdownImport(),
viteNodeModuleStub(),
vitePlatformResolve(options.platform),
- enableRouteChunkPreload && routeChunkPreload(),
isDev && {
name: 'lobe-dev-strip-manifest',
@@ -266,6 +361,7 @@ export function sharedRendererPlugins(options: SharedRendererOptions) {
hotKeys: ['altKey', 'ctrlKey'],
}),
react(),
+ ...(options.platform === 'desktop' ? [] : lobeIconImports()),
];
}
diff --git a/scripts/copySpaBuild.mts b/scripts/copySpaBuild.mts
index e1e7748e755..a72e1261bc6 100644
--- a/scripts/copySpaBuild.mts
+++ b/scripts/copySpaBuild.mts
@@ -1,39 +1,9 @@
-import { cpSync, existsSync, mkdirSync, readdirSync, statSync } from 'node:fs';
import path from 'node:path';
-const root = path.resolve(import.meta.dirname, '..');
-const copyDirs = ['assets', 'i18n', 'vendor'] as const;
-const copyRootFilePatterns = [/^favicon.*\.ico$/, /^apple-touch-icon\.png$/] as const;
-const targets = [
- { distDir: 'desktop', publicDir: 'public/_spa' },
- { distDir: 'mobile', publicDir: 'public/_spa' },
- { distDir: 'auth', publicDir: 'public/_spa-auth' },
-] as const;
+import { copySpaBuild } from './copySpaBuildCore.ts';
-for (const { distDir, publicDir } of targets) {
- const distRoot = path.resolve(root, `dist/${distDir}`);
- const spaDir = path.resolve(root, publicDir);
- mkdirSync(spaDir, { recursive: true });
+const root = process.argv[2]
+ ? path.resolve(process.argv[2])
+ : path.resolve(import.meta.dirname, '..');
- for (const dir of copyDirs) {
- const sourceDir = path.resolve(distRoot, dir);
- const targetDir = path.resolve(spaDir, dir);
-
- if (!existsSync(sourceDir)) continue;
-
- cpSync(sourceDir, targetDir, { recursive: true });
- console.log(`Copied dist/${distDir}/${dir} -> ${publicDir}/${dir}`);
- }
-
- if (!existsSync(distRoot)) continue;
-
- for (const file of readdirSync(distRoot)) {
- const sourceFile = path.resolve(distRoot, file);
-
- if (!statSync(sourceFile).isFile()) continue;
- if (!copyRootFilePatterns.some((pattern) => pattern.test(file))) continue;
-
- cpSync(sourceFile, path.resolve(spaDir, file));
- console.log(`Copied dist/${distDir}/${file} -> ${publicDir}/${file}`);
- }
-}
+copySpaBuild(root);
diff --git a/scripts/copySpaBuild.test.ts b/scripts/copySpaBuild.test.ts
new file mode 100644
index 00000000000..ec54cae2074
--- /dev/null
+++ b/scripts/copySpaBuild.test.ts
@@ -0,0 +1,49 @@
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { copySpaBuild } from './copySpaBuildCore';
+
+const testRoots: string[] = [];
+
+afterEach(() => {
+ for (const root of testRoots.splice(0)) rmSync(root, { force: true, recursive: true });
+});
+
+describe('copySpaBuild', () => {
+ it('publishes on-demand chunk directories required by the production SPA', () => {
+ const root = mkdtempSync(path.join(tmpdir(), 'copy-spa-build-'));
+ testRoots.push(root);
+
+ for (const dir of ['assets', 'i18n', 'model-bank', 'shiki', 'vendor']) {
+ const sourceDir = path.join(root, 'dist/desktop', dir);
+ mkdirSync(sourceDir, { recursive: true });
+ writeFileSync(path.join(sourceDir, `${dir}.js`), `export default '${dir}';`);
+ }
+
+ copySpaBuild(root);
+
+ for (const dir of ['assets', 'i18n', 'model-bank', 'shiki', 'vendor']) {
+ expect(existsSync(path.join(root, 'public/_spa', dir, `${dir}.js`))).toBe(true);
+ }
+ });
+
+ it('runs through the production Node entrypoint', () => {
+ const root = mkdtempSync(path.join(tmpdir(), 'copy-spa-build-entry-'));
+ testRoots.push(root);
+
+ const sourceDir = path.join(root, 'dist/desktop/model-bank');
+ mkdirSync(sourceDir, { recursive: true });
+ writeFileSync(path.join(sourceDir, 'catalog.js'), 'export default [];');
+
+ execFileSync(process.execPath, [path.resolve(import.meta.dirname, 'copySpaBuild.mts'), root], {
+ cwd: tmpdir(),
+ stdio: 'pipe',
+ });
+
+ expect(existsSync(path.join(root, 'public/_spa/model-bank/catalog.js'))).toBe(true);
+ });
+});
diff --git a/scripts/copySpaBuildCore.ts b/scripts/copySpaBuildCore.ts
new file mode 100644
index 00000000000..aa41d040b7d
--- /dev/null
+++ b/scripts/copySpaBuildCore.ts
@@ -0,0 +1,40 @@
+import { cpSync, existsSync, mkdirSync, readdirSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+const copyDirs = ['assets', 'i18n', 'model-bank', 'shiki', 'vendor'] as const;
+const copyRootFilePatterns = [/^favicon.*\.ico$/, /^apple-touch-icon\.png$/] as const;
+const targets = [
+ { distDir: 'desktop', publicDir: 'public/_spa' },
+ { distDir: 'mobile', publicDir: 'public/_spa' },
+ { distDir: 'auth', publicDir: 'public/_spa-auth' },
+] as const;
+
+export const copySpaBuild = (root = path.resolve(import.meta.dirname, '..')) => {
+ for (const { distDir, publicDir } of targets) {
+ const distRoot = path.resolve(root, `dist/${distDir}`);
+ const spaDir = path.resolve(root, publicDir);
+ mkdirSync(spaDir, { recursive: true });
+
+ for (const dir of copyDirs) {
+ const sourceDir = path.resolve(distRoot, dir);
+ const targetDir = path.resolve(spaDir, dir);
+
+ if (!existsSync(sourceDir)) continue;
+
+ cpSync(sourceDir, targetDir, { recursive: true });
+ console.log(`Copied dist/${distDir}/${dir} -> ${publicDir}/${dir}`);
+ }
+
+ if (!existsSync(distRoot)) continue;
+
+ for (const file of readdirSync(distRoot)) {
+ const sourceFile = path.resolve(distRoot, file);
+
+ if (!statSync(sourceFile).isFile()) continue;
+ if (!copyRootFilePatterns.some((pattern) => pattern.test(file))) continue;
+
+ cpSync(sourceFile, path.resolve(spaDir, file));
+ console.log(`Copied dist/${distDir}/${file} -> ${publicDir}/${file}`);
+ }
+ }
+};
diff --git a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
index 1e7640efa78..3b253a71e18 100644
--- a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -88,7 +88,7 @@ export const useTopicItemDropdownMenu = ({
const handleOpenShareModal = useCallback(() => {
if (!id) return;
- openShareModal({ context: { threadId: null, topicId: id } });
+ void openShareModal({ context: { threadId: null, topicId: id } });
}, [id]);
const dropdownMenu = useCallback(() => {
diff --git a/src/features/AgentSidebar/index.tsx b/src/features/AgentSidebar/index.tsx
index caa56a4c087..a4c5df2dba8 100644
--- a/src/features/AgentSidebar/index.tsx
+++ b/src/features/AgentSidebar/index.tsx
@@ -1,6 +1,6 @@
import React, { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import AgentSidebarContent from './Content';
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx
index 8de5c2eba2e..b05dcd862d4 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx
@@ -15,8 +15,8 @@ import { FileLock2Icon, FileTextIcon, MoreHorizontal, Package, Trash } from 'luc
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { openDocumentModal } from '@/features/DocumentModal/loader';
import Time from '@/routes/(main)/home/features/components/Time';
-import { useDocumentStore } from '@/store/document';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
@@ -30,7 +30,6 @@ const flattenWorkspace = (nodes: TaskDetailWorkspaceNode[]): TaskDetailWorkspace
const ArtifactCard = memo<{ node: TaskDetailWorkspaceNode }>(({ node }) => {
const { t } = useTranslation('chat');
- const openDocumentPreview = useDocumentStore((s) => s.openDocumentPreview);
const unpinDocument = useTaskStore((s) => s.unpinDocument);
const activeTaskId = useTaskStore(taskDetailSelectors.activeTaskId);
// Tombstone: the viewer lost access to the pinned document (switched back
@@ -77,7 +76,7 @@ const ArtifactCard = memo<{ node: TaskDetailWorkspaceNode }>(({ node }) => {
paddingBlock={8}
paddingInline={12}
variant="outlined"
- onClick={() => openDocumentPreview(node.documentId)}
+ onClick={() => void openDocumentModal(node.documentId)}
>
<Icon
color={cssVar.colorTextSecondary}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
index f35621808e9..8fd39cee604 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
@@ -8,7 +8,6 @@ import NotFound from '@/components/404';
import AsyncError from '@/components/AsyncError';
import AutoSaveHint from '@/components/Editor/AutoSaveHint';
import Loading from '@/components/Loading/BrandTextLoading';
-import DocumentPreviewModal from '@/features/DocumentModal/Preview';
import NavHeader from '@/features/NavHeader';
import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
import WideScreenContainer from '@/features/WideScreenContainer';
@@ -110,7 +109,6 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId, showTaskAgentPanelTo
</WideScreenContainer>
</Flexbox>
<TopicChatDrawer />
- <DocumentPreviewModal />
</Flexbox>
);
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/FeedbackInput.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/FeedbackInput.tsx
index 5f919205df8..a52a41a2865 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/FeedbackInput.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/FeedbackInput.tsx
@@ -7,9 +7,9 @@ import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AttachmentUploadButton } from '@/features/AttachmentInput';
-import { useConversationStore } from '@/features/Conversation';
import OpStatusTray from '@/features/Conversation/ChatInput/OpStatusTray';
import { useConversationResourceAccess } from '@/features/Conversation/hooks/useConversationResourceAccess';
+import { useConversationStore } from '@/features/Conversation/store';
import { EditorCanvas } from '@/features/EditorCanvas';
import {
getAttachmentFileIdsFromEditor,
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
index 479a95ad09c..921ad4c4b84 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
@@ -158,10 +158,16 @@ vi.mock('react-i18next', () => ({
}),
}));
-vi.mock('@/features/Conversation', () => ({
- ChatList: () => <div data-testid="chat-list" />,
+vi.mock('@/features/Conversation/ChatList', () => ({
+ default: () => <div data-testid="chat-list" />,
+}));
+
+vi.mock('@/features/Conversation/ConversationProvider', () => ({
ConversationProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,
- MessageItem: ({ id }: { id: string }) => <div data-testid="message-item">{id}</div>,
+}));
+
+vi.mock('@/features/Conversation/Messages', () => ({
+ default: ({ id }: { id: string }) => <div data-testid="message-item">{id}</div>,
}));
vi.mock('@/features/Conversation/Markdown/plugins/Task', () => ({
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
index 0cb2388d4b2..671b6b7d040 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx
@@ -8,8 +8,10 @@ import { Copy, MoreHorizontal, Share2 } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { ChatList, ConversationProvider, MessageItem } from '@/features/Conversation';
+import ChatList from '@/features/Conversation/ChatList';
+import { ConversationProvider } from '@/features/Conversation/ConversationProvider';
import { TaskCardScopeProvider } from '@/features/Conversation/Markdown/plugins/Task';
+import MessageItem from '@/features/Conversation/Messages';
import { useShareModal } from '@/features/ShareModal';
import { LazySharePopover as SharePopover } from '@/features/SharePopover/lazy';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
diff --git a/src/features/AgentTasks/TaskWorkspaceLayout.test.tsx b/src/features/AgentTasks/TaskWorkspaceLayout.test.tsx
index e46ada0078a..456d0dee7d7 100644
--- a/src/features/AgentTasks/TaskWorkspaceLayout.test.tsx
+++ b/src/features/AgentTasks/TaskWorkspaceLayout.test.tsx
@@ -5,8 +5,6 @@ import { render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { resetNavPanel } from '@/features/NavPanel';
-
import TaskWorkspaceLayout from './TaskWorkspaceLayout';
const mocks = vi.hoisted(() => ({
@@ -33,14 +31,9 @@ vi.mock('@/features/AgentTaskManager', () => ({
default: () => <div data-testid="task-agent-manager" />,
}));
-vi.mock('@/features/NavPanel', () => ({
- resetNavPanel: vi.fn(),
-}));
-
vi.mock('@/features/Portal/Mobile', () => ({
default: () => <div data-testid="mobile-task-portal" />,
}));
-
vi.mock('@/hooks/useIsMobile', () => ({
useIsMobile: () => mocks.isMobile,
}));
@@ -48,13 +41,11 @@ vi.mock('@/hooks/useIsMobile', () => ({
describe('TaskWorkspaceLayout', () => {
beforeEach(() => {
mocks.isMobile = false;
- vi.mocked(resetNavPanel).mockClear();
});
- it('resets the nav panel to the home sidebar fallback', () => {
+ it('renders the task workspace without mutating global NavPanel state', () => {
render(<TaskWorkspaceLayout />);
- expect(resetNavPanel).toHaveBeenCalledTimes(1);
expect(screen.getByTestId('task-workspace-outlet')).toBeInTheDocument();
expect(screen.getByTestId('task-agent-manager')).toBeInTheDocument();
});
diff --git a/src/features/AgentTasks/TaskWorkspaceLayout.tsx b/src/features/AgentTasks/TaskWorkspaceLayout.tsx
index 367d9c4926d..75c8f1fd723 100644
--- a/src/features/AgentTasks/TaskWorkspaceLayout.tsx
+++ b/src/features/AgentTasks/TaskWorkspaceLayout.tsx
@@ -1,21 +1,16 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { memo, useLayoutEffect } from 'react';
+import { memo } from 'react';
import { Outlet } from 'react-router';
import AgentTaskManager from '@/features/AgentTaskManager';
-import { resetNavPanel } from '@/features/NavPanel';
import MobilePortal from '@/features/Portal/Mobile';
import { useIsMobile } from '@/hooks/useIsMobile';
const TaskWorkspaceLayout = memo(() => {
const isMobile = useIsMobile();
- useLayoutEffect(() => {
- resetNavPanel();
- }, []);
-
return (
<Flexbox flex={1} height={'100%'} horizontal={!isMobile} width={'100%'}>
<Flexbox flex={1} style={{ minWidth: 0 }}>
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.loader.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.loader.ts
new file mode 100644
index 00000000000..cab109377b6
--- /dev/null
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.loader.ts
@@ -0,0 +1,33 @@
+import { isPdfFile } from '@/features/FileViewer/fileType';
+import { preloadPDFRenderer } from '@/features/FileViewer/Renderer/PDF/loader';
+import { type UploadFileItem } from '@/types/files/upload';
+
+const importFilePreviewModal = () => import('./FilePreviewModal');
+
+let filePreviewModalPromise: ReturnType<typeof importFilePreviewModal> | undefined;
+
+export const preloadFilePreviewModal = (): ReturnType<typeof importFilePreviewModal> =>
+ (filePreviewModalPromise ??= importFilePreviewModal().catch((error) => {
+ filePreviewModalPromise = undefined;
+ throw error;
+ }));
+
+export const openFilePreviewModal = async (file: UploadFileItem) => {
+ const modalPromise = preloadFilePreviewModal();
+
+ if (
+ isPdfFile({
+ fileName: file.file.name,
+ fileType: file.file.type,
+ path: file.previewUrl || file.fileUrl || file.base64Url,
+ })
+ ) {
+ void preloadPDFRenderer().catch((error) => {
+ console.error('Failed to preload the PDF renderer:', error);
+ });
+ }
+
+ const { createFilePreviewModal } = await modalPromise;
+
+ return createFilePreviewModal(file);
+};
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.tsx
index a368ef2aa7c..8ce61e4f366 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.tsx
@@ -1,58 +1,40 @@
'use client';
-import { memo } from 'react';
+import { createModal } from '@lobehub/ui/base-ui';
-import ImperativeModal from '@/components/ImperativeModal';
import FileViewer from '@/features/FileViewer';
import { type UploadFileItem } from '@/types/files/upload';
-interface FilePreviewModalProps {
- file: UploadFileItem;
- onClose: () => void;
- open: boolean;
-}
-
-const FilePreviewModal = memo<FilePreviewModalProps>(({ file, open, onClose }) => {
+const FilePreviewModalContent = ({ file }: { file: UploadFileItem }) => {
// Get the best available URL for preview
const previewUrl = file.previewUrl || file.fileUrl || file.base64Url || '';
return (
- <ImperativeModal
- allowFullscreen
- centered
- destroyOnHidden
- footer={null}
- height={'80vh'}
- open={open}
- title={file.file.name}
- width={'min(90vw, 1024px)'}
- styles={{
- body: {
- height: '80vh',
- overflow: 'auto',
- padding: 0,
- },
- }}
- onCancel={onClose}
- >
- <FileViewer
- chunkCount={null}
- chunkingError={null}
- createdAt={new Date()}
- embeddingError={null}
- fileType={file.file.type}
- finishEmbedding={false}
- id={file.id}
- name={file.file.name}
- size={file.file.size}
- sourceType="upload"
- updatedAt={new Date()}
- url={previewUrl}
- />
- </ImperativeModal>
+ <FileViewer
+ chunkCount={null}
+ chunkingError={null}
+ createdAt={new Date()}
+ embeddingError={null}
+ fileType={file.file.type}
+ finishEmbedding={false}
+ id={file.id}
+ name={file.file.name}
+ size={file.file.size}
+ sourceType="upload"
+ updatedAt={new Date()}
+ url={previewUrl}
+ />
);
-});
-
-FilePreviewModal.displayName = 'FilePreviewModal';
+};
-export default FilePreviewModal;
+export const createFilePreviewModal = (file: UploadFileItem) =>
+ createModal({
+ content: <FilePreviewModalContent file={file} />,
+ footer: null,
+ maskClosable: true,
+ styles: {
+ content: { height: '80vh', minHeight: 0, overflow: 'auto', padding: 0 },
+ },
+ title: file.file.name,
+ width: 'min(90vw, 1024px)',
+ });
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
index 4e363f9b9c6..4295bd7769e 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
@@ -1,4 +1,4 @@
-import { createRawModal, Flexbox, Tag, Tooltip } from '@lobehub/ui';
+import { Flexbox, Tag, Tooltip } from '@lobehub/ui';
import { Progress } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
import { memo } from 'react';
@@ -9,7 +9,7 @@ import { type UploadFileItem } from '@/types/files/upload';
import { UPLOAD_STATUS_SET } from '@/types/files/upload';
import Content from './Content';
-import FilePreviewModal from './FilePreviewModal';
+import { openFilePreviewModal } from './FilePreviewModal.loader';
import { getFileBasename } from './utils';
const styles = createStaticStyles(({ css }) => ({
@@ -85,9 +85,7 @@ const ContextItem = memo<FileItemProps>((props) => {
const progress = uploadState?.progress ?? 0;
const handleClick = useEventCallback(() => {
- createRawModal(FilePreviewModal, {
- file: props,
- });
+ void openFilePreviewModal(props);
});
const handleClose = useEventCallback(() => {
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index cc2f5963b74..2b8abe0e8b7 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -91,6 +91,7 @@ interface DesktopChatInputProps extends ActionToolbarProps {
controlBarSlot?: ReactNode;
extentHeaderContent?: ReactNode;
hidden?: boolean;
+ initialContent?: string;
inputContainerProps?: ChatInputProps;
/**
* Swap the action bar and send area for skeleton placeholders while
@@ -120,6 +121,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
extraActionItems,
dropdownPlacement,
hidden,
+ initialContent,
isConfigLoading = false,
leftContent,
placeholder,
@@ -258,7 +260,11 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
{...inputContainerProps}
className={cx(expand && styles.inputFullscreen, inputContainerProps?.className)}
>
- <InputEditor placeholder={placeholder} placeholderVariant={placeholderVariant} />
+ <InputEditor
+ initialContent={initialContent}
+ placeholder={placeholder}
+ placeholderVariant={placeholderVariant}
+ />
</ChatInput>
{controlBarSlot ?? (showControlBar && <ControlBar />)}
{showFootnote && !expand && (
diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsx
index a2ad48c5418..4f7a4751823 100644
--- a/src/features/ChatInput/InputEditor/index.test.tsx
+++ b/src/features/ChatInput/InputEditor/index.test.tsx
@@ -104,8 +104,8 @@ vi.mock('@lobehub/editor', () => ({
}));
vi.mock('@lobehub/editor/react', () => {
const Editor = Object.assign(
- vi.fn(({ editable }: { editable?: boolean }) => (
- <div data-editable={String(editable)} data-testid="mock-editor" />
+ vi.fn(({ content, editable }: { content?: string; editable?: boolean }) => (
+ <div data-content={content} data-editable={String(editable)} data-testid="mock-editor" />
)),
{
withProps: vi.fn((plugin, props) => [plugin, props]),
@@ -271,6 +271,15 @@ describe('ChatInput InputEditor', () => {
expect(screen.getByTestId('mock-editor')).toHaveAttribute('data-editable', 'false');
});
+ it('initializes the editor with content captured by a fallback input', () => {
+ render(<InputEditor initialContent="typed before the editor loaded" />);
+
+ expect(screen.getByTestId('mock-editor')).toHaveAttribute(
+ 'data-content',
+ 'typed before the editor loaded',
+ );
+ });
+
it('renders the editor at 16px on mobile', async () => {
permission.allowed = true;
platform.isMobile = true;
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index ce0d0645fe7..8efecc7dc8d 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -78,9 +78,10 @@ type MentionOption = ISlashMenuOption | ISlashSectionOption;
const InputEditor = memo<{
defaultRows?: number;
+ initialContent?: string;
placeholder?: ReactNode;
placeholderVariant?: PlaceholderVariant;
-}>(({ defaultRows = 2, placeholder, placeholderVariant }) => {
+}>(({ defaultRows = 2, initialContent = '', placeholder, placeholderVariant }) => {
const { t } = useTranslation('chat');
const mobile = useServerConfigStore((s) => s.isMobile);
const [
@@ -542,7 +543,7 @@ const InputEditor = memo<{
autoFocus
pasteAsPlainText
className={className}
- content={''}
+ content={initialContent}
editable={canCreateContent && canUseResource}
editor={editor}
getPopupContainer={() => (slashMenuRef as any)?.current ?? null}
diff --git a/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx b/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx
index f4ef95313c0..851ed637648 100644
--- a/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx
+++ b/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx
@@ -30,7 +30,10 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock('@/features/Conversation', () => ({
+vi.mock('@/features/Conversation/store', () => ({
+ dataSelectors: {
+ getDisplayMessageById: (id: string) => () => ({ content: messageContent, id }),
+ },
useConversationStore: (selector: (s: unknown) => unknown) =>
selector({
deleteMessage: deleteMessageMock,
@@ -38,12 +41,6 @@ vi.mock('@/features/Conversation', () => ({
}),
}));
-vi.mock('@/features/Conversation/store', () => ({
- dataSelectors: {
- getDisplayMessageById: (id: string) => () => ({ content: messageContent, id }),
- },
-}));
-
describe('ErrorContent dismiss behavior', () => {
beforeEach(() => {
deleteMessageMock.mockClear();
diff --git a/src/features/Conversation/ChatItem/components/ErrorContent.tsx b/src/features/Conversation/ChatItem/components/ErrorContent.tsx
index 63662c4d088..6d01e127b14 100644
--- a/src/features/Conversation/ChatItem/components/ErrorContent.tsx
+++ b/src/features/Conversation/ChatItem/components/ErrorContent.tsx
@@ -4,8 +4,7 @@ import { RotateCcw } from 'lucide-react';
import { memo, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
-import { useConversationStore } from '@/features/Conversation';
-import { dataSelectors } from '@/features/Conversation/store';
+import { dataSelectors, useConversationStore } from '@/features/Conversation/store';
import { type ChatItemProps } from '../type';
diff --git a/src/features/Conversation/FollowUp/FollowUpChips.test.tsx b/src/features/Conversation/FollowUp/FollowUpChips.test.tsx
index 07c60e21481..584e53d27b0 100644
--- a/src/features/Conversation/FollowUp/FollowUpChips.test.tsx
+++ b/src/features/Conversation/FollowUp/FollowUpChips.test.tsx
@@ -31,7 +31,11 @@ const editorMock = { focus: editorFocusMock, setDocument: editorSetDocumentMock
let isGeneratingMock = false;
let displayMessagesMock: Array<{ children?: Array<{ id: string }>; id: string }> = [];
-vi.mock('@/features/Conversation', () => ({
+vi.mock('@/features/Conversation/store', () => ({
+ messageStateSelectors: {
+ isAssistantGroupItemGenerating: () => (state: any) =>
+ state.operationState.getMessageOperationState().isGenerating,
+ },
useConversationStore: (selector: any) =>
selector({
displayMessages: displayMessagesMock,
diff --git a/src/features/Conversation/FollowUp/FollowUpChips.tsx b/src/features/Conversation/FollowUp/FollowUpChips.tsx
index e59913689ec..154940966e0 100644
--- a/src/features/Conversation/FollowUp/FollowUpChips.tsx
+++ b/src/features/Conversation/FollowUp/FollowUpChips.tsx
@@ -4,10 +4,9 @@ import type { FollowUpChip } from '@lobechat/types';
import { Reply } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
-import { useConversationStore } from '@/features/Conversation';
+import { messageStateSelectors, useConversationStore } from '@/features/Conversation/store';
import { followUpActionSelectors, useFollowUpActionStore } from '@/store/followUpAction';
-import { messageStateSelectors } from '../store';
import { styles } from './style';
interface FollowUpChipsProps {
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/share.tsx b/src/features/Conversation/Messages/components/MessageActionBar/actions/share.tsx
index 33995c5e424..1fbdafa1cd9 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/share.tsx
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/share.tsx
@@ -1,10 +1,9 @@
-import { createRawModal } from '@lobehub/ui';
import { Share2 } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import ShareMessageModal, { type ShareModalProps } from '../../../../components/ShareMessageModal';
-import { createStore, Provider, useConversationStoreApi } from '../../../../store';
+import { openShareMessageModal } from '../../../../components/ShareMessageModal';
+import { createStore, useConversationStoreApi } from '../../../../store';
import { defineAction } from '../defineAction';
export const shareAction = defineAction({
@@ -17,24 +16,14 @@ export const shareAction = defineAction({
if (ctx.role === 'user') return null;
return {
handleClick: () => {
- createRawModal(
- (props: ShareModalProps) => (
- <Provider
- createStore={() => {
- const state = storeApi.getState();
- return createStore({
- context: state.context,
- hooks: state.hooks,
- skipFetch: state.skipFetch,
- });
- }}
- >
- <ShareMessageModal {...props} />
- </Provider>
- ),
- { message: ctx.data },
- { onCloseKey: 'onCancel', openKey: 'open' },
- );
+ openShareMessageModal(ctx.data, () => {
+ const state = storeApi.getState();
+ return createStore({
+ context: state.context,
+ hooks: state.hooks,
+ skipFetch: state.skipFetch,
+ });
+ });
},
icon: Share2,
key: 'share',
diff --git a/src/features/Conversation/components/ShareMessageModal/index.tsx b/src/features/Conversation/components/ShareMessageModal/index.tsx
index 8d03032e035..e21675a150f 100644
--- a/src/features/Conversation/components/ShareMessageModal/index.tsx
+++ b/src/features/Conversation/components/ShareMessageModal/index.tsx
@@ -1,15 +1,16 @@
import { type UIChatMessage } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
-import { Tabs } from '@lobehub/ui/base-ui';
+import { createModal, Tabs } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
import { memo, useId, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import ImperativeModal from '@/components/ImperativeModal';
import ShareDataProvider from '@/features/ShareModal/ShareDataProvider';
import SharePdf from '@/features/ShareModal/SharePdf';
import { useIsMobile } from '@/hooks/useIsMobile';
-import { useConversationStore } from '../../store';
+import type { createStore } from '../../store';
+import { Provider, useConversationStore } from '../../store';
import ShareImage from './ShareImage';
import ShareText from './ShareText';
@@ -19,13 +20,11 @@ enum Tab {
Text = 'text',
}
-export interface ShareModalProps {
+interface ShareMessageModalContentProps {
message: UIChatMessage;
- onCancel: () => void;
- open: boolean;
}
-const ShareModal = memo<ShareModalProps>(({ onCancel, open, message }) => {
+const ShareMessageModalContent = memo<ShareMessageModalContentProps>(({ message }) => {
const [tab, setTab] = useState<Tab>(Tab.Screenshot);
const { t } = useTranslation('chat');
const uniqueId = useId();
@@ -59,29 +58,34 @@ const ShareModal = memo<ShareModalProps>(({ onCancel, open, message }) => {
}, [context, isMobile, message, uniqueId, t]);
return (
- <ImperativeModal
- allowFullscreen
- centered={false}
- destroyOnHidden={true}
- footer={null}
- open={open}
- title={t('share', { ns: 'common' })}
- width={1440}
- onCancel={onCancel}
- >
- <Flexbox gap={isMobile ? 8 : 24}>
- <Tabs
- activeKey={tab}
- items={tabItems}
- styles={{
- list: { display: 'flex', width: '100%' },
- tab: { flex: 1 },
- }}
- onChange={(key) => setTab(key as Tab)}
- />
- </Flexbox>
- </ImperativeModal>
+ <Flexbox gap={isMobile ? 8 : 24}>
+ <Tabs
+ activeKey={tab}
+ items={tabItems}
+ styles={{
+ list: { display: 'flex', width: '100%' },
+ tab: { flex: 1 },
+ }}
+ onChange={(key) => setTab(key as Tab)}
+ />
+ </Flexbox>
);
});
-export default ShareModal;
+ShareMessageModalContent.displayName = 'ShareMessageModalContent';
+
+export const openShareMessageModal = (
+ message: UIChatMessage,
+ createConversationStore: () => ReturnType<typeof createStore>,
+) =>
+ createModal({
+ content: (
+ <Provider createStore={createConversationStore}>
+ <ShareMessageModalContent message={message} />
+ </Provider>
+ ),
+ footer: null,
+ maskClosable: true,
+ title: t('share', { ns: 'common' }),
+ width: 'min(95vw, 1440px)',
+ });
diff --git a/src/features/Conversation/hooks/useChatItemContextMenu.tsx b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
index 931e0a88df1..1efd0cd7374 100644
--- a/src/features/Conversation/hooks/useChatItemContextMenu.tsx
+++ b/src/features/Conversation/hooks/useChatItemContextMenu.tsx
@@ -4,7 +4,6 @@ import {
type ActionIconGroupItemType,
type GenericItemType,
} from '@lobehub/ui';
-import { createRawModal } from '@lobehub/ui';
import { App } from 'antd';
import isEqual from 'fast-deep-equal';
import { type MouseEvent, type ReactNode } from 'react';
@@ -21,13 +20,11 @@ import { sessionSelectors } from '@/store/session/selectors';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
-import { type ShareModalProps } from '../components/ShareMessageModal';
-import ShareMessageModal from '../components/ShareMessageModal';
+import { openShareMessageModal } from '../components/ShareMessageModal';
import {
createStore,
dataSelectors,
messageStateSelectors,
- Provider,
useConversationStore,
useConversationStoreApi,
} from '../store';
@@ -234,26 +231,14 @@ export const useChatItemContextMenu = ({
const item = getMessage();
if (!item || item.role !== 'assistant') return;
- createRawModal(
- (props: ShareModalProps) => (
- <Provider
- createStore={() => {
- const state = storeApi.getState();
- return createStore({
- context: state.context,
- hooks: state.hooks,
- skipFetch: state.skipFetch,
- });
- }}
- >
- <ShareMessageModal {...props} />
- </Provider>
- ),
- {
- message: item,
- },
- { onCloseKey: 'onCancel', openKey: 'open' },
- );
+ openShareMessageModal(item, () => {
+ const state = storeApi.getState();
+ return createStore({
+ context: state.context,
+ hooks: state.hooks,
+ skipFetch: state.skipFetch,
+ });
+ });
}, [getMessage, storeApi]);
const handleAction = useCallback(
diff --git a/src/features/DailyBrief/BriefCardArtifacts.tsx b/src/features/DailyBrief/BriefCardArtifacts.tsx
index 3e4c2585245..a5e9ea19632 100644
--- a/src/features/DailyBrief/BriefCardArtifacts.tsx
+++ b/src/features/DailyBrief/BriefCardArtifacts.tsx
@@ -4,7 +4,7 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronRightIcon, FileTextIcon } from 'lucide-react';
import { memo } from 'react';
-import { useDocumentStore } from '@/store/document';
+import { openDocumentModal, preloadDocumentModal } from '@/features/DocumentModal/loader';
const styles = createStaticStyles(({ css, cssVar }) => ({
iconWrap: css`
@@ -22,7 +22,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const BriefArtifactCard = memo<{ doc: BriefArtifactDocument }>(({ doc }) => {
- const openDocumentPreview = useDocumentStore((s) => s.openDocumentPreview);
const title = doc.title || 'Untitled';
return (
@@ -34,7 +33,9 @@ const BriefArtifactCard = memo<{ doc: BriefArtifactDocument }>(({ doc }) => {
paddingBlock={10}
paddingInline={12}
variant={'filled'}
- onClick={() => openDocumentPreview(doc.id)}
+ onClick={() => void openDocumentModal(doc.id)}
+ onFocus={preloadDocumentModal}
+ onPointerEnter={preloadDocumentModal}
>
<div className={styles.iconWrap}>
<Icon
diff --git a/src/features/DocumentModal/Header.tsx b/src/features/DocumentModal/Header.tsx
index 8166bca74b8..190efbabacd 100644
--- a/src/features/DocumentModal/Header.tsx
+++ b/src/features/DocumentModal/Header.tsx
@@ -1,6 +1,7 @@
'use client';
import { ActionIcon, Avatar, Flexbox, Skeleton, Text } from '@lobehub/ui';
+import { useModalContext } from '@lobehub/ui/base-ui';
import { cssVar } from 'antd-style';
import { XIcon } from 'lucide-react';
import { memo } from 'react';
@@ -16,12 +17,9 @@ import { editorSelectors } from '@/store/document/slices/editor';
const HEADER_HEIGHT = 44;
-interface DocumentModalHeaderProps {
- onClose: () => void;
-}
-
-const DocumentModalHeader = memo<DocumentModalHeaderProps>(({ onClose }) => {
+const DocumentModalHeader = memo(() => {
const { t } = useTranslation(['file', 'common']);
+ const { close } = useModalContext();
const [documentId, emoji, title] = usePageEditorStore((s) => [s.documentId, s.emoji, s.title]);
const isDocumentLoading = useDocumentStore(editorSelectors.isDocumentLoading(documentId));
@@ -65,7 +63,7 @@ const DocumentModalHeader = memo<DocumentModalHeaderProps>(({ onClose }) => {
icon={XIcon}
size={DESKTOP_HEADER_ICON_SIZE}
title={t('close', { ns: 'common' })}
- onClick={onClose}
+ onClick={close}
/>
</Flexbox>
</Flexbox>
diff --git a/src/features/DocumentModal/Preview.tsx b/src/features/DocumentModal/Preview.tsx
deleted file mode 100644
index 68a02fe97c9..00000000000
--- a/src/features/DocumentModal/Preview.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-'use client';
-
-import { memo, useEffect } from 'react';
-
-import { useDocumentStore } from '@/store/document';
-
-import DocumentModal from '.';
-
-/**
- * Mount this once per route surface that should render the global document
- * preview modal. Connects to `useDocumentStore.previewDocumentId` and clears
- * that state on unmount, so navigating away with the modal open doesn't
- * leak a stale id into the next surface that mounts a preview modal.
- */
-const DocumentPreviewModal = memo(() => {
- const previewDocumentId = useDocumentStore((s) => s.previewDocumentId);
- const closeDocumentPreview = useDocumentStore((s) => s.closeDocumentPreview);
-
- // Route-teardown cleanup: previewDocumentId is global, so a stale value
- // would reopen on the next surface mount. Action is a no-op when already
- // empty, so this is safe to fire unconditionally.
- useEffect(() => () => closeDocumentPreview(), [closeDocumentPreview]);
-
- return (
- <DocumentModal
- documentId={previewDocumentId}
- open={!!previewDocumentId}
- onClose={closeDocumentPreview}
- />
- );
-});
-
-DocumentPreviewModal.displayName = 'DocumentPreviewModal';
-
-export default DocumentPreviewModal;
diff --git a/src/features/DocumentModal/index.tsx b/src/features/DocumentModal/index.tsx
index 16397ea4e3a..0b13aeca3d3 100644
--- a/src/features/DocumentModal/index.tsx
+++ b/src/features/DocumentModal/index.tsx
@@ -1,54 +1,40 @@
'use client';
+import { createModal } from '@lobehub/ui/base-ui';
import { memo } from 'react';
-import ImperativeModal from '@/components/ImperativeModal';
import { PageAgentPanelOverrideProvider } from '@/features/PageEditor/RightPanel/OverrideContext';
import PageExplorer from '@/features/PageExplorer';
import DocumentModalHeader from './Header';
-interface DocumentModalProps {
- documentId?: string | null;
- onClose: () => void;
- open: boolean;
+interface DocumentModalContentProps {
+ documentId: string;
}
-/**
- * Generic document preview modal. Pass `documentId` + `open` + `onClose`;
- * the modal owns its own page-agent panel state (collapsed by default,
- * ephemeral β€” does not persist to the global preference).
- */
-const DocumentModal = memo<DocumentModalProps>(({ documentId, open, onClose }) => {
+const DocumentModalContent = memo<DocumentModalContentProps>(({ documentId }) => {
return (
- <ImperativeModal
- allowFullscreen
- centered
- destroyOnHidden
- closable={false}
- footer={null}
- open={open}
- title={null}
- width={'min(95vw, 1600px)'}
- styles={{
- body: { flex: 1, maxHeight: 'none', minHeight: 0, overflow: 'hidden', padding: 0 },
- container: { display: 'flex', flexDirection: 'column', height: '92vh' },
- }}
- onCancel={onClose}
- >
- {open && documentId && (
- <PageAgentPanelOverrideProvider defaultExpand={false}>
- <PageExplorer
- fullWidthHeader
- header={<DocumentModalHeader onClose={onClose} />}
- pageId={documentId}
- />
- </PageAgentPanelOverrideProvider>
- )}
- </ImperativeModal>
+ <PageAgentPanelOverrideProvider defaultExpand={false}>
+ <PageExplorer fullWidthHeader header={<DocumentModalHeader />} pageId={documentId} />
+ </PageAgentPanelOverrideProvider>
);
});
-DocumentModal.displayName = 'DocumentModal';
+DocumentModalContent.displayName = 'DocumentModalContent';
-export default DocumentModal;
+export const createDocumentModal = (documentId: string) =>
+ createModal({
+ content: <DocumentModalContent documentId={documentId} />,
+ footer: null,
+ maskClosable: true,
+ styles: {
+ content: {
+ display: 'flex',
+ height: '92vh',
+ minHeight: 0,
+ overflow: 'hidden',
+ padding: 0,
+ },
+ },
+ width: 'min(95vw, 1600px)',
+ });
diff --git a/src/features/DocumentModal/loader.ts b/src/features/DocumentModal/loader.ts
new file mode 100644
index 00000000000..8aa0cdf6c86
--- /dev/null
+++ b/src/features/DocumentModal/loader.ts
@@ -0,0 +1,15 @@
+const importDocumentModal = () => import('.');
+
+let documentModalPromise: ReturnType<typeof importDocumentModal> | undefined;
+
+export const preloadDocumentModal = (): ReturnType<typeof importDocumentModal> =>
+ (documentModalPromise ??= importDocumentModal().catch((error) => {
+ documentModalPromise = undefined;
+ throw error;
+ }));
+
+export const openDocumentModal = async (documentId: string) => {
+ const { createDocumentModal } = await preloadDocumentModal();
+
+ return createDocumentModal(documentId);
+};
diff --git a/src/features/FileViewer/Renderer/PDF/index.tsx b/src/features/FileViewer/Renderer/PDF/index.tsx
index b6a1ffdc37d..0b10c440197 100644
--- a/src/features/FileViewer/Renderer/PDF/index.tsx
+++ b/src/features/FileViewer/Renderer/PDF/index.tsx
@@ -21,7 +21,7 @@ const options = {
const maxWidth = 1200;
-interface PDFViewerProps {
+export interface PDFViewerProps {
fileId: string;
url: string | null;
}
@@ -32,7 +32,6 @@ const PDFViewer = memo<PDFViewerProps>(({ url, fileId }) => {
const [containerWidth, setContainerWidth] = useState<number>();
const [isLoaded, setIsLoaded] = useState(false);
-
const onResize = useCallback<ResizeObserverCallback>((entries) => {
const [entry] = entries;
diff --git a/src/features/FileViewer/Renderer/PDF/loader.ts b/src/features/FileViewer/Renderer/PDF/loader.ts
new file mode 100644
index 00000000000..544f1fb79b7
--- /dev/null
+++ b/src/features/FileViewer/Renderer/PDF/loader.ts
@@ -0,0 +1,9 @@
+const importPDFRenderer = () => import('.');
+
+let pdfRendererPromise: ReturnType<typeof importPDFRenderer> | undefined;
+
+export const preloadPDFRenderer = (): ReturnType<typeof importPDFRenderer> =>
+ (pdfRendererPromise ??= importPDFRenderer().catch((error) => {
+ pdfRendererPromise = undefined;
+ throw error;
+ }));
diff --git a/src/features/FileViewer/index.tsx b/src/features/FileViewer/index.tsx
index 197373e8875..9d22cee48e2 100644
--- a/src/features/FileViewer/index.tsx
+++ b/src/features/FileViewer/index.tsx
@@ -1,10 +1,13 @@
'use client';
import { MARKDOWN_MIME_TYPES } from '@lobechat/const';
-import type { CSSProperties } from 'react';
-import { memo } from 'react';
+import { Center } from '@lobehub/ui';
+import type { CSSProperties, JSXElementConstructor } from 'react';
+import { memo, useCallback, useEffect, useState } from 'react';
+import AsyncError from '@/components/AsyncError';
import { isHtmlFile } from '@/components/HtmlPreview';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { type FileListItem } from '@/types/files';
import { isPdfFile } from './fileType';
@@ -13,7 +16,8 @@ import CodeViewer from './Renderer/Code';
import HTMLViewer from './Renderer/HTML';
import ImageViewer from './Renderer/Image';
import MSDocViewer from './Renderer/MSDoc';
-import PDFViewer from './Renderer/PDF';
+import type { PDFViewerProps } from './Renderer/PDF';
+import { preloadPDFRenderer } from './Renderer/PDF/loader';
import VideoViewer from './Renderer/Video';
// File type definitions
@@ -234,13 +238,68 @@ interface FileViewerProps extends FileListItem {
style?: CSSProperties;
}
+type PDFRenderer = JSXElementConstructor<PDFViewerProps>;
+
+type PDFRendererState =
+ | { status: 'idle' | 'loading' }
+ | { error: unknown; status: 'error' }
+ | { Renderer: PDFRenderer; status: 'ready' };
+
+const usePDFRenderer = (enabled: boolean) => {
+ const [attempt, setAttempt] = useState(0);
+ const [state, setState] = useState<PDFRendererState>({ status: 'idle' });
+
+ useEffect(() => {
+ if (!enabled) return;
+
+ let active = true;
+ setState({ status: 'loading' });
+
+ void preloadPDFRenderer().then(
+ ({ default: Renderer }) => {
+ if (active) setState({ Renderer, status: 'ready' });
+ },
+ (error: unknown) => {
+ if (active) setState({ error, status: 'error' });
+ },
+ );
+
+ return () => {
+ active = false;
+ };
+ }, [attempt, enabled]);
+
+ const retry = useCallback(() => setAttempt((value) => value + 1), []);
+
+ return { retry, state };
+};
+
/**
* Preview any file type.
*/
const FileViewer = memo<FileViewerProps>(({ id, style, fileType, url, name }) => {
+ const isPDF = isPdfFile({ fileName: name, fileType, path: url });
+ const { retry: retryPDFRenderer, state: pdfRendererState } = usePDFRenderer(isPDF);
+
// PDF files
- if (isPdfFile({ fileName: name, fileType, path: url })) {
- return <PDFViewer fileId={id} url={url} />;
+ if (isPDF) {
+ if (pdfRendererState.status === 'error')
+ return (
+ <Center height={'100%'} width={'100%'}>
+ <AsyncError error={pdfRendererState.error} variant={'block'} onRetry={retryPDFRenderer} />
+ </Center>
+ );
+
+ if (pdfRendererState.status === 'ready') {
+ const { Renderer } = pdfRendererState;
+ return <Renderer fileId={id} url={url} />;
+ }
+
+ return (
+ <Center height={'100%'} width={'100%'}>
+ <NeuralNetworkLoading size={36} />
+ </Center>
+ );
}
// Image files
diff --git a/src/features/HomeInbox/UnreadTopicList.tsx b/src/features/HomeInbox/UnreadTopicList.tsx
index 892fed36fcb..dff83508cd0 100644
--- a/src/features/HomeInbox/UnreadTopicList.tsx
+++ b/src/features/HomeInbox/UnreadTopicList.tsx
@@ -4,11 +4,10 @@ import { Avatar, Flexbox, Icon, Markdown, stopPropagation, Text } from '@lobehub
import { Button } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronDownIcon, ChevronRightIcon, MessageSquarePlus } from 'lucide-react';
-import { memo, useCallback, useState } from 'react';
+import { lazy, memo, Suspense, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import UnreadDot from '@/components/UnreadDot';
-import RunReplyEditor from '@/features/AgentTasks/AgentTaskDetail/RunReplyEditor';
import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import Time from '@/routes/(main)/home/features/components/Time';
@@ -22,6 +21,13 @@ const ROW_GAP = 8;
const ROW_PADDING_INLINE = 14;
const AVATAR_SIZE = 20;
+const loadRunReplyEditor = () => import('@/features/AgentTasks/AgentTaskDetail/RunReplyEditor');
+const RunReplyEditor = lazy(loadRunReplyEditor);
+
+const preloadRunReplyEditor = () => {
+ void loadRunReplyEditor();
+};
+
const styles = createStaticStyles(({ css, cssVar }) => ({
// Line the reply up under the agent that wrote it, not under the unread dot.
body: css`
@@ -54,6 +60,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
border-block-end: 1px solid ${cssVar.colorBorderSecondary};
}
`,
+ replyEditorFallback: css`
+ min-height: 88px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorFillQuaternary};
+ `,
}));
interface UnreadTopicItemProps {
@@ -171,11 +183,13 @@ const UnreadTopicItem = memo<UnreadTopicItemProps>(({ topic, onFollowUpSent, sho
{replying ? (
<Flexbox onClick={stopPropagation}>
- <RunReplyEditor
- placeholder={t('inbox.unread.followUpPlaceholder')}
- onCancel={() => setReplying(false)}
- onSubmit={submitFollowUp}
- />
+ <Suspense fallback={<div aria-hidden className={styles.replyEditorFallback} />}>
+ <RunReplyEditor
+ placeholder={t('inbox.unread.followUpPlaceholder')}
+ onCancel={() => setReplying(false)}
+ onSubmit={submitFollowUp}
+ />
+ </Suspense>
</Flexbox>
) : (
<Flexbox horizontal align={'center'} justify={'space-between'}>
@@ -188,6 +202,8 @@ const UnreadTopicItem = memo<UnreadTopicItemProps>(({ topic, onFollowUpSent, sho
size={'small'}
type={'fill'}
onClick={() => setReplying(true)}
+ onFocus={preloadRunReplyEditor}
+ onPointerEnter={preloadRunReplyEditor}
>
{t('inbox.unread.followUp')}
</Button>
diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsx
index 481c00dfac8..d88a0ced07b 100644
--- a/src/features/HomeInbox/index.tsx
+++ b/src/features/HomeInbox/index.tsx
@@ -6,9 +6,7 @@ import { useTranslation } from 'react-i18next';
import { useWorkspaceMemberProfiles } from '@/business/client/hooks/useWorkspaceMemberProfiles';
import AsyncError from '@/components/AsyncError';
-import TopicChatDrawer from '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer';
import { BriefCardSkeleton } from '@/features/DailyBrief/BriefCardSkeleton';
-import DocumentPreviewModal from '@/features/DocumentModal/Preview';
import Recommendations, { useRecommendationsVisible } from '@/features/Recommendations';
import GroupBlock from '@/routes/(main)/home/features/components/GroupBlock';
import { useBriefStore } from '@/store/brief';
@@ -128,29 +126,17 @@ const HomeInbox = memo(() => {
if (!isLogin) return null;
- // Both overlays open from a card in here and must outlive it β€” a followed-up
- // topic leaves the unread list the moment it's read.
- const overlays = (
- <>
- <DocumentPreviewModal />
- <TopicChatDrawer />
- </>
- );
-
// The brief feed is the primary content; a first-load failure blocks the whole
// surface. No fabricated section heading β€” we don't know what's under it yet.
if (briefsSWR.error && !isBriefsInit && !briefsSWR.isLoading) {
return (
- <>
- <AsyncError
- error={briefsSWR.error}
- variant={'block'}
- onRetry={() => {
- void briefsSWR.mutate();
- }}
- />
- {overlays}
- </>
+ <AsyncError
+ error={briefsSWR.error}
+ variant={'block'}
+ onRetry={() => {
+ void briefsSWR.mutate();
+ }}
+ />
);
}
@@ -162,7 +148,6 @@ const HomeInbox = memo(() => {
<BriefCardSkeleton />
<BriefCardSkeleton />
<Recommendations />
- {overlays}
</Flexbox>
);
}
@@ -260,7 +245,6 @@ const HomeInbox = memo(() => {
<Recommendations />
</Flexbox>
)}
- {overlays}
</>
);
}
@@ -283,8 +267,6 @@ const HomeInbox = memo(() => {
)}
<Recommendations />
-
- {overlays}
</Flexbox>
);
});
diff --git a/src/features/NavPanel/NavPanelPortal.tsx b/src/features/NavPanel/NavPanelPortal.tsx
new file mode 100644
index 00000000000..c6f7733c25a
--- /dev/null
+++ b/src/features/NavPanel/NavPanelPortal.tsx
@@ -0,0 +1,34 @@
+'use client';
+
+import { memo, type PropsWithChildren, useLayoutEffect, useRef } from 'react';
+
+import { registerNavPanelContent, unregisterNavPanelContent } from './registry';
+
+interface NavPanelPortalProps extends PropsWithChildren {
+ /**
+ * Stable route-owned key used by NavPanelHost to select the active content.
+ * @example <NavPanelPortal navKey="agent">...</NavPanelPortal>
+ */
+ navKey?: string;
+}
+
+export const NavPanelPortal = memo<NavPanelPortalProps>(({ children, navKey = 'default' }) => {
+ const ownerRef = useRef(Symbol('NavPanelPortal'));
+
+ useLayoutEffect(() => {
+ if (!children) return;
+ const owner = ownerRef.current;
+
+ registerNavPanelContent(navKey, owner, children);
+
+ return () => {
+ unregisterNavPanelContent(navKey, owner);
+ };
+ }, [children, navKey]);
+
+ return null;
+});
+
+NavPanelPortal.displayName = 'NavPanelPortal';
+
+export default NavPanelPortal;
diff --git a/src/features/NavPanel/SideBarDrawer.tsx b/src/features/NavPanel/SideBarDrawer.tsx
index 72d6849fa51..75e41d4fd1e 100644
--- a/src/features/NavPanel/SideBarDrawer.tsx
+++ b/src/features/NavPanel/SideBarDrawer.tsx
@@ -9,8 +9,8 @@ import { cloneElement, isValidElement, memo, Suspense, useCallback, useState } f
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
-import { NAV_PANEL_RIGHT_DRAWER_ID } from './';
import SkeletonList from './components/SkeletonList';
+import { NAV_PANEL_RIGHT_DRAWER_ID } from './constants';
import { OverlayContainerContext } from './OverlayContainer';
import SideBarHeaderLayout from './SideBarHeaderLayout';
diff --git a/src/features/NavPanel/components/NavPanelDraggable.tsx b/src/features/NavPanel/components/NavPanelDraggable.tsx
index 1d036009e09..428adc1fa06 100644
--- a/src/features/NavPanel/components/NavPanelDraggable.tsx
+++ b/src/features/NavPanel/components/NavPanelDraggable.tsx
@@ -7,9 +7,9 @@ import { memo, Suspense, useMemo, useRef } from 'react';
import NavPanelUpgradeEntry from '@/business/client/features/NavPanelUpgradeEntry';
import { isDesktop } from '@/const/version';
+import { USER_DROPDOWN_ICON_ID } from '@/features/NavPanel/constants';
import { TOGGLE_BUTTON_ID } from '@/features/NavPanel/ToggleLeftPanelButton';
import Footer from '@/routes/(main)/home/_layout/Footer';
-import { USER_DROPDOWN_ICON_ID } from '@/routes/(main)/home/_layout/Header/components/User';
import { useGlobalStore } from '@/store/global';
import {
NAV_PANEL_MAX_WIDTH,
diff --git a/src/features/NavPanel/constants.ts b/src/features/NavPanel/constants.ts
new file mode 100644
index 00000000000..7152d558aeb
--- /dev/null
+++ b/src/features/NavPanel/constants.ts
@@ -0,0 +1,2 @@
+export const NAV_PANEL_RIGHT_DRAWER_ID = 'nav-panel-drawer';
+export const USER_DROPDOWN_ICON_ID = 'user-dropdown-icon';
diff --git a/src/features/NavPanel/index.test.tsx b/src/features/NavPanel/index.test.tsx
index 39a9eba6bd5..210f3fb7fb7 100644
--- a/src/features/NavPanel/index.test.tsx
+++ b/src/features/NavPanel/index.test.tsx
@@ -2,6 +2,10 @@ import { render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import NavPanel from './index';
+import { NavPanelPortal } from './NavPanelPortal';
+import { clearNavPanelRegistry } from './registry';
+
let pathname = '/lobe-team/settings/general';
interface WorkspaceMock {
@@ -31,54 +35,6 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
?.slug ?? null,
}));
-vi.mock('@/routes/(main)/home/_layout/SidebarContent', () => ({
- default: () => <div>Home sidebar</div>,
-}));
-
-vi.mock('@/features/WorkspaceSetting/SideBar/Content', () => ({
- default: () => <div>Workspace settings sidebar</div>,
-}));
-
-vi.mock('@/routes/(main)/settings/_layout/SidebarContent', () => ({
- default: () => <div>Personal settings sidebar</div>,
-}));
-
-vi.mock('@/features/AgentSidebar/Content', () => ({
- default: () => <div>Agent sidebar</div>,
-}));
-
-vi.mock('@/routes/(main)/group/_layout/Sidebar/Content', () => ({
- default: () => <div>Group sidebar</div>,
-}));
-
-vi.mock('@/routes/(main)/community/_layout/Sidebar/Content', () => ({
- default: () => <div>Community sidebar</div>,
-}));
-
-vi.mock('@/routes/(main)/resource/(home)/_layout/SidebarContent', () => ({
- default: () => <div>Resource sidebar</div>,
-}));
-
-vi.mock('@/routes/(main)/memory/_layout/Sidebar/Content', () => ({
- default: () => <div>Memory sidebar</div>,
-}));
-
-vi.mock('@/routes/(main)/eval/_layout/Sidebar/Content', () => ({
- default: () => <div>Eval sidebar</div>,
-}));
-
-vi.mock('@/features/Pages/PageLayout/SidebarContent', () => ({
- default: () => <div>Page sidebar</div>,
-}));
-
-vi.mock('@/routes/(main)/(create)/image/_layout/Sidebar/Content', () => ({
- default: () => <div>Image sidebar</div>,
-}));
-
-vi.mock('@/routes/(main)/(create)/video/_layout/Sidebar/Content', () => ({
- default: () => <div>Video sidebar</div>,
-}));
-
vi.mock('./components/NavPanelDraggable', () => ({
NavPanelDraggable: ({ activeContent }: NavPanelDraggableMockProps) => (
<div data-nav-key={activeContent.key} data-testid="nav-panel">
@@ -87,18 +43,24 @@ vi.mock('./components/NavPanelDraggable', () => ({
),
}));
+vi.mock('./components/SkeletonList', () => ({
+ default: () => <div>Nav panel loading</div>,
+}));
+
describe('NavPanel', () => {
beforeEach(() => {
pathname = '/lobe-team/settings/general';
+ clearNavPanelRegistry();
});
- it('uses workspace settings sidebar instead of a stale home snapshot on workspace settings routes', async () => {
- const { default: NavPanel, NavPanelPortal } = await import('./index');
-
+ it('selects the route-owned entry instead of a concurrently registered Home entry', async () => {
render(
<>
<NavPanelPortal navKey="home">
- <div>Stale home snapshot</div>
+ <div>Home sidebar</div>
+ </NavPanelPortal>
+ <NavPanelPortal navKey="workspace-settings">
+ <div>Workspace settings sidebar</div>
</NavPanelPortal>
<NavPanel />
</>,
@@ -107,142 +69,74 @@ describe('NavPanel', () => {
await waitFor(() => {
expect(screen.getByText('Workspace settings sidebar')).toBeInTheDocument();
});
- expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'workspace-settings');
+ expect(screen.queryByText('Home sidebar')).not.toBeInTheDocument();
});
- it('uses personal settings sidebar instead of a stale home snapshot on user settings routes', async () => {
- pathname = '/settings/profile';
- const { default: NavPanel, NavPanelPortal } = await import('./index');
+ it('uses the Home entry for routes without a dedicated navigation panel', async () => {
+ pathname = '/lobe-team/tasks';
render(
<>
<NavPanelPortal navKey="home">
- <div>Stale home snapshot</div>
+ <div>Home sidebar</div>
</NavPanelPortal>
<NavPanel />
</>,
);
await waitFor(() => {
- expect(screen.getByText('Personal settings sidebar')).toBeInTheDocument();
+ expect(screen.getByText('Home sidebar')).toBeInTheDocument();
});
- expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'home');
});
- it('uses agent sidebar instead of a stale home snapshot on workspace agent routes', async () => {
- pathname = '/lobe-team/agent/agent-1';
- const { default: NavPanel, NavPanelPortal } = await import('./index');
+ it('shows a route-keyed fallback instead of stale Home content while a dedicated portal loads', async () => {
+ pathname = '/lobe-team/community';
render(
<>
<NavPanelPortal navKey="home">
- <div>Stale home snapshot</div>
+ <div>Home sidebar</div>
</NavPanelPortal>
<NavPanel />
</>,
);
await waitFor(() => {
- expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'agent');
+ expect(screen.getByText('Nav panel loading')).toBeInTheDocument();
});
- expect(screen.getByText('Agent sidebar')).toBeInTheDocument();
- expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
+ expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'pending:discover');
+ expect(screen.queryByText('Home sidebar')).not.toBeInTheDocument();
});
- it.each([
- '/lobe-team/resource',
- '/lobe-team/community',
- '/lobe-team/memory',
- '/lobe-team/page',
- '/lobe-team/image',
- '/lobe-team/video',
- '/lobe-team/eval',
- '/lobe-team/group/group-1',
- ])('does not keep a stale home snapshot on %s', async (route) => {
- pathname = route;
- const { default: NavPanel, NavPanelPortal } = await import('./index');
-
- render(
+ it('does not let an older owner cleanup remove the newer entry for the same key', async () => {
+ const Harness = ({ showOld }: { showOld: boolean }) => (
<>
- <NavPanelPortal navKey="home">
- <div>Stale home snapshot</div>
+ {showOld && (
+ <NavPanelPortal key="old" navKey="home">
+ <div>Old Home sidebar</div>
+ </NavPanelPortal>
+ )}
+ <NavPanelPortal key="new" navKey="home">
+ <div>New Home sidebar</div>
</NavPanelPortal>
<NavPanel />
- </>,
+ </>
);
- await waitFor(() => {
- expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
- });
- expect(screen.getByTestId('nav-panel')).not.toHaveAttribute('data-nav-key', 'home');
- });
-
- it.each(['/group/group-1', '/group/group-1/profile', '/lobe-team/group/group-1/profile'])(
- 'uses the group sidebar fallback instead of a stale home snapshot on %s',
- async (route) => {
- pathname = route;
- const { default: NavPanel, NavPanelPortal } = await import('./index');
-
- render(
- <>
- <NavPanelPortal navKey="home">
- <div>Stale home snapshot</div>
- </NavPanelPortal>
- <NavPanel />
- </>,
- );
-
- await waitFor(() => {
- expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'group');
- });
- expect(screen.getByText('Group sidebar')).toBeInTheDocument();
- expect(screen.queryByText('Stale home snapshot')).not.toBeInTheDocument();
- },
- );
-
- it('uses the group sidebar fallback before its route portal registers', async () => {
- pathname = '/group/group-1/profile';
- const { default: NavPanel } = await import('./index');
-
- render(<NavPanel />);
+ pathname = '/';
+ const { rerender } = render(<Harness showOld />);
await waitFor(() => {
- expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'group');
+ expect(screen.getByText('New Home sidebar')).toBeInTheDocument();
});
- expect(screen.getByText('Group sidebar')).toBeInTheDocument();
- });
-
- it('uses the community sidebar fallback before its route portal registers', async () => {
- pathname = '/lobe-team/community';
- const { default: NavPanel } = await import('./index');
- render(<NavPanel />);
+ rerender(<Harness showOld={false} />);
await waitFor(() => {
- expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'discover');
+ expect(screen.getByText('New Home sidebar')).toBeInTheDocument();
});
- expect(screen.getByText('Community sidebar')).toBeInTheDocument();
+ expect(screen.queryByText('Nav panel loading')).not.toBeInTheDocument();
});
-
- it.each(['/lobe-team/tasks', '/lobe-team/task/task-1'])(
- 'keeps the home sidebar on %s because it has no route sidebar',
- async (route) => {
- pathname = route;
- const { default: NavPanel, NavPanelPortal } = await import('./index');
-
- render(
- <>
- <NavPanelPortal navKey="home">
- <div>Home navigation snapshot</div>
- </NavPanelPortal>
- <NavPanel />
- </>,
- );
-
- await waitFor(() => {
- expect(screen.getByText('Home navigation snapshot')).toBeInTheDocument();
- });
- expect(screen.getByTestId('nav-panel')).toHaveAttribute('data-nav-key', 'home');
- },
- );
});
diff --git a/src/features/NavPanel/index.tsx b/src/features/NavPanel/index.tsx
index c7d42303512..1d6744bd2c8 100644
--- a/src/features/NavPanel/index.tsx
+++ b/src/features/NavPanel/index.tsx
@@ -1,224 +1,31 @@
'use client';
-import { type PropsWithChildren, type ReactNode } from 'react';
-import { memo, useLayoutEffect, useRef, useSyncExternalStore } from 'react';
-
-import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
-import AgentSidebarContent from '@/features/AgentSidebar/Content';
-import PageSidebarContent from '@/features/Pages/PageLayout/SidebarContent';
-import WorkspaceSettingsSideBarContent from '@/features/WorkspaceSetting/SideBar/Content';
-import { useActiveLocation } from '@/hooks/useActiveLocation';
-import ImageSidebarContent from '@/routes/(main)/(create)/image/_layout/Sidebar/Content';
-import VideoSidebarContent from '@/routes/(main)/(create)/video/_layout/Sidebar/Content';
-import CommunitySidebarContent from '@/routes/(main)/community/_layout/Sidebar/Content';
-import EvalSidebarContent from '@/routes/(main)/eval/_layout/Sidebar/Content';
-import GroupSidebarContent from '@/routes/(main)/group/_layout/Sidebar/Content';
-import SidebarContent from '@/routes/(main)/home/_layout/SidebarContent';
-import MemorySidebarContent from '@/routes/(main)/memory/_layout/Sidebar/Content';
-import ResourceSidebarContent from '@/routes/(main)/resource/(home)/_layout/SidebarContent';
-import SettingsSidebarContent from '@/routes/(main)/settings/_layout/SidebarContent';
+import { Flexbox } from '@lobehub/ui';
+import { memo, useSyncExternalStore } from 'react';
import { NavPanelDraggable } from './components/NavPanelDraggable';
+import SkeletonList from './components/SkeletonList';
+import { NAV_PANEL_RIGHT_DRAWER_ID } from './constants';
+import { getNavPanelRegistrySnapshot, subscribeNavPanelRegistry } from './registry';
+import { useActiveNavKey } from './useActiveNavKey';
-export const NAV_PANEL_RIGHT_DRAWER_ID = 'nav-panel-drawer';
-
-type NavPanelSnapshot = {
- key: string;
- node: ReactNode;
-} | null;
-
-let currentSnapshot: NavPanelSnapshot = null;
-const listeners = new Set<() => void>();
-
-const subscribeNavPanel = (listener: () => void) => {
- listeners.add(listener);
- return () => listeners.delete(listener);
-};
-
-const getNavPanelSnapshot = () => currentSnapshot;
-const setNavPanelSnapshot = (snapshot: NavPanelSnapshot) => {
- currentSnapshot = snapshot;
- listeners.forEach((listener) => listener());
-};
-
-export const resetNavPanel = () => {
- if (!currentSnapshot) return;
-
- setNavPanelSnapshot(null);
-};
-
-const FALLBACK_NAV_KEY = 'home';
-const AGENT_NAV_KEY = 'agent';
-const GROUP_NAV_KEY = 'group';
-const COMMUNITY_NAV_KEY = 'discover';
-const EMPTY_NAV_KEY = 'empty';
-const SETTINGS_NAV_KEY = 'settings';
-const WORKSPACE_SETTINGS_NAV_KEY = 'workspace-settings';
-const RESOURCE_NAV_KEY = 'resource';
-const MEMORY_NAV_KEY = 'memory';
-const EVAL_NAV_KEY = 'eval';
-const PAGE_NAV_KEY = 'page';
-const IMAGE_NAV_KEY = 'image';
-const VIDEO_NAV_KEY = 'video';
-
-const DEDICATED_ROUTE_NAV_SEGMENTS = new Set([
- 'community',
- 'eval',
- 'group',
- 'image',
- 'memory',
- 'page',
- 'resource',
- 'video',
-]);
-
-const getActiveNavKey = () => currentSnapshot?.key ?? FALLBACK_NAV_KEY;
-
-export const useActiveNavKey = () =>
- useSyncExternalStore(subscribeNavPanel, getActiveNavKey, getActiveNavKey);
-
-const getMainRouteSegment = (pathname: string, activeSlug: string | null) => {
- const segments = pathname.split('/').filter(Boolean);
- if (activeSlug && segments[0] === activeSlug) return segments[1];
- return segments[0];
-};
+const NavPanelFallback = memo(() => (
+ <Flexbox gap={1} paddingBlock={1} paddingInline={4}>
+ <SkeletonList rows={8} />
+ </Flexbox>
+));
const NavPanel = memo(() => {
- const { pathname } = useActiveLocation();
- const activeSlug = useActiveWorkspaceSlug();
- const panelContent = useSyncExternalStore(
- subscribeNavPanel,
- getNavPanelSnapshot,
- getNavPanelSnapshot,
+ const activeNavKey = useActiveNavKey();
+ const registry = useSyncExternalStore(
+ subscribeNavPanelRegistry,
+ getNavPanelRegistrySnapshot,
+ getNavPanelRegistrySnapshot,
);
-
- const isWorkspaceSettingsRoute =
- !!activeSlug &&
- (pathname === `/${activeSlug}/settings` || pathname.startsWith(`/${activeSlug}/settings/`));
- const isHomeRoute =
- pathname === '/' ||
- (!!activeSlug && (pathname === `/${activeSlug}` || pathname === `/${activeSlug}/`));
- const isPersonalSettingsRoute = pathname === '/settings' || pathname.startsWith('/settings/');
- const isWorkspaceAgentRoute =
- !!activeSlug &&
- (pathname === `/${activeSlug}/agent` || pathname.startsWith(`/${activeSlug}/agent/`));
- const isPersonalAgentRoute = pathname === '/agent' || pathname.startsWith('/agent/');
- const isWorkspaceGroupRoute =
- !!activeSlug &&
- (pathname === `/${activeSlug}/group` || pathname.startsWith(`/${activeSlug}/group/`));
- const isPersonalGroupRoute = pathname === '/group' || pathname.startsWith('/group/');
-
- const agentFallback =
- isWorkspaceAgentRoute || isPersonalAgentRoute
- ? {
- key: AGENT_NAV_KEY,
- node: <AgentSidebarContent />,
- }
- : null;
-
- const groupFallback =
- isWorkspaceGroupRoute || isPersonalGroupRoute
- ? {
- key: GROUP_NAV_KEY,
- node: <GroupSidebarContent />,
- }
- : null;
-
- const workspaceSettingsFallback = isWorkspaceSettingsRoute
- ? {
- key: WORKSPACE_SETTINGS_NAV_KEY,
- node: <WorkspaceSettingsSideBarContent />,
- }
- : null;
- const personalSettingsFallback = isPersonalSettingsRoute
- ? {
- key: SETTINGS_NAV_KEY,
- node: <SettingsSidebarContent />,
- }
- : null;
- const mainRouteSegment = getMainRouteSegment(pathname, activeSlug);
- const communityFallback =
- mainRouteSegment === 'community'
- ? {
- key: COMMUNITY_NAV_KEY,
- node: <CommunitySidebarContent />,
- }
- : null;
- const resourceFallback =
- mainRouteSegment === 'resource'
- ? {
- key: RESOURCE_NAV_KEY,
- node: <ResourceSidebarContent />,
- }
- : null;
- const memoryFallback =
- mainRouteSegment === 'memory'
- ? {
- key: MEMORY_NAV_KEY,
- node: <MemorySidebarContent />,
- }
- : null;
- const evalFallback =
- mainRouteSegment === 'eval'
- ? {
- key: EVAL_NAV_KEY,
- node: <EvalSidebarContent />,
- }
- : null;
- const pageFallback =
- mainRouteSegment === 'page'
- ? {
- key: PAGE_NAV_KEY,
- node: <PageSidebarContent />,
- }
- : null;
- const imageFallback =
- mainRouteSegment === 'image'
- ? {
- key: IMAGE_NAV_KEY,
- node: <ImageSidebarContent />,
- }
- : null;
- const videoFallback =
- mainRouteSegment === 'video'
- ? {
- key: VIDEO_NAV_KEY,
- node: <VideoSidebarContent />,
- }
- : null;
- const routeFallback =
- agentFallback ||
- groupFallback ||
- workspaceSettingsFallback ||
- personalSettingsFallback ||
- communityFallback ||
- resourceFallback ||
- memoryFallback ||
- evalFallback ||
- pageFallback ||
- imageFallback ||
- videoFallback;
- const hasDedicatedRouteNavPanel = DEDICATED_ROUTE_NAV_SEGMENTS.has(mainRouteSegment ?? '');
- const isStaleHomeSnapshot =
- panelContent?.key === FALLBACK_NAV_KEY && hasDedicatedRouteNavPanel && !isHomeRoute;
-
- const resolvedPanelContent =
- routeFallback && panelContent?.key === FALLBACK_NAV_KEY
- ? routeFallback
- : isStaleHomeSnapshot
- ? null
- : panelContent;
-
- // Fallback renders the home sidebar's content directly β€” using `<Sidebar />`
- // (the portal wrapper) here loops with the portal's unmount cleanup:
- // mount fallback β†’ portal sets snapshot β†’ fallback unmounts β†’ cleanup
- // clears snapshot β†’ mount fallback β†’ …
- const activeContent =
- resolvedPanelContent ||
- routeFallback ||
- (isHomeRoute || !hasDedicatedRouteNavPanel
- ? ({ key: FALLBACK_NAV_KEY, node: <SidebarContent /> } satisfies NavPanelSnapshot)
- : ({ key: EMPTY_NAV_KEY, node: null } satisfies NavPanelSnapshot));
+ const registeredContent = registry.get(activeNavKey);
+ const activeContent = registeredContent
+ ? { key: activeNavKey, node: registeredContent.node }
+ : { key: `pending:${activeNavKey}`, node: <NavPanelFallback /> };
return (
<>
@@ -236,43 +43,8 @@ const NavPanel = memo(() => {
);
});
-export default NavPanel;
-
-interface NavPanelPortalProps extends PropsWithChildren {
- /**
- * Unique key to trigger transition animation when content changes
- * @example <NavPanelPortal navKey="chat">...</NavPanelPortal>
- */
- navKey?: string;
-}
-
-export const NavPanelPortal = memo<NavPanelPortalProps>(({ children, navKey = 'default' }) => {
- const navKeyRef = useRef(navKey);
- navKeyRef.current = navKey;
+NavPanel.displayName = 'NavPanel';
- useLayoutEffect(() => {
- if (!children) return;
-
- setNavPanelSnapshot({
- key: navKey,
- node: children,
- });
- }, [children, navKey]);
-
- // Clear the snapshot on unmount if this portal still owns it. Without this,
- // a route transition where the next layout's portal effect doesn't fire in
- // the same commit (concurrent transitions, lazy boundaries, Fragment-key
- // remounts) leaves the previous owner's snapshot in place β€” visible as a
- // stale sidebar that may render empty under its new state (e.g. workspace
- // settings sidebar after the active workspace is deleted).
- useLayoutEffect(
- () => () => {
- if (currentSnapshot?.key === navKeyRef.current) {
- setNavPanelSnapshot(null);
- }
- },
- [],
- );
-
- return null;
-});
+export { NavPanelPortal } from './NavPanelPortal';
+export { useActiveNavKey } from './useActiveNavKey';
+export default NavPanel;
diff --git a/src/features/NavPanel/registry.ts b/src/features/NavPanel/registry.ts
new file mode 100644
index 00000000000..8ccd6e2811f
--- /dev/null
+++ b/src/features/NavPanel/registry.ts
@@ -0,0 +1,47 @@
+import { type ReactNode } from 'react';
+
+export type NavPanelOwner = symbol;
+
+export interface NavPanelRegistryEntry {
+ node: ReactNode;
+ owner: NavPanelOwner;
+}
+
+export type NavPanelRegistrySnapshot = ReadonlyMap<string, NavPanelRegistryEntry>;
+
+let snapshot: NavPanelRegistrySnapshot = new Map();
+const listeners = new Set<() => void>();
+
+const publish = (nextSnapshot: Map<string, NavPanelRegistryEntry>) => {
+ snapshot = nextSnapshot;
+ listeners.forEach((listener) => listener());
+};
+
+export const subscribeNavPanelRegistry = (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+};
+
+export const getNavPanelRegistrySnapshot = (): NavPanelRegistrySnapshot => snapshot;
+
+export const registerNavPanelContent = (key: string, owner: NavPanelOwner, node: ReactNode) => {
+ const current = snapshot.get(key);
+ if (current?.owner === owner && current.node === node) return;
+
+ const nextSnapshot = new Map(snapshot);
+ nextSnapshot.set(key, { node, owner });
+ publish(nextSnapshot);
+};
+
+export const unregisterNavPanelContent = (key: string, owner: NavPanelOwner) => {
+ if (snapshot.get(key)?.owner !== owner) return;
+
+ const nextSnapshot = new Map(snapshot);
+ nextSnapshot.delete(key);
+ publish(nextSnapshot);
+};
+
+export const clearNavPanelRegistry = () => {
+ if (snapshot.size === 0) return;
+ publish(new Map());
+};
diff --git a/src/features/NavPanel/routeKey.test.ts b/src/features/NavPanel/routeKey.test.ts
new file mode 100644
index 00000000000..d1a39be0bfb
--- /dev/null
+++ b/src/features/NavPanel/routeKey.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveNavPanelKey } from './routeKey';
+
+describe('resolveNavPanelKey', () => {
+ it.each([
+ ['/', null, 'home'],
+ ['/lobe-team', 'lobe-team', 'home'],
+ ['/tasks', null, 'home'],
+ ['/lobe-team/task/task-1', 'lobe-team', 'home'],
+ ['/agent/agent-1', null, 'agent'],
+ ['/lobe-team/agent/agent-1', 'lobe-team', 'agent'],
+ ['/group/group-1', null, 'group'],
+ ['/settings/profile', null, 'settings'],
+ ['/lobe-team/settings/general', 'lobe-team', 'workspace-settings'],
+ ['/lobe-team/community', 'lobe-team', 'discover'],
+ ['/lobe-team/resource', 'lobe-team', 'resource'],
+ ['/lobe-team/resource/library', 'lobe-team', 'resourceLibrary'],
+ ['/lobe-team/memory', 'lobe-team', 'memory'],
+ ['/lobe-team/eval', 'lobe-team', 'eval'],
+ ['/lobe-team/eval/bench/benchmark-1', 'lobe-team', 'evalBench'],
+ ['/lobe-team/page/page-1', 'lobe-team', 'page'],
+ ['/lobe-team/image', 'lobe-team', 'image'],
+ ['/lobe-team/video', 'lobe-team', 'video'],
+ ])('maps %s to %s', (pathname, activeWorkspaceSlug, expected) => {
+ expect(resolveNavPanelKey(pathname, activeWorkspaceSlug)).toBe(expected);
+ });
+});
diff --git a/src/features/NavPanel/routeKey.ts b/src/features/NavPanel/routeKey.ts
new file mode 100644
index 00000000000..7d39bcd59ff
--- /dev/null
+++ b/src/features/NavPanel/routeKey.ts
@@ -0,0 +1,56 @@
+export const resolveNavPanelKey = (
+ pathname: string,
+ activeWorkspaceSlug: string | null,
+): string => {
+ const segments = pathname.split('/').filter(Boolean);
+ const isWorkspaceRoute =
+ !!activeWorkspaceSlug && segments.length > 0 && segments[0] === activeWorkspaceSlug;
+ const routeSegments = isWorkspaceRoute ? segments.slice(1) : segments;
+ const [rootSegment, childSegment] = routeSegments;
+
+ if (rootSegment === 'settings') {
+ return isWorkspaceRoute ? 'workspace-settings' : 'settings';
+ }
+
+ switch (rootSegment) {
+ case 'agent': {
+ return 'agent';
+ }
+
+ case 'community': {
+ return 'discover';
+ }
+
+ case 'eval': {
+ return childSegment === 'bench' ? 'evalBench' : 'eval';
+ }
+
+ case 'group': {
+ return 'group';
+ }
+
+ case 'image': {
+ return 'image';
+ }
+
+ case 'memory': {
+ return 'memory';
+ }
+
+ case 'page': {
+ return 'page';
+ }
+
+ case 'resource': {
+ return childSegment === 'library' ? 'resourceLibrary' : 'resource';
+ }
+
+ case 'video': {
+ return 'video';
+ }
+
+ default: {
+ return 'home';
+ }
+ }
+};
diff --git a/src/features/NavPanel/useActiveNavKey.ts b/src/features/NavPanel/useActiveNavKey.ts
new file mode 100644
index 00000000000..9669e41a170
--- /dev/null
+++ b/src/features/NavPanel/useActiveNavKey.ts
@@ -0,0 +1,11 @@
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+
+import { resolveNavPanelKey } from './routeKey';
+
+export const useActiveNavKey = () => {
+ const { pathname } = useActiveLocation();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+
+ return resolveNavPanelKey(pathname, activeWorkspaceSlug);
+};
diff --git a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx
index fa6bf44bcd8..8f1e809ffb4 100644
--- a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx
+++ b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.tsx
@@ -83,7 +83,7 @@ export const useDropdownMenu = ({
const isCompleted = status === 'completed';
const handleOpenShareModal = useCallback(() => {
- openShareModal({ context: { threadId: null, topicId } });
+ void openShareModal({ context: { threadId: null, topicId } });
}, [topicId]);
return useCallback(
diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsx
index c2869508da6..be5c1724a9e 100644
--- a/src/features/PageEditor/StoreUpdater.tsx
+++ b/src/features/PageEditor/StoreUpdater.tsx
@@ -7,7 +7,7 @@ import { hasMeaningfulEditorContent } from '@/libs/editor/hasMeaningfulEditorCon
import { documentHistoryQueueService } from '@/services/documentHistoryQueue';
import { useDocumentStore } from '@/store/document';
import { pageSelectors, usePageStore } from '@/store/page';
-import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';
import { type PublicState } from './store';
import { usePageEditorStore, useStoreApi } from './store';
diff --git a/src/features/Pages/PageLayout/Sidebar.tsx b/src/features/Pages/PageLayout/Sidebar.tsx
index dfaee9886eb..3603553281e 100644
--- a/src/features/Pages/PageLayout/Sidebar.tsx
+++ b/src/features/Pages/PageLayout/Sidebar.tsx
@@ -2,7 +2,7 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import SidebarContent from './SidebarContent';
diff --git a/src/features/Portal/TaskDetail/Body.tsx b/src/features/Portal/TaskDetail/Body.tsx
index 938e025efe9..c90202f303a 100644
--- a/src/features/Portal/TaskDetail/Body.tsx
+++ b/src/features/Portal/TaskDetail/Body.tsx
@@ -6,7 +6,6 @@ import NotFound from '@/components/404';
import AsyncError from '@/components/AsyncError';
import Loading from '@/components/Loading/BrandTextLoading';
import { TaskDetailSections, TopicChatDrawer, useActiveTaskDetail } from '@/features/AgentTasks';
-import DocumentPreviewModal from '@/features/DocumentModal/Preview';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -46,7 +45,6 @@ const Body = memo(() => {
>
{isInitialLoading ? <Loading debugId="PortalTaskDetail" /> : <TaskDetailSections />}
<TopicChatDrawer />
- <DocumentPreviewModal />
</Flexbox>
);
});
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
index 1c59578d6d2..04155d67eb5 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx
@@ -1,6 +1,6 @@
import { CUSTOM_FOLDER_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
import type { SFSymbol } from '@lobechat/electron-client-ipc';
-import { copyToClipboard, createRawModal, Icon, Tooltip } from '@lobehub/ui';
+import { copyToClipboard, Icon, Tooltip } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { type ItemType } from 'antd/es/menu/interface';
@@ -35,7 +35,7 @@ import { userProfileSelectors } from '@/store/user/selectors';
import { downloadFile } from '@/utils/client/downloadFile';
import { isForbiddenError } from '@/utils/forbiddenError';
-import MoveToFolderModal from '../MoveToFolderModal';
+import { openMoveToFolderModal } from '../MoveToFolderModal';
interface UseFileItemDropdownParams {
enabled?: boolean;
@@ -325,7 +325,7 @@ export const useFileItemDropdown = ({
onClick: async ({ domEvent }) => {
domEvent.stopPropagation();
- createRawModal(MoveToFolderModal, {
+ openMoveToFolderModal({
fileId: id,
knowledgeBaseId: libraryId,
});
diff --git a/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx b/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx
index eddf42bcd72..a79a2e4857e 100644
--- a/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx
+++ b/src/features/ResourceManager/components/Explorer/MoveToFolderModal.tsx
@@ -1,28 +1,27 @@
import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import { Flexbox, Icon } from '@lobehub/ui';
-import { Button } from '@lobehub/ui/base-ui';
+import { Button, createModal, ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
import { App } from 'antd';
+import { t as translate } from 'i18next';
import { FolderIcon } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import ImperativeModal from '@/components/ImperativeModal';
import { type FolderTreeItem } from '@/features/ResourceManager/components/FolderTree';
import FolderTree from '@/features/ResourceManager/components/FolderTree';
import { fileService } from '@/services/file';
import { useFileStore } from '@/store/file';
import { useTreeStore } from '@/store/tree';
-interface MoveToFolderModalProps {
+interface MoveToFolderModalContentProps {
fileId: string;
knowledgeBaseId?: string;
- onClose: () => void;
- open: boolean;
}
-const MoveToFolderModal = memo<MoveToFolderModalProps>(
- ({ open, onClose, fileId, knowledgeBaseId }) => {
+const MoveToFolderModalContent = memo<MoveToFolderModalContentProps>(
+ ({ fileId, knowledgeBaseId }) => {
const { t } = useTranslation('components');
+ const { close } = useModalContext();
const { message } = App.useApp();
const [folders, setFolders] = useState<FolderTreeItem[]>([]);
@@ -70,10 +69,8 @@ const MoveToFolderModal = memo<MoveToFolderModalProps>(
}, [knowledgeBaseId, sortItems]);
useEffect(() => {
- if (open) {
- fetchRootFolders();
- }
- }, [open, fetchRootFolders]);
+ void fetchRootFolders();
+ }, [fetchRootFolders]);
const handleLoadFolder = useCallback(
async (folderId: string) => {
@@ -237,7 +234,7 @@ const MoveToFolderModal = memo<MoveToFolderModalProps>(
message.error(t('FileManager.actions.moveError'));
});
message.success(t('FileManager.actions.moveSuccess'));
- onClose();
+ close();
};
const handleMoveToRoot = () => {
@@ -254,63 +251,66 @@ const MoveToFolderModal = memo<MoveToFolderModalProps>(
message.error(t('FileManager.actions.moveError'));
});
message.success(t('FileManager.actions.moveSuccess'));
- onClose();
+ close();
};
return (
- <ImperativeModal
- open={open}
- title={t('FileManager.actions.moveToFolder')}
- footer={
- <Flexbox horizontal gap={8} justify={'flex-end'}>
- <Button onClick={onClose}>{t('cancel', { ns: 'common' })}</Button>
- <Button type="default" onClick={handleMoveToRoot}>
- {t('FileManager.actions.moveToRoot')}
- </Button>
- <Button disabled={!selectedFolderId} type="primary" onClick={handleMove}>
- {t('FileManager.actions.moveHere')}
+ <>
+ <Flexbox style={{ padding: 16 }}>
+ <Flexbox horizontal justify="flex-end" style={{ marginBottom: 12 }}>
+ <Button
+ icon={<Icon icon={FolderIcon} />}
+ loading={isCreatingFolder}
+ size="small"
+ type="default"
+ onClick={handleCreateNewFolder}
+ >
+ {t('header.actions.newFolder', { ns: 'file' })}
</Button>
</Flexbox>
- }
- onCancel={onClose}
- >
- <Flexbox horizontal justify="flex-end" style={{ marginBottom: 12 }}>
- <Button
- icon={<Icon icon={FolderIcon} />}
- loading={isCreatingFolder}
- size="small"
- type="default"
- onClick={handleCreateNewFolder}
- >
- {t('header.actions.newFolder', { ns: 'file' })}
- </Button>
- </Flexbox>
- <Flexbox style={{ maxHeight: 400, minHeight: 200, overflowY: 'auto' }}>
- {loading ? (
- <div>{t('loading', { ns: 'common' })}</div>
- ) : folders.length === 0 ? (
- <Flexbox align="center" justify="center" style={{ minHeight: 200 }}>
- <div style={{ color: 'var(--lobe-color-text-secondary)' }}>
- {t('FileManager.noFolders')}
- </div>
- </Flexbox>
- ) : (
- <FolderTree
- expandedFolders={expandedFolders}
- items={folders}
- loadedFolders={loadedFolders}
- selectedKey={selectedFolderId}
- onFolderClick={handleFolderClick}
- onLoadFolder={handleLoadFolder}
- onToggleFolder={handleToggleFolder}
- />
- )}
+ <Flexbox style={{ maxHeight: 400, minHeight: 200, overflowY: 'auto' }}>
+ {loading ? (
+ <div>{t('loading', { ns: 'common' })}</div>
+ ) : folders.length === 0 ? (
+ <Flexbox align="center" justify="center" style={{ minHeight: 200 }}>
+ <div style={{ color: 'var(--lobe-color-text-secondary)' }}>
+ {t('FileManager.noFolders')}
+ </div>
+ </Flexbox>
+ ) : (
+ <FolderTree
+ expandedFolders={expandedFolders}
+ items={folders}
+ loadedFolders={loadedFolders}
+ selectedKey={selectedFolderId}
+ onFolderClick={handleFolderClick}
+ onLoadFolder={handleLoadFolder}
+ onToggleFolder={handleToggleFolder}
+ />
+ )}
+ </Flexbox>
</Flexbox>
- </ImperativeModal>
+ <ModalFooter>
+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
+ <Button type="default" onClick={handleMoveToRoot}>
+ {t('FileManager.actions.moveToRoot')}
+ </Button>
+ <Button disabled={!selectedFolderId} type="primary" onClick={handleMove}>
+ {t('FileManager.actions.moveHere')}
+ </Button>
+ </ModalFooter>
+ </>
);
},
);
-MoveToFolderModal.displayName = 'MoveToFolderModal';
+MoveToFolderModalContent.displayName = 'MoveToFolderModalContent';
-export default MoveToFolderModal;
+export const openMoveToFolderModal = (props: MoveToFolderModalContentProps) =>
+ createModal({
+ content: <MoveToFolderModalContent {...props} />,
+ footer: null,
+ maskClosable: true,
+ styles: { content: { padding: 0 } },
+ title: translate('FileManager.actions.moveToFolder', { ns: 'components' }),
+ });
diff --git a/src/features/RouteMeta/AgentDynamicMeta.tsx b/src/features/RouteMeta/AgentDynamicMeta.tsx
new file mode 100644
index 00000000000..d2f314e57ec
--- /dev/null
+++ b/src/features/RouteMeta/AgentDynamicMeta.tsx
@@ -0,0 +1,80 @@
+'use client';
+
+import { useTranslation } from 'react-i18next';
+
+import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { topicMapKey } from '@/store/chat/utils/topicMapKey';
+
+import { usePublishDynamicRouteMeta } from './usePublishDynamicRouteMeta';
+import { matchesRouteWorkspace, useRouteWorkspaceId } from './workspaceScope';
+
+const useTopicTitle = (
+ agentId: string | undefined,
+ topicId: string | undefined,
+ routeWorkspaceId: string | null | undefined,
+): string | undefined =>
+ useChatStore((state) => {
+ if (!agentId || !topicId || routeWorkspaceId === undefined) return undefined;
+
+ const topic = state.topicDataMap[topicMapKey({ agentId })]?.items?.find(
+ (item) => item.id === topicId,
+ );
+ return topic?.title || undefined;
+ });
+
+const AgentDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
+ const routeWorkspaceId = useRouteWorkspaceId(params);
+ const meta = useAgentStore((state) => {
+ const agentId = params.aid ?? '';
+ const agent = state.agentMap[agentId];
+
+ if (!matchesRouteWorkspace(agent?.workspaceId, routeWorkspaceId)) return {};
+
+ return agentSelectors.getAgentMetaById(agentId)(state);
+ });
+ const topicTitle = useTopicTitle(params.aid, params.topicId ?? params.topic, routeWorkspaceId);
+ const hasMeta = Object.keys(meta).length > 0;
+ const agentTitle = hasMeta ? meta.title : undefined;
+
+ usePublishDynamicRouteMeta(
+ {
+ avatar: meta.avatar,
+ backgroundColor: meta.backgroundColor,
+ title: [topicTitle, agentTitle].filter(Boolean).join(' Β· ') || undefined,
+ },
+ onResolve,
+ );
+
+ return null;
+};
+
+export const TopicsDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
+ const { t } = useTranslation('electron');
+ const routeWorkspaceId = useRouteWorkspaceId(params);
+ const meta = useAgentStore((state) => {
+ const agentId = params.aid ?? '';
+ const agent = state.agentMap[agentId];
+
+ if (!matchesRouteWorkspace(agent?.workspaceId, routeWorkspaceId)) return {};
+
+ return agentSelectors.getAgentMetaById(agentId)(state);
+ });
+ const hasMeta = Object.keys(meta).length > 0;
+ const agentTitle = hasMeta ? meta.title : undefined;
+
+ usePublishDynamicRouteMeta(
+ {
+ avatar: meta.avatar,
+ backgroundColor: meta.backgroundColor,
+ title: [t('navigation.topics'), agentTitle].filter(Boolean).join(' Β· ') || undefined,
+ },
+ onResolve,
+ );
+
+ return null;
+};
+
+export default AgentDynamicMeta;
diff --git a/src/features/RouteMeta/DynamicMetaRunner.tsx b/src/features/RouteMeta/DynamicMetaRunner.tsx
index b478dfe93de..46c66bdc3a8 100644
--- a/src/features/RouteMeta/DynamicMetaRunner.tsx
+++ b/src/features/RouteMeta/DynamicMetaRunner.tsx
@@ -1,7 +1,7 @@
'use client';
import debug from 'debug';
-import { memo } from 'react';
+import { memo, Suspense } from 'react';
import { SafeBoundary } from '@/components/ErrorBoundary';
import { type DynamicRouteMetaProps, type RouteMeta } from '@/spa/router/routeMeta';
@@ -19,7 +19,9 @@ const DynamicMetaRunner = memo<DynamicMetaRunnerProps>(({ DynamicMeta, onResolve
onResolve({});
}}
>
- <DynamicMeta params={params} onResolve={onResolve} />
+ <Suspense fallback={null}>
+ <DynamicMeta params={params} onResolve={onResolve} />
+ </Suspense>
</SafeBoundary>
));
diff --git a/src/features/RouteMeta/GroupDynamicMeta.tsx b/src/features/RouteMeta/GroupDynamicMeta.tsx
new file mode 100644
index 00000000000..78cd7415ed4
--- /dev/null
+++ b/src/features/RouteMeta/GroupDynamicMeta.tsx
@@ -0,0 +1,47 @@
+'use client';
+
+import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';
+import { useChatStore } from '@/store/chat';
+import { topicMapKey } from '@/store/chat/utils/topicMapKey';
+import { useSessionStore } from '@/store/session';
+import { sessionGroupSelectors } from '@/store/session/slices/sessionGroup/selectors';
+
+import { usePublishDynamicRouteMeta } from './usePublishDynamicRouteMeta';
+import { matchesRouteWorkspace, useRouteWorkspaceId } from './workspaceScope';
+
+const getWorkspaceId = (item: unknown): string | null | undefined =>
+ (item as { workspaceId?: string | null } | undefined)?.workspaceId;
+
+const useTopicTitle = (
+ groupId: string | undefined,
+ topicId: string | undefined,
+ routeWorkspaceId: string | null | undefined,
+): string | undefined =>
+ useChatStore((state) => {
+ if (!groupId || !topicId || routeWorkspaceId === undefined) return undefined;
+
+ const topic = state.topicDataMap[topicMapKey({ groupId })]?.items?.find(
+ (item) => item.id === topicId,
+ );
+ return topic?.title || undefined;
+ });
+
+const GroupDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
+ const routeWorkspaceId = useRouteWorkspaceId(params);
+ const group = useSessionStore((state) => {
+ const item = sessionGroupSelectors.getGroupById(params.gid ?? '')(state);
+ return matchesRouteWorkspace(getWorkspaceId(item), routeWorkspaceId) ? item : undefined;
+ });
+ const topicTitle = useTopicTitle(params.gid, params.topicId ?? params.topic, routeWorkspaceId);
+
+ usePublishDynamicRouteMeta(
+ {
+ title: topicTitle || group?.name || undefined,
+ },
+ onResolve,
+ );
+
+ return null;
+};
+
+export default GroupDynamicMeta;
diff --git a/src/features/RouteMeta/RouteMetaBridge.test.tsx b/src/features/RouteMeta/RouteMetaBridge.test.tsx
index ee679f9c08c..70e35ac9fa9 100644
--- a/src/features/RouteMeta/RouteMetaBridge.test.tsx
+++ b/src/features/RouteMeta/RouteMetaBridge.test.tsx
@@ -1,6 +1,7 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { act, cleanup, render, waitFor } from '@testing-library/react';
import type * as ReactModule from 'react';
+import { lazy } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { DynamicRouteMeta, DynamicRouteMetaProps } from '@/spa/router/routeMeta';
@@ -231,6 +232,33 @@ describe('RouteMetaBridge', () => {
});
});
+ it('resolves route metadata from a lazy dynamic component', async () => {
+ const LazyDynamicMeta = lazy(async () => ({
+ default: createDynamicMeta(() => ({ title: 'Lazy chat' })),
+ }));
+
+ mocks.setMatches([
+ {
+ data: undefined,
+ handle: {
+ meta: {
+ DynamicMeta: LazyDynamicMeta,
+ titleKey: 'navigation.chat',
+ },
+ },
+ id: 'routes/lazy-agent',
+ params: { aid: 'agent-lazy' },
+ pathname: '/agent/agent-lazy',
+ },
+ ]);
+
+ render(<RouteMetaBridge />);
+
+ await waitFor(() => {
+ expect(document.title).toBe(`Lazy chat Β· ${BRANDING_NAME}`);
+ });
+ });
+
it('publishes empty dynamic meta for a static route without DynamicMeta', async () => {
mocks.setMatches([
{
diff --git a/src/features/ShareModal/Modal.tsx b/src/features/ShareModal/Modal.tsx
index fbd08e4533b..463e5e2a5ae 100644
--- a/src/features/ShareModal/Modal.tsx
+++ b/src/features/ShareModal/Modal.tsx
@@ -4,23 +4,19 @@ import { type ConversationContext } from '@lobechat/types';
import { Flexbox, Skeleton } from '@lobehub/ui';
import { createModal, type ModalInstance, Tabs } from '@lobehub/ui/base-ui';
import { t } from 'i18next';
-import { memo, useMemo, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import { useIsMobile } from '@/hooks/useIsMobile';
import ShareDataProvider, { useShareData } from './ShareDataProvider';
-import ShareImage from './ShareImage';
-import ShareJSON from './ShareJSON';
-import SharePdf from './SharePdf';
-import ShareText from './ShareText';
+import { loadShareTabRenderer, ShareTab, type ShareTabRenderer } from './tabRegistry';
-enum Tab {
- JSON = 'json',
- PDF = 'pdf',
- Screenshot = 'screenshot',
- Text = 'text',
-}
+type ShareTabRendererState =
+ | { status: 'loading' }
+ | { error: unknown; status: 'error'; tab: ShareTab }
+ | { render: ShareTabRenderer; status: 'ready'; tab: ShareTab };
export interface OpenShareModalOptions {
afterClose?: () => void;
@@ -28,27 +24,49 @@ export interface OpenShareModalOptions {
}
const ShareModalContent = memo(() => {
- const [tab, setTab] = useState<Tab>(Tab.Screenshot);
+ const [tab, setTab] = useState<ShareTab>(ShareTab.Screenshot);
+ const [rendererAttempt, setRendererAttempt] = useState(0);
+ const [rendererState, setRendererState] = useState<ShareTabRendererState>({ status: 'loading' });
const { t } = useTranslation('chat');
const isMobile = useIsMobile();
const { dbMessages, isLoading } = useShareData();
+ useEffect(() => {
+ let active = true;
+ setRendererState({ status: 'loading' });
+
+ void loadShareTabRenderer(tab).then(
+ (render) => {
+ if (active) setRendererState({ render, status: 'ready', tab });
+ },
+ (error: unknown) => {
+ if (active) setRendererState({ error, status: 'error', tab });
+ },
+ );
+
+ return () => {
+ active = false;
+ };
+ }, [rendererAttempt, tab]);
+
+ const retryRenderer = useCallback(() => setRendererAttempt((value) => value + 1), []);
+
const tabItems = useMemo(
() => [
{
- key: Tab.Screenshot,
+ key: ShareTab.Screenshot,
label: t('shareModal.screenshot'),
},
{
- key: Tab.Text,
+ key: ShareTab.Text,
label: t('shareModal.text'),
},
{
- key: Tab.PDF,
+ key: ShareTab.PDF,
label: t('shareModal.pdf'),
},
{
- key: Tab.JSON,
+ key: ShareTab.JSON,
label: 'JSON',
},
],
@@ -69,19 +87,20 @@ const ShareModalContent = memo(() => {
list: { display: 'flex', width: '100%' },
tab: { flex: 1 },
}}
- onChange={(key) => setTab(key as Tab)}
+ onChange={(key) => setTab(key as ShareTab)}
/>
{isLoading && dbMessages.length === 0 ? (
<Flexbox gap={12} paddingBlock={8}>
<Skeleton active paragraph={{ rows: 8 }} />
</Flexbox>
+ ) : rendererState.status === 'error' && rendererState.tab === tab ? (
+ <AsyncError error={rendererState.error} variant={'block'} onRetry={retryRenderer} />
+ ) : rendererState.status === 'ready' && rendererState.tab === tab ? (
+ rendererState.render({ mobile: isMobile })
) : (
- <>
- {tab === Tab.Screenshot && <ShareImage mobile={isMobile} />}
- {tab === Tab.Text && <ShareText />}
- {tab === Tab.PDF && <SharePdf />}
- {tab === Tab.JSON && <ShareJSON />}
- </>
+ <Flexbox gap={12} paddingBlock={8}>
+ <Skeleton active paragraph={{ rows: 8 }} />
+ </Flexbox>
)}
</Flexbox>
);
diff --git a/src/features/ShareModal/ShareImage/ChatList/index.tsx b/src/features/ShareModal/ShareImage/ChatList/index.tsx
index 4ddd173210e..8ed2b7f2e72 100644
--- a/src/features/ShareModal/ShareImage/ChatList/index.tsx
+++ b/src/features/ShareModal/ShareImage/ChatList/index.tsx
@@ -2,7 +2,9 @@ import { type ConversationContext, type UIChatMessage } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
-import { ConversationProvider, MessageItem, useConversationStore } from '@/features/Conversation';
+import { ConversationProvider } from '@/features/Conversation/ConversationProvider';
+import MessageItem from '@/features/Conversation/Messages';
+import { useConversationStore } from '@/features/Conversation/store';
interface ChatListContentProps {
ids: string[];
diff --git a/src/features/ShareModal/index.tsx b/src/features/ShareModal/index.tsx
index 1a9c64a2842..b1d39a56ecd 100644
--- a/src/features/ShareModal/index.tsx
+++ b/src/features/ShareModal/index.tsx
@@ -1,2 +1,3 @@
-export { openShareModal } from './Modal';
+export { openShareModal, preloadShareModal } from './loader';
+export type { OpenShareModalOptions } from './Modal';
export { useShareModal } from './useShareModal';
diff --git a/src/features/ShareModal/loader.ts b/src/features/ShareModal/loader.ts
new file mode 100644
index 00000000000..32e658ee68c
--- /dev/null
+++ b/src/features/ShareModal/loader.ts
@@ -0,0 +1,19 @@
+import { type ModalInstance } from '@lobehub/ui/base-ui';
+
+import { type OpenShareModalOptions } from './Modal';
+
+const importShareModal = () => import('./Modal');
+
+let shareModalModulePromise: ReturnType<typeof importShareModal> | undefined;
+
+export const preloadShareModal = (): ReturnType<typeof importShareModal> =>
+ (shareModalModulePromise ??= importShareModal().catch((error) => {
+ shareModalModulePromise = undefined;
+ throw error;
+ }));
+
+export const openShareModal = async (options?: OpenShareModalOptions): Promise<ModalInstance> => {
+ const { openShareModal: createShareModal } = await preloadShareModal();
+
+ return createShareModal(options);
+};
diff --git a/src/features/ShareModal/tabRegistry.tsx b/src/features/ShareModal/tabRegistry.tsx
new file mode 100644
index 00000000000..abfc6a3daa3
--- /dev/null
+++ b/src/features/ShareModal/tabRegistry.tsx
@@ -0,0 +1,50 @@
+import type { ReactNode } from 'react';
+
+export const ShareTab = {
+ JSON: 'json',
+ PDF: 'pdf',
+ Screenshot: 'screenshot',
+ Text: 'text',
+} as const;
+
+export type ShareTab = (typeof ShareTab)[keyof typeof ShareTab];
+
+interface ShareTabRenderOptions {
+ mobile: boolean;
+}
+
+export type ShareTabRenderer = (options: ShareTabRenderOptions) => ReactNode;
+
+const rendererLoaders: Record<ShareTab, () => Promise<ShareTabRenderer>> = {
+ [ShareTab.JSON]: async () => {
+ const { default: ShareJSON } = await import('./ShareJSON');
+ return () => <ShareJSON />;
+ },
+ [ShareTab.PDF]: async () => {
+ const { default: SharePdf } = await import('./SharePdf');
+ return () => <SharePdf />;
+ },
+ [ShareTab.Screenshot]: async () => {
+ const { default: ShareImage } = await import('./ShareImage');
+ return ({ mobile }) => <ShareImage mobile={mobile} />;
+ },
+ [ShareTab.Text]: async () => {
+ const { default: ShareText } = await import('./ShareText');
+ return () => <ShareText />;
+ },
+};
+
+const rendererPromises = new Map<ShareTab, Promise<ShareTabRenderer>>();
+
+export const loadShareTabRenderer = (tab: ShareTab): Promise<ShareTabRenderer> => {
+ const cached = rendererPromises.get(tab);
+ if (cached) return cached;
+
+ const promise = rendererLoaders[tab]().catch((error) => {
+ rendererPromises.delete(tab);
+ throw error;
+ });
+ rendererPromises.set(tab, promise);
+
+ return promise;
+};
diff --git a/src/features/ShareModal/useShareModal.tsx b/src/features/ShareModal/useShareModal.tsx
index 1ba10145cea..1658ee9decc 100644
--- a/src/features/ShareModal/useShareModal.tsx
+++ b/src/features/ShareModal/useShareModal.tsx
@@ -4,7 +4,7 @@ import { type ConversationContext } from '@lobechat/types';
import { type ModalInstance } from '@lobehub/ui/base-ui';
import { useCallback, useEffect, useRef } from 'react';
-import { openShareModal as createShareModal } from './Modal';
+import { openShareModal as createShareModal } from './loader';
interface UseShareModalOptions {
context?: Partial<ConversationContext>;
@@ -14,32 +14,64 @@ interface UseShareModalOptions {
export const useShareModal = ({ context, open, setOpen }: UseShareModalOptions = {}) => {
const modalRef = useRef<ModalInstance | null>(null);
+ const openingRef = useRef<Promise<ModalInstance> | null>(null);
+ const requestIdRef = useRef(0);
const closeShareModal = useCallback(() => {
+ requestIdRef.current += 1;
modalRef.current?.close();
modalRef.current = null;
- }, []);
+ openingRef.current = null;
+ setOpen?.(false);
+ }, [setOpen]);
const openShareModal = useCallback(() => {
- if (modalRef.current) return modalRef.current;
+ if (modalRef.current) return Promise.resolve(modalRef.current);
+ if (openingRef.current) return openingRef.current;
setOpen?.(true);
- modalRef.current = createShareModal({
+ const requestId = ++requestIdRef.current;
+ let createdModal: ModalInstance | undefined;
+
+ const opening = createShareModal({
afterClose: () => {
- modalRef.current = null;
+ if (requestId !== requestIdRef.current) return;
+ if (modalRef.current === createdModal) modalRef.current = null;
setOpen?.(false);
},
context,
- });
+ }).then(
+ (modal) => {
+ createdModal = modal;
+ if (requestId === requestIdRef.current) openingRef.current = null;
+
+ if (requestId !== requestIdRef.current) {
+ modal.close();
+ return modal;
+ }
+
+ modalRef.current = modal;
+ return modal;
+ },
+ (error) => {
+ if (requestId === requestIdRef.current) {
+ openingRef.current = null;
+ setOpen?.(false);
+ }
+ throw error;
+ },
+ );
+
+ openingRef.current = opening;
- return modalRef.current;
+ return opening;
}, [context, setOpen]);
useEffect(() => {
if (open === undefined) return;
if (open) {
- openShareModal();
+ void openShareModal();
return;
}
diff --git a/src/features/WorkGallery/index.tsx b/src/features/WorkGallery/index.tsx
index 3530fbda5a0..8d38711d64a 100644
--- a/src/features/WorkGallery/index.tsx
+++ b/src/features/WorkGallery/index.tsx
@@ -9,10 +9,9 @@ import { useTranslation } from 'react-i18next';
import { formatTaskItemDate } from '@/features/AgentTasks/features/formatTaskItemDate';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
-import DocumentPreviewModal from '@/features/DocumentModal/Preview';
+import { openDocumentModal } from '@/features/DocumentModal/loader';
import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useDocumentStore } from '@/store/document';
import type { WorkGalleryKey } from './const';
import { useWorkspaceWorksInfinite } from './hooks';
@@ -198,7 +197,6 @@ interface WorkGalleryProps {
const WorkGallery = memo<WorkGalleryProps>(({ galleryKey }) => {
const { t, i18n } = useTranslation('file');
const navigate = useWorkspaceAwareNavigate();
- const openDocumentPreview = useDocumentStore((s) => s.openDocumentPreview);
const { items, error, hasMore, isLoadingInitial, isLoadingMore, loadMore, reload } =
useWorkspaceWorksInfinite(galleryKey);
@@ -235,7 +233,7 @@ const WorkGallery = memo<WorkGalleryProps>(({ galleryKey }) => {
switch (openTarget.kind) {
case 'document': {
- openDocumentPreview(openTarget.documentId);
+ void openDocumentModal(openTarget.documentId);
return;
}
// external skill works (linear / github): external link (URL-less cards
@@ -253,7 +251,7 @@ const WorkGallery = memo<WorkGalleryProps>(({ galleryKey }) => {
}
}
},
- [navigate, openDocumentPreview],
+ [navigate],
);
// Infinite scroll: load the next page when a sentinel near the list's end
@@ -354,7 +352,6 @@ const WorkGallery = memo<WorkGalleryProps>(({ galleryKey }) => {
</Text>
</div>
<Flexbox className={styles.scroll}>{renderBody()}</Flexbox>
- <DocumentPreviewModal />
</Flexbox>
);
});
diff --git a/src/features/WorkspaceSetting/SideBar/index.tsx b/src/features/WorkspaceSetting/SideBar/index.tsx
index 489b70ae603..c9c923f4eb8 100644
--- a/src/features/WorkspaceSetting/SideBar/index.tsx
+++ b/src/features/WorkspaceSetting/SideBar/index.tsx
@@ -2,7 +2,7 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import WorkspaceSettingsSideBarContent from './Content';
diff --git a/src/layout/SPAGlobalProvider/index.test.tsx b/src/layout/SPAGlobalProvider/index.test.tsx
index 5f5f6b54f20..41df64289ef 100644
--- a/src/layout/SPAGlobalProvider/index.test.tsx
+++ b/src/layout/SPAGlobalProvider/index.test.tsx
@@ -5,6 +5,7 @@ import { render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { setPostRenderReady } from '@/spa/atoms/app';
import { setDevDockUnlocked } from '@/utils/devDockUnlock';
import type SPAGlobalProviderComponent from './index';
@@ -124,7 +125,7 @@ vi.mock('@/layout/GlobalProvider/CacheHydrationGate', async () => {
});
vi.mock('@/layout/GlobalProvider/DynamicFavicon', () => ({
- default: () => null,
+ default: () => <div data-testid="dynamic-favicon" />,
}));
vi.mock('@/layout/GlobalProvider/FaviconProvider', async () => {
@@ -196,6 +197,7 @@ describe('SPAGlobalProvider', () => {
canAccessDevDock.mockReturnValue(false);
setDevDockUnlocked(false);
Reflect.deleteProperty(window, '__SERVER_CONFIG__');
+ setPostRenderReady(false);
});
afterEach(() => {
@@ -213,7 +215,6 @@ describe('SPAGlobalProvider', () => {
expect(routeContent.closest('[data-testid="market-auth-provider"]')).not.toBeNull();
});
-
it('mounts DevDock in dev builds even without server-resolved access', async () => {
render(
<DevDockLayout>
@@ -263,4 +264,27 @@ describe('SPAGlobalProvider', () => {
expect(await screen.findByTestId('dev-dock')).toBeInTheDocument();
});
+
+ it('mounts global interaction hosts with the application shell', () => {
+ render(
+ <SPAGlobalProvider>
+ <div />
+ </SPAGlobalProvider>,
+ );
+
+ expect(screen.getByTestId('legacy-modal-host')).toBeInTheDocument();
+ expect(screen.getByTestId('base-modal-host')).toBeInTheDocument();
+ expect(screen.getByTestId('toast-host')).toBeInTheDocument();
+ expect(screen.getByTestId('context-menu-host')).toBeInTheDocument();
+ });
+
+ it('does not mount the chat-store favicon subscriber before post-render initialization', () => {
+ render(
+ <SPAGlobalProvider>
+ <div />
+ </SPAGlobalProvider>,
+ );
+
+ expect(screen.queryByTestId('dynamic-favicon')).not.toBeInTheDocument();
+ });
});
diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsx
index ee17eb23612..85d1ff0655a 100644
--- a/src/layout/SPAGlobalProvider/index.tsx
+++ b/src/layout/SPAGlobalProvider/index.tsx
@@ -1,6 +1,7 @@
'use client';
-import { TooltipGroup } from '@lobehub/ui';
+import { ContextMenuHost, ModalHost, TooltipGroup } from '@lobehub/ui';
+import { ModalHost as BaseModalHost, ToastHost } from '@lobehub/ui/base-ui';
import { StyleProvider } from 'antd-style';
import { domMax, LazyMotion } from 'motion/react';
import { type CSSProperties, lazy, memo, type PropsWithChildren, Suspense } from 'react';
@@ -13,30 +14,22 @@ import AuthProvider from '@/layout/AuthProvider';
import { MarketAuthProvider } from '@/layout/AuthProvider/MarketAuth';
import AppTheme from '@/layout/GlobalProvider/AppTheme';
import CacheHydrationGate from '@/layout/GlobalProvider/CacheHydrationGate';
-import DynamicFavicon from '@/layout/GlobalProvider/DynamicFavicon';
import { FaviconProvider } from '@/layout/GlobalProvider/FaviconProvider';
import { GroupWizardProvider } from '@/layout/GlobalProvider/GroupWizardProvider';
import QueryProvider from '@/layout/GlobalProvider/Query';
import ServerVersionOutdatedAlert from '@/layout/GlobalProvider/ServerVersionOutdatedAlert';
import StoreInitialization from '@/layout/GlobalProvider/StoreInitialization';
import { registerNativeContextMenuInterceptor } from '@/libs/contextMenu';
+import { usePostRenderReady } from '@/spa/atoms/app';
import { ServerConfigStoreProvider } from '@/store/serverConfig/Provider';
import type { SPAServerConfig } from '@/types/spaServerConfig';
import Locale from './Locale';
registerNativeContextMenuInterceptor();
-
-const ModalHost = lazy(() => import('@lobehub/ui').then((m) => ({ default: m.ModalHost })));
-const BaseModalHost = lazy(() =>
- import('@lobehub/ui/base-ui').then((m) => ({ default: m.ModalHost })),
-);
-const ToastHost = lazy(() => import('@lobehub/ui/base-ui').then((m) => ({ default: m.ToastHost })));
-const ContextMenuHost = lazy(() =>
- import('@lobehub/ui').then((m) => ({ default: m.ContextMenuHost })),
-);
const DevDock = lazy(() => import('@/features/DevDock'));
const ImperativeMountHost = lazy(() => import('@/components/ImperativeMount'));
+const DynamicFavicon = lazy(() => import('@/layout/GlobalProvider/DynamicFavicon'));
const devDockLayoutStyle: CSSProperties = {
alignItems: 'center',
@@ -65,6 +58,7 @@ export const DevDockLayout = memo<PropsWithChildren>(({ children }) => {
DevDockLayout.displayName = 'DevDockLayout';
const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
+ const postRenderReady = usePostRenderReady();
const serverConfig: SPAServerConfig | undefined = window.__SERVER_CONFIG__;
const locale = document.documentElement.lang || 'en-US';
@@ -79,7 +73,11 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
{isDesktop && <ServerVersionOutdatedAlert />}
<FaviconProvider>
- <DynamicFavicon />
+ {postRenderReady && (
+ <Suspense>
+ <DynamicFavicon />
+ </Suspense>
+ )}
<GroupWizardProvider>
<DragUploadProvider>
<LazyMotion features={domMax}>
@@ -90,11 +88,11 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
</LobeAnalyticsProviderWrapper>
</StyleProvider>
</TooltipGroup>
+ <ModalHost />
+ <BaseModalHost />
+ <ToastHost />
+ <ContextMenuHost />
<Suspense>
- <ModalHost />
- <BaseModalHost />
- <ToastHost />
- <ContextMenuHost />
<ImperativeMountHost />
</Suspense>
</LazyMotion>
diff --git a/src/routes/(main)/(create)/image/_layout/Sidebar/index.tsx b/src/routes/(main)/(create)/image/_layout/Sidebar/index.tsx
index b4948b617fd..271bc7c50ad 100644
--- a/src/routes/(main)/(create)/image/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/(create)/image/_layout/Sidebar/index.tsx
@@ -2,7 +2,7 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import ImageSidebarContent from './Content';
diff --git a/src/routes/(main)/(create)/video/_layout/Sidebar/Content.tsx b/src/routes/(main)/(create)/video/_layout/Sidebar/Content.tsx
index ec5b10fd5b4..5a10b6e2fc2 100644
--- a/src/routes/(main)/(create)/video/_layout/Sidebar/Content.tsx
+++ b/src/routes/(main)/(create)/video/_layout/Sidebar/Content.tsx
@@ -16,7 +16,7 @@ const useVideoSidebarProps = (): GenerationLayoutCommonProps => {
breadcrumb: [{ href: '/video', title: t('tab.video') }],
generationTopicsSelector: generationTopicSelectors.generationTopics,
namespace: 'video',
- navKey: 'image',
+ navKey: 'video',
useStore: useVideoStore,
viewModeStatusKey: 'videoTopicViewMode',
};
diff --git a/src/routes/(main)/(create)/video/_layout/Sidebar/index.tsx b/src/routes/(main)/(create)/video/_layout/Sidebar/index.tsx
index bb2c640269f..ea4ecaf30b6 100644
--- a/src/routes/(main)/(create)/video/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/(create)/video/_layout/Sidebar/index.tsx
@@ -2,12 +2,12 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import VideoSidebarContent from './Content';
const Sidebar = memo(() => (
- <NavPanelPortal navKey="image">
+ <NavPanelPortal navKey="video">
<VideoSidebarContent />
</NavPanelPortal>
));
diff --git a/src/routes/(main)/agent/features/routeMeta.ts b/src/routes/(main)/agent/features/routeMeta.ts
index af4a97c9a07..a6cfea4ce47 100644
--- a/src/routes/(main)/agent/features/routeMeta.ts
+++ b/src/routes/(main)/agent/features/routeMeta.ts
@@ -1,54 +1,14 @@
import { MessageSquare, MessagesSquareIcon } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
+import { lazy } from 'react';
-import { usePublishDynamicRouteMeta } from '@/features/RouteMeta/usePublishDynamicRouteMeta';
-import { matchesRouteWorkspace, useRouteWorkspaceId } from '@/features/RouteMeta/workspaceScope';
-import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';
import { routeMeta } from '@/spa/router/routeMeta';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
-import { useChatStore } from '@/store/chat';
-import { topicMapKey } from '@/store/chat/utils/topicMapKey';
-const useTopicTitle = (
- agentId: string | undefined,
- topicId: string | undefined,
- routeWorkspaceId: string | null | undefined,
-): string | undefined =>
- useChatStore((s) => {
- if (!agentId || !topicId || routeWorkspaceId === undefined) return undefined;
-
- const topic = s.topicDataMap[topicMapKey({ agentId })]?.items?.find(
- (item) => item.id === topicId,
- );
- return topic?.title || undefined;
- });
-
-const AgentDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
- const routeWorkspaceId = useRouteWorkspaceId(params);
- const meta = useAgentStore((s) => {
- const agentId = params.aid ?? '';
- const agent = s.agentMap[agentId];
-
- if (!matchesRouteWorkspace(agent?.workspaceId, routeWorkspaceId)) return {};
-
- return agentSelectors.getAgentMetaById(agentId)(s);
- });
- const topicTitle = useTopicTitle(params.aid, params.topicId ?? params.topic, routeWorkspaceId);
- const hasMeta = Object.keys(meta).length > 0;
- const agentTitle = hasMeta ? meta.title : undefined;
-
- usePublishDynamicRouteMeta(
- {
- avatar: meta.avatar,
- backgroundColor: meta.backgroundColor,
- title: [topicTitle, agentTitle].filter(Boolean).join(' Β· ') || undefined,
- },
- onResolve,
- );
-
- return null;
-};
+const AgentDynamicMeta = lazy(() => import('@/features/RouteMeta/AgentDynamicMeta'));
+const TopicsDynamicMeta = lazy(() =>
+ import('@/features/RouteMeta/AgentDynamicMeta').then((module) => ({
+ default: module.TopicsDynamicMeta,
+ })),
+);
export const agentRouteMeta = routeMeta({
DynamicMeta: AgentDynamicMeta,
@@ -56,32 +16,6 @@ export const agentRouteMeta = routeMeta({
titleKey: 'navigation.chat',
});
-const TopicsDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
- const { t } = useTranslation('electron');
- const routeWorkspaceId = useRouteWorkspaceId(params);
- const meta = useAgentStore((s) => {
- const agentId = params.aid ?? '';
- const agent = s.agentMap[agentId];
-
- if (!matchesRouteWorkspace(agent?.workspaceId, routeWorkspaceId)) return {};
-
- return agentSelectors.getAgentMetaById(agentId)(s);
- });
- const hasMeta = Object.keys(meta).length > 0;
- const agentTitle = hasMeta ? meta.title : undefined;
-
- usePublishDynamicRouteMeta(
- {
- avatar: meta.avatar,
- backgroundColor: meta.backgroundColor,
- title: [t('navigation.topics'), agentTitle].filter(Boolean).join(' Β· ') || undefined,
- },
- onResolve,
- );
-
- return null;
-};
-
export const topicsRouteMeta = routeMeta({
DynamicMeta: TopicsDynamicMeta,
icon: MessagesSquareIcon,
diff --git a/src/routes/(main)/community/_layout/Sidebar/index.tsx b/src/routes/(main)/community/_layout/Sidebar/index.tsx
index caf9740236a..a2fb8bb3e3d 100644
--- a/src/routes/(main)/community/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/community/_layout/Sidebar/index.tsx
@@ -1,6 +1,6 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import Content from './Content';
diff --git a/src/routes/(main)/eval/_layout/Sidebar/index.tsx b/src/routes/(main)/eval/_layout/Sidebar/index.tsx
index fe5fd4aed42..a9c75d30107 100644
--- a/src/routes/(main)/eval/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/eval/_layout/Sidebar/index.tsx
@@ -2,7 +2,7 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import EvalSidebarContent from './Content';
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/index.tsx
index c643af4f04f..30d731b03dc 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/_layout/Sidebar/index.tsx
@@ -2,7 +2,7 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import SideBarLayout from '@/features/NavPanel/SideBarLayout';
import Body from './Body';
diff --git a/src/routes/(main)/group/_layout/Sidebar/index.tsx b/src/routes/(main)/group/_layout/Sidebar/index.tsx
index 8082a0c14ee..1beb02c9e99 100644
--- a/src/routes/(main)/group/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/index.tsx
@@ -1,6 +1,6 @@
import React, { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import GroupSidebarContent from './Content';
diff --git a/src/routes/(main)/group/features/routeMeta.ts b/src/routes/(main)/group/features/routeMeta.ts
index 7ff68b33674..dd32e3292f2 100644
--- a/src/routes/(main)/group/features/routeMeta.ts
+++ b/src/routes/(main)/group/features/routeMeta.ts
@@ -1,48 +1,9 @@
import { Users } from 'lucide-react';
+import { lazy } from 'react';
-import { usePublishDynamicRouteMeta } from '@/features/RouteMeta/usePublishDynamicRouteMeta';
-import { matchesRouteWorkspace, useRouteWorkspaceId } from '@/features/RouteMeta/workspaceScope';
-import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';
import { routeMeta } from '@/spa/router/routeMeta';
-import { useChatStore } from '@/store/chat';
-import { topicMapKey } from '@/store/chat/utils/topicMapKey';
-import { useSessionStore } from '@/store/session';
-import { sessionGroupSelectors } from '@/store/session/slices/sessionGroup/selectors';
-const getWorkspaceId = (item: unknown): string | null | undefined =>
- (item as { workspaceId?: string | null } | undefined)?.workspaceId;
-
-const useTopicTitle = (
- groupId: string | undefined,
- topicId: string | undefined,
- routeWorkspaceId: string | null | undefined,
-): string | undefined =>
- useChatStore((s) => {
- if (!groupId || !topicId || routeWorkspaceId === undefined) return undefined;
-
- const topic = s.topicDataMap[topicMapKey({ groupId })]?.items?.find(
- (item) => item.id === topicId,
- );
- return topic?.title || undefined;
- });
-
-const GroupDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
- const routeWorkspaceId = useRouteWorkspaceId(params);
- const group = useSessionStore((s) => {
- const item = sessionGroupSelectors.getGroupById(params.gid ?? '')(s);
- return matchesRouteWorkspace(getWorkspaceId(item), routeWorkspaceId) ? item : undefined;
- });
- const topicTitle = useTopicTitle(params.gid, params.topicId ?? params.topic, routeWorkspaceId);
-
- usePublishDynamicRouteMeta(
- {
- title: topicTitle || group?.name || undefined,
- },
- onResolve,
- );
-
- return null;
-};
+const GroupDynamicMeta = lazy(() => import('@/features/RouteMeta/GroupDynamicMeta'));
export const groupRouteMeta = routeMeta({
DynamicMeta: GroupDynamicMeta,
diff --git a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.test.tsx b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.test.tsx
index c39fc529f22..059c3a86515 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.test.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.test.tsx
@@ -21,11 +21,13 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
}));
vi.mock('@/components/ChatGroupWizard', () => ({
- ChatGroupWizard: () => null,
+ ChatGroupWizard: ({ open }: { open: boolean }) =>
+ open ? <div>Deferred group wizard</div> : null,
}));
vi.mock('@/components/MemberSelectionModal', () => ({
- MemberSelectionModal: () => null,
+ MemberSelectionModal: ({ open }: { open: boolean }) =>
+ open ? <div>Deferred member selection</div> : null,
}));
vi.mock('@/features/CreatePlatformAgent', () => ({
@@ -106,12 +108,20 @@ vi.mock('./Modals/CreateGroupModal', () => ({
}));
const OpenCreateAgentModalButton = () => {
- const { openCreateModal } = useAgentModal();
+ const { openCreateModal, openGroupWizardModal, openMemberSelectionModal } = useAgentModal();
return (
- <button type="button" onClick={() => openCreateModal('agent')}>
- Open create agent modal
- </button>
+ <>
+ <button type="button" onClick={() => openCreateModal('agent')}>
+ Open create agent modal
+ </button>
+ <button type="button" onClick={() => openGroupWizardModal({})}>
+ Open group wizard
+ </button>
+ <button type="button" onClick={() => openMemberSelectionModal({})}>
+ Open member selection
+ </button>
+ </>
);
};
@@ -136,7 +146,7 @@ describe('AgentModalProvider', () => {
renderProvider();
fireEvent.click(screen.getByText('Open create agent modal'));
- fireEvent.click(screen.getByText('Start Blank'));
+ fireEvent.click(await screen.findByText('Start Blank'));
await waitFor(() => {
expect(mocks.createAgent).toHaveBeenCalledWith({ groupId: undefined });
@@ -150,10 +160,23 @@ describe('AgentModalProvider', () => {
renderProvider();
fireEvent.click(screen.getByText('Open create agent modal'));
- fireEvent.click(screen.getByText('View in Skills'));
+ fireEvent.click(await screen.findByText('View in Skills'));
expect(mocks.navigate).toHaveBeenCalledWith(
'/settings/skill?skill=product-requirements-writer',
);
});
+
+ it('loads deferred selection modals when their interactions request them', async () => {
+ renderProvider();
+
+ expect(screen.queryByText('Deferred group wizard')).not.toBeInTheDocument();
+ expect(screen.queryByText('Deferred member selection')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Open group wizard'));
+ expect(await screen.findByText('Deferred group wizard')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Open member selection'));
+ expect(await screen.findByText('Deferred member selection')).toBeInTheDocument();
+ });
});
diff --git a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
index ea847101634..7eb84589100 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/ModalProvider.tsx
@@ -1,15 +1,21 @@
'use client';
import { AGENT_CHAT_URL } from '@lobechat/const';
-import { type ReactNode, useCallback } from 'react';
-import { createContext, memo, use, useMemo, useState } from 'react';
+import {
+ createContext,
+ lazy,
+ memo,
+ type ReactNode,
+ Suspense,
+ use,
+ useCallback,
+ useMemo,
+ useState,
+} from 'react';
-import { ChatGroupWizard } from '@/components/ChatGroupWizard';
-import { MemberSelectionModal } from '@/components/MemberSelectionModal';
import { openCreatePlatformAgentModal } from '@/features/CreatePlatformAgent';
import EditingPopover from '@/features/EditingPopover';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { CreateAgentModal } from '@/routes/(main)/home/_layout/hooks/useCreateModal';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useGlobalStore } from '@/store/global';
@@ -18,6 +24,24 @@ import { useHomeStore } from '@/store/home';
import ConfigGroupModal from './Modals/ConfigGroupModal';
import CreateGroupModal from './Modals/CreateGroupModal';
+const CreateAgentModal = lazy(() =>
+ import('@/routes/(main)/home/_layout/hooks/useCreateModal').then((module) => ({
+ default: module.CreateAgentModal,
+ })),
+);
+
+const ChatGroupWizard = lazy(() =>
+ import('@/components/ChatGroupWizard').then((module) => ({
+ default: module.ChatGroupWizard,
+ })),
+);
+
+const MemberSelectionModal = lazy(() =>
+ import('@/components/MemberSelectionModal').then((module) => ({
+ default: module.MemberSelectionModal,
+ })),
+);
+
interface OpenCreateModalOptions {
groupId?: string;
/**
@@ -223,13 +247,17 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
return (
<AgentModalContext value={contextValue}>
- <CreateModalRenderer
- groupId={createModalGroupId}
- open={createModalOpen}
- type={createModalType}
- visibility={createModalVisibility}
- onClose={() => setCreateModalOpen(false)}
- />
+ {createModalOpen && (
+ <Suspense fallback={null}>
+ <CreateModalRenderer
+ open
+ groupId={createModalGroupId}
+ type={createModalType}
+ visibility={createModalVisibility}
+ onClose={() => setCreateModalOpen(false)}
+ />
+ </Suspense>
+ )}
{children}
{/* All modals rendered at top level */}
@@ -248,32 +276,40 @@ export const AgentModalProvider = memo<AgentModalProviderProps>(({ children }) =
onCancel={() => setConfigGroupModalOpen(false)}
/>
- <ChatGroupWizard
- isCreatingFromTemplate={groupWizardLoading}
- open={groupWizardOpen}
- onCancel={() => {
- groupWizardCallbacks.onCancel?.();
- setGroupWizardOpen(false);
- }}
- onCreateCustom={async (selectedAgents: string[]) => {
- await groupWizardCallbacks.onCreateCustom?.(selectedAgents);
- }}
- onCreateFromTemplate={async (templateId: string, selectedMemberTitles?: string[]) => {
- await groupWizardCallbacks.onCreateFromTemplate?.(templateId, selectedMemberTitles);
- }}
- />
+ {groupWizardOpen && (
+ <Suspense fallback={null}>
+ <ChatGroupWizard
+ open
+ isCreatingFromTemplate={groupWizardLoading}
+ onCancel={() => {
+ groupWizardCallbacks.onCancel?.();
+ setGroupWizardOpen(false);
+ }}
+ onCreateCustom={async (selectedAgents: string[]) => {
+ await groupWizardCallbacks.onCreateCustom?.(selectedAgents);
+ }}
+ onCreateFromTemplate={async (templateId: string, selectedMemberTitles?: string[]) => {
+ await groupWizardCallbacks.onCreateFromTemplate?.(templateId, selectedMemberTitles);
+ }}
+ />
+ </Suspense>
+ )}
- <MemberSelectionModal
- mode="create"
- open={memberSelectionOpen}
- onCancel={() => {
- memberSelectionCallbacks.onCancel?.();
- setMemberSelectionOpen(false);
- }}
- onConfirm={async (selectedAgents: string[]) => {
- await memberSelectionCallbacks.onConfirm?.(selectedAgents);
- }}
- />
+ {memberSelectionOpen && (
+ <Suspense fallback={null}>
+ <MemberSelectionModal
+ open
+ mode="create"
+ onCancel={() => {
+ memberSelectionCallbacks.onCancel?.();
+ setMemberSelectionOpen(false);
+ }}
+ onConfirm={async (selectedAgents: string[]) => {
+ await memberSelectionCallbacks.onConfirm?.(selectedAgents);
+ }}
+ />
+ </Suspense>
+ )}
<EditingPopover />
</AgentModalContext>
diff --git a/src/routes/(main)/home/_layout/Footer/index.tsx b/src/routes/(main)/home/_layout/Footer/index.tsx
index 03494515fcf..26ef63c123d 100644
--- a/src/routes/(main)/home/_layout/Footer/index.tsx
+++ b/src/routes/(main)/home/_layout/Footer/index.tsx
@@ -29,7 +29,7 @@ import HighlightNotification from '@/components/HighlightNotification';
import { DOCUMENTS_REFER_URL, GITHUB } from '@/const/url';
import Billboard from '@/features/Billboard';
import { useBillboardMenuItems } from '@/features/Billboard/MenuItems';
-import { useActiveNavKey } from '@/features/NavPanel';
+import { useActiveNavKey } from '@/features/NavPanel/useActiveNavKey';
import ThemeButton from '@/features/User/UserPanel/ThemeButton';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useNavLayout } from '@/hooks/useNavLayout';
diff --git a/src/routes/(main)/home/_layout/Header/components/User.tsx b/src/routes/(main)/home/_layout/Header/components/User.tsx
index a998493e47e..20083f187e4 100644
--- a/src/routes/(main)/home/_layout/Header/components/User.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/User.tsx
@@ -7,13 +7,12 @@ import { memo } from 'react';
import { useActiveIdentity } from '@/business/client/hooks/useActiveIdentity';
import { ProductLogo } from '@/components/Branding';
+import { USER_DROPDOWN_ICON_ID } from '@/features/NavPanel/constants';
import UserAvatar from '@/features/User/UserAvatar';
import UserPanel from '@/features/User/UserPanel';
import { useUserStore } from '@/store/user';
import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
-export const USER_DROPDOWN_ICON_ID = 'user-dropdown-icon';
-
// The dropdown is a button surface, not selectable text. Without
// `user-select: none` a triple-click (or click-drag through the avatar /
// name) paints the system text-selection highlight across the whole row;
diff --git a/src/routes/(main)/home/_layout/Sidebar.tsx b/src/routes/(main)/home/_layout/Sidebar.tsx
index a78b3e7c401..4a5a24559b7 100644
--- a/src/routes/(main)/home/_layout/Sidebar.tsx
+++ b/src/routes/(main)/home/_layout/Sidebar.tsx
@@ -1,30 +1,16 @@
import { memo } from 'react';
-import { useLocation } from 'react-router';
-import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import SidebarContent from './SidebarContent';
-const Sidebar = memo(() => {
- const { pathname } = useLocation();
- const activeSlug = useActiveWorkspaceSlug();
-
- // DesktopHomeLayout stays mounted via React 19 <Activity> on non-home routes,
- // so this Sidebar also stays mounted. Without this gate, its NavPanelPortal
- // would keep racing the active route's portal (e.g. workspace settings) for
- // the global snapshot and could overwrite it on re-render.
- const isHomeRoute =
- pathname === '/' ||
- (!!activeSlug && (pathname === `/${activeSlug}` || pathname === `/${activeSlug}/`));
-
- if (!isHomeRoute) return null;
-
- return (
- <NavPanelPortal navKey="home">
- <SidebarContent />
- </NavPanelPortal>
- );
-});
+// Home stays registered while React Activity keeps its layout alive. NavPanelHost
+// selects content by pathname, so a Home update can no longer overwrite the
+// currently active route's entry.
+const Sidebar = memo(() => (
+ <NavPanelPortal navKey="home">
+ <SidebarContent />
+ </NavPanelPortal>
+));
export default Sidebar;
diff --git a/src/routes/(main)/home/_layout/index.tsx b/src/routes/(main)/home/_layout/index.tsx
index 6da349fc6f2..68e860b9d44 100644
--- a/src/routes/(main)/home/_layout/index.tsx
+++ b/src/routes/(main)/home/_layout/index.tsx
@@ -38,33 +38,39 @@ const Layout: FC<LayoutProps> = ({ children }) => {
[theme.colorBgContainerSecondary],
);
- if (!hasActivated) return null;
+ // Register the Home sidebar even on a cold deep link. Routes without a
+ // dedicated sidebar (for example /tasks) intentionally use the Home entry.
+ if (!hasActivated) return <Sidebar />;
- // Keep the Home layout alive and render it offscreen when inactive.
+ // Keep the Home layout alive and render it offscreen when inactive. The
+ // Portal stays outside Activity so its registry entry remains available to
+ // routes that intentionally reuse Home navigation (for example /tasks).
return (
- <Activity mode={isHomeRoute ? 'visible' : 'hidden'} name="DesktopHomeLayout">
- {/* `position: absolute; inset: 0` keeps overlaying the outlet when Activity is hidden,
- because Activity preserves state but doesn't visually hide the DOM. Force-hide here. */}
- <Flexbox
- className={styles.absoluteContainer}
- height={'100%'}
- style={isHomeRoute ? undefined : { display: 'none' }}
- width={'100%'}
- >
- <Sidebar />
+ <>
+ <Sidebar />
+ <Activity mode={isHomeRoute ? 'visible' : 'hidden'} name="DesktopHomeLayout">
+ {/* `position: absolute; inset: 0` keeps overlaying the outlet when Activity is hidden,
+ because Activity preserves state but doesn't visually hide the DOM. Force-hide here. */}
<Flexbox
- className={isDarkMode ? styles.contentDark : styles.contentLight}
- flex={1}
+ className={styles.absoluteContainer}
height={'100%'}
- style={cssVariables}
+ style={isHomeRoute ? undefined : { display: 'none' }}
+ width={'100%'}
>
- {content}
- </Flexbox>
+ <Flexbox
+ className={isDarkMode ? styles.contentDark : styles.contentLight}
+ flex={1}
+ height={'100%'}
+ style={cssVariables}
+ >
+ {content}
+ </Flexbox>
- <HomeAgentIdSync />
- <RecentHydration />
- </Flexbox>
- </Activity>
+ <HomeAgentIdSync />
+ <RecentHydration />
+ </Flexbox>
+ </Activity>
+ </>
);
};
diff --git a/src/routes/(main)/home/features/InputArea/EditorInput.tsx b/src/routes/(main)/home/features/InputArea/EditorInput.tsx
new file mode 100644
index 00000000000..e9c32438fba
--- /dev/null
+++ b/src/routes/(main)/home/features/InputArea/EditorInput.tsx
@@ -0,0 +1,75 @@
+import { memo, type ReactNode, useMemo } from 'react';
+
+import {
+ type ActionKeys,
+ ChatInputProvider,
+ DesktopChatInput,
+ type SendButtonHandler,
+} from '@/features/ChatInput';
+import { useChatStore } from '@/store/chat';
+
+import { HOME_INPUT_BODY_HEIGHT } from './constants';
+
+const leftActions: ActionKeys[] = ['agentMode', 'plus'];
+const rightActions: ActionKeys[] = ['modelLabel'];
+
+export interface HomeEditorInputProps {
+ agentId?: string;
+ initialValue: string;
+ isAgentConfigLoading: boolean;
+ loading: boolean;
+ onValueChange: (value: string) => void;
+ placeholder?: ReactNode;
+ send: SendButtonHandler;
+}
+
+const HomeEditorInput = memo<HomeEditorInputProps>(
+ ({ agentId, initialValue, isAgentConfigLoading, loading, onValueChange, placeholder, send }) => {
+ const inputContainerProps = useMemo(
+ () => ({
+ minHeight: HOME_INPUT_BODY_HEIGHT,
+ resize: false,
+ style: {
+ borderRadius: 20,
+ boxShadow: '0 12px 32px rgba(0,0,0,.04)',
+ },
+ }),
+ [],
+ );
+
+ return (
+ <ChatInputProvider
+ agentId={agentId}
+ allowExpand={false}
+ leftActions={leftActions}
+ rightActions={rightActions}
+ slashPlacement="bottom"
+ chatInputEditorRef={(instance) => {
+ if (!instance) return;
+ useChatStore.setState({ mainInputEditor: instance });
+ }}
+ sendButtonProps={{
+ disabled: loading || isAgentConfigLoading,
+ generating: loading,
+ onStop: () => {},
+ shape: 'round',
+ }}
+ onMarkdownContentChange={onValueChange}
+ onSend={send}
+ >
+ <DesktopChatInput
+ dropdownPlacement="bottomLeft"
+ initialContent={initialValue}
+ inputContainerProps={inputContainerProps}
+ isConfigLoading={isAgentConfigLoading}
+ placeholder={placeholder}
+ showControlBar={false}
+ />
+ </ChatInputProvider>
+ );
+ },
+);
+
+HomeEditorInput.displayName = 'HomeEditorInput';
+
+export default HomeEditorInput;
diff --git a/src/routes/(main)/home/features/InputArea/EditorSlot.desktop.tsx b/src/routes/(main)/home/features/InputArea/EditorSlot.desktop.tsx
new file mode 100644
index 00000000000..885989534af
--- /dev/null
+++ b/src/routes/(main)/home/features/InputArea/EditorSlot.desktop.tsx
@@ -0,0 +1,5 @@
+import type { HomeEditorInputProps } from './EditorInput';
+import EditorInput from './EditorInput';
+
+/** Electron loads the renderer from the local app package, so the Home editor is available eagerly. */
+export const EditorSlot = (props: HomeEditorInputProps) => <EditorInput {...props} />;
diff --git a/src/routes/(main)/home/features/InputArea/EditorSlot.tsx b/src/routes/(main)/home/features/InputArea/EditorSlot.tsx
new file mode 100644
index 00000000000..ffbb06f8cf1
--- /dev/null
+++ b/src/routes/(main)/home/features/InputArea/EditorSlot.tsx
@@ -0,0 +1,31 @@
+import type { CompositionEventHandler } from 'react';
+
+import type { HomeEditorInputProps } from './EditorInput';
+import { getFallbackPlaceholder } from './getFallbackPlaceholder';
+import InputFallback from './InputFallback';
+import { useProgressiveEditor } from './useProgressiveEditor';
+
+export const EditorSlot = (props: HomeEditorInputProps) => {
+ const { initialValue, onValueChange, placeholder } = props;
+ const { EditorInput, canRenderEditor, endComposition, startComposition } = useProgressiveEditor();
+ const fallbackPlaceholder = getFallbackPlaceholder(placeholder);
+
+ const handleCompositionEnd: CompositionEventHandler<HTMLTextAreaElement> = (event) => {
+ // The final IME value can land on compositionend before React dispatches
+ // the corresponding change event. Capture it before replacing the textarea.
+ onValueChange(event.currentTarget.value);
+ endComposition();
+ };
+
+ if (canRenderEditor && EditorInput) return <EditorInput {...props} />;
+
+ return (
+ <InputFallback
+ placeholder={fallbackPlaceholder}
+ value={initialValue}
+ onCompositionEnd={handleCompositionEnd}
+ onCompositionStart={startComposition}
+ onValueChange={onValueChange}
+ />
+ );
+};
diff --git a/src/routes/(main)/home/features/InputArea/InputFallback.tsx b/src/routes/(main)/home/features/InputArea/InputFallback.tsx
new file mode 100644
index 00000000000..ce8e28d4488
--- /dev/null
+++ b/src/routes/(main)/home/features/InputArea/InputFallback.tsx
@@ -0,0 +1,131 @@
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { type ChangeEventHandler, type CompositionEventHandler, memo } from 'react';
+
+import {
+ HOME_INPUT_ACTION_BAR_HEIGHT,
+ HOME_INPUT_BOTTOM_PADDING,
+ HOME_INPUT_FRAME_HEIGHT,
+} from './constants';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ actionBar: css`
+ flex: none;
+
+ box-sizing: border-box;
+ width: 100%;
+ height: ${HOME_INPUT_ACTION_BAR_HEIGHT}px;
+ padding-block: 4px;
+ padding-inline: 8px;
+ `,
+ frame: css`
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+
+ box-sizing: border-box;
+ width: 100%;
+ height: ${HOME_INPUT_FRAME_HEIGHT}px;
+ border: 1px solid ${cssVar.colorFill};
+ border-radius: 20px;
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow: 0 12px 32px rgb(0 0 0 / 4%);
+ `,
+ root: css`
+ box-sizing: border-box;
+ width: 100%;
+ height: ${HOME_INPUT_FRAME_HEIGHT + HOME_INPUT_BOTTOM_PADDING}px;
+ padding-block-end: ${HOME_INPUT_BOTTOM_PADDING}px;
+ `,
+ textarea: css`
+ resize: none;
+
+ display: block;
+ flex: 1;
+
+ box-sizing: border-box;
+ width: 100%;
+ min-height: 0;
+ padding-block: 8px 0;
+ padding-inline: 12px;
+ border: 0;
+
+ font-family: inherit;
+ font-size: 14px;
+ line-height: 1.4;
+ color: ${cssVar.colorText};
+
+ background: transparent;
+ outline: 0;
+
+ &::placeholder {
+ color: ${cssVar.colorTextPlaceholder};
+ }
+ `,
+}));
+
+interface InputFallbackProps {
+ onCompositionEnd: CompositionEventHandler<HTMLTextAreaElement>;
+ onCompositionStart: CompositionEventHandler<HTMLTextAreaElement>;
+ onValueChange: (value: string) => void;
+ placeholder?: string;
+ value: string;
+}
+
+const InputFallback = memo<InputFallbackProps>(
+ ({ onCompositionEnd, onCompositionStart, onValueChange, placeholder, value }) => {
+ const handleChange: ChangeEventHandler<HTMLTextAreaElement> = (event) => {
+ onValueChange(event.currentTarget.value);
+ };
+
+ return (
+ <div aria-busy className={styles.root} data-testid="home-input-fallback">
+ <div className={styles.frame}>
+ <textarea
+ autoFocus
+ aria-label={placeholder}
+ className={styles.textarea}
+ placeholder={placeholder}
+ value={value}
+ onChange={handleChange}
+ onCompositionEnd={onCompositionEnd}
+ onCompositionStart={onCompositionStart}
+ />
+ <Flexbox
+ aria-hidden
+ horizontal
+ align="center"
+ className={styles.actionBar}
+ justify="space-between"
+ >
+ <Flexbox horizontal align="center" gap={6}>
+ <Skeleton.Button
+ active
+ shape="circle"
+ size="small"
+ style={{ height: 28, minWidth: 28, width: 28 }}
+ />
+ <Skeleton.Button
+ active
+ shape="circle"
+ size="small"
+ style={{ height: 28, minWidth: 28, width: 28 }}
+ />
+ </Flexbox>
+ <Skeleton.Button
+ active
+ shape="round"
+ size="small"
+ style={{ height: 32, minWidth: 64, width: 64 }}
+ />
+ </Flexbox>
+ </div>
+ </div>
+ );
+ },
+);
+
+InputFallback.displayName = 'InputFallback';
+
+export default InputFallback;
diff --git a/src/routes/(main)/home/features/InputArea/StarterList.tsx b/src/routes/(main)/home/features/InputArea/StarterList.tsx
index e6a0352878c..b5f35f246c1 100644
--- a/src/routes/(main)/home/features/InputArea/StarterList.tsx
+++ b/src/routes/(main)/home/features/InputArea/StarterList.tsx
@@ -1,9 +1,10 @@
-import { ModelIcon } from '@lobehub/icons';
+import { Jimeng, Moonshot, OpenAI, ZAI } from '@lobehub/icons';
import { Center, Skeleton, Tag, Tooltip } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { createStaticStyles, cx } from 'antd-style';
-import { memo, useCallback, useState } from 'react';
+import { Bot } from 'lucide-react';
+import { type ComponentType, memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -20,6 +21,7 @@ import { agentByIdSelectors } from '@/store/agent/selectors';
import { useResolvedHomeAgentId } from '../AgentSelect/useResolvedHomeAgentId';
import { trackHomeModelShortcutClicked } from './starterListAnalytics';
+import { NEW_GLM_MODEL, NEW_IMAGE_MODEL, NEW_KIMI_MODEL, NEW_VIDEO_MODEL } from './starterModels';
import { useStarterModelDefaults } from './useStarterModelDefaults';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -47,6 +49,12 @@ const getStarterItemKey = (item: HomeNewModelItem) => `${item.type}:${item.model
const getStarterItemProvider = (item: HomeNewModelItem, fallbackProvider: string) =>
item.provider ?? fallbackProvider;
const skeletonWidths = [112, 150, 126, 138];
+const starterModelIcons: Record<string, ComponentType<{ size: number }>> = {
+ [NEW_GLM_MODEL]: ZAI.Avatar,
+ [NEW_IMAGE_MODEL]: OpenAI.Avatar,
+ [NEW_KIMI_MODEL]: Moonshot.Avatar,
+ [NEW_VIDEO_MODEL]: Jimeng.Avatar,
+};
const StarterList = memo(() => {
const { t } = useTranslation('home');
@@ -158,11 +166,12 @@ const StarterList = memo(() => {
: items.map((item) => {
const key = getStarterItemKey(item);
const isSwitching = switchingKey === key;
+ const StarterModelIcon = starterModelIcons[item.iconModel ?? item.model] ?? Bot;
const button = (
<Button
className={cx(styles.button)}
disabled={!canCreateContent || (!!switchingKey && !isSwitching)}
- icon={<ModelIcon model={item.iconModel ?? item.model} size={18} />}
+ icon={<StarterModelIcon size={18} />}
key={key}
loading={isSwitching}
shape={'round'}
diff --git a/src/routes/(main)/home/features/InputArea/constants.ts b/src/routes/(main)/home/features/InputArea/constants.ts
new file mode 100644
index 00000000000..37086af15f7
--- /dev/null
+++ b/src/routes/(main)/home/features/InputArea/constants.ts
@@ -0,0 +1,6 @@
+export const HOME_INPUT_BODY_HEIGHT = 88;
+export const HOME_INPUT_ACTION_BAR_HEIGHT = 40;
+// The rich ChatInput adds a one-pixel border on both block edges.
+export const HOME_INPUT_FRAME_HEIGHT = HOME_INPUT_BODY_HEIGHT + HOME_INPUT_ACTION_BAR_HEIGHT + 2;
+export const HOME_INPUT_BOTTOM_PADDING = 8;
+export const HOME_INPUT_RESERVED_HEIGHT = HOME_INPUT_FRAME_HEIGHT + HOME_INPUT_BOTTOM_PADDING;
diff --git a/src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.test.ts b/src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.test.ts
new file mode 100644
index 00000000000..a9e1acb4c24
--- /dev/null
+++ b/src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+
+import { getFallbackPlaceholder } from './getFallbackPlaceholder';
+
+describe('getFallbackPlaceholder', () => {
+ it('preserves text placeholders accepted by a native textarea', () => {
+ expect(getFallbackPlaceholder('Ask anything')).toBe('Ask anything');
+ });
+
+ it('omits rich placeholders that only the hydrated editor can render', () => {
+ expect(getFallbackPlaceholder(42)).toBeUndefined();
+ });
+});
diff --git a/src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.ts b/src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.ts
new file mode 100644
index 00000000000..bc42ddacf9c
--- /dev/null
+++ b/src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.ts
@@ -0,0 +1,5 @@
+import type { ReactNode } from 'react';
+
+/** Native textarea placeholders only accept text; rich editor placeholders render after hydration. */
+export const getFallbackPlaceholder = (placeholder: ReactNode): string | undefined =>
+ typeof placeholder === 'string' ? placeholder : undefined;
diff --git a/src/routes/(main)/home/features/InputArea/index.tsx b/src/routes/(main)/home/features/InputArea/index.tsx
index 0d780b0e125..0d796a1fcc8 100644
--- a/src/routes/(main)/home/features/InputArea/index.tsx
+++ b/src/routes/(main)/home/features/InputArea/index.tsx
@@ -1,9 +1,8 @@
import { Flexbox } from '@lobehub/ui';
-import { useMemo, useRef } from 'react';
+import { createStaticStyles } from 'antd-style';
+import { useCallback, useRef, useState } from 'react';
import { useUploadFiles } from '@/components/DragUploadZone';
-import { type ActionKeys } from '@/features/ChatInput';
-import { ChatInputProvider, DesktopChatInput } from '@/features/ChatInput';
import { useHomeDailyBrief } from '@/hooks/useHomeDailyBrief';
import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
import { useAgentStore } from '@/store/agent';
@@ -12,14 +11,20 @@ import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { HOME_INPUT_RESERVED_HEIGHT } from './constants';
+import { EditorSlot } from './EditorSlot';
import { stripMarkdownLinks } from './hintFormat';
import InputDragUpload from './InputDragUpload';
import MessengerBanner, { MESSENGER_BANNER_ID } from './MessengerBanner';
import StarterList from './StarterList';
import { useSend } from './useSend';
-const leftActions: ActionKeys[] = ['agentMode', 'plus'];
-const rightActions: ActionKeys[] = ['modelLabel'];
+const styles = createStaticStyles(({ css }) => ({
+ inputSlot: css`
+ width: 100%;
+ min-height: ${HOME_INPUT_RESERVED_HEIGHT}px;
+ `,
+}));
const InputArea = () => {
const { loading, send, agentId } = useSend();
@@ -41,6 +46,7 @@ const InputArea = () => {
// the banner never see it flash on mount.
const isStatusInit = useGlobalStore(systemStatusSelectors.isStatusInit);
const chatInputRef = useRef<HTMLDivElement>(null);
+ const [inputValue, setInputValue] = useState('');
const showMessengerBanner = isStatusInit && !isMessengerBannerDismissed;
@@ -54,26 +60,17 @@ const InputArea = () => {
);
const { handleUploadFiles } = useUploadFiles({ agentId: resolvedAgentId, model, provider });
- // A slot to insert content above the chat input
- // Override some default behavior of the chat input
- const inputContainerProps = useMemo(
- () => ({
- minHeight: 88,
- resize: false,
- style: {
- borderRadius: 20,
- boxShadow: '0 12px 32px rgba(0,0,0,.04)',
- },
- }),
- [],
- );
-
// Daily-generated input hint paired with the home WelcomeText. The hint
// tracks whichever pair the WelcomeText typewriter is currently showing,
// via the shared rotating index inside `useHomeDailyBrief`.
const { currentPair } = useHomeDailyBrief();
const dailyHint = currentPair?.hint ? stripMarkdownLinks(currentPair.hint) : undefined;
+ const handleValueChange = useCallback((value: string) => {
+ setInputValue(value);
+ useChatStore.setState({ inputMessage: value });
+ }, []);
+
return (
<Flexbox gap={16} style={{ marginBottom: 16 }}>
<Flexbox
@@ -86,35 +83,17 @@ const InputArea = () => {
style={{ position: 'relative', zIndex: 1 }}
onUploadFiles={handleUploadFiles}
>
- <ChatInputProvider
- agentId={agentId}
- allowExpand={false}
- leftActions={leftActions}
- rightActions={rightActions}
- slashPlacement="bottom"
- chatInputEditorRef={(instance) => {
- if (!instance) return;
- useChatStore.setState({ mainInputEditor: instance });
- }}
- sendButtonProps={{
- disabled: loading || isAgentConfigLoading,
- generating: loading,
- onStop: () => {},
- shape: 'round',
- }}
- onSend={send}
- onMarkdownContentChange={(content) => {
- useChatStore.setState({ inputMessage: content });
- }}
- >
- <DesktopChatInput
- dropdownPlacement="bottomLeft"
- inputContainerProps={inputContainerProps}
- isConfigLoading={isAgentConfigLoading}
+ <div className={styles.inputSlot}>
+ <EditorSlot
+ agentId={agentId}
+ initialValue={inputValue}
+ isAgentConfigLoading={isAgentConfigLoading}
+ loading={loading}
placeholder={dailyHint}
- showControlBar={false}
+ send={send}
+ onValueChange={handleValueChange}
/>
- </ChatInputProvider>
+ </div>
</InputDragUpload>
</Flexbox>
diff --git a/src/routes/(main)/home/features/InputArea/useProgressiveEditor.test.ts b/src/routes/(main)/home/features/InputArea/useProgressiveEditor.test.ts
new file mode 100644
index 00000000000..5df79e37bc0
--- /dev/null
+++ b/src/routes/(main)/home/features/InputArea/useProgressiveEditor.test.ts
@@ -0,0 +1,36 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ type HomeEditorInputComponent,
+ type HomeEditorInputLoader,
+ useProgressiveEditor,
+} from './useProgressiveEditor';
+
+describe('useProgressiveEditor', () => {
+ it('waits for an active IME composition before replacing the fallback', async () => {
+ let resolveEditor!: (module: { default: HomeEditorInputComponent }) => void;
+ const loadEditor: HomeEditorInputLoader = vi.fn(
+ () =>
+ new Promise<{ default: HomeEditorInputComponent }>((resolve) => {
+ resolveEditor = resolve;
+ }),
+ );
+ const LoadedEditor: HomeEditorInputComponent = () => null;
+ const { result } = renderHook(() => useProgressiveEditor(loadEditor));
+
+ act(() => result.current.startComposition());
+
+ await act(async () => {
+ resolveEditor({ default: LoadedEditor });
+ await Promise.resolve();
+ });
+
+ expect(result.current.EditorInput).toBe(LoadedEditor);
+ expect(result.current.canRenderEditor).toBe(false);
+
+ act(() => result.current.endComposition());
+
+ expect(result.current.canRenderEditor).toBe(true);
+ });
+});
diff --git a/src/routes/(main)/home/features/InputArea/useProgressiveEditor.ts b/src/routes/(main)/home/features/InputArea/useProgressiveEditor.ts
new file mode 100644
index 00000000000..11ee7f249d7
--- /dev/null
+++ b/src/routes/(main)/home/features/InputArea/useProgressiveEditor.ts
@@ -0,0 +1,42 @@
+import { type ComponentType, startTransition, useEffect, useState } from 'react';
+
+import { type HomeEditorInputProps } from './EditorInput';
+
+export type HomeEditorInputComponent = ComponentType<HomeEditorInputProps>;
+export type HomeEditorInputLoader = () => Promise<{ default: HomeEditorInputComponent }>;
+
+export const loadHomeEditorInput: HomeEditorInputLoader = () => import('./EditorInput');
+
+export const useProgressiveEditor = (
+ loadEditorInput: HomeEditorInputLoader = loadHomeEditorInput,
+) => {
+ const [EditorInput, setEditorInput] = useState<HomeEditorInputComponent>();
+ const [isComposing, setIsComposing] = useState(false);
+
+ useEffect(() => {
+ let active = true;
+
+ void loadEditorInput()
+ .then(({ default: LoadedEditorInput }) => {
+ if (!active) return;
+
+ startTransition(() => {
+ setEditorInput(() => LoadedEditorInput);
+ });
+ })
+ .catch((error) => {
+ if (active) console.error('[HomeInput] Failed to load the rich editor:', error);
+ });
+
+ return () => {
+ active = false;
+ };
+ }, [loadEditorInput]);
+
+ return {
+ EditorInput,
+ canRenderEditor: Boolean(EditorInput) && !isComposing,
+ endComposition: () => setIsComposing(false),
+ startComposition: () => setIsComposing(true),
+ };
+};
diff --git a/src/routes/(main)/memory/_layout/Sidebar/index.tsx b/src/routes/(main)/memory/_layout/Sidebar/index.tsx
index 5e54e968aea..83bb4a97ddc 100644
--- a/src/routes/(main)/memory/_layout/Sidebar/index.tsx
+++ b/src/routes/(main)/memory/_layout/Sidebar/index.tsx
@@ -1,6 +1,6 @@
import React, { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import MemorySidebarContent from './Content';
diff --git a/src/routes/(main)/resource/(home)/_layout/Sidebar.tsx b/src/routes/(main)/resource/(home)/_layout/Sidebar.tsx
index fc00437f0fe..adbdc83b39c 100644
--- a/src/routes/(main)/resource/(home)/_layout/Sidebar.tsx
+++ b/src/routes/(main)/resource/(home)/_layout/Sidebar.tsx
@@ -2,7 +2,7 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import SidebarContent from './SidebarContent';
diff --git a/src/routes/(main)/resource/library/_layout/Sidebar.tsx b/src/routes/(main)/resource/library/_layout/Sidebar.tsx
index 7e4a045813b..0084a94b1b8 100644
--- a/src/routes/(main)/resource/library/_layout/Sidebar.tsx
+++ b/src/routes/(main)/resource/library/_layout/Sidebar.tsx
@@ -2,7 +2,7 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import SideBarLayout from '@/features/NavPanel/SideBarLayout';
import LibraryHierarchy from '@/features/ResourceManager/components/LibraryHierarchy';
diff --git a/src/routes/(main)/settings/_layout/SideBar.tsx b/src/routes/(main)/settings/_layout/SideBar.tsx
index d0246348d37..196dd78163d 100644
--- a/src/routes/(main)/settings/_layout/SideBar.tsx
+++ b/src/routes/(main)/settings/_layout/SideBar.tsx
@@ -2,7 +2,7 @@
import { memo } from 'react';
-import { NavPanelPortal } from '@/features/NavPanel';
+import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import SidebarContent from './SidebarContent';
diff --git a/src/services/_auth.ts b/src/services/_auth.ts
index 8f57378d902..67a35196ff4 100644
--- a/src/services/_auth.ts
+++ b/src/services/_auth.ts
@@ -8,7 +8,7 @@ import {
type VertexAIKeyVault,
} from '@lobechat/types';
import { clientApiKeyManager } from '@lobechat/utils/client';
-import { ModelProvider } from 'model-bank';
+import { ModelProvider } from 'model-bank/modelProvider';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
diff --git a/src/services/aiModel/index.ts b/src/services/aiModel/index.ts
index 4691caa3d43..42c76c55515 100644
--- a/src/services/aiModel/index.ts
+++ b/src/services/aiModel/index.ts
@@ -3,10 +3,10 @@ import {
type AiModelType,
type AiProviderModelListItem,
type CreateAiModelParams,
- isAiModelVisible,
type ToggleAiModelEnableParams,
type UpdateAiModelParams,
} from 'model-bank';
+import { isAiModelVisible } from 'model-bank/aiModel';
import { lambdaClient } from '@/libs/trpc/client';
diff --git a/src/services/chat/helper.ts b/src/services/chat/helper.ts
index eeac11588b9..1b3e3659623 100644
--- a/src/services/chat/helper.ts
+++ b/src/services/chat/helper.ts
@@ -1,5 +1,5 @@
import type { EnabledAiModel } from 'model-bank';
-import { ModelProvider } from 'model-bank';
+import { ModelProvider } from 'model-bank/modelProvider';
import { getAiInfraStoreState } from '@/store/aiInfra';
import { aiProviderSelectors } from '@/store/aiInfra/selectors';
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 423d78d6d69..509b8d27753 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -10,7 +10,8 @@ import { type OfficialToolItem } from '@lobechat/context-engine';
import { type FetchSSEOptions } from '@lobechat/fetch-sse';
import { fetchSSE, standardizeAnimationStyle } from '@lobechat/fetch-sse';
import type { ChatCompletionErrorPayload } from '@lobechat/model-runtime';
-import { AgentRuntimeError, isResponsesAPIModel } from '@lobechat/model-runtime';
+import { isResponsesAPIModel } from '@lobechat/model-runtime/providers/openai/modelId';
+import { AgentRuntimeError } from '@lobechat/model-runtime/utils/createError';
import {
ChatErrorType,
getDisabledPluginIds,
@@ -21,7 +22,7 @@ import {
type UIChatMessage,
} from '@lobechat/types';
import { merge } from 'es-toolkit/compat';
-import { ModelProvider } from 'model-bank';
+import { ModelProvider } from 'model-bank/modelProvider';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
import { getSearchConfig } from '@/helpers/getSearchConfig';
diff --git a/src/services/chat/mecha/clientModelRuntime.ts b/src/services/chat/mecha/clientModelRuntime.ts
index 7b47824ddef..e0885580f17 100644
--- a/src/services/chat/mecha/clientModelRuntime.ts
+++ b/src/services/chat/mecha/clientModelRuntime.ts
@@ -1,5 +1,3 @@
-import { ModelRuntime } from '@lobechat/model-runtime';
-
import { createPayloadWithKeyVaults } from '../../_auth';
export interface InitializeWithClientStoreOptions {
@@ -17,11 +15,13 @@ export interface InitializeWithClientStoreOptions {
*
* **Note**: if you try to fetch directly, use `fetchOnClient` instead.
*/
-export const initializeWithClientStore = ({
+export const initializeWithClientStore = async ({
provider,
runtimeProvider,
payload,
}: InitializeWithClientStoreOptions) => {
+ const { ModelRuntime } = await import('@lobechat/model-runtime');
+
/**
* Since #5267, we map parameters for client-fetch in function `getProviderAuthPayload`
* which called by `createPayloadWithKeyVaults` below.
diff --git a/src/services/chat/mecha/modelParamsResolver.ts b/src/services/chat/mecha/modelParamsResolver.ts
index e6319aa6b0c..3f69a36f2c3 100644
--- a/src/services/chat/mecha/modelParamsResolver.ts
+++ b/src/services/chat/mecha/modelParamsResolver.ts
@@ -1,9 +1,9 @@
-import type { ModelExtendParams } from '@lobechat/model-runtime';
import {
applyModelExtendParams,
+ type ModelExtendParams,
resolveDefaultEnableAdaptiveThinkingForModel,
resolveDefaultThinkingLevelForModel,
-} from '@lobechat/model-runtime';
+} from '@lobechat/model-runtime/utils/modelExtendParams';
import type { LobeAgentChatConfig } from '@lobechat/types';
import { aiModelSelectors, getAiInfraStoreState } from '@/store/aiInfra';
@@ -24,8 +24,8 @@ export interface ModelParamsContext {
* Resolves extended parameters for model runtime based on model capabilities and chat config.
*
* Looks up the model's supported `extendParams` from the aiInfra store, then delegates the
- * actual resolution to the shared `applyModelExtendParams` (in `@lobechat/model-runtime`) so the
- * client chat service and the server-side agent runtime stay in sync.
+ * actual resolution to the shared `applyModelExtendParams` so the client chat service and the
+ * server-side agent runtime stay in sync.
*/
export const resolveModelExtendParams = (ctx: ModelParamsContext): ModelExtendParams => {
const { model, provider, chatConfig } = ctx;
diff --git a/src/services/upload.ts b/src/services/upload.ts
index bb76f7cd3e8..ae0c51d00f5 100644
--- a/src/services/upload.ts
+++ b/src/services/upload.ts
@@ -1,4 +1,4 @@
-import { parseDataUri } from '@lobechat/model-runtime';
+import { parseDataUri } from '@lobechat/model-runtime/utils/uriParser';
import { uuid } from '@lobechat/utils';
import dayjs from 'dayjs';
import { sha256 } from 'js-sha256';
diff --git a/src/spa/atoms/app.test.ts b/src/spa/atoms/app.test.ts
index d30a8a91a5f..a5fa0e3e1b2 100644
--- a/src/spa/atoms/app.test.ts
+++ b/src/spa/atoms/app.test.ts
@@ -20,4 +20,23 @@ describe('appReady', () => {
setAppReady(false);
expect(listener).toHaveBeenCalledTimes(1);
});
+
+ it('publishes post-render readiness independently from core app readiness', async () => {
+ vi.resetModules();
+ const { getAppReady, getPostRenderReady, setPostRenderReady, subscribeAppReady } =
+ await import('./app');
+ const listener = vi.fn();
+ const unsubscribe = subscribeAppReady(listener);
+
+ expect(getAppReady()).toBe(false);
+ expect(getPostRenderReady()).toBe(false);
+
+ setPostRenderReady(true);
+
+ expect(getAppReady()).toBe(false);
+ expect(getPostRenderReady()).toBe(true);
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+ });
});
diff --git a/src/spa/atoms/app.ts b/src/spa/atoms/app.ts
index e145b747120..550519046de 100644
--- a/src/spa/atoms/app.ts
+++ b/src/spa/atoms/app.ts
@@ -1,6 +1,7 @@
import { useSyncExternalStore } from 'react';
let appReady = false;
+let postRenderReady = false;
const listeners = new Set<() => void>();
const emit = () => {
@@ -8,6 +9,7 @@ const emit = () => {
};
export const getAppReady = () => appReady;
+export const getPostRenderReady = () => postRenderReady;
export const setAppReady = (ready: boolean) => {
if (appReady === ready) return;
@@ -16,6 +18,13 @@ export const setAppReady = (ready: boolean) => {
emit();
};
+export const setPostRenderReady = (ready: boolean) => {
+ if (postRenderReady === ready) return;
+
+ postRenderReady = ready;
+ emit();
+};
+
export const subscribeAppReady = (listener: () => void) => {
listeners.add(listener);
return () => {
@@ -24,3 +33,6 @@ export const subscribeAppReady = (listener: () => void) => {
};
export const useAppReady = () => useSyncExternalStore(subscribeAppReady, getAppReady, getAppReady);
+
+export const usePostRenderReady = () =>
+ useSyncExternalStore(subscribeAppReady, getPostRenderReady, getPostRenderReady);
diff --git a/src/spa/initialize/bootstrap.test.ts b/src/spa/initialize/bootstrap.test.ts
new file mode 100644
index 00000000000..b69c27bb4e9
--- /dev/null
+++ b/src/spa/initialize/bootstrap.test.ts
@@ -0,0 +1,42 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ postRenderModuleEvaluated: vi.fn(),
+ toolSurfacesModuleEvaluated: vi.fn(),
+}));
+
+vi.mock('react-dom', () => ({ flushSync: vi.fn((callback: () => void) => callback()) }));
+vi.mock('@/libs/bootMetrics', () => ({ startBootMetricsFinalize: vi.fn() }));
+vi.mock('@/libs/bootTiming', () => ({
+ bootTiming: {
+ mark: vi.fn(),
+ span: vi.fn((_name: string, task: () => Promise<void>) => task()),
+ spanSync: vi.fn((_name: string, task: () => void) => task()),
+ },
+}));
+vi.mock('../atoms/app', () => ({ setAppReady: vi.fn() }));
+vi.mock('.', () => ({ initializeApp: vi.fn().mockResolvedValue(undefined) }));
+vi.mock('./importSettings', () => ({ startImportSettingsFromUrl: vi.fn() }));
+vi.mock('./postRender', () => {
+ mocks.postRenderModuleEvaluated();
+ return { startPostRenderInitialization: vi.fn() };
+});
+vi.mock('./toolSurfaces', () => {
+ mocks.toolSurfacesModuleEvaluated();
+ return { ensureBuiltinToolSurfaces: vi.fn() };
+});
+
+describe('SPA bootstrap imports', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ mocks.postRenderModuleEvaluated.mockClear();
+ mocks.toolSurfacesModuleEvaluated.mockClear();
+ });
+
+ it('keeps idle-only initialization out of the synchronous bootstrap graph', async () => {
+ await import('./bootstrap');
+
+ expect(mocks.postRenderModuleEvaluated).not.toHaveBeenCalled();
+ expect(mocks.toolSurfacesModuleEvaluated).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/spa/initialize/bootstrap.ts b/src/spa/initialize/bootstrap.ts
index 3f6546b0a7b..94995b03de9 100644
--- a/src/spa/initialize/bootstrap.ts
+++ b/src/spa/initialize/bootstrap.ts
@@ -6,18 +6,24 @@ import { bootTiming } from '@/libs/bootTiming';
import { setAppReady } from '../atoms/app';
import { initializeApp } from '.';
import { startImportSettingsFromUrl } from './importSettings';
-import { startPostRenderInitialization } from './postRender';
-import { registerBuiltinToolSurfaces } from './toolSurfaces';
let started = false;
+const loadPostRenderInitialization = async () => {
+ try {
+ const { startPostRenderInitialization } = await import('./postRender');
+ startPostRenderInitialization();
+ } catch (error) {
+ console.error('[SPA Initialize] failed to load post-render initialization', error);
+ }
+};
+
export const startAppInitialization = () => {
if (started) return;
started = true;
// must run synchronously before first React render
bootTiming.spanSync('import-settings', startImportSettingsFromUrl);
- bootTiming.spanSync('tool-surfaces', registerBuiltinToolSurfaces);
void bootTiming
.span('core-init', initializeApp)
@@ -29,7 +35,7 @@ export const startAppInitialization = () => {
setAppReady(true);
});
bootTiming.mark('app-ready');
- startPostRenderInitialization();
+ void loadPostRenderInitialization();
startBootMetricsFinalize();
});
};
diff --git a/src/spa/initialize/postRender.test.ts b/src/spa/initialize/postRender.test.ts
index 81269a5d91b..1adf6c6e4c7 100644
--- a/src/spa/initialize/postRender.test.ts
+++ b/src/spa/initialize/postRender.test.ts
@@ -4,8 +4,16 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
+ ensureBuiltinToolSurfaces: vi.fn().mockResolvedValue(undefined),
registerBuiltinToolExecutors: vi.fn(),
+ setPostRenderReady: vi.fn(),
+ shouldSkipRoutePreload: vi.fn().mockReturnValue(false),
startConnectorInitialization: vi.fn(),
+ startRoutePreload: vi.fn(),
+}));
+
+vi.mock('../atoms/app', () => ({
+ setPostRenderReady: mocks.setPostRenderReady,
}));
vi.mock('@/store/tool/slices/builtin/executors', () => ({
@@ -16,11 +24,21 @@ vi.mock('./connectors', () => ({
startConnectorInitialization: mocks.startConnectorInitialization,
}));
+vi.mock('./routePreload', () => ({
+ shouldSkipRoutePreload: mocks.shouldSkipRoutePreload,
+ startRoutePreload: mocks.startRoutePreload,
+}));
+
+vi.mock('./toolSurfaces', () => ({
+ ensureBuiltinToolSurfaces: mocks.ensureBuiltinToolSurfaces,
+}));
+
describe('startPostRenderInitialization', () => {
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
vi.useFakeTimers();
+ mocks.shouldSkipRoutePreload.mockReturnValue(false);
Object.defineProperty(window, 'requestAnimationFrame', {
configurable: true,
@@ -32,23 +50,32 @@ describe('startPostRenderInitialization', () => {
value: undefined,
writable: true,
});
+ Object.defineProperty(window.navigator, 'connection', {
+ configurable: true,
+ value: undefined,
+ });
});
afterEach(() => {
vi.useRealTimers();
});
- it('defers connector initialization out of the synchronous bootstrap path', async () => {
+ it('runs post-render warmups without preloading builtin executors', async () => {
const { startPostRenderInitialization } = await import('./postRender');
startPostRenderInitialization();
expect(mocks.startConnectorInitialization).not.toHaveBeenCalled();
+ expect(mocks.ensureBuiltinToolSurfaces).not.toHaveBeenCalled();
+ expect(mocks.setPostRenderReady).not.toHaveBeenCalled();
await vi.runAllTimersAsync();
- expect(mocks.registerBuiltinToolExecutors).toHaveBeenCalledTimes(1);
+ expect(mocks.registerBuiltinToolExecutors).not.toHaveBeenCalled();
+ expect(mocks.ensureBuiltinToolSurfaces).toHaveBeenCalledTimes(1);
+ expect(mocks.setPostRenderReady).toHaveBeenCalledWith(true);
expect(mocks.startConnectorInitialization).toHaveBeenCalledTimes(1);
+ expect(mocks.startRoutePreload).toHaveBeenCalledTimes(1);
});
it('starts post-render initialization only once', async () => {
@@ -58,7 +85,22 @@ describe('startPostRenderInitialization', () => {
startPostRenderInitialization();
await vi.runAllTimersAsync();
- expect(mocks.registerBuiltinToolExecutors).toHaveBeenCalledTimes(1);
+ expect(mocks.registerBuiltinToolExecutors).not.toHaveBeenCalled();
+ expect(mocks.ensureBuiltinToolSurfaces).toHaveBeenCalledTimes(1);
+ expect(mocks.setPostRenderReady).toHaveBeenCalledTimes(1);
expect(mocks.startConnectorInitialization).toHaveBeenCalledTimes(1);
+ expect(mocks.startRoutePreload).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not preload builtin tool surfaces when background preloading is disabled', async () => {
+ mocks.shouldSkipRoutePreload.mockReturnValue(true);
+ const { startPostRenderInitialization } = await import('./postRender');
+
+ startPostRenderInitialization();
+ await vi.runAllTimersAsync();
+
+ expect(mocks.ensureBuiltinToolSurfaces).not.toHaveBeenCalled();
+ expect(mocks.setPostRenderReady).toHaveBeenCalledWith(true);
+ expect(mocks.startRoutePreload).toHaveBeenCalledTimes(1);
});
});
diff --git a/src/spa/initialize/postRender.ts b/src/spa/initialize/postRender.ts
index 9bd778c3912..5089011ffe5 100644
--- a/src/spa/initialize/postRender.ts
+++ b/src/spa/initialize/postRender.ts
@@ -1,6 +1,7 @@
-import { registerBuiltinToolExecutors } from '@/store/tool/slices/builtin/executors';
-
+import { setPostRenderReady } from '../atoms/app';
import { startConnectorInitialization } from './connectors';
+import { shouldSkipRoutePreload, startRoutePreload } from './routePreload';
+import { ensureBuiltinToolSurfaces } from './toolSurfaces';
type RequestIdleCallback = (callback: () => void, options?: { timeout?: number }) => number;
@@ -40,11 +41,24 @@ export const startPostRenderInitialization = () => {
postRenderStarted = true;
scheduleAfterFirstPaint(() => {
+ setPostRenderReady(true);
+
+ if (typeof window !== 'undefined' && !shouldSkipRoutePreload(window)) {
+ void ensureBuiltinToolSurfaces().catch((error) => {
+ console.error('[SPA Initialize] builtin tool surface preload failed', error);
+ });
+ }
+
try {
- registerBuiltinToolExecutors();
startConnectorInitialization();
} catch (error) {
console.error('[SPA Initialize] post-render initialization failed', error);
}
+
+ try {
+ startRoutePreload();
+ } catch (error) {
+ console.error('[SPA Initialize] route preload initialization failed', error);
+ }
});
};
diff --git a/src/spa/initialize/routePreload.test.ts b/src/spa/initialize/routePreload.test.ts
new file mode 100644
index 00000000000..c2ddddcd33a
--- /dev/null
+++ b/src/spa/initialize/routePreload.test.ts
@@ -0,0 +1,142 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createRoutePreloadScheduler, type RoutePreloadTask } from './routePreload';
+
+const createTask = (
+ id: string,
+ options: Partial<Pick<RoutePreloadTask, 'idleDelay' | 'matches' | 'priority'>> = {},
+) => ({
+ id,
+ idleDelay: options.idleDelay ?? 0,
+ load: vi.fn().mockResolvedValue(undefined),
+ matches: options.matches ?? (() => false),
+ priority: options.priority ?? ('medium' as const),
+});
+
+describe('createRoutePreloadScheduler', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ window.history.replaceState({}, '', '/agent');
+
+ Object.defineProperty(document, 'hidden', {
+ configurable: true,
+ value: false,
+ });
+ Object.defineProperty(window.navigator, 'connection', {
+ configurable: true,
+ value: undefined,
+ });
+ Object.defineProperty(window, 'requestIdleCallback', {
+ configurable: true,
+ value: undefined,
+ writable: true,
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('preloads eligible routes one at a time in priority order', async () => {
+ const executionOrder: string[] = [];
+ const low = createTask('low', { priority: 'low' });
+ const high = createTask('high', { priority: 'high' });
+ low.load.mockImplementation(async () => {
+ executionOrder.push('low');
+ });
+ high.load.mockImplementation(async () => {
+ executionOrder.push('high');
+ });
+
+ createRoutePreloadScheduler([low, high]).start();
+ await vi.runAllTimersAsync();
+
+ expect(executionOrder).toEqual(['high', 'low']);
+ expect(high.load).toHaveBeenCalledTimes(1);
+ expect(low.load).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not preload the route that is already active', async () => {
+ const current = createTask('agent', {
+ matches: (pathname) => pathname.startsWith('/agent'),
+ priority: 'high',
+ });
+ const next = createTask('settings');
+
+ createRoutePreloadScheduler([current, next]).start();
+ await vi.runAllTimersAsync();
+
+ expect(current.load).not.toHaveBeenCalled();
+ expect(next.load).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([{ effectiveType: 'slow-2g' }, { saveData: true }])(
+ 'does not preload on a constrained connection: %o',
+ async (connection) => {
+ Object.defineProperty(window.navigator, 'connection', {
+ configurable: true,
+ value: connection,
+ });
+ const task = createTask('settings');
+
+ createRoutePreloadScheduler([task]).start();
+ await vi.runAllTimersAsync();
+
+ expect(task.load).not.toHaveBeenCalled();
+ },
+ );
+
+ it('waits until a hidden document becomes visible', async () => {
+ Object.defineProperty(document, 'hidden', {
+ configurable: true,
+ value: true,
+ });
+ const task = createTask('settings');
+
+ createRoutePreloadScheduler([task]).start();
+ await vi.runAllTimersAsync();
+ expect(task.load).not.toHaveBeenCalled();
+
+ Object.defineProperty(document, 'hidden', {
+ configurable: true,
+ value: false,
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.runAllTimersAsync();
+
+ expect(task.load).toHaveBeenCalledTimes(1);
+ });
+
+ it('immediately promotes an intent-only route when its link is targeted', async () => {
+ const image = createTask('image', {
+ idleDelay: Number.POSITIVE_INFINITY,
+ matches: (pathname) => pathname === '/image',
+ priority: 'low',
+ });
+ const anchor = document.createElement('a');
+ anchor.href = '/image';
+ document.body.append(anchor);
+
+ createRoutePreloadScheduler([image]).start();
+ anchor.dispatchEvent(new Event('pointerover', { bubbles: true }));
+ await Promise.resolve();
+
+ expect(image.load).toHaveBeenCalledTimes(1);
+ anchor.remove();
+ });
+
+ it('does not start the same scheduler more than once', async () => {
+ const task = createTask('settings');
+ const scheduler = createRoutePreloadScheduler([task]);
+
+ scheduler.start();
+ scheduler.start();
+ await vi.runAllTimersAsync();
+
+ expect(task.load).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/spa/initialize/routePreload.ts b/src/spa/initialize/routePreload.ts
new file mode 100644
index 00000000000..409f2a4e5db
--- /dev/null
+++ b/src/spa/initialize/routePreload.ts
@@ -0,0 +1,311 @@
+import { preloadRegisteredRoute } from '@/spa/router/routePreloadRegistry';
+
+type RoutePreloadPriority = 'high' | 'low' | 'medium';
+
+export interface RoutePreloadTask {
+ id: string;
+ idleDelay: number;
+ load: () => Promise<void>;
+ matches: (pathname: string) => boolean;
+ priority: RoutePreloadPriority;
+}
+
+interface NetworkInformationLike {
+ effectiveType?: string;
+ saveData?: boolean;
+}
+
+interface IdleDeadlineLike {
+ didTimeout: boolean;
+ timeRemaining: () => number;
+}
+
+interface RoutePreloadSchedulerOptions {
+ document?: Document;
+ now?: () => number;
+ window?: Window;
+}
+
+const priorityWeight: Record<RoutePreloadPriority, number> = {
+ high: 3,
+ low: 1,
+ medium: 2,
+};
+
+const matchesRoute = (segment: string) => {
+ const routePattern = new RegExp(`^/(?:[^/]+/)?${segment}(?:/|$)`);
+
+ return (pathname: string) => routePattern.test(pathname);
+};
+
+type RoutePreloadDefinition = Omit<RoutePreloadTask, 'load'>;
+
+const createTask = (definition: RoutePreloadDefinition): RoutePreloadTask => ({
+ ...definition,
+ load: () => preloadRegisteredRoute(definition.id),
+});
+
+const createWebRoutePreloadTasks = (): RoutePreloadTask[] => [
+ createTask({
+ id: 'agent',
+ idleDelay: 1500,
+ matches: matchesRoute('agent'),
+ priority: 'high',
+ }),
+ createTask({
+ id: 'agents',
+ idleDelay: 1500,
+ matches: matchesRoute('agents'),
+ priority: 'high',
+ }),
+ createTask({
+ id: 'tasks',
+ idleDelay: 2500,
+ matches: matchesRoute('(?:tasks|task|agent/[^/]+/task)'),
+ priority: 'high',
+ }),
+ createTask({
+ id: 'group',
+ idleDelay: 4000,
+ matches: matchesRoute('group'),
+ priority: 'medium',
+ }),
+ createTask({
+ id: 'community',
+ idleDelay: 6000,
+ matches: matchesRoute('community'),
+ priority: 'medium',
+ }),
+ createTask({
+ id: 'settings',
+ idleDelay: 8000,
+ matches: matchesRoute('settings'),
+ priority: 'medium',
+ }),
+ createTask({
+ id: 'resource',
+ idleDelay: 10_000,
+ matches: matchesRoute('resource'),
+ priority: 'low',
+ }),
+ createTask({
+ id: 'memory',
+ idleDelay: 12_000,
+ matches: matchesRoute('memory'),
+ priority: 'low',
+ }),
+ createTask({
+ id: 'page',
+ idleDelay: Number.POSITIVE_INFINITY,
+ matches: matchesRoute('page'),
+ priority: 'low',
+ }),
+ createTask({
+ id: 'image',
+ idleDelay: Number.POSITIVE_INFINITY,
+ matches: matchesRoute('image'),
+ priority: 'low',
+ }),
+ createTask({
+ id: 'video',
+ idleDelay: Number.POSITIVE_INFINITY,
+ matches: matchesRoute('video'),
+ priority: 'low',
+ }),
+ createTask({
+ id: 'eval',
+ idleDelay: Number.POSITIVE_INFINITY,
+ matches: matchesRoute('eval'),
+ priority: 'low',
+ }),
+];
+
+const createMobileRoutePreloadTasks = (): RoutePreloadTask[] => [
+ createTask({
+ id: 'mobile-home',
+ idleDelay: 1500,
+ matches: (pathname) => pathname === '/',
+ priority: 'high',
+ }),
+ createTask({
+ id: 'mobile-agent',
+ idleDelay: 2500,
+ matches: matchesRoute('agent'),
+ priority: 'high',
+ }),
+ createTask({
+ id: 'mobile-agents',
+ idleDelay: 2500,
+ matches: matchesRoute('agents'),
+ priority: 'high',
+ }),
+ createTask({
+ id: 'mobile-tasks',
+ idleDelay: 4000,
+ matches: matchesRoute('(?:tasks|task|agent/[^/]+/task)'),
+ priority: 'medium',
+ }),
+ createTask({
+ id: 'mobile-community',
+ idleDelay: 6000,
+ matches: matchesRoute('community'),
+ priority: 'medium',
+ }),
+ createTask({
+ id: 'mobile-settings',
+ idleDelay: 8000,
+ matches: matchesRoute('settings'),
+ priority: 'low',
+ }),
+];
+
+const getConnection = (targetWindow: Window): NetworkInformationLike | undefined => {
+ const navigatorWithConnection = targetWindow.navigator as Navigator & {
+ connection?: NetworkInformationLike;
+ mozConnection?: NetworkInformationLike;
+ webkitConnection?: NetworkInformationLike;
+ };
+
+ return (
+ navigatorWithConnection.connection ||
+ navigatorWithConnection.mozConnection ||
+ navigatorWithConnection.webkitConnection
+ );
+};
+
+export const shouldSkipRoutePreload = (targetWindow: Window) => {
+ const connection = getConnection(targetWindow);
+
+ return Boolean(
+ connection?.saveData || /(?:^|-)2g$/.test(connection?.effectiveType?.toLowerCase() || ''),
+ );
+};
+
+const scheduleIdle = (targetWindow: Window, callback: (deadline: IdleDeadlineLike) => void) => {
+ const requestIdleCallback = (
+ targetWindow as typeof targetWindow & {
+ requestIdleCallback?: (
+ callback: (deadline: IdleDeadlineLike) => void,
+ options?: { timeout?: number },
+ ) => number;
+ }
+ ).requestIdleCallback;
+
+ if (requestIdleCallback) {
+ requestIdleCallback(callback, { timeout: 3000 });
+ return;
+ }
+
+ targetWindow.setTimeout(() => callback({ didTimeout: true, timeRemaining: () => 16 }), 200);
+};
+
+export const createRoutePreloadScheduler = (
+ tasks: RoutePreloadTask[],
+ options: RoutePreloadSchedulerOptions = {},
+) => {
+ const targetWindow = options.window ?? window;
+ const targetDocument = options.document ?? document;
+ const now = options.now ?? Date.now;
+ const startedAt = now();
+ const completed = new Set(
+ tasks.filter((task) => task.matches(targetWindow.location.pathname)).map((task) => task.id),
+ );
+ let started = false;
+ let idleScheduled = false;
+
+ const sortedTasks = [...tasks].sort(
+ (a, b) => priorityWeight[b.priority] - priorityWeight[a.priority] || a.idleDelay - b.idleDelay,
+ );
+
+ const preload = async (task: RoutePreloadTask) => {
+ if (completed.has(task.id)) return;
+ completed.add(task.id);
+
+ try {
+ await task.load();
+ } catch (error) {
+ completed.delete(task.id);
+ if (__DEV__) console.warn('[RoutePreload] failed', task.id, error);
+ }
+ };
+
+ const pendingIdleTasks = () =>
+ sortedTasks.filter((task) => !completed.has(task.id) && Number.isFinite(task.idleDelay));
+
+ const scheduleNextIdleTask = () => {
+ if (idleScheduled || targetDocument.hidden) return;
+
+ const pending = pendingIdleTasks();
+ if (pending.length === 0) return;
+
+ const elapsed = now() - startedAt;
+ const dueTask = pending.find((task) => task.idleDelay <= elapsed);
+ if (!dueTask) {
+ const wait = Math.max(0, Math.min(...pending.map((task) => task.idleDelay - elapsed)));
+ targetWindow.setTimeout(scheduleNextIdleTask, wait);
+ return;
+ }
+
+ idleScheduled = true;
+ scheduleIdle(targetWindow, (deadline) => {
+ idleScheduled = false;
+
+ if (!deadline.didTimeout && deadline.timeRemaining() < 8) {
+ targetWindow.setTimeout(scheduleNextIdleTask, 500);
+ return;
+ }
+
+ void preload(dueTask).finally(() => {
+ targetWindow.setTimeout(scheduleNextIdleTask, 500);
+ });
+ });
+ };
+
+ const preloadFromIntent = (event: Event) => {
+ const anchor =
+ event.target instanceof Element ? event.target.closest<HTMLAnchorElement>('a[href]') : null;
+ if (!anchor) return;
+
+ let url: URL;
+ try {
+ url = new URL(anchor.href, targetWindow.location.href);
+ } catch {
+ return;
+ }
+
+ if (url.origin !== targetWindow.location.origin) return;
+ const task = sortedTasks.find((candidate) => candidate.matches(url.pathname));
+ if (task) void preload(task);
+ };
+
+ const resumeWhenVisible = () => {
+ if (!targetDocument.hidden) scheduleNextIdleTask();
+ };
+
+ return {
+ start: () => {
+ if (started || shouldSkipRoutePreload(targetWindow)) return;
+ started = true;
+
+ targetDocument.addEventListener('pointerover', preloadFromIntent, { capture: true });
+ targetDocument.addEventListener('focusin', preloadFromIntent, { capture: true });
+ targetDocument.addEventListener('touchstart', preloadFromIntent, {
+ capture: true,
+ passive: true,
+ });
+ targetDocument.addEventListener('visibilitychange', resumeWhenVisible);
+
+ scheduleNextIdleTask();
+ },
+ };
+};
+
+let routePreloadStarted = false;
+
+export const startRoutePreload = () => {
+ if (routePreloadStarted || typeof window === 'undefined' || __ELECTRON__) return;
+ routePreloadStarted = true;
+
+ const tasks = __MOBILE__ ? createMobileRoutePreloadTasks() : createWebRoutePreloadTasks();
+ createRoutePreloadScheduler(tasks).start();
+};
diff --git a/src/spa/initialize/toolSurfaces.ts b/src/spa/initialize/toolSurfaces.ts
index af6b34a6d2a..91f1fabf3cb 100644
--- a/src/spa/initialize/toolSurfaces.ts
+++ b/src/spa/initialize/toolSurfaces.ts
@@ -1,10 +1,32 @@
-import { registerBuiltinToolSurfaces as registerSurfaces } from '@lobechat/builtin-tools/register';
+let registrationPromise: Promise<void> | undefined;
-let registered = false;
+/**
+ * Loads the builtin render/inspector registry only when a conversation surface is needed.
+ * The shared promise keeps idle preloading and route-demand loading idempotent.
+ */
+export const ensureBuiltinToolSurfaces = (): Promise<void> => {
+ if (!registrationPromise) {
+ registrationPromise = import('@lobechat/builtin-tools/register')
+ .then(({ registerBuiltinToolSurfaces }) => {
+ registerBuiltinToolSurfaces();
+ })
+ .catch((error) => {
+ registrationPromise = undefined;
+ throw error;
+ });
+ }
-export const registerBuiltinToolSurfaces = () => {
- if (registered) return;
- registered = true;
+ return registrationPromise;
+};
+
+/**
+ * Keeps a routed conversation suspended until its builtin tool surfaces are registered while
+ * allowing the route module and the registry chunk to download in parallel.
+ */
+export const loadRouteWithBuiltinToolSurfaces = async <T>(
+ loadRoute: () => Promise<T>,
+): Promise<T> => {
+ const [routeModule] = await Promise.all([loadRoute(), ensureBuiltinToolSurfaces()]);
- registerSurfaces();
+ return routeModule;
};
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index ed5abb5c098..d509a0ab44c 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -28,7 +28,8 @@ import {
} from '@/features/Verify/routeMeta';
import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';
import DesktopOnboarding from '@/routes/(desktop)/desktop-onboarding';
-// Layouts β€” sync import (Electron local, no network overhead)
+// Layouts β€” sync import (Electron local, no network overhead).
+// Unlike the web router, Electron intentionally does not register idle preload groups.
import DesktopMainLayout from '@/routes/(main)/_layout';
import ImagePage from '@/routes/(main)/(create)/image';
import DesktopImageLayout from '@/routes/(main)/(create)/image/_layout';
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index a4927bdeda1..9b3c4aff09d 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -32,15 +32,21 @@ import { groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';
import { settingsRouteMeta } from '@/routes/(main)/settings/features/routeMeta';
import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';
import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';
+import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
import { routeMeta } from '@/spa/router/routeMeta';
import { SettingsTabs } from '@/store/global/initialState';
import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
-const agentChatElement = dynamicElement(() => import('@/routes/(main)/agent'), 'Desktop > Chat');
+const agentChatElement = dynamicElement(
+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(main)/agent')),
+ 'Desktop > Chat',
+ { preloadId: 'agent' },
+);
const groupChatElement = dynamicElement(
- () => import('@/routes/(main)/group'),
+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(main)/group')),
'Desktop > Agent Group',
+ { preloadId: 'group' },
);
/**
@@ -77,6 +83,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicLayout(
() => import('@/routes/(main)/agent/(chat)/_layout'),
'Desktop > Chat > ChatLayout',
+ { preloadId: 'agent' },
),
},
{
@@ -159,6 +166,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicLayout(
() => import('@/routes/(main)/agent/_layout'),
'Desktop > Chat > Layout',
+ { preloadId: 'agent' },
),
errorElement: <ErrorBoundary />,
path: ':aid',
@@ -197,6 +205,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicLayout(
() => import('@/routes/(main)/group/_layout'),
'Desktop > Group > Layout',
+ { preloadId: 'group' },
),
errorElement: <ErrorBoundary />,
path: ':gid',
@@ -318,6 +327,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/community/(list)/(home)'),
'Desktop > Discover > List > Home',
+ { preloadId: 'community' },
),
handle: {
meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
@@ -328,6 +338,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/community/(list)/_layout'),
'Desktop > Discover > List > Layout',
+ { preloadId: 'community' },
),
},
// Detail routes (with DetailLayout)
@@ -399,6 +410,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/community/_layout'),
'Desktop > Discover > Layout',
+ { preloadId: 'community' },
),
errorElement: <ErrorBoundary />,
path: 'community',
@@ -414,6 +426,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/resource/(home)'),
'Desktop > Resource > Home',
+ { preloadId: 'resource' },
),
handle: {
meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),
@@ -425,6 +438,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/resource/(home)/_layout'),
'Desktop > Resource > Home > Layout',
+ { preloadId: 'resource' },
),
},
// Library routes (knowledge base detail)
@@ -461,6 +475,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/resource/_layout'),
'Desktop > Resource > Layout',
+ { preloadId: 'resource' },
),
errorElement: <ErrorBoundary />,
path: 'resource',
@@ -473,6 +488,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/memory/(home)'),
'Desktop > Memory > Home',
+ { preloadId: 'memory' },
),
handle: {
meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
@@ -533,6 +549,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicLayout(
() => import('@/routes/(main)/memory/_layout'),
'Desktop > Memory > Layout',
+ { preloadId: 'memory' },
),
errorElement: <ErrorBoundary />,
path: 'memory',
@@ -542,13 +559,16 @@ export const sharedMainAreaChildren: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(main)/(create)/video'), 'Desktop > Video'),
+ element: dynamicElement(() => import('@/routes/(main)/(create)/video'), 'Desktop > Video', {
+ preloadId: 'video',
+ }),
index: true,
},
],
element: dynamicLayout(
() => import('@/routes/(main)/(create)/video/_layout'),
'Desktop > Video > Layout',
+ { preloadId: 'video' },
),
errorElement: <ErrorBoundary />,
path: 'video',
@@ -558,7 +578,9 @@ export const sharedMainAreaChildren: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(main)/(create)/image'), 'Desktop > Image'),
+ element: dynamicElement(() => import('@/routes/(main)/(create)/image'), 'Desktop > Image', {
+ preloadId: 'image',
+ }),
handle: {
meta: routeMeta({ icon: Image, titleKey: 'navigation.image' }),
},
@@ -568,6 +590,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicLayout(
() => import('@/routes/(main)/(create)/image/_layout'),
'Desktop > Image > Layout',
+ { preloadId: 'image' },
),
errorElement: <ErrorBoundary />,
path: 'image',
@@ -585,6 +608,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/eval'),
'Desktop > Eval > Overview',
+ { preloadId: 'eval' },
),
index: true,
},
@@ -599,6 +623,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/eval/(home)/_layout'),
'Desktop > Eval > Home > Layout',
+ { preloadId: 'eval' },
),
},
// Bench routes (with dedicated sidebar)
@@ -649,6 +674,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/eval/_layout'),
'Desktop > Eval > Layout',
+ { preloadId: 'eval' },
),
errorElement: <ErrorBoundary />,
path: 'eval',
@@ -658,7 +684,9 @@ export const sharedMainAreaChildren: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(main)/agents'), 'Desktop > Agents'),
+ element: dynamicElement(() => import('@/routes/(main)/agents'), 'Desktop > Agents', {
+ preloadId: 'agents',
+ }),
handle: { meta: agentsRouteMeta },
index: true,
},
@@ -673,7 +701,9 @@ export const sharedMainAreaChildren: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Desktop > Tasks'),
+ element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Desktop > Tasks', {
+ preloadId: 'tasks',
+ }),
handle: { meta: tasksRouteMeta },
index: true,
},
@@ -699,6 +729,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicLayout(
() => import('@/routes/(main)/(task-workspace)/_layout'),
'Desktop > Task Workspace > Layout',
+ { preloadId: 'tasks' },
),
},
@@ -706,7 +737,9 @@ export const sharedMainAreaChildren: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(main)/page'), 'Desktop > Page'),
+ element: dynamicElement(() => import('@/routes/(main)/page'), 'Desktop > Page', {
+ preloadId: 'page',
+ }),
handle: {
meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.pages' }),
},
@@ -721,7 +754,11 @@ export const sharedMainAreaChildren: RouteObject[] = [
path: ':id',
},
],
- element: dynamicLayout(() => import('@/routes/(main)/page/_layout'), 'Desktop > Page > Layout'),
+ element: dynamicLayout(
+ () => import('@/routes/(main)/page/_layout'),
+ 'Desktop > Page > Layout',
+ { preloadId: 'page' },
+ ),
errorElement: <ErrorBoundary />,
path: 'page',
},
@@ -846,6 +883,7 @@ export const createMainAreaChildren = (): RouteObject[] => [
element: dynamicElement(
() => import('@/routes/(main)/[workspaceSlug]/settings/skill'),
'Desktop > Workspace > Settings > Skill',
+ { preloadId: 'settings' },
),
path: 'skill',
},
@@ -853,6 +891,7 @@ export const createMainAreaChildren = (): RouteObject[] => [
element: dynamicElement(
() => import('@/routes/(main)/[workspaceSlug]/settings/connector'),
'Desktop > Workspace > Settings > Connector',
+ { preloadId: 'settings' },
),
path: 'connector',
},
@@ -985,12 +1024,14 @@ export const createMainAreaChildren = (): RouteObject[] => [
element: dynamicLayout(
() => import('@/routes/(main)/[workspaceSlug]/settings/_content-layout'),
'Desktop > Workspace > Settings > Content Layout',
+ { preloadId: 'settings' },
),
},
],
element: dynamicLayout(
() => import('@/routes/(main)/[workspaceSlug]/settings/_layout'),
'Desktop > Workspace > Settings > Layout',
+ { preloadId: 'settings' },
),
errorElement: <ErrorBoundary />,
path: 'settings',
@@ -1054,7 +1095,10 @@ export const desktopRoutes: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/share/t/[id]'), 'Desktop > Share > Topic'),
+ element: dynamicElement(
+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/share/t/[id]')),
+ 'Desktop > Share > Topic',
+ ),
handle: { meta: shareTopicRouteMeta },
path: ':id',
},
diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsx
index a7bc96eba28..96a10d14edb 100644
--- a/src/spa/router/mobileRouter.config.tsx
+++ b/src/spa/router/mobileRouter.config.tsx
@@ -15,8 +15,15 @@ import {
import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';
import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';
+import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
+const mobileChatElement = dynamicElement(
+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(mobile)/chat')),
+ 'Mobile > Chat',
+ { preloadId: 'mobile-agent' },
+);
+
/**
* Children shared between `/` and `/:workspaceSlug` for mobile. Mobile only
* mirrors the subset of routes it actually supports β€” settings / me / default
@@ -33,15 +40,12 @@ export const sharedMainAreaChildren: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(mobile)/chat'), 'Mobile > Chat'),
+ element: mobileChatElement,
handle: { meta: agentRouteMeta },
index: true,
},
{
- element: dynamicElement(
- () => import('@/routes/(mobile)/chat'),
- 'Mobile > Chat > Topic',
- ),
+ element: mobileChatElement,
handle: { meta: agentRouteMeta },
path: ':topicId',
},
@@ -57,6 +61,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicLayout(
() => import('@/routes/(mobile)/chat/_layout'),
'Mobile > Chat > Layout',
+ { preloadId: 'mobile-agent' },
),
errorElement: <ErrorBoundary />,
path: ':aid',
@@ -82,6 +87,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/community/(list)/(home)'),
'Mobile > Discover > List > Home',
+ { preloadId: 'mobile-community' },
),
index: true,
},
@@ -139,6 +145,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(mobile)/community/(list)/_layout'),
'Mobile > Discover > List > Layout',
+ { preloadId: 'mobile-community' },
),
},
// Detail routes (with DetailLayout)
@@ -209,6 +216,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(mobile)/community/_layout'),
'Mobile > Discover > Layout',
+ { preloadId: 'mobile-community' },
),
errorElement: <ErrorBoundary />,
path: 'community',
@@ -218,7 +226,9 @@ export const sharedMainAreaChildren: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(main)/agents'), 'Mobile > Agents'),
+ element: dynamicElement(() => import('@/routes/(main)/agents'), 'Mobile > Agents', {
+ preloadId: 'mobile-agents',
+ }),
index: true,
},
],
@@ -232,7 +242,9 @@ export const sharedMainAreaChildren: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Mobile > Tasks'),
+ element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Mobile > Tasks', {
+ preloadId: 'mobile-tasks',
+ }),
index: true,
},
],
@@ -269,6 +281,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: dynamicLayout(
() => import('@/routes/(main)/(task-workspace)/_layout'),
'Mobile > Task Workspace > Layout',
+ { preloadId: 'mobile-tasks' },
),
},
@@ -295,6 +308,7 @@ export const mobileRoutes: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(mobile)/settings'),
'Mobile > Settings',
+ { preloadId: 'mobile-settings' },
),
index: true,
},
@@ -329,6 +343,7 @@ export const mobileRoutes: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/settings'),
'Mobile > Settings > Tab',
+ { preloadId: 'mobile-settings' },
),
path: ':tab',
},
@@ -336,6 +351,7 @@ export const mobileRoutes: RouteObject[] = [
element: dynamicElement(
() => import('@/routes/(main)/settings'),
'Mobile > Settings > Tab > Sub',
+ { preloadId: 'mobile-settings' },
),
path: ':tab/:sub',
},
@@ -343,6 +359,7 @@ export const mobileRoutes: RouteObject[] = [
element: dynamicLayout(
() => import('@/routes/(mobile)/settings/_layout'),
'Mobile > Settings > Layout',
+ { preloadId: 'mobile-settings' },
),
errorElement: <ErrorBoundary />,
path: 'settings',
@@ -405,13 +422,16 @@ export const mobileRoutes: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/(mobile)/(home)/'), 'Mobile > Home'),
+ element: dynamicElement(() => import('@/routes/(mobile)/(home)/'), 'Mobile > Home', {
+ preloadId: 'mobile-home',
+ }),
index: true,
},
],
element: dynamicLayout(
() => import('@/routes/(mobile)/(home)/_layout'),
'Mobile > Home > Layout',
+ { preloadId: 'mobile-home' },
),
},
@@ -550,7 +570,10 @@ export const mobileRoutes: RouteObject[] = [
{
children: [
{
- element: dynamicElement(() => import('@/routes/share/t/[id]'), 'Mobile > Share > Topic'),
+ element: dynamicElement(
+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/share/t/[id]')),
+ 'Mobile > Share > Topic',
+ ),
handle: { meta: shareTopicRouteMeta },
path: ':id',
},
diff --git a/src/spa/router/routePreloadRegistry.test.ts b/src/spa/router/routePreloadRegistry.test.ts
new file mode 100644
index 00000000000..95508879b27
--- /dev/null
+++ b/src/spa/router/routePreloadRegistry.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { preloadRegisteredRoute, registerRoutePreloadLoader } from './routePreloadRegistry';
+
+describe('routePreloadRegistry', () => {
+ it('preloads every lazy route module registered in the same business group', async () => {
+ const loadLayout = vi.fn().mockResolvedValue(undefined);
+ const loadPage = vi.fn().mockResolvedValue(undefined);
+ registerRoutePreloadLoader('test-agents', loadLayout);
+ registerRoutePreloadLoader('test-agents', loadPage);
+
+ await preloadRegisteredRoute('test-agents');
+
+ expect(loadLayout).toHaveBeenCalledTimes(1);
+ expect(loadPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('treats an unregistered group as a no-op', async () => {
+ await expect(preloadRegisteredRoute('test-missing')).resolves.toBeUndefined();
+ });
+});
diff --git a/src/spa/router/routePreloadRegistry.ts b/src/spa/router/routePreloadRegistry.ts
new file mode 100644
index 00000000000..618a069da0c
--- /dev/null
+++ b/src/spa/router/routePreloadRegistry.ts
@@ -0,0 +1,16 @@
+type RoutePreloadLoader = () => Promise<void>;
+
+const preloadLoaders = new Map<string, Set<RoutePreloadLoader>>();
+
+export const registerRoutePreloadLoader = (id: string, loader: RoutePreloadLoader) => {
+ const loaders = preloadLoaders.get(id) ?? new Set<RoutePreloadLoader>();
+ loaders.add(loader);
+ preloadLoaders.set(id, loaders);
+};
+
+export const preloadRegisteredRoute = async (id: string) => {
+ const loaders = preloadLoaders.get(id);
+ if (!loaders) return;
+
+ await Promise.all([...loaders].map((loader) => loader()));
+};
diff --git a/src/store/aiInfra/slices/aiModel/selectors.ts b/src/store/aiInfra/slices/aiModel/selectors.ts
index 16f8a3d569e..95dee1b7361 100644
--- a/src/store/aiInfra/slices/aiModel/selectors.ts
+++ b/src/store/aiInfra/slices/aiModel/selectors.ts
@@ -1,4 +1,4 @@
-import { AiModelSourceEnum } from 'model-bank';
+import { AiModelSourceEnum } from 'model-bank/aiModel';
import { type AIProviderStoreState } from '@/store/aiInfra/initialState';
import { ModelSearchImplement } from '@/types/search';
diff --git a/src/store/aiInfra/slices/aiModel/utils.ts b/src/store/aiInfra/slices/aiModel/utils.ts
index b9f3266227d..cd9998166dc 100644
--- a/src/store/aiInfra/slices/aiModel/utils.ts
+++ b/src/store/aiInfra/slices/aiModel/utils.ts
@@ -1,4 +1,4 @@
-import { isAutoGeneratedImageModelId } from '@lobechat/model-runtime';
+import { isAutoGeneratedImageModelId } from 'model-bank/standardParameters';
const IMAGE_MODEL_SUFFIX = ':image';
diff --git a/src/store/aiInfra/slices/aiProvider/__tests__/action.test.ts b/src/store/aiInfra/slices/aiProvider/__tests__/action.test.ts
index 297d468c3c6..a7f6d588119 100644
--- a/src/store/aiInfra/slices/aiProvider/__tests__/action.test.ts
+++ b/src/store/aiInfra/slices/aiProvider/__tests__/action.test.ts
@@ -1,4 +1,4 @@
-import * as runtimeModule from '@lobechat/model-runtime';
+import * as runtimeModule from '@lobechat/model-runtime/getModelPropertyWithFallback';
import type { AIImageModelCard, EnabledAiModel, ModelParamsSchema, Pricing } from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
diff --git a/src/store/aiInfra/slices/aiProvider/action.ts b/src/store/aiInfra/slices/aiProvider/action.ts
index cb5726fc2a0..b7ee09801c6 100644
--- a/src/store/aiInfra/slices/aiProvider/action.ts
+++ b/src/store/aiInfra/slices/aiProvider/action.ts
@@ -1,8 +1,6 @@
-import {
- getModelPropertyWithFallback,
- resolveImageSinglePrice,
- resolveVideoSinglePrice,
-} from '@lobechat/model-runtime';
+import { getModelPropertyWithFallback } from '@lobechat/model-runtime/getModelPropertyWithFallback';
+import { resolveImageSinglePrice } from '@lobechat/model-runtime/resolveImageSinglePrice';
+import { resolveVideoSinglePrice } from '@lobechat/model-runtime/resolveVideoSinglePrice';
import { uniqBy } from 'es-toolkit/compat';
import type {
AiFullModelCard,
@@ -13,7 +11,7 @@ import type {
ModelParamsSchema,
Pricing,
} from 'model-bank';
-import { isAiModelVisible } from 'model-bank';
+import { isAiModelVisible } from 'model-bank/aiModel';
import { type SWRResponse } from 'swr';
import { mutate, useClientDataSWR } from '@/libs/swr';
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.ts b/src/store/chat/agents/transports/ClientLLMTransport.ts
index c797efff63f..6d6ec59787b 100644
--- a/src/store/chat/agents/transports/ClientLLMTransport.ts
+++ b/src/store/chat/agents/transports/ClientLLMTransport.ts
@@ -20,7 +20,7 @@ import {
getErrorCodeSpec,
isEmptyModelCompletion,
ModelEmptyError,
-} from '@lobechat/model-runtime';
+} from '@lobechat/model-runtime/errors';
import type { ChatMessageError, MessageMetadata, ModelReasoning } from '@lobechat/types';
import { ChatErrorType } from '@lobechat/types';
import { t } from 'i18next';
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts
index 6b50b8f5b48..ca0753caf30 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/clientToolExecution.test.ts
@@ -491,6 +491,8 @@ describe('internal_executeClientTool', () => {
operationId: 'op-1',
});
+ await vi.waitFor(() => expect(invokeExecutorMock).toHaveBeenCalledTimes(1));
+
// Simulate a reconnect landing while the executor is still running:
// a fresh entry appears in gatewayConnections.
const reconnectedSend = vi.fn(() => true);
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 6c6189c6008..715b029788f 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -13,7 +13,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { getSessionStoreState } from '@/store/session';
import * as toolStoreModule from '@/store/tool';
-import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';
import { useUserStore } from '@/store/user';
import { useChatStore } from '../../../../store';
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
index 48f6dd57cfc..07d1563744c 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
@@ -35,6 +35,7 @@ vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () =
const getExecutorMock = vi.fn();
vi.mock('@/store/tool/slices/builtin/executors', () => ({
getExecutor: (...args: unknown[]) => getExecutorMock(...args),
+ registerBuiltinToolExecutors: vi.fn().mockResolvedValue(undefined),
}));
// ─── Test Helpers ───
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index aae4a36b08e..6eb89a788d3 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -11,7 +11,7 @@ import { chatService } from '@/services/chat';
import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';
import { useAgentStore } from '@/store/agent';
import { useAiInfraStore } from '@/store/aiInfra';
-import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';
import { useChatStore } from '../../../../store';
import { messageMapKey } from '../../../../utils/messageMapKey';
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 03cb7054dcf..e59880d635a 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -82,7 +82,7 @@ import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { getElectronStoreState } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';
import { type StoreSetter } from '@/store/types';
import { getUserStoreState } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts b/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts
index cf42fa132ad..9f3e14d2d02 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/clientToolExecution.ts
@@ -154,7 +154,7 @@ export class ClientToolExecutionActionImpl {
const operation = this.#get().operations[localOperationId ?? operationId];
// ─── Builtin dispatch (via registry) ───
- if (hasExecutor(identifier, apiName)) {
+ if (await hasExecutor(identifier, apiName)) {
const ctx: BuiltinToolContext = {
agentId: agentId ?? operation?.context?.agentId,
anchorMessageId: assistantMessageId,
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index 4746f5182e9..5cfbfaa3528 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -52,7 +52,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { getElectronStoreState } from '@/store/electron';
import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';
import { getTaskStoreState } from '@/store/task';
-import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';
import { type StoreSetter } from '@/store/types';
import { toolInterventionSelectors } from '@/store/user/selectors';
import { getUserStoreState } from '@/store/user/store';
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index bbabc4cd849..f0e640e1eb9 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -51,6 +51,7 @@ export const isCompletedRuntimeEnd = (reason?: string | null): boolean =>
// mid-evaluation, so the class binding is undefined.
const loadGetExecutor = async () => {
const mod = await import('@/store/tool/slices/builtin/executors');
+ await mod.registerBuiltinToolExecutors();
return mod.getExecutor;
};
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index e1b68b65efc..e662e46e63a 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -184,7 +184,7 @@ describe('ChatPluginAction', () => {
// Mock hasExecutor to return true
const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
- vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockResolvedValue(true);
// Mock Tool Store's invokeBuiltinTool
vi.spyOn(useToolStore.getState(), 'invokeBuiltinTool').mockImplementation(
@@ -219,7 +219,7 @@ describe('ChatPluginAction', () => {
// Mock hasExecutor to return false
const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
- vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(false);
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockResolvedValue(false);
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -257,7 +257,7 @@ describe('ChatPluginAction', () => {
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);
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockResolvedValue(true);
const { result } = renderHook(() => useChatStore());
const messageId = 'page-tool-message-id';
@@ -312,7 +312,7 @@ describe('ChatPluginAction', () => {
it('should pass tool call id and explicit source user message id to Tool Store executor', async () => {
const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
- vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockResolvedValue(true);
const { result } = renderHook(() => useChatStore());
const messageId = 'tool-message-id';
@@ -365,7 +365,7 @@ describe('ChatPluginAction', () => {
it('should pass sub-agent context to Tool Store executor', async () => {
const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
- vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockResolvedValue(true);
const { result } = renderHook(() => useChatStore());
const messageId = 'sub-agent-tool-message-id';
@@ -423,7 +423,7 @@ describe('ChatPluginAction', () => {
it('should fall back to root operation message id as source message id', async () => {
const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
- vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockResolvedValue(true);
const { result } = renderHook(() => useChatStore());
const messageId = 'tool-message-id';
@@ -475,7 +475,7 @@ describe('ChatPluginAction', () => {
it('should create registerAfterCompletion when root execAgentRuntime operation exists', async () => {
// Mock hasExecutor to return true
const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
- vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockResolvedValue(true);
// Setup: Create operation hierarchy
// execAgentRuntime -> toolCalling -> executeToolCall
@@ -560,7 +560,7 @@ describe('ChatPluginAction', () => {
it('should not pass registerAfterCompletion when no root operation exists', async () => {
// Mock hasExecutor to return true
const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
- vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockResolvedValue(true);
const { result } = renderHook(() => useChatStore());
const messageId = 'tool-message-id';
@@ -595,7 +595,7 @@ describe('ChatPluginAction', () => {
it('should find root operation through multiple levels of hierarchy', async () => {
// Mock hasExecutor to return true
const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');
- vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);
+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockResolvedValue(true);
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index 45850a79718..d96dff41c3c 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -82,7 +82,7 @@ export class PluginTypesActionImpl {
if (!params) return { error: 'Invalid arguments', success: false };
// Check if there's a registered executor in Tool Store (new architecture)
- if (hasExecutor(payload.identifier, payload.apiName)) {
+ if (await hasExecutor(payload.identifier, payload.apiName)) {
const { optimisticUpdateToolMessage, registerAfterCompletionCallback } = this.#get();
// Get operation context
diff --git a/src/store/document/slices/preview/action.ts b/src/store/document/slices/preview/action.ts
deleted file mode 100644
index 6c02aa5a465..00000000000
--- a/src/store/document/slices/preview/action.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-'use client';
-
-import { type StoreSetter } from '@/store/types';
-import { setNamespace } from '@/utils/storeDebug';
-
-import { type DocumentStore } from '../../store';
-
-const n = setNamespace('document/preview');
-
-type Setter = StoreSetter<DocumentStore>;
-
-export const createPreviewSlice = (set: Setter, get: () => DocumentStore, _api?: unknown) =>
- new PreviewActionImpl(set, get, _api);
-
-export class PreviewActionImpl {
- readonly #get: () => DocumentStore;
- readonly #set: Setter;
-
- constructor(set: Setter, get: () => DocumentStore, _api?: unknown) {
- void _api;
- this.#set = set;
- this.#get = get;
- }
-
- openDocumentPreview = (documentId: string): void => {
- if (this.#get().previewDocumentId === documentId) return;
- this.#set({ previewDocumentId: documentId }, false, n('openDocumentPreview'));
- };
-
- closeDocumentPreview = (): void => {
- if (!this.#get().previewDocumentId) return;
- this.#set({ previewDocumentId: undefined }, false, n('closeDocumentPreview'));
- };
-}
-
-export type PreviewAction = Pick<PreviewActionImpl, keyof PreviewActionImpl>;
diff --git a/src/store/document/slices/preview/index.ts b/src/store/document/slices/preview/index.ts
deleted file mode 100644
index 407aa03d0c2..00000000000
--- a/src/store/document/slices/preview/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { createPreviewSlice, type PreviewAction } from './action';
-export { initialPreviewState, type PreviewState } from './initialState';
diff --git a/src/store/document/slices/preview/initialState.ts b/src/store/document/slices/preview/initialState.ts
deleted file mode 100644
index 9a948a56ec0..00000000000
--- a/src/store/document/slices/preview/initialState.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * UI state for the global document preview modal.
- */
-export interface PreviewState {
- /** ID of the document currently shown in the preview modal, if any. */
- previewDocumentId?: string;
-}
-
-export const initialPreviewState: PreviewState = {
- previewDocumentId: undefined,
-};
diff --git a/src/store/document/store.ts b/src/store/document/store.ts
index db7d45df18b..15543ce45c0 100644
--- a/src/store/document/store.ts
+++ b/src/store/document/store.ts
@@ -10,14 +10,12 @@ import { type DocumentAction } from './slices/document';
import { createDocumentSlice } from './slices/document';
import { type EditorAction, type EditorState } from './slices/editor';
import { createEditorSlice, initialEditorState } from './slices/editor';
-import { type PreviewAction, type PreviewState } from './slices/preview';
-import { createPreviewSlice, initialPreviewState } from './slices/preview';
// State type
-export type DocumentState = EditorState & PreviewState;
+export type DocumentState = EditorState;
// Action type
-export type DocumentStoreAction = DocumentAction & EditorAction & PreviewAction & ResetableStore;
+export type DocumentStoreAction = DocumentAction & EditorAction & ResetableStore;
// Full store type
export type DocumentStore = DocumentState & DocumentStoreAction;
@@ -25,7 +23,6 @@ export type DocumentStore = DocumentState & DocumentStoreAction;
// Initial state
const initialState: DocumentState = {
...initialEditorState,
- ...initialPreviewState,
};
class DocumentStoreResetAction extends ResetableStoreAction<DocumentStore> {
@@ -39,7 +36,6 @@ const createStore: StateCreator<DocumentStore, [['zustand/devtools', never]]> =
...flattenActions<DocumentStoreAction>([
createDocumentSlice(...parameters),
createEditorSlice(...parameters),
- createPreviewSlice(...parameters),
new DocumentStoreResetAction(...parameters),
]),
});
diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.ts
new file mode 100644
index 00000000000..a75b324d136
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/catalog.ts
@@ -0,0 +1,62 @@
+import { agentBuilderExecutor } from '@lobechat/builtin-tool-agent-builder/executor';
+import { agentManagementExecutor } from '@lobechat/builtin-tool-agent-management/executor';
+import { browserExecutor } from '@lobechat/builtin-tool-browser/client/executor';
+import { calculatorExecutor } from '@lobechat/builtin-tool-calculator/executor';
+import { cloudSandboxExecutor } from '@lobechat/builtin-tool-cloud-sandbox/executor';
+import { credsExecutor } from '@lobechat/builtin-tool-creds/executor';
+import { groupAgentBuilderExecutor } from '@lobechat/builtin-tool-group-agent-builder/executor';
+import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management/executor';
+import { imageGenerationExecutor } from '@lobechat/builtin-tool-image-generation/executor';
+import { knowledgeBaseExecutor } from '@lobechat/builtin-tool-knowledge-base/client/executor';
+import { lobeAgentExecutor } from '@lobechat/builtin-tool-lobe-agent/client/executor';
+import { localSystemExecutor } from '@lobechat/builtin-tool-local-system/client/executor';
+import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';
+import { taskExecutor } from '@lobechat/builtin-tool-task/client/executor';
+
+import type { IBuiltinToolExecutor } from '../types';
+import { ampExecutor, claudeCodeExecutor, codexExecutor, openCodeExecutor } from './heteroCli';
+import { activatorExecutor } from './lobe-activator';
+import { agentDocumentsExecutor } from './lobe-agent-documents';
+import { messageExecutor } from './lobe-message';
+import { notebookExecutor } from './lobe-notebook';
+import { pageAgentExecutor } from './lobe-page-agent';
+import { skillStoreExecutor } from './lobe-skill-store';
+import { skillsExecutor } from './lobe-skills';
+import { topicReferenceExecutor } from './lobe-topic-reference';
+import { userInteractionExecutor } from './lobe-user-interaction';
+import { webBrowsing } from './lobe-web-browsing';
+import { webOnboardingExecutor } from './lobe-web-onboarding';
+
+export const builtinToolExecutors = [
+ // Hook-only executors for heterogeneous CLI agents β€”
+ // observe their shell tool results via `onAfterCall` (never invoked).
+ ampExecutor,
+ claudeCodeExecutor,
+ codexExecutor,
+ openCodeExecutor,
+ agentBuilderExecutor,
+ agentDocumentsExecutor,
+ agentManagementExecutor,
+ calculatorExecutor,
+ cloudSandboxExecutor,
+ credsExecutor,
+ groupAgentBuilderExecutor,
+ groupManagementExecutor,
+ imageGenerationExecutor,
+ knowledgeBaseExecutor,
+ browserExecutor,
+ localSystemExecutor,
+ memoryExecutor,
+ messageExecutor,
+ notebookExecutor,
+ pageAgentExecutor,
+ skillStoreExecutor,
+ skillsExecutor,
+ taskExecutor,
+ activatorExecutor,
+ topicReferenceExecutor,
+ userInteractionExecutor,
+ lobeAgentExecutor,
+ webOnboardingExecutor,
+ webBrowsing,
+] satisfies IBuiltinToolExecutor[];
diff --git a/src/store/tool/slices/builtin/executors/index.lazy.test.ts b/src/store/tool/slices/builtin/executors/index.lazy.test.ts
new file mode 100644
index 00000000000..3431e75e645
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/index.lazy.test.ts
@@ -0,0 +1,27 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ catalogEvaluated: vi.fn(),
+}));
+
+vi.mock('./catalog', () => {
+ mocks.catalogEvaluated();
+ return { builtinToolExecutors: [] };
+});
+
+describe('builtin executor catalog loading', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ mocks.catalogEvaluated.mockClear();
+ });
+
+ it('keeps executor implementations out of the registry shell import', async () => {
+ const { registerBuiltinToolExecutors } = await import('./index');
+
+ expect(mocks.catalogEvaluated).not.toHaveBeenCalled();
+
+ await registerBuiltinToolExecutors();
+
+ expect(mocks.catalogEvaluated).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/index.test.ts b/src/store/tool/slices/builtin/executors/index.test.ts
index 1e05766451f..22f67067a26 100644
--- a/src/store/tool/slices/builtin/executors/index.test.ts
+++ b/src/store/tool/slices/builtin/executors/index.test.ts
@@ -7,6 +7,7 @@ import { describe, expect, it, vi } from 'vitest';
import {
getApiNamesForIdentifier,
+ getRegisteredIdentifiers,
hasExecutor,
invokeExecutor,
registerBuiltinToolExecutors,
@@ -36,14 +37,18 @@ vi.hoisted(() => {
describe('builtin executor registry', () => {
it('does not register executors as an import side effect', () => {
- expect(hasExecutor(WebOnboardingIdentifier, WebOnboardingApiName.saveUserQuestion)).toBe(false);
+ expect(getRegisteredIdentifiers()).toEqual([]);
});
it('registers web onboarding executor APIs explicitly', async () => {
await registerBuiltinToolExecutors();
- expect(hasExecutor(WebOnboardingIdentifier, WebOnboardingApiName.saveUserQuestion)).toBe(true);
- expect(hasExecutor(WebOnboardingIdentifier, WebOnboardingApiName.finishOnboarding)).toBe(true);
+ await expect(
+ hasExecutor(WebOnboardingIdentifier, WebOnboardingApiName.saveUserQuestion),
+ ).resolves.toBe(true);
+ await expect(
+ hasExecutor(WebOnboardingIdentifier, WebOnboardingApiName.finishOnboarding),
+ ).resolves.toBe(true);
expect(getApiNamesForIdentifier(WebOnboardingIdentifier)).toEqual(
Object.values(WebOnboardingApiName),
);
@@ -52,7 +57,9 @@ describe('builtin executor registry', () => {
it('registers visual understanding executor APIs', async () => {
await registerBuiltinToolExecutors();
- expect(hasExecutor(LobeAgentIdentifier, LobeAgentApiName.analyzeVisualMedia)).toBe(true);
+ await expect(
+ hasExecutor(LobeAgentIdentifier, LobeAgentApiName.analyzeVisualMedia),
+ ).resolves.toBe(true);
}, 30_000);
it('rejects nested sub-agent execution', async () => {
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index e9e6d93e7c6..15356c25ed8 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -1,39 +1,12 @@
/**
* Builtin Tool Executor Registry
*
- * Central registry for builtin tool executors.
- * Executor modules are registered by explicit app bootstrap registration, not
- * by importing this registry module.
+ * Lightweight registry shell for builtin tool executors. Executor
+ * implementations live behind one asynchronous catalog boundary so importing
+ * the store does not pull every tool runtime into the initial SPA graph.
*/
-import { agentBuilderExecutor } from '@lobechat/builtin-tool-agent-builder/executor';
-import { agentManagementExecutor } from '@lobechat/builtin-tool-agent-management/executor';
-import { browserExecutor } from '@lobechat/builtin-tool-browser/client/executor';
-import { calculatorExecutor } from '@lobechat/builtin-tool-calculator/executor';
-import { cloudSandboxExecutor } from '@lobechat/builtin-tool-cloud-sandbox/executor';
-import { credsExecutor } from '@lobechat/builtin-tool-creds/executor';
-import { groupAgentBuilderExecutor } from '@lobechat/builtin-tool-group-agent-builder/executor';
-import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management/executor';
-import { imageGenerationExecutor } from '@lobechat/builtin-tool-image-generation/executor';
-import { knowledgeBaseExecutor } from '@lobechat/builtin-tool-knowledge-base/client/executor';
-import { lobeAgentExecutor } from '@lobechat/builtin-tool-lobe-agent/client/executor';
-import { localSystemExecutor } from '@lobechat/builtin-tool-local-system/client/executor';
-import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';
-import { taskExecutor } from '@lobechat/builtin-tool-task/client/executor';
-
import type { BuiltinToolContext, BuiltinToolResult, IBuiltinToolExecutor } from '../types';
-import { ampExecutor, claudeCodeExecutor, codexExecutor, openCodeExecutor } from './heteroCli';
-import { activatorExecutor } from './lobe-activator';
-import { agentDocumentsExecutor } from './lobe-agent-documents';
-import { messageExecutor } from './lobe-message';
-import { notebookExecutor } from './lobe-notebook';
-import { pageAgentExecutor } from './lobe-page-agent';
-import { skillStoreExecutor } from './lobe-skill-store';
-import { skillsExecutor } from './lobe-skills';
-import { topicReferenceExecutor } from './lobe-topic-reference';
-import { userInteractionExecutor } from './lobe-user-interaction';
-import { webBrowsing } from './lobe-web-browsing';
-import { webOnboardingExecutor } from './lobe-web-onboarding';
import { stashBuiltinToolWorkIntent } from './workRegistration';
/**
@@ -41,6 +14,7 @@ import { stashBuiltinToolWorkIntent } from './workRegistration';
*/
const executorRegistry = new Map<string, IBuiltinToolExecutor>();
let executorsRegistered = false;
+let registrationPromise: Promise<void> | undefined;
/**
* Get a builtin tool executor by identifier
@@ -59,7 +33,9 @@ export const getExecutor = (identifier: string): IBuiltinToolExecutor | undefine
* @param apiName - The API name
* @returns Whether the executor exists and supports the API
*/
-export const hasExecutor = (identifier: string, apiName: string): boolean => {
+export const hasExecutor = async (identifier: string, apiName: string): Promise<boolean> => {
+ await registerBuiltinToolExecutors();
+
const executor = executorRegistry.get(identifier);
return executor?.hasApi(apiName) ?? false;
};
@@ -145,42 +121,18 @@ const registerExecutors = (executors: IBuiltinToolExecutor[]): void => {
}
};
-export const registerBuiltinToolExecutors = (): void => {
+export const registerBuiltinToolExecutors = async (): Promise<void> => {
if (executorsRegistered) return;
- registerExecutors([
- // Hook-only executors for heterogeneous CLI agents β€”
- // observe their shell tool results via `onAfterCall` (never invoked).
- ampExecutor,
- claudeCodeExecutor,
- codexExecutor,
- openCodeExecutor,
- agentBuilderExecutor,
- agentDocumentsExecutor,
- agentManagementExecutor,
- calculatorExecutor,
- cloudSandboxExecutor,
- credsExecutor,
- groupAgentBuilderExecutor,
- groupManagementExecutor,
- imageGenerationExecutor,
- knowledgeBaseExecutor,
- browserExecutor,
- localSystemExecutor,
- memoryExecutor,
- messageExecutor,
- notebookExecutor,
- pageAgentExecutor,
- skillStoreExecutor,
- skillsExecutor,
- taskExecutor,
- activatorExecutor,
- topicReferenceExecutor,
- userInteractionExecutor,
- lobeAgentExecutor,
- webOnboardingExecutor,
- webBrowsing,
- ]);
-
- executorsRegistered = true;
+ registrationPromise ??= import('./catalog').then(({ builtinToolExecutors }) => {
+ registerExecutors(builtinToolExecutors);
+ executorsRegistered = true;
+ });
+
+ try {
+ await registrationPromise;
+ } catch (error) {
+ registrationPromise = undefined;
+ throw error;
+ }
};
diff --git a/src/store/tool/slices/builtin/executors/lobe-page-agent.ts b/src/store/tool/slices/builtin/executors/lobe-page-agent.ts
index 090ebdd3b2f..77d3adff0bf 100644
--- a/src/store/tool/slices/builtin/executors/lobe-page-agent.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-page-agent.ts
@@ -1,14 +1,11 @@
/**
* Lobe Page Agent Executor
*
- * Creates and exports the PageAgentExecutor instance for registration.
- * Also exports the runtime for editor instance injection.
+ * Creates and exports the PageAgentExecutor instance for lazy registration.
*/
-import { PageAgentExecutor } from '@lobechat/builtin-tool-page-agent/client';
-import { EditorRuntime } from '@lobechat/editor-runtime';
+import { PageAgentExecutor } from '@lobechat/builtin-tool-page-agent/client/executor';
-// Create singleton instance of the runtime
-export const pageAgentRuntime = new EditorRuntime();
+import { pageAgentRuntime } from './pageAgentRuntime';
// Create executor instance with the runtime
export const pageAgentExecutor = new PageAgentExecutor(pageAgentRuntime);
diff --git a/src/store/tool/slices/builtin/executors/pageAgentRuntime.ts b/src/store/tool/slices/builtin/executors/pageAgentRuntime.ts
new file mode 100644
index 00000000000..dbbb8ec19c6
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/pageAgentRuntime.ts
@@ -0,0 +1,4 @@
+import { EditorRuntime } from '@lobechat/editor-runtime';
+
+// Lightweight singleton shared by page context collection and the lazily loaded executor.
+export const pageAgentRuntime = new EditorRuntime();
diff --git a/src/utils/errorResponse.ts b/src/utils/errorResponse.ts
index d3b3abfc7ce..a69cda41d59 100644
--- a/src/utils/errorResponse.ts
+++ b/src/utils/errorResponse.ts
@@ -1,6 +1,8 @@
import { AUTH_REQUIRED_HEADER } from '@lobechat/desktop-bridge';
-import { type ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';
-import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
+import {
+ AgentRuntimeErrorType,
+ type ILobeAgentRuntimeErrorType,
+} from '@lobechat/model-runtime/types/error';
import { type ErrorResponse, type ErrorType } from '@lobechat/types';
import { ChatErrorType } from '@lobechat/types';
diff --git a/src/utils/i18n/loadI18nNamespaceModule.desktop.ts b/src/utils/i18n/loadI18nNamespaceModule.desktop.ts
index 9db12834fb5..17f670b23c7 100644
--- a/src/utils/i18n/loadI18nNamespaceModule.desktop.ts
+++ b/src/utils/i18n/loadI18nNamespaceModule.desktop.ts
@@ -7,9 +7,14 @@ type NamespaceModule = { default: Record<string, unknown> };
type NamespaceModuleMap = Record<string, NamespaceModule>;
// eager: true β€” all locale JSON inlined at build time, synchronous access at runtime
-const defaultModules = import.meta.glob('/packages/locales/src/default/*.ts', {
- eager: true,
-}) as NamespaceModuleMap;
+const defaultModules = import.meta.glob(
+ [
+ '/packages/locales/src/default/*.ts',
+ '!/packages/locales/src/default/*.vite.ts',
+ '!/packages/locales/src/default/index.ts',
+ ],
+ { eager: true },
+) as NamespaceModuleMap;
const localeModules = import.meta.glob('/locales/*/*.json', {
eager: true,
}) as NamespaceModuleMap;
diff --git a/src/utils/i18n/loadI18nNamespaceModule.vite.ts b/src/utils/i18n/loadI18nNamespaceModule.vite.ts
index 37bdb2464b0..5bc0cce6cbf 100644
--- a/src/utils/i18n/loadI18nNamespaceModule.vite.ts
+++ b/src/utils/i18n/loadI18nNamespaceModule.vite.ts
@@ -6,8 +6,14 @@ import type {
type NamespaceModule = { default: Record<string, unknown> };
type NamespaceLoaderMap = Record<string, () => Promise<NamespaceModule>>;
-// Use import.meta.glob so Vite can statically analyze and avoid CJS/dynamic import issues
-const defaultLoaders = import.meta.glob('/packages/locales/src/default/*.ts') as NamespaceLoaderMap;
+// Use import.meta.glob so Vite can statically analyze and avoid CJS/dynamic import issues.
+// Platform variants are resolved from their canonical file; exposing them as
+// separate namespace keys creates duplicate, unreachable dynamic entries.
+const defaultLoaders = import.meta.glob([
+ '/packages/locales/src/default/*.ts',
+ '!/packages/locales/src/default/*.vite.ts',
+ '!/packages/locales/src/default/index.ts',
+]) as NamespaceLoaderMap;
const localeLoaders = import.meta.glob('/locales/*/*.json') as NamespaceLoaderMap;
const getDefaultKey = (ns: string) => `/packages/locales/src/default/${ns}.ts`;
diff --git a/src/utils/router.tsx b/src/utils/router.tsx
index 656a6e16f2f..3518fa6dcc1 100644
--- a/src/utils/router.tsx
+++ b/src/utils/router.tsx
@@ -13,6 +13,7 @@ import Loading from '@/components/Loading/BrandTextLoading';
import { useIsDark } from '@/hooks/useIsDark';
import SPAGlobalProvider from '@/layout/SPAGlobalProvider';
import AppLayer from '@/spa/AppLayer';
+import { registerRoutePreloadLoader } from '@/spa/router/routePreloadRegistry';
import { createSPABrowserRouter } from '@/spa/runtime';
import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';
@@ -37,6 +38,54 @@ function resolveLazyModule<P>(module: { default: ComponentType<P> } | ComponentT
return { default: module as unknown as ComponentType<P> };
}
+interface DynamicRouteOptions {
+ preloadId?: string;
+}
+
+const createPreloadableComponent = <P,>(
+ importFn: () => Promise<{ default: ComponentType<P> } | ComponentType<P>>,
+) => {
+ let loadPromise: Promise<{ default: ComponentType<P> }> | undefined;
+ let ResolvedComponent: ComponentType<P> | undefined;
+
+ const load = () => {
+ if (!loadPromise) {
+ loadPromise = importModule(importFn)
+ .then(resolveLazyModule<P>)
+ .then((module) => {
+ ResolvedComponent = module.default;
+ return module;
+ })
+ .catch((error) => {
+ loadPromise = undefined;
+ throw error;
+ });
+ }
+
+ return loadPromise;
+ };
+
+ const LazyComponent = lazy(load);
+ const PreloadableComponent = (props: P) => {
+ const Component = ResolvedComponent;
+
+ if (Component) {
+ // @ts-ignore generic route props are resolved by the imported component
+ return <Component {...props} />;
+ }
+
+ // @ts-ignore generic route props are resolved by the imported component
+ return <LazyComponent {...props} />;
+ };
+
+ return {
+ Component: PreloadableComponent,
+ preload: async () => {
+ await load();
+ },
+ };
+};
+
/**
* Helper function to create a dynamic page element directly for router configuration
* This eliminates the need to define const for each component
@@ -52,17 +101,16 @@ function resolveLazyModule<P>(module: { default: ComponentType<P> } | ComponentT
export function dynamicElement<P = NonNullable<unknown>>(
importFn: () => Promise<{ default: ComponentType<P> } | ComponentType<P>>,
debugId?: string,
+ options?: DynamicRouteOptions,
): ReactElement {
- const LazyComponent = lazy(async () => {
- const mod = await importModule(importFn);
- return resolveLazyModule(mod);
- });
+ const { Component, preload } = createPreloadableComponent(importFn);
+ if (options?.preloadId) registerRoutePreloadLoader(options.preloadId, preload);
// @ts-ignore
return (
<Suspense fallback={<Loading debugId={debugId || 'dynamicElement'} />}>
{/* @ts-ignore */}
- <LazyComponent {...({} as P)} />
+ <Component {...({} as P)} />
</Suspense>
);
}
@@ -74,17 +122,16 @@ export function dynamicElement<P = NonNullable<unknown>>(
export function dynamicLayout<P = NonNullable<unknown>>(
importFn: () => Promise<{ default: ComponentType<P> } | ComponentType<P>>,
debugId?: string,
+ options?: DynamicRouteOptions,
): ReactElement {
- const LazyComponent = lazy(async () => {
- const mod = await importModule(importFn);
- return resolveLazyModule(mod);
- });
+ const { Component, preload } = createPreloadableComponent(importFn);
+ if (options?.preloadId) registerRoutePreloadLoader(options.preloadId, preload);
// @ts-ignore
return (
<Suspense fallback={<Loading debugId={debugId || 'dynamicLayout'} />}>
{/* @ts-ignore */}
- <LazyComponent {...({} as P)} />
+ <Component {...({} as P)} />
</Suspense>
);
}
diff --git a/vite.config.ts b/vite.config.ts
index 7b0f157f486..8d4e67f4882 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -13,6 +13,7 @@ import {
sharedModulePreload,
sharedOptimizeDeps,
sharedPwaGlobIgnores,
+ sharedPwaRuntimeCaching,
sharedRendererDefine,
sharedRendererPlugins,
} from './plugins/vite/sharedRendererConfig';
@@ -265,6 +266,7 @@ export default defineConfig({
globPatterns: ['**/*.{js,css,html,woff2}'],
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024,
runtimeCaching: [
+ ...sharedPwaRuntimeCaching,
{
handler: 'StaleWhileRevalidate',
options: { cacheName: 'google-fonts-stylesheets' },