Skip to content

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

⚑️ perf(spa): cut first-screen boot renders by 80% (#19120)

Innei207058df27b4
diff --git a/packages/locales/src/create.test.ts b/packages/locales/src/create.test.ts
new file mode 100644
index 00000000000..20594c6f52b
--- /dev/null
+++ b/packages/locales/src/create.test.ts
@@ -0,0 +1,64 @@
+import type { InitOptions } from 'i18next';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { emit, init, on, reloadResources, storeOn, use } = vi.hoisted(() => ({
+ emit: vi.fn(),
+ init: vi.fn((_options: InitOptions) => Promise.resolve()),
+ on: vi.fn(),
+ reloadResources: vi.fn(() => Promise.resolve()),
+ storeOn: vi.fn(),
+ use: vi.fn(),
+}));
+
+vi.mock('i18next', () => {
+ const instance: any = {
+ emit,
+ init,
+ language: 'zh-CN',
+ on,
+ reloadResources,
+ store: { on: storeOn },
+ use: (...args: unknown[]) => {
+ use(...args);
+ return instance;
+ },
+ };
+ return { default: instance };
+});
+vi.mock('i18next-browser-languagedetector', () => ({ default: {} }));
+vi.mock('i18next-resources-to-backend', () => ({ default: () => ({}) }));
+vi.mock('react-i18next', () => ({ initReactI18next: {} }));
+
+const { createI18nNext } = await import('./create');
+
+describe('createI18nNext', () => {
+ beforeEach(() => {
+ init.mockClear();
+ emit.mockClear();
+ reloadResources.mockClear();
+ });
+
+ it('does not bind every consumer to the resource store', () => {
+ createI18nNext('zh-CN').init();
+
+ // `bindI18nStore: 'added'` re-renders every `useTranslation` consumer once per
+ // lazily-loaded bundle β€” ~30 full-tree passes during boot.
+ expect(init.mock.calls[0]![0].react).not.toHaveProperty('bindI18nStore');
+ });
+
+ it('emits one languageChanged after the fallback resources are replaced', async () => {
+ await createI18nNext('zh-CN').init();
+ await vi.waitFor(() => expect(reloadResources).toHaveBeenCalled());
+
+ expect(emit).toHaveBeenCalledWith('languageChanged', 'zh-CN');
+ expect(emit.mock.calls.filter(([event]) => event === 'languageChanged')).toHaveLength(1);
+ });
+
+ it('skips the refresh when the app already runs the default language', async () => {
+ await createI18nNext('en-US').init();
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(reloadResources).not.toHaveBeenCalled();
+ expect(emit).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/locales/src/create.ts b/packages/locales/src/create.ts
index 3656edd7236..c73c3463fba 100644
--- a/packages/locales/src/create.ts
+++ b/packages/locales/src/create.ts
@@ -100,10 +100,13 @@ export const createI18nNext = (lang?: string) => {
interpolation: {
escapeValue: false,
},
- // Re-render components when new language resources are loaded from backend,
- // so preloaded en-US fallback gets replaced by the user's actual language.
react: {
- bindI18nStore: 'added',
+ // NOT `bindI18nStore: 'added'`: that subscribes every `useTranslation` consumer
+ // to every lazily-loaded bundle, so each namespace arrival re-renders the whole
+ // app β€” ~30 full-tree passes during boot. Components waiting on their own
+ // namespace are already covered by react-i18next's `!ready` path; the only
+ // event that must reach everyone is the one-time en-US -> user-language swap,
+ // emitted once after `reloadResources` below.
useSuspense: false,
},
keySeparator: false,
@@ -114,8 +117,11 @@ export const createI18nNext = (lang?: string) => {
});
if (initialLang !== DEFAULT_LANG) {
- initPromise.then(() => {
- void instance.reloadResources([initialLang], bundledNamespaces);
+ initPromise.then(async () => {
+ await instance.reloadResources([initialLang], bundledNamespaces);
+ // One refresh for the whole tree instead of one per bundle: `bindI18n`
+ // defaults to `languageChanged`, which every `useTranslation` already binds.
+ instance.emit('languageChanged', instance.language);
});
}
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
index a7a9b6e5b86..f678d848de3 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
@@ -353,6 +353,42 @@ describe('AgentDocumentsGroup', () => {
expect(screen.getByText('device-writer')).toBeInTheDocument();
});
+ it('keeps the filesystem skill scan inert while the pane is disabled', () => {
+ const projectItem = {
+ description: 'writes things',
+ fileCount: 2,
+ files: [],
+ id: 'project-skill',
+ name: 'project-writer',
+ scope: 'project' as const,
+ };
+ useProjectSkillsMock.mockReturnValue({
+ deviceItems: [],
+ error: undefined,
+ getRowActions: () => [],
+ isLoading: false,
+ items: [projectItem],
+ mutate: vi.fn(),
+ onOpenFile: () => undefined,
+ onOpenSkill: () => undefined,
+ projectItems: [projectItem],
+ raw: undefined,
+ });
+ useClientDataSWR.mockReturnValue({
+ data: [],
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<AgentDocumentsGroup showLocalProjectSkills enabled={false} workingDirectory="/repo" />);
+
+ // `undefined` workingDirectory is the hook's documented inert mode: no scan fires.
+ expect(useProjectSkillsMock).toHaveBeenCalledWith(undefined, undefined);
+ expect(screen.queryByTestId('skills-list')).not.toBeInTheDocument();
+ expect(screen.queryByText('project-writer')).not.toBeInTheDocument();
+ });
+
it('opens the SKILL.md document in the portal when clicking a skill bundle row', () => {
useClientDataSWR.mockReturnValue({
data: [skillBundleRow, skillIndexRow],
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
index a4f75c3484f..65424597cee 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -330,13 +330,16 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
}, [controlledFilter, isDocumentMode]);
// Local desktop reads skills over IPC; a bound device reads over RPC.
+ // `enabled` is false while the pane sits hidden behind `<Activity>`. Without it
+ // a closed panel still ran the filesystem skill scan and mounted a row subtree
+ // per skill β€” thousands of zero-box components the user never sees.
const showProjectSkills =
- (showLocalProjectSkills || isLocalEnabled || !!deviceId) && !!workingDirectory;
+ enabled && (showLocalProjectSkills || isLocalEnabled || !!deviceId) && !!workingDirectory;
// Mirror what each child component reads so the parent can decide the
// section layout (flat when a single source has items, sectioned otherwise).
// Both hooks are SWR-deduped against their respective child fetches.
- const userSkillItems = useUserSkills();
+ const userSkillItems = useUserSkills(enabled);
const {
deviceItems: deviceSkillItems,
error: projectSkillsError,
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx
index 9a077befa1b..1f712e1d558 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/UserLevelSkills.tsx
@@ -20,6 +20,8 @@ import { agentSkillsSelectors } from '@/store/tool/selectors';
const AgentSkillDetail = lazy(() => import('@/features/AgentSkillDetail'));
+const EMPTY_ITEMS: SkillListItem[] = [];
+
const handleSkillDragStart = (item: SkillListItem, event: React.DragEvent) => {
startSkillDrag(event, {
category: 'skill',
@@ -51,21 +53,23 @@ const openSkillDetailModal = (skillId: string) =>
* data even when the Tools popover hasn't been opened in this session. The key
* is deduplicated, so co-mounting with `useControls` doesn't double-fetch.
*/
-export const useUserSkills = (): SkillListItem[] => {
- useToolStore((s) => s.useFetchAgentSkills)(true);
+export const useUserSkills = (enabled = true): SkillListItem[] => {
+ useToolStore((s) => s.useFetchAgentSkills)(enabled);
const agentSkills = useToolStore(agentSkillsSelectors.getAgentSkills, isEqual);
return useMemo(
() =>
- agentSkills.map((skill) => ({
- description: skill.description ?? undefined,
- // `identifier` is what the runtime resolves through the skill registry,
- // and is unique per skill β€” reuse it as both the React key and the
- // drag payload's `type`.
- id: skill.identifier,
- name: skill.name,
- })),
- [agentSkills],
+ !enabled
+ ? EMPTY_ITEMS
+ : agentSkills.map((skill) => ({
+ description: skill.description ?? undefined,
+ // `identifier` is what the runtime resolves through the skill registry,
+ // and is unique per skill β€” reuse it as both the React key and the
+ // drag payload's `type`.
+ id: skill.identifier,
+ name: skill.name,
+ })),
+ [agentSkills, enabled],
);
};
diff --git a/src/layout/SPAGlobalProvider/Locale.test.tsx b/src/layout/SPAGlobalProvider/Locale.test.tsx
new file mode 100644
index 00000000000..fec07517f53
--- /dev/null
+++ b/src/layout/SPAGlobalProvider/Locale.test.tsx
@@ -0,0 +1,65 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, waitFor } from '@testing-library/react';
+import { type PropsWithChildren, useEffect } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { getAntdLocale } = vi.hoisted(() => ({ getAntdLocale: vi.fn() }));
+
+vi.mock('@/utils/locale', () => ({ getAntdLocale }));
+vi.mock('@/utils/dayjsLocale', () => ({
+ loadDayjsLocaleModule: vi.fn(async () => ({ default: {} })),
+ normalizeDayjsLocale: (lang: string) => lang,
+}));
+vi.mock('@/locales/create', () => ({
+ createI18nNext: () => ({
+ init: vi.fn(async () => {}),
+ instance: { isInitialized: true, language: 'zh-CN', off: vi.fn(), on: vi.fn() },
+ }),
+}));
+vi.mock('@/layout/GlobalProvider/Editor', () => ({
+ default: ({ children }: PropsWithChildren) => children,
+}));
+
+const Locale = (await import('./Locale')).default;
+
+let mounts = 0;
+
+const MountCounter = () => {
+ useEffect(() => {
+ mounts += 1;
+ }, []);
+ return <div>child</div>;
+};
+
+describe('Locale', () => {
+ beforeEach(() => {
+ mounts = 0;
+ getAntdLocale.mockReset();
+ });
+
+ it('keeps the subtree mounted when the antd locale resolves', async () => {
+ let resolveLocale: (value: unknown) => void = () => {};
+ getAntdLocale.mockReturnValue(
+ new Promise((resolve) => {
+ resolveLocale = resolve;
+ }),
+ );
+
+ render(
+ <Locale defaultLang="zh-CN">
+ <MountCounter />
+ </Locale>,
+ );
+ expect(mounts).toBe(1);
+
+ resolveLocale({ locale: 'zh-cn' });
+ await waitFor(() => expect(getAntdLocale).toHaveBeenCalled());
+ await new Promise((r) => setTimeout(r, 0));
+
+ // antd's ConfigProvider only wraps children in `LocaleProvider` when `locale` is
+ // truthy β€” a falsy-to-resolved transition would insert a node and remount everything.
+ expect(mounts).toBe(1);
+ });
+});
diff --git a/src/layout/SPAGlobalProvider/Locale.tsx b/src/layout/SPAGlobalProvider/Locale.tsx
index 2889086a6fd..bd39a7b5e5f 100644
--- a/src/layout/SPAGlobalProvider/Locale.tsx
+++ b/src/layout/SPAGlobalProvider/Locale.tsx
@@ -1,4 +1,5 @@
import { ConfigProvider } from 'antd';
+import enUS from 'antd/locale/en_US';
import dayjs from 'dayjs';
import type { PropsWithChildren } from 'react';
import { memo, useEffect, useState } from 'react';
@@ -106,7 +107,10 @@ const Locale = memo<LocaleLayoutProps>(({ children, defaultLang, antdLocale }) =
return (
<ConfigProvider
direction={documentDir}
- locale={locale}
+ // antd only wraps children in `LocaleProvider` when `locale` is truthy. Going
+ // from undefined to a resolved locale therefore inserts a node into the tree and
+ // remounts every provider below β€” the whole app boots twice. Keep the shape stable.
+ locale={locale ?? enUS}
theme={{
components: {
Button: {