Skip to content

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

✨ feat(spa): bootstrap app initialization (#15937)

Innei46439bbd167d
diff --git a/packages/builtin-tool-knowledge-base/package.json b/packages/builtin-tool-knowledge-base/package.json
index bf0a54de87f..ff00a816eaa 100644
--- a/packages/builtin-tool-knowledge-base/package.json
+++ b/packages/builtin-tool-knowledge-base/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-knowledge-base/src/client/index.ts b/packages/builtin-tool-knowledge-base/src/client/index.ts
index d451f55ff81..57bfae3515a 100644
--- a/packages/builtin-tool-knowledge-base/src/client/index.ts
+++ b/packages/builtin-tool-knowledge-base/src/client/index.ts
@@ -4,9 +4,6 @@ export { KnowledgeBaseInspectors } from './Inspector';
// Render components (read-only snapshots)
export { KnowledgeBaseRenders } from './Render';
-// Client-side executor (browser runtime adapter for the agent)
-export { knowledgeBaseExecutor } from './executor';
-
// Re-export types and manifest for convenience
export { KnowledgeBaseManifest } from '../manifest';
export * from '../types';
diff --git a/packages/builtin-tool-lobe-agent/package.json b/packages/builtin-tool-lobe-agent/package.json
index 02fa3ce1bb3..3ffec6829bf 100644
--- a/packages/builtin-tool-lobe-agent/package.json
+++ b/packages/builtin-tool-lobe-agent/package.json
@@ -4,7 +4,8 @@
"private": true,
"exports": {
".": "./src/index.ts",
- "./client": "./src/client/index.ts"
+ "./client": "./src/client/index.ts",
+ "./client/executor": "./src/client/executor/index.ts"
},
"main": "./src/index.ts",
"scripts": {
diff --git a/packages/builtin-tool-lobe-agent/src/client/index.ts b/packages/builtin-tool-lobe-agent/src/client/index.ts
index d10457bb1d0..0a8427f1ba2 100644
--- a/packages/builtin-tool-lobe-agent/src/client/index.ts
+++ b/packages/builtin-tool-lobe-agent/src/client/index.ts
@@ -1,6 +1,3 @@
-// Executor (client-side β€” depends on app stores/services)
-export { lobeAgentExecutor } from './executor';
-
// Inspector components (customized tool call headers)
export { LobeAgentInspectors } from './Inspector';
diff --git a/packages/builtin-tool-local-system/package.json b/packages/builtin-tool-local-system/package.json
index fe36d06e16d..285f808a864 100644
--- a/packages/builtin-tool-local-system/package.json
+++ b/packages/builtin-tool-local-system/package.json
@@ -4,7 +4,8 @@
"private": true,
"exports": {
".": "./src/index.ts",
- "./client": "./src/client/index.ts"
+ "./client": "./src/client/index.ts",
+ "./client/executor": "./src/client/executor/index.ts"
},
"main": "./src/index.ts",
"dependencies": {
diff --git a/packages/builtin-tool-local-system/src/client/index.ts b/packages/builtin-tool-local-system/src/client/index.ts
index 1a051ec4a6e..8676f8e2594 100644
--- a/packages/builtin-tool-local-system/src/client/index.ts
+++ b/packages/builtin-tool-local-system/src/client/index.ts
@@ -1,6 +1,3 @@
-// Client-side executor (browser runtime adapter for the agent)
-export { localSystemExecutor } from './executor';
-
// Inspector components (customized tool call headers)
export { LocalSystemInspectors } from './Inspector';
diff --git a/packages/builtin-tool-task/package.json b/packages/builtin-tool-task/package.json
index fb48630299b..5f87ccc7251 100644
--- a/packages/builtin-tool-task/package.json
+++ b/packages/builtin-tool-task/package.json
@@ -4,7 +4,8 @@
"private": true,
"exports": {
".": "./src/index.ts",
- "./client": "./src/client/index.ts"
+ "./client": "./src/client/index.ts",
+ "./client/executor": "./src/client/executor/index.ts"
},
"main": "./src/index.ts",
"dependencies": {
diff --git a/packages/builtin-tool-task/src/client/index.ts b/packages/builtin-tool-task/src/client/index.ts
index f3f684dbfd6..f3473a9d335 100644
--- a/packages/builtin-tool-task/src/client/index.ts
+++ b/packages/builtin-tool-task/src/client/index.ts
@@ -18,9 +18,6 @@ export {
// Render components (read-only snapshots)
export { CreateTaskRender, CreateTasksRender, RunTasksRender, TaskRenders } from './Render';
-// Client-side executor (browser runtime adapter for the agent)
-export { taskExecutor } from './executor';
-
// Re-export manifest and types for convenience
export { TaskIdentifier, TaskManifest } from '../manifest';
export * from '../types';
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index ef3009528da..c75c229cb90 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -6,6 +6,7 @@
"exports": {
".": "./src/index.ts",
"./renders": "./src/renders.ts",
+ "./register": "./src/register.ts",
"./displayControls": "./src/displayControls.ts",
"./inspectors": "./src/inspectors.ts",
"./interventions": "./src/interventions.ts",
diff --git a/packages/builtin-tools/src/inspectors.ts b/packages/builtin-tools/src/inspectors.ts
index ab2a8fb54da..c1bd21a3fb8 100644
--- a/packages/builtin-tools/src/inspectors.ts
+++ b/packages/builtin-tools/src/inspectors.ts
@@ -1,76 +1,5 @@
-import {
- LobeActivatorInspectors,
- LobeActivatorManifest,
-} from '@lobechat/builtin-tool-activator/client';
-import {
- AgentBuilderInspectors,
- AgentBuilderManifest,
-} from '@lobechat/builtin-tool-agent-builder/client';
-import {
- AgentDocumentsInspectors,
- AgentDocumentsManifest,
-} from '@lobechat/builtin-tool-agent-documents/client';
-import {
- AgentManagementInspectors,
- AgentManagementManifest,
-} from '@lobechat/builtin-tool-agent-management/client';
-import {
- ClaudeCodeIdentifier,
- ClaudeCodeInspectors,
-} from '@lobechat/builtin-tool-claude-code/client';
-import {
- CloudSandboxIdentifier,
- CloudSandboxInspectors,
-} from '@lobechat/builtin-tool-cloud-sandbox/client';
-import {
- GroupAgentBuilderInspectors,
- GroupAgentBuilderManifest,
-} from '@lobechat/builtin-tool-group-agent-builder/client';
-import {
- GroupManagementInspectors,
- GroupManagementManifest,
-} from '@lobechat/builtin-tool-group-management/client';
-import {
- KnowledgeBaseInspectors,
- KnowledgeBaseManifest,
-} from '@lobechat/builtin-tool-knowledge-base/client';
-import { LobeAgentInspectors, LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent/client';
-import {
- LobeDeliveryCheckerInspectors,
- LobeDeliveryCheckerManifest,
-} from '@lobechat/builtin-tool-lobe-delivery-checker/client';
-import {
- LocalSystemInspectors,
- LocalSystemManifest,
-} from '@lobechat/builtin-tool-local-system/client';
-import { MemoryInspectors, MemoryManifest } from '@lobechat/builtin-tool-memory/client';
-import { MessageInspectors, MessageManifest } from '@lobechat/builtin-tool-message/client';
-import { PageAgentInspectors, PageAgentManifest } from '@lobechat/builtin-tool-page-agent/client';
-import {
- SelfFeedbackIntentInspectors,
- selfFeedbackIntentManifest,
-} from '@lobechat/builtin-tool-self-iteration/client';
-import {
- SkillStoreInspectors,
- SkillStoreManifest,
-} from '@lobechat/builtin-tool-skill-store/client';
-import { SkillsInspectors, SkillsManifest } from '@lobechat/builtin-tool-skills/client';
-import { TaskInspectors, TaskManifest } from '@lobechat/builtin-tool-task/client';
-import {
- WebBrowsingInspectors,
- WebBrowsingManifest,
-} from '@lobechat/builtin-tool-web-browsing/client';
-import {
- WebOnboardingInspectors,
- WebOnboardingManifest,
-} from '@lobechat/builtin-tool-web-onboarding/client';
import type { BuiltinInspector } from '@lobechat/types';
-import { CodexInspectors } from './codex';
-import { GithubIdentifier, GithubInspectors } from './github';
-import { LinearIdentifier, LinearInspectors } from './linear';
-import { TwitterIdentifier, TwitterInspectors } from './twitter';
-
/**
* Builtin tools inspector registry
* Organized by toolset (identifier) -> API name
@@ -78,47 +7,15 @@ import { TwitterIdentifier, TwitterInspectors } from './twitter';
* Inspector components are used to customize the title/header area
* of tool calls in the conversation UI.
*/
-const BuiltinToolInspectors: Record<string, Record<string, BuiltinInspector>> = {
- [AgentBuilderManifest.identifier]: AgentBuilderInspectors as Record<string, BuiltinInspector>,
- [AgentDocumentsManifest.identifier]: AgentDocumentsInspectors as Record<string, BuiltinInspector>,
- [AgentManagementManifest.identifier]: AgentManagementInspectors as Record<
- string,
- BuiltinInspector
- >,
- [ClaudeCodeIdentifier]: ClaudeCodeInspectors as Record<string, BuiltinInspector>,
- [CloudSandboxIdentifier]: CloudSandboxInspectors as Record<string, BuiltinInspector>,
- [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderInspectors as Record<
- string,
- BuiltinInspector
- >,
- [GroupManagementManifest.identifier]: GroupManagementInspectors as Record<
- string,
- BuiltinInspector
- >,
- [KnowledgeBaseManifest.identifier]: KnowledgeBaseInspectors as Record<string, BuiltinInspector>,
- [LobeAgentManifest.identifier]: LobeAgentInspectors as Record<string, BuiltinInspector>,
- [LobeDeliveryCheckerManifest.identifier]: LobeDeliveryCheckerInspectors as Record<
- string,
- BuiltinInspector
- >,
- [LocalSystemManifest.identifier]: LocalSystemInspectors as Record<string, BuiltinInspector>,
- [MemoryManifest.identifier]: MemoryInspectors as Record<string, BuiltinInspector>,
- [MessageManifest.identifier]: MessageInspectors as Record<string, BuiltinInspector>,
- [PageAgentManifest.identifier]: PageAgentInspectors as Record<string, BuiltinInspector>,
- [LobeActivatorManifest.identifier]: LobeActivatorInspectors as Record<string, BuiltinInspector>,
- [selfFeedbackIntentManifest.identifier]: SelfFeedbackIntentInspectors as Record<
- string,
- BuiltinInspector
- >,
- [SkillStoreManifest.identifier]: SkillStoreInspectors as Record<string, BuiltinInspector>,
- [SkillsManifest.identifier]: SkillsInspectors as Record<string, BuiltinInspector>,
- [TaskManifest.identifier]: TaskInspectors as Record<string, BuiltinInspector>,
- [WebBrowsingManifest.identifier]: WebBrowsingInspectors as Record<string, BuiltinInspector>,
- [WebOnboardingManifest.identifier]: WebOnboardingInspectors as Record<string, BuiltinInspector>,
- codex: CodexInspectors,
- [GithubIdentifier]: GithubInspectors,
- [LinearIdentifier]: LinearInspectors,
- [TwitterIdentifier]: TwitterInspectors,
+const builtinToolInspectors: Record<string, Record<string, BuiltinInspector>> = {};
+
+export const registerBuiltinInspectors = (
+ entries: Record<string, Record<string, BuiltinInspector>>,
+): void => {
+ for (const [identifier, inspectors] of Object.entries(entries)) {
+ const current = builtinToolInspectors[identifier];
+ builtinToolInspectors[identifier] = current ? Object.assign(current, inspectors) : inspectors;
+ }
};
export interface BuiltinInspectorRegistryEntry {
@@ -128,7 +25,7 @@ export interface BuiltinInspectorRegistryEntry {
}
export const listBuiltinInspectorEntries = (): BuiltinInspectorRegistryEntry[] =>
- Object.entries(BuiltinToolInspectors).flatMap(([identifier, toolset]) =>
+ Object.entries(builtinToolInspectors).flatMap(([identifier, toolset]) =>
Object.entries(toolset)
.filter((entry): entry is [string, BuiltinInspector] => !!entry[1])
.map(([apiName, inspector]) => ({
@@ -149,7 +46,7 @@ export const getBuiltinInspector = (
): BuiltinInspector | undefined => {
if (!identifier || !apiName) return undefined;
- const toolset = BuiltinToolInspectors[identifier];
+ const toolset = builtinToolInspectors[identifier];
if (!toolset) return undefined;
return toolset[apiName];
diff --git a/packages/builtin-tools/src/interventions.ts b/packages/builtin-tools/src/interventions.ts
index 1cc15d5c6ce..0bdb99706b8 100644
--- a/packages/builtin-tools/src/interventions.ts
+++ b/packages/builtin-tools/src/interventions.ts
@@ -1,53 +1,21 @@
-import {
- AgentBuilderInterventions,
- AgentBuilderManifest,
-} from '@lobechat/builtin-tool-agent-builder/client';
-import {
- ClaudeCodeIdentifier,
- ClaudeCodeInterventions,
-} from '@lobechat/builtin-tool-claude-code/client';
-import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
-import { CloudSandboxInterventions } from '@lobechat/builtin-tool-cloud-sandbox/client';
-import {
- GroupManagementInterventions,
- GroupManagementManifest,
-} from '@lobechat/builtin-tool-group-management/client';
-import {
- LobeAgentInterventions,
- LobeAgentManifest,
-} from '@lobechat/builtin-tool-lobe-agent/client';
-import {
- LocalSystemIdentifier,
- LocalSystemInterventions,
-} from '@lobechat/builtin-tool-local-system/client';
-import { MemoryInterventions, MemoryManifest } from '@lobechat/builtin-tool-memory/client';
-import { MessageInterventions, MessageManifest } from '@lobechat/builtin-tool-message/client';
-import {
- UserInteractionIdentifier,
- UserInteractionInterventions,
-} from '@lobechat/builtin-tool-user-interaction/client';
-import {
- WebOnboardingInterventions,
- WebOnboardingManifest,
-} from '@lobechat/builtin-tool-web-onboarding/client';
-import { type BuiltinIntervention } from '@lobechat/types';
+import type { BuiltinIntervention } from '@lobechat/types';
/**
* Builtin tools interventions registry
* Organized by toolset (identifier) -> API name
* Only register APIs that have custom intervention UI
*/
-export const BuiltinToolInterventions: Record<string, Record<string, any>> = {
- [AgentBuilderManifest.identifier]: AgentBuilderInterventions,
- [ClaudeCodeIdentifier]: ClaudeCodeInterventions,
- [CloudSandboxManifest.identifier]: CloudSandboxInterventions,
- [GroupManagementManifest.identifier]: GroupManagementInterventions,
- [LobeAgentManifest.identifier]: LobeAgentInterventions,
- [LocalSystemIdentifier]: LocalSystemInterventions,
- [MemoryManifest.identifier]: MemoryInterventions,
- [MessageManifest.identifier]: MessageInterventions,
- [UserInteractionIdentifier]: UserInteractionInterventions,
- [WebOnboardingManifest.identifier]: WebOnboardingInterventions,
+const builtinToolInterventions: Record<string, Record<string, BuiltinIntervention>> = {};
+
+export const registerBuiltinInterventions = (
+ entries: Record<string, Record<string, BuiltinIntervention>>,
+): void => {
+ for (const [identifier, interventions] of Object.entries(entries)) {
+ const current = builtinToolInterventions[identifier];
+ builtinToolInterventions[identifier] = current
+ ? Object.assign(current, interventions)
+ : interventions;
+ }
};
export interface BuiltinInterventionRegistryEntry {
@@ -57,7 +25,7 @@ export interface BuiltinInterventionRegistryEntry {
}
export const listBuiltinInterventionEntries = (): BuiltinInterventionRegistryEntry[] =>
- Object.entries(BuiltinToolInterventions).flatMap(([identifier, toolset]) =>
+ Object.entries(builtinToolInterventions).flatMap(([identifier, toolset]) =>
Object.entries(toolset)
.filter((entry): entry is [string, BuiltinIntervention] => !!entry[1])
.map(([apiName, intervention]) => ({
@@ -78,7 +46,7 @@ export const getBuiltinIntervention = (
): BuiltinIntervention | undefined => {
if (!identifier || !apiName) return undefined;
- const toolset = BuiltinToolInterventions[identifier];
+ const toolset = builtinToolInterventions[identifier];
if (!toolset) return undefined;
return toolset[apiName];
diff --git a/packages/builtin-tools/src/placeholders.ts b/packages/builtin-tools/src/placeholders.ts
index db945806d0d..6479d04054e 100644
--- a/packages/builtin-tools/src/placeholders.ts
+++ b/packages/builtin-tools/src/placeholders.ts
@@ -1,28 +1,20 @@
-import {
- LocalSystemApiName,
- LocalSystemIdentifier,
- LocalSystemListFilesPlaceholder,
- LocalSystemSearchFilesPlaceholder,
-} from '@lobechat/builtin-tool-local-system/client';
-import {
- WebBrowsingManifest,
- WebBrowsingPlaceholders,
-} from '@lobechat/builtin-tool-web-browsing/client';
-import { type BuiltinPlaceholder } from '@lobechat/types';
+import type { BuiltinPlaceholder } from '@lobechat/types';
/**
* Builtin tools placeholders registry
* Organized by toolset (identifier) -> API name
*/
-export const BuiltinToolPlaceholders: Record<string, Record<string, any>> = {
- [LocalSystemIdentifier]: {
- [LocalSystemApiName.searchFiles]: LocalSystemSearchFilesPlaceholder,
- [LocalSystemApiName.listFiles]: LocalSystemListFilesPlaceholder,
- // Legacy aliases β€” keep these so historical messages keep rendering
- listLocalFiles: LocalSystemListFilesPlaceholder,
- searchLocalFiles: LocalSystemSearchFilesPlaceholder,
- },
- [WebBrowsingManifest.identifier]: WebBrowsingPlaceholders as Record<string, any>,
+const builtinToolPlaceholders: Record<string, Record<string, BuiltinPlaceholder>> = {};
+
+export const registerBuiltinPlaceholders = (
+ entries: Record<string, Record<string, BuiltinPlaceholder>>,
+): void => {
+ for (const [identifier, placeholders] of Object.entries(entries)) {
+ const current = builtinToolPlaceholders[identifier];
+ builtinToolPlaceholders[identifier] = current
+ ? Object.assign(current, placeholders)
+ : placeholders;
+ }
};
export interface BuiltinPlaceholderRegistryEntry {
@@ -32,7 +24,7 @@ export interface BuiltinPlaceholderRegistryEntry {
}
export const listBuiltinPlaceholderEntries = (): BuiltinPlaceholderRegistryEntry[] =>
- Object.entries(BuiltinToolPlaceholders).flatMap(([identifier, toolset]) =>
+ Object.entries(builtinToolPlaceholders).flatMap(([identifier, toolset]) =>
Object.entries(toolset)
.filter((entry): entry is [string, BuiltinPlaceholder] => !!entry[1])
.map(([apiName, placeholder]) => ({
@@ -53,7 +45,7 @@ export const getBuiltinPlaceholder = (
): BuiltinPlaceholder | undefined => {
if (!identifier || !apiName) return undefined;
- const toolset = BuiltinToolPlaceholders[identifier];
+ const toolset = builtinToolPlaceholders[identifier];
if (!toolset) return undefined;
return toolset[apiName];
diff --git a/packages/builtin-tools/src/portals.ts b/packages/builtin-tools/src/portals.ts
index e791064031a..4231e7309a1 100644
--- a/packages/builtin-tools/src/portals.ts
+++ b/packages/builtin-tools/src/portals.ts
@@ -1,28 +1,40 @@
-import {
- LobeDeliveryCheckerManifest,
- LobeDeliveryCheckerPortal,
- LobeDeliveryCheckerPortalActions,
- LobeDeliveryCheckerPortalTitle,
-} from '@lobechat/builtin-tool-lobe-delivery-checker/client';
-import {
- WebBrowsingManifest,
- WebBrowsingPortal,
- WebBrowsingPortalTitle,
-} from '@lobechat/builtin-tool-web-browsing/client';
-import { type BuiltinPortal, type BuiltinPortalTitle } from '@lobechat/types';
-
-export const BuiltinToolsPortals: Record<string, BuiltinPortal> = {
- [LobeDeliveryCheckerManifest.identifier]: LobeDeliveryCheckerPortal as BuiltinPortal,
- [WebBrowsingManifest.identifier]: WebBrowsingPortal as BuiltinPortal,
-};
+import type { BuiltinPortal, BuiltinPortalTitle } from '@lobechat/types';
+
+const builtinToolsPortals: Record<string, BuiltinPortal> = {};
/** Optional custom header content per tool, rendered in the portal title slot. */
-export const BuiltinToolsPortalTitles: Record<string, BuiltinPortalTitle> = {
- [LobeDeliveryCheckerManifest.identifier]: LobeDeliveryCheckerPortalTitle,
- [WebBrowsingManifest.identifier]: WebBrowsingPortalTitle,
-};
+const builtinToolsPortalTitles: Record<string, BuiltinPortalTitle> = {};
/** Optional header right-actions per tool, rendered next to the portal close. */
-export const BuiltinToolsPortalActions: Record<string, BuiltinPortalTitle> = {
- [LobeDeliveryCheckerManifest.identifier]: LobeDeliveryCheckerPortalActions,
+const builtinToolsPortalActions: Record<string, BuiltinPortalTitle> = {};
+
+interface BuiltinPortalRegistration {
+ actions?: Record<string, BuiltinPortalTitle>;
+ portals?: Record<string, BuiltinPortal>;
+ titles?: Record<string, BuiltinPortalTitle>;
+}
+
+export const registerBuiltinPortals = ({
+ actions,
+ portals,
+ titles,
+}: BuiltinPortalRegistration): void => {
+ if (portals) Object.assign(builtinToolsPortals, portals);
+ if (titles) Object.assign(builtinToolsPortalTitles, titles);
+ if (actions) Object.assign(builtinToolsPortalActions, actions);
+};
+
+export const getBuiltinPortal = (identifier?: string): BuiltinPortal | undefined => {
+ if (!identifier) return undefined;
+ return builtinToolsPortals[identifier];
+};
+
+export const getBuiltinPortalTitle = (identifier?: string): BuiltinPortalTitle | undefined => {
+ if (!identifier) return undefined;
+ return builtinToolsPortalTitles[identifier];
+};
+
+export const getBuiltinPortalAction = (identifier?: string): BuiltinPortalTitle | undefined => {
+ if (!identifier) return undefined;
+ return builtinToolsPortalActions[identifier];
};
diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.ts
new file mode 100644
index 00000000000..24831130c04
--- /dev/null
+++ b/packages/builtin-tools/src/register.ts
@@ -0,0 +1,333 @@
+import {
+ LobeActivatorInspectors,
+ LobeActivatorManifest,
+ LobeActivatorRenders,
+} from '@lobechat/builtin-tool-activator/client';
+import {
+ AgentBuilderInspectors,
+ AgentBuilderInterventions,
+ AgentBuilderManifest,
+ AgentBuilderRenders,
+ AgentBuilderStreamings,
+} from '@lobechat/builtin-tool-agent-builder/client';
+import {
+ AgentDocumentsInspectors,
+ AgentDocumentsManifest,
+ AgentDocumentsRenders,
+ AgentDocumentsStreamings,
+} from '@lobechat/builtin-tool-agent-documents/client';
+import {
+ AgentManagementInspectors,
+ AgentManagementManifest,
+ AgentManagementRenders,
+ AgentManagementStreamings,
+} from '@lobechat/builtin-tool-agent-management/client';
+import {
+ ClaudeCodeIdentifier,
+ ClaudeCodeInspectors,
+ ClaudeCodeInterventions,
+ ClaudeCodeRenders,
+ ClaudeCodeStreamings,
+} from '@lobechat/builtin-tool-claude-code/client';
+import {
+ CloudSandboxInspectors,
+ CloudSandboxInterventions,
+ CloudSandboxManifest,
+ CloudSandboxRenders,
+ CloudSandboxStreamings,
+} from '@lobechat/builtin-tool-cloud-sandbox/client';
+import {
+ GroupAgentBuilderInspectors,
+ GroupAgentBuilderManifest,
+ GroupAgentBuilderRenders,
+ GroupAgentBuilderStreamings,
+} from '@lobechat/builtin-tool-group-agent-builder/client';
+import {
+ GroupManagementInspectors,
+ GroupManagementInterventions,
+ GroupManagementManifest,
+ GroupManagementRenders,
+ GroupManagementStreamings,
+} from '@lobechat/builtin-tool-group-management/client';
+import {
+ KnowledgeBaseInspectors,
+ KnowledgeBaseManifest,
+ KnowledgeBaseRenders,
+} from '@lobechat/builtin-tool-knowledge-base/client';
+import {
+ LobeAgentInspectors,
+ LobeAgentInterventions,
+ LobeAgentManifest,
+ LobeAgentRenders,
+ LobeAgentStreamings,
+} from '@lobechat/builtin-tool-lobe-agent/client';
+import {
+ LobeDeliveryCheckerInspectors,
+ LobeDeliveryCheckerManifest,
+ LobeDeliveryCheckerPortal,
+ LobeDeliveryCheckerPortalActions,
+ LobeDeliveryCheckerPortalTitle,
+ LobeDeliveryCheckerRenders,
+} from '@lobechat/builtin-tool-lobe-delivery-checker/client';
+import {
+ LocalSystemApiName,
+ LocalSystemIdentifier,
+ LocalSystemInspectors,
+ LocalSystemInterventions,
+ LocalSystemListFilesPlaceholder,
+ LocalSystemManifest,
+ LocalSystemRenders,
+ LocalSystemSearchFilesPlaceholder,
+ LocalSystemStreamings,
+} from '@lobechat/builtin-tool-local-system/client';
+import {
+ MemoryInspectors,
+ MemoryInterventions,
+ MemoryManifest,
+ MemoryRenders,
+ MemoryStreamings,
+} from '@lobechat/builtin-tool-memory/client';
+import {
+ MessageInspectors,
+ MessageInterventions,
+ MessageManifest,
+ MessageRenders,
+ MessageStreamings,
+} from '@lobechat/builtin-tool-message/client';
+import {
+ PageAgentInspectors,
+ PageAgentManifest,
+ PageAgentRenders,
+ PageAgentStreamings,
+} from '@lobechat/builtin-tool-page-agent/client';
+import {
+ RemoteDeviceManifest,
+ RemoteDeviceRenders,
+} from '@lobechat/builtin-tool-remote-device/client';
+import {
+ SelfFeedbackIntentInspectors,
+ selfFeedbackIntentManifest,
+} from '@lobechat/builtin-tool-self-iteration/client';
+import {
+ SkillStoreInspectors,
+ SkillStoreManifest,
+ SkillStoreRenders,
+} from '@lobechat/builtin-tool-skill-store/client';
+import {
+ SkillsInspectors,
+ SkillsManifest,
+ SkillsRenders,
+} from '@lobechat/builtin-tool-skills/client';
+import { TaskInspectors, TaskManifest, TaskRenders } from '@lobechat/builtin-tool-task/client';
+import {
+ UserInteractionIdentifier,
+ UserInteractionInterventions,
+} from '@lobechat/builtin-tool-user-interaction/client';
+import {
+ WebBrowsingInspectors,
+ WebBrowsingManifest,
+ WebBrowsingPlaceholders,
+ WebBrowsingPortal,
+ WebBrowsingPortalTitle,
+ WebBrowsingRenders,
+} from '@lobechat/builtin-tool-web-browsing/client';
+import {
+ WebOnboardingInspectors,
+ WebOnboardingInterventions,
+ WebOnboardingManifest,
+ WebOnboardingRenders,
+} from '@lobechat/builtin-tool-web-onboarding/client';
+import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';
+import type {
+ BuiltinInspector,
+ BuiltinIntervention,
+ BuiltinPlaceholder,
+ BuiltinPortal,
+ BuiltinPortalTitle,
+ BuiltinRender,
+ BuiltinStreaming,
+} from '@lobechat/types';
+
+import { CodexInspectors, CodexRenders } from './codex';
+import { GithubIdentifier, GithubInspectors, GithubRenders } from './github';
+import { registerBuiltinInspectors } from './inspectors';
+import { registerBuiltinInterventions } from './interventions';
+import { LinearIdentifier, LinearInspectors } from './linear';
+import { NotebookIdentifier, NotebookRenders } from './notebook';
+import { registerBuiltinPlaceholders } from './placeholders';
+import { registerBuiltinPortals } from './portals';
+import { registerBuiltinRenders } from './renders';
+import { registerBuiltinStreamings } from './streamings';
+import { TwitterIdentifier, TwitterInspectors } from './twitter';
+
+let builtinToolSurfacesRegistered = false;
+
+export const registerBuiltinToolSurfaces = (): void => {
+ if (builtinToolSurfacesRegistered) return;
+
+ registerBuiltinRenders({
+ [AgentBuilderManifest.identifier]: AgentBuilderRenders as Record<string, BuiltinRender>,
+ [AgentDocumentsManifest.identifier]: AgentDocumentsRenders as Record<string, BuiltinRender>,
+ [AgentManagementManifest.identifier]: AgentManagementRenders as Record<string, BuiltinRender>,
+ [ClaudeCodeIdentifier]: ClaudeCodeRenders as Record<string, BuiltinRender>,
+ [CloudSandboxManifest.identifier]: CloudSandboxRenders as Record<string, BuiltinRender>,
+ [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderRenders as Record<
+ string,
+ BuiltinRender
+ >,
+ [GroupManagementManifest.identifier]: GroupManagementRenders as Record<string, BuiltinRender>,
+ [KnowledgeBaseManifest.identifier]: KnowledgeBaseRenders as Record<string, BuiltinRender>,
+ [LobeAgentManifest.identifier]: LobeAgentRenders as Record<string, BuiltinRender>,
+ [LobeDeliveryCheckerManifest.identifier]: LobeDeliveryCheckerRenders as Record<
+ string,
+ BuiltinRender
+ >,
+ [LocalSystemManifest.identifier]: LocalSystemRenders as Record<string, BuiltinRender>,
+ [MemoryManifest.identifier]: MemoryRenders as Record<string, BuiltinRender>,
+ [MessageManifest.identifier]: MessageRenders as Record<string, BuiltinRender>,
+ [NotebookIdentifier]: NotebookRenders,
+ [PageAgentManifest.identifier]: PageAgentRenders as Record<string, BuiltinRender>,
+ [RemoteDeviceManifest.identifier]: RemoteDeviceRenders as Record<string, BuiltinRender>,
+ [SkillStoreManifest.identifier]: SkillStoreRenders as Record<string, BuiltinRender>,
+ [SkillsManifest.identifier]: SkillsRenders as Record<string, BuiltinRender>,
+ [TaskManifest.identifier]: TaskRenders as Record<string, BuiltinRender>,
+ [LobeActivatorManifest.identifier]: LobeActivatorRenders as Record<string, BuiltinRender>,
+ [WebBrowsingManifest.identifier]: WebBrowsingRenders as Record<string, BuiltinRender>,
+ [WebOnboardingManifest.identifier]: WebOnboardingRenders as Record<string, BuiltinRender>,
+ codex: {
+ ...CodexRenders,
+ command_execution: RunCommandRender as BuiltinRender,
+ },
+ [GithubIdentifier]: GithubRenders,
+ });
+
+ registerBuiltinInspectors({
+ [AgentBuilderManifest.identifier]: AgentBuilderInspectors as Record<string, BuiltinInspector>,
+ [AgentDocumentsManifest.identifier]: AgentDocumentsInspectors as Record<
+ string,
+ BuiltinInspector
+ >,
+ [AgentManagementManifest.identifier]: AgentManagementInspectors as Record<
+ string,
+ BuiltinInspector
+ >,
+ [ClaudeCodeIdentifier]: ClaudeCodeInspectors as Record<string, BuiltinInspector>,
+ [CloudSandboxManifest.identifier]: CloudSandboxInspectors as Record<string, BuiltinInspector>,
+ [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderInspectors as Record<
+ string,
+ BuiltinInspector
+ >,
+ [GroupManagementManifest.identifier]: GroupManagementInspectors as Record<
+ string,
+ BuiltinInspector
+ >,
+ [KnowledgeBaseManifest.identifier]: KnowledgeBaseInspectors as Record<string, BuiltinInspector>,
+ [LobeAgentManifest.identifier]: LobeAgentInspectors as Record<string, BuiltinInspector>,
+ [LobeDeliveryCheckerManifest.identifier]: LobeDeliveryCheckerInspectors as Record<
+ string,
+ BuiltinInspector
+ >,
+ [LocalSystemManifest.identifier]: LocalSystemInspectors as Record<string, BuiltinInspector>,
+ [MemoryManifest.identifier]: MemoryInspectors as Record<string, BuiltinInspector>,
+ [MessageManifest.identifier]: MessageInspectors as Record<string, BuiltinInspector>,
+ [PageAgentManifest.identifier]: PageAgentInspectors as Record<string, BuiltinInspector>,
+ [LobeActivatorManifest.identifier]: LobeActivatorInspectors as Record<string, BuiltinInspector>,
+ [selfFeedbackIntentManifest.identifier]: SelfFeedbackIntentInspectors as Record<
+ string,
+ BuiltinInspector
+ >,
+ [SkillStoreManifest.identifier]: SkillStoreInspectors as Record<string, BuiltinInspector>,
+ [SkillsManifest.identifier]: SkillsInspectors as Record<string, BuiltinInspector>,
+ [TaskManifest.identifier]: TaskInspectors as Record<string, BuiltinInspector>,
+ [WebBrowsingManifest.identifier]: WebBrowsingInspectors as Record<string, BuiltinInspector>,
+ [WebOnboardingManifest.identifier]: WebOnboardingInspectors as Record<string, BuiltinInspector>,
+ codex: CodexInspectors,
+ [GithubIdentifier]: GithubInspectors,
+ [LinearIdentifier]: LinearInspectors,
+ [TwitterIdentifier]: TwitterInspectors,
+ });
+
+ registerBuiltinStreamings({
+ [AgentBuilderManifest.identifier]: AgentBuilderStreamings as Record<string, BuiltinStreaming>,
+ [AgentDocumentsManifest.identifier]: AgentDocumentsStreamings as Record<
+ string,
+ BuiltinStreaming
+ >,
+ [AgentManagementManifest.identifier]: AgentManagementStreamings as Record<
+ string,
+ BuiltinStreaming
+ >,
+ [ClaudeCodeIdentifier]: ClaudeCodeStreamings as Record<string, BuiltinStreaming>,
+ [CloudSandboxManifest.identifier]: CloudSandboxStreamings as Record<string, BuiltinStreaming>,
+ [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderStreamings as Record<
+ string,
+ BuiltinStreaming
+ >,
+ [GroupManagementManifest.identifier]: GroupManagementStreamings as Record<
+ string,
+ BuiltinStreaming
+ >,
+ [LobeAgentManifest.identifier]: LobeAgentStreamings as Record<string, BuiltinStreaming>,
+ [LocalSystemManifest.identifier]: LocalSystemStreamings as Record<string, BuiltinStreaming>,
+ [MemoryManifest.identifier]: MemoryStreamings as Record<string, BuiltinStreaming>,
+ [MessageManifest.identifier]: MessageStreamings as Record<string, BuiltinStreaming>,
+ [PageAgentManifest.identifier]: PageAgentStreamings as Record<string, BuiltinStreaming>,
+ });
+
+ registerBuiltinInterventions({
+ [AgentBuilderManifest.identifier]: AgentBuilderInterventions as Record<
+ string,
+ BuiltinIntervention
+ >,
+ [ClaudeCodeIdentifier]: ClaudeCodeInterventions as Record<string, BuiltinIntervention>,
+ [CloudSandboxManifest.identifier]: CloudSandboxInterventions as Record<
+ string,
+ BuiltinIntervention
+ >,
+ [GroupManagementManifest.identifier]: GroupManagementInterventions as Record<
+ string,
+ BuiltinIntervention
+ >,
+ [LobeAgentManifest.identifier]: LobeAgentInterventions as Record<string, BuiltinIntervention>,
+ [LocalSystemIdentifier]: LocalSystemInterventions as Record<string, BuiltinIntervention>,
+ [MemoryManifest.identifier]: MemoryInterventions as Record<string, BuiltinIntervention>,
+ [MessageManifest.identifier]: MessageInterventions as Record<string, BuiltinIntervention>,
+ [UserInteractionIdentifier]: UserInteractionInterventions as Record<
+ string,
+ BuiltinIntervention
+ >,
+ [WebOnboardingManifest.identifier]: WebOnboardingInterventions as Record<
+ string,
+ BuiltinIntervention
+ >,
+ });
+
+ registerBuiltinPlaceholders({
+ [LocalSystemIdentifier]: {
+ [LocalSystemApiName.searchFiles]: LocalSystemSearchFilesPlaceholder as BuiltinPlaceholder,
+ [LocalSystemApiName.listFiles]: LocalSystemListFilesPlaceholder as BuiltinPlaceholder,
+ // Legacy aliases β€” keep these so historical messages keep rendering.
+ listLocalFiles: LocalSystemListFilesPlaceholder as BuiltinPlaceholder,
+ searchLocalFiles: LocalSystemSearchFilesPlaceholder as BuiltinPlaceholder,
+ },
+ [WebBrowsingManifest.identifier]: WebBrowsingPlaceholders as Record<string, BuiltinPlaceholder>,
+ });
+
+ registerBuiltinPortals({
+ actions: {
+ [LobeDeliveryCheckerManifest.identifier]:
+ LobeDeliveryCheckerPortalActions as BuiltinPortalTitle,
+ },
+ portals: {
+ [LobeDeliveryCheckerManifest.identifier]: LobeDeliveryCheckerPortal as BuiltinPortal,
+ [WebBrowsingManifest.identifier]: WebBrowsingPortal as BuiltinPortal,
+ },
+ titles: {
+ [LobeDeliveryCheckerManifest.identifier]:
+ LobeDeliveryCheckerPortalTitle as BuiltinPortalTitle,
+ [WebBrowsingManifest.identifier]: WebBrowsingPortalTitle as BuiltinPortalTitle,
+ },
+ });
+
+ builtinToolSurfacesRegistered = true;
+};
diff --git a/packages/builtin-tools/src/renders.ts b/packages/builtin-tools/src/renders.ts
index 5c1491319bb..c4b782810e8 100644
--- a/packages/builtin-tools/src/renders.ts
+++ b/packages/builtin-tools/src/renders.ts
@@ -1,57 +1,4 @@
-import {
- LobeActivatorManifest,
- LobeActivatorRenders,
-} from '@lobechat/builtin-tool-activator/client';
-import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';
-import { AgentBuilderRenders } from '@lobechat/builtin-tool-agent-builder/client';
-import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';
-import { AgentDocumentsRenders } from '@lobechat/builtin-tool-agent-documents/client';
-import { AgentManagementManifest } from '@lobechat/builtin-tool-agent-management';
-import { AgentManagementRenders } from '@lobechat/builtin-tool-agent-management/client';
-import { ClaudeCodeIdentifier, ClaudeCodeRenders } from '@lobechat/builtin-tool-claude-code/client';
-import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
-import { CloudSandboxRenders } from '@lobechat/builtin-tool-cloud-sandbox/client';
-import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';
-import { GroupAgentBuilderRenders } from '@lobechat/builtin-tool-group-agent-builder/client';
-import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
-import { GroupManagementRenders } from '@lobechat/builtin-tool-group-management/client';
-import {
- KnowledgeBaseManifest,
- KnowledgeBaseRenders,
-} from '@lobechat/builtin-tool-knowledge-base/client';
-import { LobeAgentManifest, LobeAgentRenders } from '@lobechat/builtin-tool-lobe-agent/client';
-import {
- LobeDeliveryCheckerManifest,
- LobeDeliveryCheckerRenders,
-} from '@lobechat/builtin-tool-lobe-delivery-checker/client';
-import {
- LocalSystemManifest,
- LocalSystemRenders,
-} from '@lobechat/builtin-tool-local-system/client';
-import { MemoryManifest, MemoryRenders } from '@lobechat/builtin-tool-memory/client';
-import { MessageManifest, MessageRenders } from '@lobechat/builtin-tool-message/client';
-import { PageAgentManifest, PageAgentRenders } from '@lobechat/builtin-tool-page-agent/client';
-import {
- RemoteDeviceManifest,
- RemoteDeviceRenders,
-} from '@lobechat/builtin-tool-remote-device/client';
-import { SkillStoreManifest, SkillStoreRenders } from '@lobechat/builtin-tool-skill-store/client';
-import { SkillsManifest, SkillsRenders } from '@lobechat/builtin-tool-skills/client';
-import { TaskManifest, TaskRenders } from '@lobechat/builtin-tool-task/client';
-import {
- WebBrowsingManifest,
- WebBrowsingRenders,
-} from '@lobechat/builtin-tool-web-browsing/client';
-import {
- WebOnboardingManifest,
- WebOnboardingRenders,
-} from '@lobechat/builtin-tool-web-onboarding/client';
-import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';
-import { type BuiltinRender } from '@lobechat/types';
-
-import { CodexRenders } from './codex';
-import { GithubIdentifier, GithubRenders } from './github';
-import { NotebookIdentifier, NotebookRenders } from './notebook';
+import type { BuiltinRender } from '@lobechat/types';
export interface BuiltinRenderRegistryEntry {
apiName: string;
@@ -63,41 +10,19 @@ export interface BuiltinRenderRegistryEntry {
* Builtin tools renders registry
* Organized by toolset (identifier) -> API name
*/
-const BuiltinToolsRenders: Record<string, Record<string, BuiltinRender>> = {
- [AgentBuilderManifest.identifier]: AgentBuilderRenders as Record<string, BuiltinRender>,
- [AgentDocumentsManifest.identifier]: AgentDocumentsRenders as Record<string, BuiltinRender>,
- [AgentManagementManifest.identifier]: AgentManagementRenders as Record<string, BuiltinRender>,
- [ClaudeCodeIdentifier]: ClaudeCodeRenders as Record<string, BuiltinRender>,
- [CloudSandboxManifest.identifier]: CloudSandboxRenders as Record<string, BuiltinRender>,
- [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderRenders as Record<string, BuiltinRender>,
- [GroupManagementManifest.identifier]: GroupManagementRenders as Record<string, BuiltinRender>,
- [KnowledgeBaseManifest.identifier]: KnowledgeBaseRenders as Record<string, BuiltinRender>,
- [LobeAgentManifest.identifier]: LobeAgentRenders as Record<string, BuiltinRender>,
- [LobeDeliveryCheckerManifest.identifier]: LobeDeliveryCheckerRenders as Record<
- string,
- BuiltinRender
- >,
- [LocalSystemManifest.identifier]: LocalSystemRenders as Record<string, BuiltinRender>,
- [MemoryManifest.identifier]: MemoryRenders as Record<string, BuiltinRender>,
- [MessageManifest.identifier]: MessageRenders as Record<string, BuiltinRender>,
- [NotebookIdentifier]: NotebookRenders,
- [PageAgentManifest.identifier]: PageAgentRenders as Record<string, BuiltinRender>,
- [RemoteDeviceManifest.identifier]: RemoteDeviceRenders as Record<string, BuiltinRender>,
- [SkillStoreManifest.identifier]: SkillStoreRenders as Record<string, BuiltinRender>,
- [SkillsManifest.identifier]: SkillsRenders as Record<string, BuiltinRender>,
- [TaskManifest.identifier]: TaskRenders as Record<string, BuiltinRender>,
- [LobeActivatorManifest.identifier]: LobeActivatorRenders as Record<string, BuiltinRender>,
- [WebBrowsingManifest.identifier]: WebBrowsingRenders as Record<string, BuiltinRender>,
- [WebOnboardingManifest.identifier]: WebOnboardingRenders as Record<string, BuiltinRender>,
- codex: {
- ...CodexRenders,
- command_execution: RunCommandRender as BuiltinRender,
- },
- [GithubIdentifier]: GithubRenders,
+const builtinToolsRenders: Record<string, Record<string, BuiltinRender>> = {};
+
+export const registerBuiltinRenders = (
+ entries: Record<string, Record<string, BuiltinRender>>,
+): void => {
+ for (const [identifier, renders] of Object.entries(entries)) {
+ const current = builtinToolsRenders[identifier];
+ builtinToolsRenders[identifier] = current ? Object.assign(current, renders) : renders;
+ }
};
export const listBuiltinRenderEntries = (): BuiltinRenderRegistryEntry[] =>
- Object.entries(BuiltinToolsRenders).flatMap(([identifier, toolset]) =>
+ Object.entries(builtinToolsRenders).flatMap(([identifier, toolset]) =>
Object.entries(toolset)
.filter((entry): entry is [string, BuiltinRender] => !!entry[1])
.map(([apiName, render]) => ({
@@ -118,7 +43,7 @@ export const getBuiltinRender = (
): BuiltinRender | undefined => {
if (!identifier) return undefined;
- const toolset = BuiltinToolsRenders[identifier];
+ const toolset = builtinToolsRenders[identifier];
if (!toolset) return undefined;
if (apiName && toolset[apiName]) {
diff --git a/packages/builtin-tools/src/streamings.ts b/packages/builtin-tools/src/streamings.ts
index afaa2bd70d2..90ee8dad7dc 100644
--- a/packages/builtin-tools/src/streamings.ts
+++ b/packages/builtin-tools/src/streamings.ts
@@ -1,40 +1,4 @@
-import {
- AgentBuilderManifest,
- AgentBuilderStreamings,
-} from '@lobechat/builtin-tool-agent-builder/client';
-import {
- AgentDocumentsManifest,
- AgentDocumentsStreamings,
-} from '@lobechat/builtin-tool-agent-documents/client';
-import {
- AgentManagementManifest,
- AgentManagementStreamings,
-} from '@lobechat/builtin-tool-agent-management/client';
-import {
- ClaudeCodeIdentifier,
- ClaudeCodeStreamings,
-} from '@lobechat/builtin-tool-claude-code/client';
-import {
- CloudSandboxManifest,
- CloudSandboxStreamings,
-} from '@lobechat/builtin-tool-cloud-sandbox/client';
-import {
- GroupAgentBuilderManifest,
- GroupAgentBuilderStreamings,
-} from '@lobechat/builtin-tool-group-agent-builder/client';
-import {
- GroupManagementManifest,
- GroupManagementStreamings,
-} from '@lobechat/builtin-tool-group-management/client';
-import { LobeAgentManifest, LobeAgentStreamings } from '@lobechat/builtin-tool-lobe-agent/client';
-import {
- LocalSystemManifest,
- LocalSystemStreamings,
-} from '@lobechat/builtin-tool-local-system/client';
-import { MemoryManifest, MemoryStreamings } from '@lobechat/builtin-tool-memory/client';
-import { MessageManifest, MessageStreamings } from '@lobechat/builtin-tool-message/client';
-import { PageAgentManifest, PageAgentStreamings } from '@lobechat/builtin-tool-page-agent/client';
-import { type BuiltinStreaming } from '@lobechat/types';
+import type { BuiltinStreaming } from '@lobechat/types';
/**
* Builtin tools streaming renderer registry
@@ -44,28 +8,15 @@ import { type BuiltinStreaming } from '@lobechat/types';
* still executing, allowing real-time feedback to users.
* The component should fetch streaming content from store internally.
*/
-const BuiltinToolStreamings: Record<string, Record<string, BuiltinStreaming>> = {
- [AgentBuilderManifest.identifier]: AgentBuilderStreamings as Record<string, BuiltinStreaming>,
- [AgentDocumentsManifest.identifier]: AgentDocumentsStreamings as Record<string, BuiltinStreaming>,
- [AgentManagementManifest.identifier]: AgentManagementStreamings as Record<
- string,
- BuiltinStreaming
- >,
- [ClaudeCodeIdentifier]: ClaudeCodeStreamings as Record<string, BuiltinStreaming>,
- [CloudSandboxManifest.identifier]: CloudSandboxStreamings as Record<string, BuiltinStreaming>,
- [GroupAgentBuilderManifest.identifier]: GroupAgentBuilderStreamings as Record<
- string,
- BuiltinStreaming
- >,
- [GroupManagementManifest.identifier]: GroupManagementStreamings as Record<
- string,
- BuiltinStreaming
- >,
- [LobeAgentManifest.identifier]: LobeAgentStreamings as Record<string, BuiltinStreaming>,
- [LocalSystemManifest.identifier]: LocalSystemStreamings as Record<string, BuiltinStreaming>,
- [MemoryManifest.identifier]: MemoryStreamings as Record<string, BuiltinStreaming>,
- [MessageManifest.identifier]: MessageStreamings as Record<string, BuiltinStreaming>,
- [PageAgentManifest.identifier]: PageAgentStreamings as Record<string, BuiltinStreaming>,
+const builtinToolStreamings: Record<string, Record<string, BuiltinStreaming>> = {};
+
+export const registerBuiltinStreamings = (
+ entries: Record<string, Record<string, BuiltinStreaming>>,
+): void => {
+ for (const [identifier, streamings] of Object.entries(entries)) {
+ const current = builtinToolStreamings[identifier];
+ builtinToolStreamings[identifier] = current ? Object.assign(current, streamings) : streamings;
+ }
};
export interface BuiltinStreamingRegistryEntry {
@@ -75,7 +26,7 @@ export interface BuiltinStreamingRegistryEntry {
}
export const listBuiltinStreamingEntries = (): BuiltinStreamingRegistryEntry[] =>
- Object.entries(BuiltinToolStreamings).flatMap(([identifier, toolset]) =>
+ Object.entries(builtinToolStreamings).flatMap(([identifier, toolset]) =>
Object.entries(toolset)
.filter((entry): entry is [string, BuiltinStreaming] => !!entry[1])
.map(([apiName, streaming]) => ({
@@ -96,7 +47,7 @@ export const getBuiltinStreaming = (
): BuiltinStreaming | undefined => {
if (!identifier || !apiName) return undefined;
- const toolset = BuiltinToolStreamings[identifier];
+ const toolset = builtinToolStreamings[identifier];
if (!toolset) return undefined;
return toolset[apiName];
diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.test.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.test.ts
index 80bcac259e6..b36896b18a7 100644
--- a/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.test.ts
+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-page-agent.test.ts
@@ -1,7 +1,8 @@
+import { registerBuiltinToolSurfaces } from '@lobechat/builtin-tools/register';
import { getBuiltinStreaming } from '@lobechat/builtin-tools/streamings';
import { render, screen } from '@testing-library/react';
import { createElement } from 'react';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
import { deriveFixtureProps } from '../lifecycleMode';
import lobePageAgent from './lobe-page-agent';
@@ -11,6 +12,10 @@ vi.mock('@/components/StreamingMarkdown', () => ({
}));
describe('lobe-page-agent render gallery fixtures', () => {
+ beforeAll(() => {
+ registerBuiltinToolSurfaces();
+ });
+
it('exposes a partial initPage markdown payload for streaming previews', () => {
const variant = lobePageAgent.fixtures.initPage.variants[0];
const props = deriveFixtureProps(variant, 'streaming');
diff --git a/src/features/Portal/Plugins/Body/ToolRender.tsx b/src/features/Portal/Plugins/Body/ToolRender.tsx
index 6ad58eba902..e4bb6bf28c1 100644
--- a/src/features/Portal/Plugins/Body/ToolRender.tsx
+++ b/src/features/Portal/Plugins/Body/ToolRender.tsx
@@ -1,4 +1,4 @@
-import { BuiltinToolsPortals } from '@lobechat/builtin-tools/portals';
+import { getBuiltinPortal } from '@lobechat/builtin-tools/portals';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
@@ -23,7 +23,7 @@ const ToolRender = memo(() => {
if (!args) return;
- const Render = BuiltinToolsPortals[plugin.identifier];
+ const Render = getBuiltinPortal(plugin.identifier);
if (!Render) return null;
diff --git a/src/features/Portal/Plugins/Header.tsx b/src/features/Portal/Plugins/Header.tsx
index d4f7f10167d..95f41b4ec10 100644
--- a/src/features/Portal/Plugins/Header.tsx
+++ b/src/features/Portal/Plugins/Header.tsx
@@ -1,4 +1,4 @@
-import { BuiltinToolsPortalActions } from '@lobechat/builtin-tools/portals';
+import { getBuiltinPortalAction } from '@lobechat/builtin-tools/portals';
import type { BuiltinPortalTitle } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
@@ -20,7 +20,7 @@ const Header = () => {
const params = useChatStore(chatPortalSelectors.toolUIParams, isEqual);
const message = useChatStore(dbMessageSelectors.getDbMessageById(messageId || ''), isEqual);
- const Actions = BuiltinToolsPortalActions[toolUIIdentifier] as BuiltinPortalTitle | undefined;
+ const Actions = getBuiltinPortalAction(toolUIIdentifier) as BuiltinPortalTitle | undefined;
return (
<HeaderChrome
diff --git a/src/features/Portal/Plugins/Title.tsx b/src/features/Portal/Plugins/Title.tsx
index 8c414f3a018..364cc4d716a 100644
--- a/src/features/Portal/Plugins/Title.tsx
+++ b/src/features/Portal/Plugins/Title.tsx
@@ -1,4 +1,4 @@
-import { BuiltinToolsPortalTitles } from '@lobechat/builtin-tools/portals';
+import { getBuiltinPortalTitle } from '@lobechat/builtin-tools/portals';
import type { BuiltinPortalTitle } from '@lobechat/types';
import { Flexbox, Text } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
@@ -23,7 +23,7 @@ const Title = () => {
// A tool may ship its own portal header content; otherwise fall back to the
// generic plugin avatar + title. The back/close chrome is owned by the header
// wrapper (HeaderChrome), so the title slot must not add its own back arrow.
- const CustomTitle = BuiltinToolsPortalTitles[toolUIIdentifier] as BuiltinPortalTitle | undefined;
+ const CustomTitle = getBuiltinPortalTitle(toolUIIdentifier) as BuiltinPortalTitle | undefined;
if (CustomTitle) {
return (
diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsx
deleted file mode 100644
index 28a04fb9eaf..00000000000
--- a/src/layout/GlobalProvider/CacheHydrationGate.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-'use client';
-
-import { type PropsWithChildren, useEffect, useLayoutEffect, useState } from 'react';
-import { useSyncExternalStore } from 'react';
-
-import { cacheHydration } from '@/libs/swr/cacheHydration';
-import { useCacheScope } from '@/libs/swr/useCacheScope';
-import { useUserStore } from '@/store/user';
-import { authSelectors } from '@/store/user/selectors';
-
-/**
- * Max time to wait for the IndexedDB cache tier before rendering anyway, so a
- * slow / hung IndexedDB (or auth) never blocks the app indefinitely.
- */
-const HYDRATION_TIMEOUT = 1500;
-
-/**
- * Boot hydration gate.
- *
- * Holds the routed app until the *current identity scope's* IndexedDB cache
- * tier has hydrated, so local-first data (messages, topics, …) is present in
- * the SWR cache synchronously by the time components mount β€” including on a
- * deep-link cold load.
- *
- * While booting it renders nothing and lets the static HTML `#loading-screen`
- * (a fixed, top-most overlay defined in index.html) stay visible, then removes
- * it in the same layout pass that mounts the children. That keeps the boot a
- * single continuous loading screen β€” static loader β†’ app β€” with no second
- * in-React logo and no flash.
- *
- * We deliberately gate through the pre-auth (anon) phase too: before auth
- * resolves the scope is `anon:*`, and un-gating there would paint the app for a
- * frame before auth flips the scope to the signed-in one and re-hydration kicks
- * in β€” the old `app β†’ logo β†’ app` flicker. Waiting on `isAuthLoaded && ready`
- * collapses that into one uninterrupted loader.
- */
-const CacheHydrationGate = ({ children }: PropsWithChildren) => {
- const scope = useCacheScope();
- const isAuthLoaded = useUserStore(authSelectors.isLoaded);
-
- const ready = useSyncExternalStore(
- cacheHydration.subscribe,
- () => cacheHydration.isReady(scope),
- () => true, // SSR: nothing to hydrate
- );
-
- // Safety valve: never block longer than HYDRATION_TIMEOUT, even if auth or
- // IndexedDB hangs. A single boot-level timer (the workspace remount keyed on
- // activeWorkspaceId gives a fresh gate β€” and timer β€” when the scope changes).
- const [timedOut, setTimedOut] = useState(false);
- useEffect(() => {
- const timer = setTimeout(() => setTimedOut(true), HYDRATION_TIMEOUT);
- return () => clearTimeout(timer);
- }, []);
-
- const booting = !(isAuthLoaded && ready) && !timedOut;
-
- // Hand off from the static loader to the app in one layout pass: children are
- // already committed to the DOM by the time this runs, so removing the loader
- // here (before paint) reveals the app with no intermediate blank/logo frame.
- useLayoutEffect(() => {
- if (booting) return;
- document.getElementById('loading-screen')?.remove();
- }, [booting]);
-
- if (booting) return null;
-
- return <>{children}</>;
-};
-
-export default CacheHydrationGate;
diff --git a/src/layout/GlobalProvider/DeferredStoreInitialization.tsx b/src/layout/GlobalProvider/DeferredStoreInitialization.tsx
index ba542ebd789..2eb4af72eb1 100644
--- a/src/layout/GlobalProvider/DeferredStoreInitialization.tsx
+++ b/src/layout/GlobalProvider/DeferredStoreInitialization.tsx
@@ -1,11 +1,10 @@
'use client';
-import { memo, useEffect } from 'react';
+import { memo } from 'react';
import { useAiInfraStore } from '@/store/aiInfra';
import { useElectronStore } from '@/store/electron';
import { electronSyncSelectors } from '@/store/electron/selectors';
-import { useToolStore } from '@/store/tool';
import { useUserMemoryStore } from '@/store/userMemory';
interface DeferredStoreInitializationProps {
@@ -20,13 +19,6 @@ const DeferredStoreInitialization = memo<DeferredStoreInitializationProps>(({ is
useInitAiProviderKeyVaults(isLogin, isSyncActive);
useFetchPersona(isLogin);
- // Load custom connectors so the classic chat path can expose their tools.
- const fetchConnectors = useToolStore((s) => s.fetchConnectors);
- const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);
- useEffect(() => {
- if (isLogin && !isConnectorsInit) fetchConnectors();
- }, [isLogin, isConnectorsInit, fetchConnectors]);
-
return null;
});
diff --git a/src/layout/GlobalProvider/ImportSettings.tsx b/src/layout/GlobalProvider/ImportSettings.tsx
deleted file mode 100644
index ff376759ef1..00000000000
--- a/src/layout/GlobalProvider/ImportSettings.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-'use client';
-
-import { memo, useEffect, useState } from 'react';
-
-import { LOBE_URL_IMPORT_NAME } from '@/const/url';
-import { useUserStore } from '@/store/user';
-
-const ImportSettings = memo(() => {
- const [importUrlShareSettings, isUserStateInit] = useUserStore((s) => [
- s.importUrlShareSettings,
- s.isUserStateInit,
- ]);
-
- // Read initial URL param using browser API (not router-dependent)
- const [searchParam, setSearchParam] = useState<string>('');
-
- useEffect(() => {
- // Read from URL on mount
- if (typeof window !== 'undefined') {
- const params = new URLSearchParams(window.location.search);
- const param = params.get(LOBE_URL_IMPORT_NAME);
- if (param) {
- setSearchParam(param);
- // Clear the param from URL after reading
- params.delete(LOBE_URL_IMPORT_NAME);
- const newUrl = `${window.location.pathname}${params.toString() ? `?${params.toString()}` : ''}${window.location.hash}`;
- window.history.replaceState({}, '', newUrl);
- }
- }
- }, []);
-
- useEffect(() => {
- // Why use `usUserStateInit`,
- // see: https://github.com/lobehub/lobe-chat/pull/4072
- if (searchParam && isUserStateInit) {
- importUrlShareSettings(searchParam);
- }
- }, [searchParam, isUserStateInit, importUrlShareSettings]);
-
- return null;
-});
-
-export default ImportSettings;
diff --git a/src/layout/GlobalProvider/Query.tsx b/src/layout/GlobalProvider/Query.tsx
index 1f99674505c..ca5a527ae85 100644
--- a/src/layout/GlobalProvider/Query.tsx
+++ b/src/layout/GlobalProvider/Query.tsx
@@ -2,12 +2,10 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { type PropsWithChildren } from 'react';
-import React, { useLayoutEffect, useRef, useState } from 'react';
+import React, { useState } from 'react';
import { type Cache, SWRConfig } from 'swr';
-import { cacheHydration } from '@/libs/swr/cacheHydration';
-import { swrCacheProvider } from '@/libs/swr/localStorageProvider';
-import { getCacheScope, useCacheScope } from '@/libs/swr/useCacheScope';
+import { appSWRCacheProvider } from '@/libs/swr/appCacheProvider';
import { lambdaQuery, lambdaQueryClient } from '@/libs/trpc/client';
import SWRMutateInitializer from './SWRMutateInitializer';
@@ -19,31 +17,9 @@ const QueryProvider = ({ children }: PropsWithChildren) => {
typeof lambdaQuery.Provider
>['queryClient'];
- // The persistence namespace follows the live identity scope. `getCacheScope`
- // is read lazily on every load/save, so we don't recreate the provider (and
- // remount the tree) when the scope changes β€” instead we re-hydrate in place.
- // `cacheHydration.markReady` lets the boot gate wait for the IndexedDB tier.
- const [provider] = useState(() => swrCacheProvider(getCacheScope, cacheHydration.markReady));
-
- // Re-hydrate the cache from the new scope's namespace whenever the signed-in
- // user or active workspace changes (e.g. once async auth resolves), so data
- // never leaks across scopes and the correct local data is surfaced.
- //
- // Clear the new scope's hydration readiness *before* reloading: a scope we
- // visited earlier is still marked ready, so without this the boot gate would
- // render children immediately while `reloadScope()` has just dropped the
- // persisted entries and the IndexedDB re-load is still in flight β€” surfacing
- // empty/stale data that then flashes. Reset β†’ reload β†’ `markReady` (fired by
- // the provider once IDB finishes) keeps the gate blocking through the reload.
- // Run in a layout effect so the reset lands before paint, avoiding the flash.
- const scope = useCacheScope();
- const lastScope = useRef(scope);
- useLayoutEffect(() => {
- if (lastScope.current === scope) return;
- lastScope.current = scope;
- cacheHydration.reset(scope);
- provider.reloadScope?.();
- }, [scope, provider]);
+ // Reuse the app-level SWR provider initialized by the SPA bootstrap, so React
+ // consumes the same cache map that the bootstrap hydrates.
+ const [provider] = useState(() => appSWRCacheProvider);
return (
<SWRConfig value={{ provider: provider as unknown as (cache: Readonly<Cache>) => Cache }}>
diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsx
index eddfe46d889..a82465f37c2 100644
--- a/src/layout/SPAGlobalProvider/index.tsx
+++ b/src/layout/SPAGlobalProvider/index.tsx
@@ -12,11 +12,9 @@ import AgentMockDevtools from '@/features/AgentMockDevtools';
import DevFeatureFlagPanel from '@/features/DevFeatureFlagPanel';
import AuthProvider from '@/layout/AuthProvider';
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 ImportSettings from '@/layout/GlobalProvider/ImportSettings';
import QueryProvider from '@/layout/GlobalProvider/Query';
import ServerVersionOutdatedAlert from '@/layout/GlobalProvider/ServerVersionOutdatedAlert';
import StoreInitialization from '@/layout/GlobalProvider/StoreInitialization';
@@ -35,10 +33,6 @@ const ContextMenuHost = lazy(() =>
);
const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
- // The static HTML #loading-screen is removed by CacheHydrationGate once the
- // SWR cache has hydrated, so the boot stays one continuous loading screen
- // (static loader β†’ app) instead of flashing the loader away before the app
- // and its local-first data are ready.
const serverConfig: SPAServerConfig | undefined = window.__SERVER_CONFIG__;
const locale = document.documentElement.lang || 'en-US';
@@ -65,9 +59,7 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
<LazyMotion features={domMax}>
<TooltipGroup layoutAnimation={false}>
<StyleProvider speedy={import.meta.env.PROD}>
- <LobeAnalyticsProviderWrapper>
- <CacheHydrationGate>{children}</CacheHydrationGate>
- </LobeAnalyticsProviderWrapper>
+ <LobeAnalyticsProviderWrapper>{children}</LobeAnalyticsProviderWrapper>
</StyleProvider>
</TooltipGroup>
<Suspense>
@@ -83,7 +75,6 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
</AuthProvider>
</QueryProvider>
<Suspense>
- <ImportSettings />
{/* DevPanel disabled in SPA: depends on node:fs */}
{__DEV__ && (
<>
diff --git a/src/libs/swr/appCacheProvider.ts b/src/libs/swr/appCacheProvider.ts
new file mode 100644
index 00000000000..06314dae7bc
--- /dev/null
+++ b/src/libs/swr/appCacheProvider.ts
@@ -0,0 +1,8 @@
+import { swrCacheProvider } from './localStorageProvider';
+import { getCacheScope } from './useCacheScope';
+
+export const appSWRCacheProvider = swrCacheProvider(getCacheScope);
+
+export const hydrateAppSWRCache = async (): Promise<void> => {
+ await appSWRCacheProvider.hydrateScope?.();
+};
diff --git a/src/libs/swr/cacheHydration.test.ts b/src/libs/swr/cacheHydration.test.ts
deleted file mode 100644
index 3fbe2c78f71..00000000000
--- a/src/libs/swr/cacheHydration.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-
-import { cacheHydration } from './cacheHydration';
-import { buildCacheScope } from './useCacheScope';
-
-describe('cacheHydration', () => {
- it('tracks readiness per scope and notifies subscribers', () => {
- const scope = 'cacheHydration-test-1';
- const listener = vi.fn();
- const unsubscribe = cacheHydration.subscribe(listener);
-
- expect(cacheHydration.isReady(scope)).toBe(false);
-
- cacheHydration.markReady(scope);
- expect(cacheHydration.isReady(scope)).toBe(true);
- expect(listener).toHaveBeenCalledTimes(1);
-
- // marking again is a no-op (no extra emit)
- cacheHydration.markReady(scope);
- expect(listener).toHaveBeenCalledTimes(1);
-
- cacheHydration.reset(scope);
- expect(cacheHydration.isReady(scope)).toBe(false);
- expect(listener).toHaveBeenCalledTimes(2);
-
- unsubscribe();
- cacheHydration.markReady(scope);
- expect(listener).toHaveBeenCalledTimes(2); // unsubscribed
- });
-});
-
-describe('buildCacheScope', () => {
- it('falls back to anon/personal', () => {
- expect(buildCacheScope(undefined, undefined)).toBe('anon:personal');
- expect(buildCacheScope(null, null)).toBe('anon:personal');
- });
-
- it('combines user and workspace', () => {
- expect(buildCacheScope('u1', 'w1')).toBe('u1:w1');
- expect(buildCacheScope('u1', null)).toBe('u1:personal');
- });
-
- it('isolates different users and workspaces', () => {
- expect(buildCacheScope('u1', 'w1')).not.toBe(buildCacheScope('u2', 'w1'));
- expect(buildCacheScope('u1', 'w1')).not.toBe(buildCacheScope('u1', 'w2'));
- });
-});
diff --git a/src/libs/swr/cacheHydration.ts b/src/libs/swr/cacheHydration.ts
deleted file mode 100644
index c829be5625a..00000000000
--- a/src/libs/swr/cacheHydration.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * Cache hydration readiness store
- *
- * A tiny external store (consumable via `useSyncExternalStore`) that tracks
- * which identity scopes have finished hydrating their IndexedDB cache tier.
- *
- * The unified SWR cache provider marks a scope ready once its async IndexedDB
- * load completes; the boot `CacheHydrationGate` waits on this before mounting
- * the routed app, so local-first data (messages, topics, …) is present in the
- * cache synchronously by the time components mount β€” even on a deep-link cold
- * load. Decoupling through a module singleton lets the provider (high in the
- * tree) and the gate (around the routed children) communicate without prop or
- * context threading.
- */
-
-const readyScopes = new Set<string>();
-const listeners = new Set<() => void>();
-
-const emit = () => {
- for (const listener of listeners) listener();
-};
-
-export const cacheHydration = {
- isReady: (scope: string): boolean => readyScopes.has(scope),
-
- /** Mark a scope's IndexedDB tier as hydrated. */
- markReady: (scope: string): void => {
- if (readyScopes.has(scope)) return;
- readyScopes.add(scope);
- emit();
- },
-
- /** Clear readiness for a scope (e.g. before re-hydrating on scope change). */
- reset: (scope: string): void => {
- if (!readyScopes.delete(scope)) return;
- emit();
- },
-
- subscribe: (listener: () => void): (() => void) => {
- listeners.add(listener);
- return () => listeners.delete(listener);
- },
-};
diff --git a/src/libs/swr/cacheProvider.integration.test.tsx b/src/libs/swr/cacheProvider.integration.test.tsx
index 50302b5e357..683073c5069 100644
--- a/src/libs/swr/cacheProvider.integration.test.tsx
+++ b/src/libs/swr/cacheProvider.integration.test.tsx
@@ -62,12 +62,10 @@ describe('local-first cache chain (SWR + tiered provider + IndexedDB)', () => {
r1.unmount();
// --- session 2 ("reload"): fresh provider hydrates IndexedDB ------------
- // Model the boot gate: create the cache and await IndexedDB hydration
- // *before* the consuming component mounts, then hand SWR that hydrated map.
- const { hydrated: hydrated2, provider: p2 } = makeProvider();
- const hydratedMap = p2();
- await hydrated2;
- const stableProvider = (() => hydratedMap) as typeof p2;
+ // Model SPA bootstrap: hydrate the app-level provider before the consuming
+ // React tree mounts. SWR then receives the already-hydrated provider Map.
+ const { provider: p2 } = makeProvider();
+ await p2.hydrateScope?.();
// a slow network so the local snapshot must win the first paint
let resolveSlow: (v: unknown) => void;
@@ -75,7 +73,7 @@ describe('local-first cache chain (SWR + tiered provider + IndexedDB)', () => {
resolveSlow = r;
});
const fetcher2 = () => slow;
- const r2 = renderHook(() => useSWR(key, fetcher2), { wrapper: wrapper(stableProvider) });
+ const r2 = renderHook(() => useSWR(key, fetcher2), { wrapper: wrapper(p2) });
// local-first: data is available synchronously from the hydrated cache,
// before the slow fetch resolves
diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.ts
index 3313ee13c6b..47c8d184ee6 100644
--- a/src/libs/swr/localStorageProvider.ts
+++ b/src/libs/swr/localStorageProvider.ts
@@ -61,12 +61,17 @@ export interface CacheProviderOptions {
* SWR cache provider function with an in-place scope reloader.
*/
export type ScopedSWRProvider = (() => Map<string, unknown>) & {
+ /**
+ * Ensure the provider's Map exists and hydrate the current scope's IndexedDB
+ * tier. This is used by the SPA bootstrap while React mounts the root tree.
+ */
+ hydrateScope?: () => Promise<void>;
/**
* Flush pending writes, then re-hydrate the in-memory cache from the *current*
* scope's namespaces (localStorage synchronously, IndexedDB asynchronously).
* No-op until SWR has created the provider's Map.
*/
- reloadScope?: () => void;
+ reloadScope?: () => Promise<void>;
};
const isLocalStorageAvailable = (): boolean => {
@@ -113,12 +118,18 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
} = options;
// SSR / no storage β†’ plain memory cache, no persistence. Still signal
- // hydration so the boot gate never blocks.
+ // hydration so boot initialization never blocks.
if (!isLocalStorageAvailable()) {
- return () => {
+ const memoryProvider = (() => {
onScopeHydrated?.(getScope());
return new Map();
+ }) as ScopedSWRProvider;
+ memoryProvider.hydrateScope = async () => {
+ onScopeHydrated?.(getScope());
};
+ memoryProvider.reloadScope = memoryProvider.hydrateScope;
+
+ return memoryProvider;
}
/** Route a key to its persistence tier (idb wins over local). */
@@ -129,6 +140,9 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
};
let cacheMapInstance: TieredCacheMap | null = null;
+ let hydratedScope: string | null = null;
+ let hydrationEpoch = 0;
+ let pendingHydration: { promise: Promise<void>; scope: string } | null = null;
// --- localStorage tier (synchronous snapshot) ----------------------------
let localTimer: ReturnType<typeof setTimeout> | null = null;
@@ -212,8 +226,7 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
idbTimer = setTimeout(flushIdb, debounceMs);
};
- const loadIdb = async () => {
- const scope = getScope();
+ const loadIdb = async (scope: string, epoch: number) => {
try {
const entries = await localDataCache.entriesByScope(scope);
const now = Date.now();
@@ -221,13 +234,17 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
(e) => (e.version === undefined || e.version === version) && now - e.updatedAt <= ttl,
);
// Map may have changed scope while we awaited; only apply if still current.
- if (cacheMapInstance && getScope() === scope) {
+ if (cacheMapInstance && getScope() === scope && hydrationEpoch === epoch) {
cacheMapInstance.hydrate(valid.map((e) => [e.key, e.data]));
+ hydratedScope = scope;
}
} catch (error) {
onError(error as Error);
} finally {
onScopeHydrated?.(scope);
+ if (pendingHydration?.scope === scope && hydrationEpoch === epoch) {
+ pendingHydration = null;
+ }
}
};
@@ -325,16 +342,45 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
}
});
- const provider: ScopedSWRProvider = () => {
+ const ensureMap = (): TieredCacheMap => {
+ if (cacheMapInstance) return cacheMapInstance;
+
const map = new TieredCacheMap();
cacheMapInstance = map;
map.hydrate([...loadLocal().entries()]); // synchronous first paint
- void loadIdb(); // asynchronous local-first hydration
return map;
};
- provider.reloadScope = () => {
- if (!cacheMapInstance) return;
+ const hydrateScope = async (): Promise<void> => {
+ const scope = getScope();
+ ensureMap();
+ if (hydratedScope === scope) return;
+ if (pendingHydration?.scope === scope) return pendingHydration.promise;
+
+ const epoch = ++hydrationEpoch;
+ const promise = loadIdb(scope, epoch);
+ pendingHydration = { promise, scope };
+ return promise;
+ };
+
+ const provider: ScopedSWRProvider = () => {
+ const map = ensureMap();
+ void hydrateScope();
+ return map;
+ };
+
+ provider.hydrateScope = hydrateScope;
+
+ provider.reloadScope = async () => {
+ if (!cacheMapInstance) {
+ await hydrateScope();
+ return;
+ }
+
+ hydrationEpoch += 1;
+ hydratedScope = null;
+ pendingHydration = null;
+
// Drop pending writes scheduled for the previous scope.
if (localTimer) {
clearTimeout(localTimer);
@@ -349,7 +395,7 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
cacheMapInstance.dropPersisted();
cacheMapInstance.hydrate([...loadLocal().entries()]);
- void loadIdb();
+ await hydrateScope();
};
return provider;
@@ -403,8 +449,7 @@ export const CACHE_TIERS = {
* @param getScope resolver for the current identity scope. Evaluated lazily so
* persistence follows the active user/workspace; call `provider.reloadScope()`
* after the scope changes to re-hydrate in place.
- * @param onScopeHydrated notified after a scope's IndexedDB tier finishes
- * loading (used by the boot hydration gate).
+ * @param onScopeHydrated notified after a scope's IndexedDB tier finishes loading.
*/
export const swrCacheProvider = (
getScope: () => string,
diff --git a/src/libs/swr/useCacheScope.test.ts b/src/libs/swr/useCacheScope.test.ts
new file mode 100644
index 00000000000..cc1d6840895
--- /dev/null
+++ b/src/libs/swr/useCacheScope.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildCacheScope } from './useCacheScope';
+
+describe('buildCacheScope', () => {
+ it('falls back to anon/personal', () => {
+ expect(buildCacheScope(undefined, undefined)).toBe('anon:personal');
+ expect(buildCacheScope(null, null)).toBe('anon:personal');
+ });
+
+ it('combines user and workspace', () => {
+ expect(buildCacheScope('u1', 'w1')).toBe('u1:w1');
+ expect(buildCacheScope('u1', null)).toBe('u1:personal');
+ });
+
+ it('isolates different users and workspaces', () => {
+ expect(buildCacheScope('u1', 'w1')).not.toBe(buildCacheScope('u2', 'w1'));
+ expect(buildCacheScope('u1', 'w1')).not.toBe(buildCacheScope('u1', 'w2'));
+ });
+});
diff --git a/src/spa/AppLayer.tsx b/src/spa/AppLayer.tsx
new file mode 100644
index 00000000000..b7ffb5660c7
--- /dev/null
+++ b/src/spa/AppLayer.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import { memo, type PropsWithChildren, useLayoutEffect, useRef } from 'react';
+
+import { useAppReady } from './atoms/app';
+
+const removeLoadingScreen = () => {
+ document.querySelector('#loading-screen')?.remove();
+};
+
+const AppLayer = memo<PropsWithChildren>(({ children }) => {
+ const appReady = useAppReady();
+ const onceReady = useRef(false);
+
+ useLayoutEffect(() => {
+ if (!appReady || onceReady.current) return;
+
+ onceReady.current = true;
+ removeLoadingScreen();
+ }, [appReady]);
+
+ return appReady ? <>{children}</> : null;
+});
+
+AppLayer.displayName = 'AppLayer';
+
+export default AppLayer;
diff --git a/src/spa/atoms/app.test.ts b/src/spa/atoms/app.test.ts
new file mode 100644
index 00000000000..d30a8a91a5f
--- /dev/null
+++ b/src/spa/atoms/app.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it, vi } from 'vitest';
+
+describe('appReady', () => {
+ it('notifies subscribers when readiness changes', async () => {
+ vi.resetModules();
+ const { getAppReady, setAppReady, subscribeAppReady } = await import('./app');
+ const listener = vi.fn();
+ const unsubscribe = subscribeAppReady(listener);
+
+ expect(getAppReady()).toBe(false);
+
+ setAppReady(true);
+ expect(getAppReady()).toBe(true);
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ setAppReady(true);
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+ setAppReady(false);
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/spa/atoms/app.ts b/src/spa/atoms/app.ts
new file mode 100644
index 00000000000..e145b747120
--- /dev/null
+++ b/src/spa/atoms/app.ts
@@ -0,0 +1,26 @@
+import { useSyncExternalStore } from 'react';
+
+let appReady = false;
+const listeners = new Set<() => void>();
+
+const emit = () => {
+ for (const listener of listeners) listener();
+};
+
+export const getAppReady = () => appReady;
+
+export const setAppReady = (ready: boolean) => {
+ if (appReady === ready) return;
+
+ appReady = ready;
+ emit();
+};
+
+export const subscribeAppReady = (listener: () => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+export const useAppReady = () => useSyncExternalStore(subscribeAppReady, getAppReady, getAppReady);
diff --git a/src/spa/entry.desktop.tsx b/src/spa/entry.desktop.tsx
index fd60178409f..681eb45cce3 100644
--- a/src/spa/entry.desktop.tsx
+++ b/src/spa/entry.desktop.tsx
@@ -6,8 +6,11 @@ import { RouterProvider } from 'react-router-dom';
import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
import { createAppRouter } from '@/utils/router';
+import { startAppInitialization } from './initialize/bootstrap';
import { desktopRoutes } from './router/desktopRouter.config';
+startAppInitialization();
+
const router = createAppRouter(desktopRoutes);
createRoot(document.getElementById('root')!).render(
diff --git a/src/spa/entry.mobile.tsx b/src/spa/entry.mobile.tsx
index 64526b32aad..3cb73279086 100644
--- a/src/spa/entry.mobile.tsx
+++ b/src/spa/entry.mobile.tsx
@@ -6,8 +6,11 @@ import { RouterProvider } from 'react-router-dom';
import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
import { createAppRouter } from '@/utils/router';
+import { startAppInitialization } from './initialize/bootstrap';
import { mobileRoutes } from './router/mobileRouter.config';
+startAppInitialization();
+
const router = createAppRouter(mobileRoutes);
createRoot(document.getElementById('root')!).render(
diff --git a/src/spa/entry.popup.tsx b/src/spa/entry.popup.tsx
index 7141eef060c..fd36956c733 100644
--- a/src/spa/entry.popup.tsx
+++ b/src/spa/entry.popup.tsx
@@ -6,8 +6,11 @@ import { RouterProvider } from 'react-router-dom';
import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
import { createAppRouter } from '@/utils/router';
+import { startAppInitialization } from './initialize/bootstrap';
import { popupRoutes } from './router/popupRouter.config';
+startAppInitialization();
+
const router = createAppRouter(popupRoutes);
createRoot(document.getElementById('root')!).render(
diff --git a/src/spa/entry.web.tsx b/src/spa/entry.web.tsx
index bb31c9b1dfe..40a717135de 100644
--- a/src/spa/entry.web.tsx
+++ b/src/spa/entry.web.tsx
@@ -7,8 +7,11 @@ import BootErrorBoundary from '@/components/BootErrorBoundary';
import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
import { createAppRouter } from '@/utils/router';
+import { startAppInitialization } from './initialize/bootstrap';
import { desktopRoutes } from './router/desktopRouter.config';
+startAppInitialization();
+
const debugProxyBase = '/_dangerous_local_dev_proxy';
const basename =
window.__DEBUG_PROXY__ || window.location.pathname.startsWith(debugProxyBase)
diff --git a/src/spa/initialize/bootstrap.ts b/src/spa/initialize/bootstrap.ts
new file mode 100644
index 00000000000..76d4f394ae8
--- /dev/null
+++ b/src/spa/initialize/bootstrap.ts
@@ -0,0 +1,30 @@
+import { flushSync } from 'react-dom';
+
+import { setAppReady } from '../atoms/app';
+import { initializeApp } from '.';
+import { startSWRCacheScopeSync } from './cacheScope';
+import { startImportSettingsFromUrl } from './importSettings';
+import { startPostRenderInitialization } from './postRender';
+import { registerBuiltinToolSurfaces } from './toolSurfaces';
+
+let started = false;
+
+export const startAppInitialization = () => {
+ if (started) return;
+ started = true;
+
+ startSWRCacheScopeSync();
+ startImportSettingsFromUrl();
+ registerBuiltinToolSurfaces();
+
+ void initializeApp()
+ .catch((error) => {
+ console.error('[SPA Initialize] failed', error);
+ })
+ .finally(() => {
+ flushSync(() => {
+ setAppReady(true);
+ });
+ startPostRenderInitialization();
+ });
+};
diff --git a/src/spa/initialize/cacheScope.ts b/src/spa/initialize/cacheScope.ts
new file mode 100644
index 00000000000..e43bf0f9742
--- /dev/null
+++ b/src/spa/initialize/cacheScope.ts
@@ -0,0 +1,22 @@
+import { appSWRCacheProvider } from '@/libs/swr/appCacheProvider';
+import { getCacheScope } from '@/libs/swr/useCacheScope';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+let lastScope: string | undefined;
+let unsubscribeUserScope: (() => void) | undefined;
+
+const syncSWRCacheScope = () => {
+ const scope = getCacheScope();
+ if (lastScope === scope) return;
+
+ lastScope = scope;
+ void appSWRCacheProvider.reloadScope?.();
+};
+
+export const startSWRCacheScopeSync = () => {
+ if (unsubscribeUserScope) return;
+
+ lastScope = getCacheScope();
+ unsubscribeUserScope = useUserStore.subscribe(userProfileSelectors.userId, syncSWRCacheScope);
+};
diff --git a/src/spa/initialize/connectors.test.ts b/src/spa/initialize/connectors.test.ts
new file mode 100644
index 00000000000..ee5185c4eda
--- /dev/null
+++ b/src/spa/initialize/connectors.test.ts
@@ -0,0 +1,60 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ fetchConnectors: vi.fn(async () => {}),
+ isConnectorsInit: false,
+ isSignedIn: false,
+ toolSubscribe: vi.fn(),
+ userSubscribe: vi.fn(),
+}));
+
+vi.mock('@/store/tool', () => ({
+ getToolStoreState: () => ({
+ fetchConnectors: mocks.fetchConnectors,
+ isConnectorsInit: mocks.isConnectorsInit,
+ }),
+ useToolStore: {
+ subscribe: mocks.toolSubscribe,
+ },
+}));
+
+vi.mock('@/store/user', () => ({
+ getUserStoreState: () => ({
+ isSignedIn: mocks.isSignedIn,
+ }),
+ useUserStore: {
+ subscribe: mocks.userSubscribe,
+ },
+}));
+
+describe('startConnectorInitialization', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ mocks.fetchConnectors.mockResolvedValue(undefined);
+ mocks.isConnectorsInit = false;
+ mocks.isSignedIn = false;
+ });
+
+ it('fetches connectors when a signed-in user is present', async () => {
+ mocks.isSignedIn = true;
+
+ const { startConnectorInitialization } = await import('./connectors');
+ startConnectorInitialization();
+
+ expect(mocks.fetchConnectors).toHaveBeenCalledTimes(1);
+ });
+
+ it('waits for login before fetching connectors', async () => {
+ const { startConnectorInitialization } = await import('./connectors');
+ startConnectorInitialization();
+
+ expect(mocks.fetchConnectors).not.toHaveBeenCalled();
+
+ const userListener = mocks.userSubscribe.mock.calls[0]![0] as () => void;
+ mocks.isSignedIn = true;
+ userListener();
+
+ expect(mocks.fetchConnectors).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/spa/initialize/connectors.ts b/src/spa/initialize/connectors.ts
new file mode 100644
index 00000000000..d3a89c2dde9
--- /dev/null
+++ b/src/spa/initialize/connectors.ts
@@ -0,0 +1,29 @@
+import { getToolStoreState, useToolStore } from '@/store/tool';
+import { getUserStoreState, useUserStore } from '@/store/user';
+
+let connectorsStarted = false;
+let pendingFetch: Promise<void> | undefined;
+
+const ensureConnectors = () => {
+ const { isSignedIn } = getUserStoreState();
+ const { fetchConnectors, isConnectorsInit } = getToolStoreState();
+
+ if (!isSignedIn || isConnectorsInit || pendingFetch) return;
+
+ pendingFetch = fetchConnectors()
+ .catch((error) => {
+ console.error('[SPA Initialize] fetchConnectors failed', error);
+ })
+ .finally(() => {
+ pendingFetch = undefined;
+ });
+};
+
+export const startConnectorInitialization = () => {
+ if (connectorsStarted) return;
+ connectorsStarted = true;
+
+ ensureConnectors();
+ useUserStore.subscribe(ensureConnectors);
+ useToolStore.subscribe(ensureConnectors);
+};
diff --git a/src/spa/initialize/importSettings.test.ts b/src/spa/initialize/importSettings.test.ts
new file mode 100644
index 00000000000..0e454f6a7fe
--- /dev/null
+++ b/src/spa/initialize/importSettings.test.ts
@@ -0,0 +1,66 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ importUrlShareSettings: vi.fn(),
+ isUserStateInit: false,
+ subscribe: vi.fn(),
+ unsubscribe: vi.fn(),
+}));
+
+vi.mock('@/const/url', () => ({
+ LOBE_URL_IMPORT_NAME: 'settings',
+}));
+
+vi.mock('@/store/user', () => ({
+ getUserStoreState: () => ({
+ importUrlShareSettings: mocks.importUrlShareSettings,
+ isUserStateInit: mocks.isUserStateInit,
+ }),
+ useUserStore: {
+ subscribe: mocks.subscribe,
+ },
+}));
+
+describe('startImportSettingsFromUrl', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ mocks.isUserStateInit = false;
+ mocks.subscribe.mockReturnValue(mocks.unsubscribe);
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('imports settings once user state is ready and removes the URL param', async () => {
+ window.history.replaceState({}, '', '/agent/a?settings=encoded&foo=bar#hash');
+
+ const { startImportSettingsFromUrl } = await import('./importSettings');
+ startImportSettingsFromUrl();
+
+ expect(window.location.pathname + window.location.search + window.location.hash).toBe(
+ '/agent/a?foo=bar#hash',
+ );
+ expect(mocks.importUrlShareSettings).not.toHaveBeenCalled();
+ expect(mocks.subscribe).toHaveBeenCalledTimes(1);
+
+ const listener = mocks.subscribe.mock.calls[0]![1] as () => void;
+ mocks.isUserStateInit = true;
+ listener();
+
+ expect(mocks.importUrlShareSettings).toHaveBeenCalledWith('encoded');
+ expect(mocks.unsubscribe).toHaveBeenCalledTimes(1);
+ });
+
+ it('imports immediately when user state is already ready', async () => {
+ mocks.isUserStateInit = true;
+ window.history.replaceState({}, '', '/?settings=encoded');
+
+ const { startImportSettingsFromUrl } = await import('./importSettings');
+ startImportSettingsFromUrl();
+
+ expect(mocks.importUrlShareSettings).toHaveBeenCalledWith('encoded');
+ expect(mocks.subscribe).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/spa/initialize/importSettings.ts b/src/spa/initialize/importSettings.ts
new file mode 100644
index 00000000000..5d0a0849427
--- /dev/null
+++ b/src/spa/initialize/importSettings.ts
@@ -0,0 +1,55 @@
+import { LOBE_URL_IMPORT_NAME } from '@/const/url';
+import { getUserStoreState, useUserStore } from '@/store/user';
+
+let importSettingsStarted = false;
+let pendingSettings: string | null = null;
+let unsubscribeUserState: (() => void) | undefined;
+
+const clearUserStateSubscription = () => {
+ unsubscribeUserState?.();
+ unsubscribeUserState = undefined;
+};
+
+const readImportSettingsFromUrl = (): string | null => {
+ if (typeof window === 'undefined') return null;
+
+ const params = new URLSearchParams(window.location.search);
+ const settings = params.get(LOBE_URL_IMPORT_NAME);
+ if (!settings) return null;
+
+ params.delete(LOBE_URL_IMPORT_NAME);
+ const search = params.toString();
+ const nextUrl = `${window.location.pathname}${search ? `?${search}` : ''}${window.location.hash}`;
+ window.history.replaceState({}, '', nextUrl);
+
+ return settings;
+};
+
+const tryImportSettings = () => {
+ if (!pendingSettings) return;
+
+ const { importUrlShareSettings, isUserStateInit } = getUserStoreState();
+ if (!isUserStateInit) return;
+
+ const settings = pendingSettings;
+ pendingSettings = null;
+ clearUserStateSubscription();
+
+ void importUrlShareSettings(settings);
+};
+
+export const startImportSettingsFromUrl = () => {
+ if (importSettingsStarted) return;
+ importSettingsStarted = true;
+
+ pendingSettings = readImportSettingsFromUrl();
+ if (!pendingSettings) return;
+
+ tryImportSettings();
+ if (pendingSettings) {
+ unsubscribeUserState = useUserStore.subscribe(
+ (state) => state.isUserStateInit,
+ tryImportSettings,
+ );
+ }
+};
diff --git a/src/spa/initialize/index.ts b/src/spa/initialize/index.ts
new file mode 100644
index 00000000000..a115ff539ee
--- /dev/null
+++ b/src/spa/initialize/index.ts
@@ -0,0 +1,20 @@
+import { hydrateAppSWRCache } from '@/libs/swr/appCacheProvider';
+
+const appLog = (...args: unknown[]) => {
+ if (__DEV__) console.info('[SPA Initialize]', ...args);
+};
+
+const apm = async <T>(label: string, task: () => Promise<T> | T): Promise<T> => {
+ const start = Date.now();
+ const result = await task();
+ appLog(`${label} took ${Date.now() - start}ms`);
+ return result;
+};
+
+export const initializeApp = async (): Promise<void> => {
+ const start = Date.now();
+
+ await apm('hydrateSWRCache', hydrateAppSWRCache);
+
+ appLog('done', `${Date.now() - start}ms`);
+};
diff --git a/src/spa/initialize/postRender.test.ts b/src/spa/initialize/postRender.test.ts
new file mode 100644
index 00000000000..81269a5d91b
--- /dev/null
+++ b/src/spa/initialize/postRender.test.ts
@@ -0,0 +1,64 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ registerBuiltinToolExecutors: vi.fn(),
+ startConnectorInitialization: vi.fn(),
+}));
+
+vi.mock('@/store/tool/slices/builtin/executors', () => ({
+ registerBuiltinToolExecutors: mocks.registerBuiltinToolExecutors,
+}));
+
+vi.mock('./connectors', () => ({
+ startConnectorInitialization: mocks.startConnectorInitialization,
+}));
+
+describe('startPostRenderInitialization', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+
+ Object.defineProperty(window, 'requestAnimationFrame', {
+ configurable: true,
+ value: undefined,
+ writable: true,
+ });
+ Object.defineProperty(window, 'requestIdleCallback', {
+ configurable: true,
+ value: undefined,
+ writable: true,
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('defers connector initialization out of the synchronous bootstrap path', async () => {
+ const { startPostRenderInitialization } = await import('./postRender');
+
+ startPostRenderInitialization();
+
+ expect(mocks.startConnectorInitialization).not.toHaveBeenCalled();
+
+ await vi.runAllTimersAsync();
+
+ expect(mocks.registerBuiltinToolExecutors).toHaveBeenCalledTimes(1);
+ expect(mocks.startConnectorInitialization).toHaveBeenCalledTimes(1);
+ });
+
+ it('starts post-render initialization only once', async () => {
+ const { startPostRenderInitialization } = await import('./postRender');
+
+ startPostRenderInitialization();
+ startPostRenderInitialization();
+ await vi.runAllTimersAsync();
+
+ expect(mocks.registerBuiltinToolExecutors).toHaveBeenCalledTimes(1);
+ expect(mocks.startConnectorInitialization).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/spa/initialize/postRender.ts b/src/spa/initialize/postRender.ts
new file mode 100644
index 00000000000..9bd778c3912
--- /dev/null
+++ b/src/spa/initialize/postRender.ts
@@ -0,0 +1,50 @@
+import { registerBuiltinToolExecutors } from '@/store/tool/slices/builtin/executors';
+
+import { startConnectorInitialization } from './connectors';
+
+type RequestIdleCallback = (callback: () => void, options?: { timeout?: number }) => number;
+
+let postRenderStarted = false;
+
+const scheduleAfterFirstPaint = (task: () => void) => {
+ if (typeof window === 'undefined') {
+ task();
+ return;
+ }
+
+ const runWhenIdle = () => {
+ const requestIdleCallback = (
+ window as typeof window & {
+ requestIdleCallback?: RequestIdleCallback;
+ }
+ ).requestIdleCallback;
+
+ if (typeof requestIdleCallback === 'function') {
+ requestIdleCallback(task, { timeout: 1500 });
+ return;
+ }
+
+ window.setTimeout(task, 0);
+ };
+
+ if (typeof window.requestAnimationFrame === 'function') {
+ window.requestAnimationFrame(runWhenIdle);
+ return;
+ }
+
+ runWhenIdle();
+};
+
+export const startPostRenderInitialization = () => {
+ if (postRenderStarted) return;
+ postRenderStarted = true;
+
+ scheduleAfterFirstPaint(() => {
+ try {
+ registerBuiltinToolExecutors();
+ startConnectorInitialization();
+ } catch (error) {
+ console.error('[SPA Initialize] post-render initialization failed', error);
+ }
+ });
+};
diff --git a/src/spa/initialize/toolSurfaces.ts b/src/spa/initialize/toolSurfaces.ts
new file mode 100644
index 00000000000..af6b34a6d2a
--- /dev/null
+++ b/src/spa/initialize/toolSurfaces.ts
@@ -0,0 +1,10 @@
+import { registerBuiltinToolSurfaces as registerSurfaces } from '@lobechat/builtin-tools/register';
+
+let registered = false;
+
+export const registerBuiltinToolSurfaces = () => {
+ if (registered) return;
+ registered = true;
+
+ registerSurfaces();
+};
diff --git a/src/store/tool/builtinToolRegistry.test.ts b/src/store/tool/builtinToolRegistry.test.ts
index 1e207a333a6..0de8daf58ef 100644
--- a/src/store/tool/builtinToolRegistry.test.ts
+++ b/src/store/tool/builtinToolRegistry.test.ts
@@ -16,10 +16,15 @@ import {
import { getBuiltinRenderDisplayControl } from '@lobechat/builtin-tools/displayControls';
import { builtinToolIdentifiers } from '@lobechat/builtin-tools/identifiers';
import { getBuiltinInspector } from '@lobechat/builtin-tools/inspectors';
+import { registerBuiltinToolSurfaces } from '@lobechat/builtin-tools/register';
import { getBuiltinRender } from '@lobechat/builtin-tools/renders';
-import { describe, expect, it } from 'vitest';
+import { beforeAll, describe, expect, it } from 'vitest';
describe('builtin tool registry', () => {
+ beforeAll(() => {
+ registerBuiltinToolSurfaces();
+ });
+
it('includes skill store in builtin identifiers', () => {
expect(builtinToolIdentifiers).toContain(SkillStoreIdentifier);
});
diff --git a/src/store/tool/slices/builtin/executors/index.test.ts b/src/store/tool/slices/builtin/executors/index.test.ts
index 3973557fec7..1e05766451f 100644
--- a/src/store/tool/slices/builtin/executors/index.test.ts
+++ b/src/store/tool/slices/builtin/executors/index.test.ts
@@ -5,7 +5,12 @@ import {
} from '@lobechat/builtin-tool-web-onboarding';
import { describe, expect, it, vi } from 'vitest';
-import { getApiNamesForIdentifier, hasExecutor, invokeExecutor } from './index';
+import {
+ getApiNamesForIdentifier,
+ hasExecutor,
+ invokeExecutor,
+ registerBuiltinToolExecutors,
+} from './index';
vi.hoisted(() => {
const storage = new Map<string, string>();
@@ -30,17 +35,25 @@ vi.hoisted(() => {
});
describe('builtin executor registry', () => {
- it('registers web onboarding executor APIs', () => {
+ it('does not register executors as an import side effect', () => {
+ expect(hasExecutor(WebOnboardingIdentifier, WebOnboardingApiName.saveUserQuestion)).toBe(false);
+ });
+
+ it('registers web onboarding executor APIs explicitly', async () => {
+ await registerBuiltinToolExecutors();
+
expect(hasExecutor(WebOnboardingIdentifier, WebOnboardingApiName.saveUserQuestion)).toBe(true);
expect(hasExecutor(WebOnboardingIdentifier, WebOnboardingApiName.finishOnboarding)).toBe(true);
expect(getApiNamesForIdentifier(WebOnboardingIdentifier)).toEqual(
Object.values(WebOnboardingApiName),
);
- });
+ }, 30_000);
+
+ it('registers visual understanding executor APIs', async () => {
+ await registerBuiltinToolExecutors();
- it('registers visual understanding executor APIs', () => {
expect(hasExecutor(LobeAgentIdentifier, LobeAgentApiName.analyzeVisualMedia)).toBe(true);
- });
+ }, 30_000);
it('rejects nested sub-agent execution', async () => {
const subAgentRun = vi.fn();
@@ -63,5 +76,5 @@ describe('builtin executor registry', () => {
});
expect(subAgentRun).not.toHaveBeenCalled();
- });
+ }, 30_000);
});
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index a5762e01d79..587e723d958 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -1,9 +1,11 @@
/**
* Builtin Tool Executor Registry
*
- * Central registry for all builtin tool executors.
- * Executors are registered as class instances by identifier.
+ * Central registry for builtin tool executors.
+ * Executor modules are registered by explicit app bootstrap registration, not
+ * by importing this registry module.
*/
+
import { agentBuilderExecutor } from '@lobechat/builtin-tool-agent-builder/executor';
import { agentManagementExecutor } from '@lobechat/builtin-tool-agent-management/executor';
import { calculatorExecutor } from '@lobechat/builtin-tool-calculator/executor';
@@ -11,11 +13,11 @@ import { cloudSandboxExecutor } from '@lobechat/builtin-tool-cloud-sandbox/execu
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 { knowledgeBaseExecutor } from '@lobechat/builtin-tool-knowledge-base/client';
-import { lobeAgentExecutor } from '@lobechat/builtin-tool-lobe-agent/client';
-import { localSystemExecutor } from '@lobechat/builtin-tool-local-system/client';
+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';
+import { taskExecutor } from '@lobechat/builtin-tool-task/client/executor';
import type { BuiltinToolContext, BuiltinToolResult, IBuiltinToolExecutor } from '../types';
import { activatorExecutor } from './lobe-activator';
@@ -30,12 +32,11 @@ import { userInteractionExecutor } from './lobe-user-interaction';
import { webBrowsing } from './lobe-web-browsing';
import { webOnboardingExecutor } from './lobe-web-onboarding';
-// ==================== Import and register all executors ====================
-
/**
* Registry structure: Map<identifier, executor instance>
*/
const executorRegistry = new Map<string, IBuiltinToolExecutor>();
+let executorsRegistered = false;
/**
* Get a builtin tool executor by identifier
@@ -94,6 +95,8 @@ export const invokeExecutor = async (
params: any,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
+ await registerBuiltinToolExecutors();
+
const executor = executorRegistry.get(identifier);
if (!executor) {
@@ -130,29 +133,34 @@ const registerExecutors = (executors: IBuiltinToolExecutor[]): void => {
}
};
-// Register all executor instances
-registerExecutors([
- agentBuilderExecutor,
- agentDocumentsExecutor,
- agentManagementExecutor,
- calculatorExecutor,
- cloudSandboxExecutor,
- credsExecutor,
- groupAgentBuilderExecutor,
- groupManagementExecutor,
- knowledgeBaseExecutor,
- localSystemExecutor,
- memoryExecutor,
- messageExecutor,
- notebookExecutor,
- pageAgentExecutor,
- skillStoreExecutor,
- skillsExecutor,
- taskExecutor,
- activatorExecutor,
- topicReferenceExecutor,
- userInteractionExecutor,
- lobeAgentExecutor,
- webOnboardingExecutor,
- webBrowsing,
-]);
+export const registerBuiltinToolExecutors = (): void => {
+ if (executorsRegistered) return;
+
+ registerExecutors([
+ agentBuilderExecutor,
+ agentDocumentsExecutor,
+ agentManagementExecutor,
+ calculatorExecutor,
+ cloudSandboxExecutor,
+ credsExecutor,
+ groupAgentBuilderExecutor,
+ groupManagementExecutor,
+ knowledgeBaseExecutor,
+ localSystemExecutor,
+ memoryExecutor,
+ messageExecutor,
+ notebookExecutor,
+ pageAgentExecutor,
+ skillStoreExecutor,
+ skillsExecutor,
+ taskExecutor,
+ activatorExecutor,
+ topicReferenceExecutor,
+ userInteractionExecutor,
+ lobeAgentExecutor,
+ webOnboardingExecutor,
+ webBrowsing,
+ ]);
+
+ executorsRegistered = true;
+};
diff --git a/src/utils/router.tsx b/src/utils/router.tsx
index 3547f7d19f5..8f47837801a 100644
--- a/src/utils/router.tsx
+++ b/src/utils/router.tsx
@@ -17,6 +17,7 @@ import ErrorCapture from '@/components/Error';
import Loading from '@/components/Loading/BrandTextLoading';
import { useIsDark } from '@/hooks/useIsDark';
import SPAGlobalProvider from '@/layout/SPAGlobalProvider';
+import AppLayer from '@/spa/AppLayer';
import { useGlobalStore } from '@/store/global';
import { createNavigationRef } from '@/store/global/initialState';
import { isChunkLoadError, notifyChunkError } from '@/utils/chunkError';
@@ -143,7 +144,9 @@ const RouterRoot = memo(() => (
<SPAGlobalProvider>
<BusinessGlobalProvider>
<NavigatorRegistrar />
- <Outlet />
+ <AppLayer>
+ <Outlet />
+ </AppLayer>
</BusinessGlobalProvider>
</SPAGlobalProvider>
));