π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(spa): replace the boot logo with a low-fidelity app shell (#17829)
Inneie4fc8fa2d189
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 04c1c319174..ca7eab064ae 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -172,6 +172,78 @@ Acceptance fixture through the local CLI, and capture the same route in separateauthenticated and storage-empty browser contexts. This proves both owner andshared-viewer rendering without depending on production browser cookies.+### The dev Electron main window runs the WEB entry β desktop-entry boot code is unverifiable in dev++**Situation:** verifying anything that lives in `src/spa/entry.desktop.tsx` (bootstrap+identity, adapter registration, boot marks) on an `electron-dev.sh` instance.++**Doesn't work:** assuming the desktop instance loads the desktop entry. Measured on a+live dev instance, the **main window's entry script is `app://renderer/src/spa/entry.web.tsx`**,+while the **topicPopup window in the same instance correctly loads `entry.popup.tsx`**.+So Vite dev does resolve some MPA paths but the main window falls through to the root+`index.html`. (Mechanism not established β do not repeat the plausible-sounding+"`ViteRendererFallback` is a dumb proxy so everything falls back" explanation; the popup+result falsifies it.) Consequence: desktop-entry boot code never executes in dev, and a+deletion there passes every dev smoke test β which is exactly how one such call was lost+for a whole release.++**Works:** before claiming anything about a desktop entry, read the loaded entry script+and branch on it:++```js+[...document.querySelectorAll('script')].map((s) => s.src).find((s) => s.includes('entry.'));+```++If it is not the entry you are testing, the surface cannot prove your claim β fall back to+a source-order regression test, and say in the report that the runtime path needs a+packaged build (`DESKTOP_RENDERER_STATIC` / `resolveRendererFilePath` maps+`apps/desktop/index.html`, `popup.html`, `overlay.html`).++### Driving and probing a real Electron popup window++**Situation:** verifying `entry.popup.tsx` behavior (its own HTML shell, no `BootShell`).++**Works:** open the real window from the renderer store, then attach raw CDP to the+popup's own target β the agent-browser daemon holds the main window's target, and one+page target accepts only one websocket:++```bash+agent-browser --cdp 9222 eval '(async () => {+ await window.__LOBE_STORES.global().openTopicInNewWindow("inbox","verify-popup");+ return "requested"; })()'+curl -s http://127.0.0.1:9222/json/list # pick the target whose url contains /popup/+```++Any `(agentId, topicId)` pair works β the popup boots regardless of whether the route+resolves data, which is what makes this usable on a signed-out instance. For overlay+claims, measure rather than eyeball: `getComputedStyle` for `pointer-events` / background+alpha plus `document.elementFromPoint(x, y)` β a 50%-alpha scrim looks like a cosmetic+tint in a screenshot while actually swallowing every click.++### The debug proxy cannot reach a settled app β workspace `packages/*` dynamic imports fail cross-origin++**Situation:** verifying frontend work through `/_dangerous_local_dev_proxy` (production+page + production login + local Vite modules), needing a screenshot of the app after it+has finished loading.++**Doesn't work:** treating the resulting `ErrorBoundary` ("ι‘΅ι’ζζΆδΈε―η¨") as a defect in+the change under test. The document origin is `https://app.lobehub.com`, and dynamic+`import()` of workspace modules served from `http://localhost:9876` β `packages/builtin-tools/src/register.ts`,+and intermittently `src/routes/**` β fails with `Failed to fetch dynamically imported module`.+The same URLs return **200** to `curl` and to an in-page `fetch()`; only module scripts+fail, because their cross-origin requirements are stricter. So the usual "is it reachable"+probes all say yes while the app still dies.++**Works:** treat this channel as good for boot-phase and pre-settle evidence only, and+prove attribution rather than assuming it β `git stash -u` the whole change, reload the+same proxy URL, and confirm the identical ErrorBoundary appears at HEAD. Report the+settled-state check as blocked with that A/B attached instead of chasing the module+graph. For a genuinely settled authenticated app, use Electron with an injected login+snapshot; the local Vite entry (`http://localhost:9876/`) loads modules correctly but has+no session, so it ends in the same error for a different reason. See also the two+neighbouring entries on this proxy (loading-shell in an isolated context; no seeded+agent-browser session).+### Reading a transitioned CSS property immediately after focus/hover**Situation:** asserting that a `:focus-within` / `:hover` rule reveals a@@ -501,6 +573,61 @@ Then assert on `aside.innerText` line count plus a count of text-free rounded bocollapsing to \~8 text-free rows is the nav-panel fallback, while fixed items presentwith only the list area shimmering is ordinary data loading.+### Boot-phase UI cannot be observed by CDP polling β sample in-page, and mirror the timer++**Situation:** asserting whether a transient boot-phase surface (a splash, a skeleton,+a first-paint gate) appears between React's first commit and the app painting.++**Doesn't work:** polling `Runtime.evaluate` from a CDP driver, even at a 50ms step.+The desktop renderer's boot spends multi-second stretches in a single synchronous+task, and every `Runtime.evaluate` queues behind it β the driver observes the state+before the window and again after it, and reports the phase "never happened". CPU+throttling makes it worse: it stretches the blocking task and the probe equally.++**Works:** inject a pure observer with `Page.addScriptToEvaluateOnNewDocument` and+sample from inside the page. Note `document.documentElement` does not exist yet in an+on-new-document script, so a `MutationObserver` cannot be attached there β use+`setInterval(check, 8)`. Record the largest gap between consecutive ticks: that gap+is the main thread's longest blocking task, and a boot window with no intermediate+sample is a blocked window, not a missing state.++When the behavior under test is time-thresholded, also **mirror the product's own+timer**: at the moment the observer first sees `#root` gain a child, schedule the same+`setTimeout(β¦, N)` the component uses and record when it actually fires. On a blocked+main thread it fires far later than `N` β which is the difference between "the+threshold logic is wrong" and "the threshold never had a chance to run", and no+screenshot can tell those apart.++**When the driver has no CDP (claude-in-chrome, the debug proxy), deliver the same+sampler through Vite instead**: a temporary `[AGENT-TEST]` block at the top of+`src/spa/entry.{web,desktop}.tsx` runs at bundle-eval β early enough for every+post-React phase β and needs no `Page.addScriptToEvaluateOnNewDocument`. Two things+to get right in the phase predicate: scope any `[role="status"][aria-label="Loading"]`+check with `.closest('#loading-screen')` so the **static HTML shell's own logo** is not+counted as the React `BrandTextLoading` (they share the same role/label, and conflating+them turns a clean boot into a false "the logo flashed"); and record the max gap between+consecutive ticks β LobeHub's boot routinely shows a single 0.6β1.1s blocking task, so a+phase with no sample inside it is a blocked window, not a missing state.++### A global `indexedDB.open` stall holds the boot on web but kills the Electron renderer++**Situation:** needing to freeze the boot at a pre-app phase long enough to capture it,+by keeping the SWR cache hydration from ever completing.++**Doesn't work on desktop:** replacing `indexedDB.open` with a never-settling stub+breaks the Electron renderer outright β the local database adapter registered in+`entry.desktop.tsx` needs IndexedDB, so the entry dies before React renders and the+HTML loading screen stays up forever. The symptom reads as "the phase under test never+appears", i.e. exactly like the product defect you were looking for.++**Works:** use the stall only on the web entry, where it holds `CacheHydrationGate`+for its full `HYDRATION_TIMEOUT` (about 8s) β ample for a screenshot plus+`getBoundingClientRect` / `getComputedStyle` measurements over the same CDP+connection. For desktop, do not stall storage: observe the natural boot with the+in-page sampler above. Either way, disarm with+`Page.removeScriptToEvaluateOnNewDocument` and reload before capturing the settled+state, or the comparison shot is taken against a still-crippled runtime.+## Detailed references- [Probe field notes](./references/probe-field-notes.md) β all historicaldiff --git a/src/components/Loading/ContentLoading/index.tsx b/src/components/Loading/ContentLoading/index.tsxnew file mode 100644index 00000000000..927b0689816--- /dev/null+++ b/src/components/Loading/ContentLoading/index.tsx@@ -0,0 +1,45 @@+import { createStaticStyles, cssVar } from 'antd-style';++const styles = createStaticStyles(({ css }) => ({+ container: css`+ display: flex;+ align-items: center;+ justify-content: center;++ width: 100%;+ height: 100%;+ min-height: 96px;+ `,+ spinner: css`+ width: 28px;+ height: 28px;+ border: 2px solid ${cssVar.colorFillSecondary};+ border-block-start-color: ${cssVar.colorTextSecondary};+ border-radius: 50%;++ animation: content-loading-spin 0.8s linear infinite;++ @keyframes content-loading-spin {+ to {+ transform: rotate(360deg);+ }+ }+ `,+}));++/**+ * Loading state for a content region whose chrome is already on screen.+ *+ * Deliberately draws no structure: it fills whatever container it is given, so+ * it cannot promise a layout the incoming page does not have. That is why it β+ * and not a skeleton β sits in the main layout's outlet boundary, which is+ * shared by pages as different as a settings form, a community grid and a+ * conversation. `BrandTextLoading` stays for full-page boundaries.+ */+const ContentLoading = () => (+ <div className={styles.container}>+ <span aria-label={'Loading'} className={styles.spinner} role={'status'} />+ </div>+);++export default ContentLoading;diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsxindex 619952d9679..9e4f35f5ad5 100644--- a/src/features/ChatInput/Desktop/index.tsx+++ b/src/features/ChatInput/Desktop/index.tsx@@ -11,7 +11,7 @@ import { useTranslation } from 'react-i18next';import ChatInputNotice from '@/features/ChatInput/ChatInputNotice';import { useChatInputStore } from '@/features/ChatInput/store';-import { LayoutContainerContext } from '@/routes/(main)/_layout/DesktopLayoutContainer/LayoutContainerContext';+import { LayoutContainerContext } from '@/features/DesktopLayoutContainer/LayoutContainerContext';import { useChatStore } from '@/store/chat';import { chatSelectors } from '@/store/chat/selectors';import { fileChatSelectors, useFileStore } from '@/store/file';diff --git a/src/routes/(main)/_layout/DesktopLayoutContainer/LayoutContainerContext.ts b/src/features/DesktopLayoutContainer/LayoutContainerContext.tssimilarity index 100%rename from src/routes/(main)/_layout/DesktopLayoutContainer/LayoutContainerContext.tsrename to src/features/DesktopLayoutContainer/LayoutContainerContext.tsdiff --git a/src/features/DesktopLayoutContainer/cssVariables.test.ts b/src/features/DesktopLayoutContainer/cssVariables.test.tsnew file mode 100644index 00000000000..d60972321f0--- /dev/null+++ b/src/features/DesktopLayoutContainer/cssVariables.test.ts@@ -0,0 +1,65 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getDarwinMajorVersion, isMacOSWithLargeWindowBorders } from '@/utils/platform';++import { getInnerCssVariables, getOuterCssVariables } from './cssVariables';++vi.mock('@/utils/platform', () => ({+ getDarwinMajorVersion: vi.fn(() => 0),+ isMacOSWithLargeWindowBorders: vi.fn(() => false),+}));++const mockDarwin = vi.mocked(getDarwinMajorVersion);+const mockLargeBorders = vi.mocked(isMacOSWithLargeWindowBorders);++beforeEach(() => {+ mockDarwin.mockReturnValue(0);+ mockLargeBorders.mockReturnValue(false);+});++describe('getOuterCssVariables', () => {+ it('drops the left padding while the nav panel is expanded', () => {+ expect(getOuterCssVariables({ expand: true })['--container-padding-left']).toBe('0px');+ expect(getOuterCssVariables({ expand: false })['--container-padding-left']).toBe('8px');+ });+});++describe('getInnerCssVariables', () => {+ it('uses the token radius below darwin 25', () => {+ mockDarwin.mockReturnValue(24);+ const vars = getInnerCssVariables({ isDark: false });++ expect(vars['--container-border-radius']).toBe('var(--ant-border-radius)');+ expect(vars['--container-border-bottom-right-radius']).toBe('var(--ant-border-radius)');+ });++ it('switches to 12px from darwin 25, and rounds the bottom-right too from darwin 26', () => {+ mockDarwin.mockReturnValue(25);+ const darwin25 = getInnerCssVariables({ isDark: false });+ expect(darwin25['--container-border-radius']).toBe('12px');+ expect(darwin25['--container-border-bottom-right-radius']).toBe('12px');++ mockDarwin.mockReturnValue(26);+ expect(getInnerCssVariables({ isDark: false })['--container-border-bottom-right-radius']).toBe(+ '12px',+ );+ });++ it('rounds the bottom-right on macOS builds with large window borders', () => {+ mockDarwin.mockReturnValue(24);+ mockLargeBorders.mockReturnValue(true);++ expect(getInnerCssVariables({ isDark: false })['--container-border-bottom-right-radius']).toBe(+ '12px',+ );+ });++ it('softens the border color in dark mode', () => {+ expect(getInnerCssVariables({ isDark: true })['--container-border-color']).toBe(+ 'var(--ant-color-border-secondary)',+ );+ expect(getInnerCssVariables({ isDark: false })['--container-border-color']).toBe(+ 'var(--ant-color-border)',+ );+ });+});diff --git a/src/features/DesktopLayoutContainer/cssVariables.ts b/src/features/DesktopLayoutContainer/cssVariables.tsnew file mode 100644index 00000000000..a97c2bd9c83--- /dev/null+++ b/src/features/DesktopLayoutContainer/cssVariables.ts@@ -0,0 +1,23 @@+import { cssVar } from 'antd-style';++import { isDesktop } from '@/const/version';+import { getDarwinMajorVersion, isMacOSWithLargeWindowBorders } from '@/utils/platform';++export const getOuterCssVariables = ({ expand }: { expand?: boolean }): Record<string, string> => ({+ '--container-padding-left': expand ? '0px' : '8px',+ '--container-padding-top': isDesktop ? '0px' : '8px',+});++export const getInnerCssVariables = ({ isDark }: { isDark: boolean }): Record<string, string> => {+ const darwinMajorVersion = getDarwinMajorVersion();++ const borderRadius = darwinMajorVersion >= 25 ? '12px' : cssVar.borderRadius;+ const borderBottomRightRadius =+ darwinMajorVersion >= 26 || isMacOSWithLargeWindowBorders() ? '12px' : borderRadius;++ return {+ '--container-border-bottom-right-radius': borderBottomRightRadius,+ '--container-border-color': isDark ? cssVar.colorBorderSecondary : cssVar.colorBorder,+ '--container-border-radius': borderRadius,+ };+};diff --git a/src/features/DesktopLayoutContainer/index.tsx b/src/features/DesktopLayoutContainer/index.tsxnew file mode 100644index 00000000000..b7ea4fe6453--- /dev/null+++ b/src/features/DesktopLayoutContainer/index.tsx@@ -0,0 +1,45 @@+import { Flexbox } from '@lobehub/ui';+import { type FC, type PropsWithChildren } from 'react';+import { useMemo, useRef } from 'react';++import { useIsDark } from '@/hooks/useIsDark';+import { useGlobalStore } from '@/store/global';+import { systemStatusSelectors } from '@/store/global/selectors';++import { getInnerCssVariables, getOuterCssVariables } from './cssVariables';+import { LayoutContainerContext } from './LayoutContainerContext';+import { styles } from './style';++const DesktopLayoutContainer: FC<PropsWithChildren> = ({ children }) => {+ const innerContainerRef = useRef<HTMLDivElement>(null);+ const isDarkMode = useIsDark();+ const [expand] = useGlobalStore((s) => [systemStatusSelectors.showLeftPanel(s)]);++ const outerCssVariables = useMemo(() => getOuterCssVariables({ expand }), [expand]);++ const innerCssVariables = useMemo(+ () => getInnerCssVariables({ isDark: isDarkMode }),+ [isDarkMode],+ );++ return (+ <Flexbox+ className={styles.outerContainer}+ height={'100%'}+ padding={8}+ style={outerCssVariables}+ width={'100%'}+ >+ <Flexbox+ className={styles.innerContainer}+ height={'100%'}+ ref={innerContainerRef}+ style={innerCssVariables}+ width={'100%'}+ >+ <LayoutContainerContext value={innerContainerRef}>{children}</LayoutContainerContext>+ </Flexbox>+ </Flexbox>+ );+};+export default DesktopLayoutContainer;diff --git a/src/routes/(main)/_layout/DesktopLayoutContainer/style.ts b/src/features/DesktopLayoutContainer/style.tssimilarity index 100%rename from src/routes/(main)/_layout/DesktopLayoutContainer/style.tsrename to src/features/DesktopLayoutContainer/style.tsdiff --git a/src/features/WorkbenchShell/WorkbenchLoading.tsx b/src/features/WorkbenchShell/WorkbenchLoading.tsxindex e157b47127b..16df3311ada 100644--- a/src/features/WorkbenchShell/WorkbenchLoading.tsx+++ b/src/features/WorkbenchShell/WorkbenchLoading.tsx@@ -1,36 +1,5 @@-import { createStaticStyles, cssVar } from 'antd-style';+import ContentLoading from '@/components/Loading/ContentLoading';-const styles = createStaticStyles(({ css }) => ({- container: css`- display: flex;- align-items: center;- justify-content: center;-- width: 100%;- height: 100%;- min-height: 96px;- `,- spinner: css`- width: 28px;- height: 28px;- border: 2px solid ${cssVar.colorFillSecondary};- border-block-start-color: ${cssVar.colorTextSecondary};- border-radius: 50%;-- animation: workbench-spin 0.8s linear infinite;-- @keyframes workbench-spin {- to {- transform: rotate(360deg);- }- }- `,-}));--const WorkbenchLoading = () => (- <div className={styles.container}>- <span aria-label={'Loading'} className={styles.spinner} role={'status'} />- </div>-);+const WorkbenchLoading = () => <ContentLoading />;export default WorkbenchLoading;diff --git a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx b/src/layout/GlobalProvider/CacheHydrationGate.test.tsxindex 556f07307d3..caee5294b70 100644--- a/src/layout/GlobalProvider/CacheHydrationGate.test.tsx+++ b/src/layout/GlobalProvider/CacheHydrationGate.test.tsx@@ -2,6 +2,7 @@ import { act, render, screen } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheHydration } from '@/libs/swr/cacheHydration';+import { getAppPainted, setAppPainted, setAppReady } from '@/spa/atoms/app';// Import after mocks are registered.import CacheHydrationGate from './CacheHydrationGate';@@ -32,16 +33,15 @@ const renderGate = () =>beforeEach(() => {mockScope = 'anon:personal';resetHydration();- // A loading-screen node so the gate's removal side-effect has a target.- const el = document.createElement('div');- el.id = 'loading-screen';- document.body.appendChild(el);+ setAppPainted(false);+ setAppReady(true);});afterEach(() => {window.history.replaceState(null, '', '/');resetHydration();- document.getElementById('loading-screen')?.remove();+ setAppPainted(false);+ setAppReady(false);vi.useRealTimers();});@@ -50,15 +50,15 @@ describe('CacheHydrationGate', () => {renderGate();// not ready yet β blockedexpect(screen.queryByTestId('app')).toBeNull();- expect(document.getElementById('loading-screen')).not.toBeNull();+ expect(getAppPainted()).toBe(false);act(() => {cacheHydration.markReady('anon:personal');});expect(screen.queryByTestId('app')).not.toBeNull();- // loading-screen removed once released- expect(document.getElementById('loading-screen')).toBeNull();+ // signals the boot shell to tear down once the real app has committed+ expect(getAppPainted()).toBe(true);});it('CORE: after first release, a scope change does NOT unmount the app (no white-screen)', () => {@@ -115,6 +115,49 @@ describe('CacheHydrationGate', () => {expect(screen.queryByTestId('app')).not.toBeNull();});+ it('tears down the static loading screen for entries that mount no boot shell', () => {+ // The Electron popup entry renders no `BootShell`, and `popup.html` ships an+ // opaque z-index 99999 `#loading-screen`. `useBootShell` is what normally+ // removes it, so the gate has to be the backstop or the popup stays covered+ // forever after hydration.+ const loadingScreen = document.createElement('div');+ loadingScreen.id = 'loading-screen';+ document.body.append(loadingScreen);++ renderGate();+ expect(document.getElementById('loading-screen')).not.toBeNull();++ act(() => {+ cacheHydration.markReady('anon:personal');+ });++ expect(document.getElementById('loading-screen')).toBeNull();+ });++ it('holds the static loading screen until the app can actually paint', () => {+ // Hydration can finish before initialization. In that window `AppLayer`+ // renders null and the boot shell's phase is still `hidden` (it needs BOTH+ // signals, and the 200ms timer has not fired), so tearing the splash down on+ // release alone leaves the window blank.+ setAppReady(false);+ const loadingScreen = document.createElement('div');+ loadingScreen.id = 'loading-screen';+ document.body.append(loadingScreen);++ renderGate();+ act(() => {+ cacheHydration.markReady('anon:personal');+ });++ expect(document.getElementById('loading-screen')).not.toBeNull();++ act(() => {+ setAppReady(true);+ });++ expect(document.getElementById('loading-screen')).toBeNull();+ });+it('hung-hydration backstop still releases if ready never fires', () => {vi.useFakeTimers();renderGate();diff --git a/src/layout/GlobalProvider/CacheHydrationGate.tsx b/src/layout/GlobalProvider/CacheHydrationGate.tsxindex 3d0184dccb8..5cb95e6bbd5 100644--- a/src/layout/GlobalProvider/CacheHydrationGate.tsx+++ b/src/layout/GlobalProvider/CacheHydrationGate.tsx@@ -6,6 +6,8 @@ import { useEffect, useLayoutEffect, useState, useSyncExternalStore } from 'reacimport { bootTiming } from '@/libs/bootTiming';import { cacheHydration } from '@/libs/swr/cacheHydration';import { useCacheScope } from '@/libs/swr/useCacheScope';+import { setAppPainted, useAppReady } from '@/spa/atoms/app';+import { removeStaticLoadingScreen } from '@/spa/loadingScreen';// first-write-wins: only the very first paint records the boot timing mark.let firstPaintMarked = false;@@ -26,7 +28,8 @@ const HYDRATION_TIMEOUT = 8000;/*** Blocks the first paint until the active scope's IndexedDB cache has hydrated,* so the app never flashes empty on cold boot β the static `loading-screen`- * overlay covers exactly this window.+ * overlay and then `BootShell` cover exactly this window, and releasing here is+ * what signals `appPainted` to tear them down.** This is a one-way latch: once released it never blanks again. A later scope* change (anonymous β signed-in, or workspace switch) re-hydrates the SWR cache@@ -48,6 +51,7 @@ const HYDRATION_TIMEOUT = 8000;*/const CacheHydrationGate = ({ children }: PropsWithChildren) => {const scope = useCacheScope();+ const appReady = useAppReady();const ready = useSyncExternalStore(cacheHydration.subscribe,@@ -80,9 +84,30 @@ const CacheHydrationGate = ({ children }: PropsWithChildren) => {firstPaintMarked = true;bootTiming.mark('first-paint');}- document.getElementById('loading-screen')?.remove();+ // Runs after `children` have committed, so the boot shell only tears down+ // once the real app is already in the DOM.+ setAppPainted(true);}, [released]);+ // Backstop for entries that mount no `BootShell` (the Electron popup window,+ // whose `popup.html` ships a z-index 99999 scrim with `pointer-events: auto`):+ // the shell normally owns this removal, so without a backstop the popup stays+ // dimmed AND swallows every click.+ //+ // `appReady` is part of the condition, not decoration. Hydration can finish+ // before initialization, and in that window `AppLayer` still renders null while+ // `resolveBootShellPhase` is `hidden` (it needs BOTH signals for `done`, and+ // the 200ms timer has not fired) β so the shell is not up either. Removing the+ // splash on `released` alone blanks the window until whichever lands first,+ // and the shell timer has been measured arriving 1153ms late on an Electron+ // cold boot. Gating on `appReady` means `AppLayer` is rendering the outlet, so+ // the route's own fallback is guaranteed to be on screen.+ useLayoutEffect(() => {+ if (!released || !appReady) return;++ removeStaticLoadingScreen();+ }, [released, appReady]);+if (!released) return null;return <>{children}</>;diff --git a/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsx b/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsxindex b0c19121763..981d961191f 100644--- a/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsx+++ b/src/layout/GlobalProvider/coldHydrationGate.integration.test.tsx@@ -70,12 +70,8 @@ describe('CacheHydrationGate + provider + consumer', () => {mockScope = SCOPE;probed = undefined;cacheHydration.markPending(SCOPE);- const el = document.createElement('div');- el.id = 'loading-screen';- document.body.appendChild(el);});afterEach(async () => {- document.getElementById('loading-screen')?.remove();cacheHydration.markPending(SCOPE);await localDataCache.clearScope(SCOPE);});diff --git a/src/routes/(main)/_layout/DesktopLayoutContainer.tsx b/src/routes/(main)/_layout/DesktopLayoutContainer.tsxdeleted file mode 100644index 3a64e4c43b8..00000000000--- a/src/routes/(main)/_layout/DesktopLayoutContainer.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { Flexbox } from '@lobehub/ui';-import { cssVar } from 'antd-style';-import { type FC, type PropsWithChildren } from 'react';-import { useMemo, useRef } from 'react';--import { isDesktop } from '@/const/version';-import { useIsDark } from '@/hooks/useIsDark';-import { useGlobalStore } from '@/store/global';-import { systemStatusSelectors } from '@/store/global/selectors';-import { getDarwinMajorVersion, isMacOSWithLargeWindowBorders } from '@/utils/platform';--import { LayoutContainerContext } from './DesktopLayoutContainer/LayoutContainerContext';-import { styles } from './DesktopLayoutContainer/style';--const DesktopLayoutContainer: FC<PropsWithChildren> = ({ children }) => {- const innerContainerRef = useRef<HTMLDivElement>(null);- const isDarkMode = useIsDark();- const [expand] = useGlobalStore((s) => [systemStatusSelectors.showLeftPanel(s)]);-- // CSS variables for dynamic styling- const outerCssVariables = useMemo<Record<string, string>>(- () => ({- '--container-padding-left': expand ? '0px' : '8px',- '--container-padding-top': isDesktop ? '0px' : '8px',- }),- [expand, isDesktop],- );-- const innerCssVariables = useMemo<Record<string, string>>(() => {- const darwinMajorVersion = getDarwinMajorVersion();-- const borderRadius = darwinMajorVersion >= 25 ? '12px' : cssVar.borderRadius;- const borderBottomRightRadius =- darwinMajorVersion >= 26 || isMacOSWithLargeWindowBorders() ? '12px' : borderRadius;-- return {- '--container-border-bottom-right-radius': borderBottomRightRadius,- '--container-border-color': isDarkMode ? cssVar.colorBorderSecondary : cssVar.colorBorder,- '--container-border-radius': borderRadius,- };- }, [isDarkMode]);-- return (- <Flexbox- className={styles.outerContainer}- height={'100%'}- padding={8}- style={outerCssVariables}- width={'100%'}- >- <Flexbox- className={styles.innerContainer}- height={'100%'}- ref={innerContainerRef}- style={innerCssVariables}- width={'100%'}- >- <LayoutContainerContext value={innerContainerRef}>{children}</LayoutContainerContext>- </Flexbox>- </Flexbox>- );-};-export default DesktopLayoutContainer;diff --git a/src/routes/(main)/_layout/index.desktop.tsx b/src/routes/(main)/_layout/index.desktop.tsxindex ce84f487cba..b464c4d2695 100644--- a/src/routes/(main)/_layout/index.desktop.tsx+++ b/src/routes/(main)/_layout/index.desktop.tsx@@ -11,6 +11,7 @@ import { HotkeysProvider } from 'react-hotkeys-hook';import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';import DesktopBrowserGatewayBridge from '@/features/DesktopBrowserGatewayBridge';import DesktopFileMenuBridge from '@/features/DesktopFileMenuBridge';+import DesktopLayoutContainer from '@/features/DesktopLayoutContainer';import DesktopNavigationBridge from '@/features/DesktopNavigationBridge';import ActiveConversationBridge from '@/features/Electron/ActiveConversationBridge';import AuthRequiredModal from '@/features/Electron/AuthRequiredModal';@@ -31,7 +32,6 @@ import { DndContextWrapper } from '@/routes/(main)/resource/features/DndContextWimport { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';import DesktopAutoOidcOnFirstOpen from './DesktopAutoOidcOnFirstOpen';-import DesktopLayoutContainer from './DesktopLayoutContainer';import RegisterHotkeys from './RegisterHotkeys';import { styles } from './style';diff --git a/src/routes/(main)/_layout/index.tsx b/src/routes/(main)/_layout/index.tsxindex 09f98471a2b..4eefba8bada 100644--- a/src/routes/(main)/_layout/index.tsx+++ b/src/routes/(main)/_layout/index.tsx@@ -10,11 +10,12 @@ import { HotkeysProvider } from 'react-hotkeys-hook';import { Outlet } from 'react-router';import WorkspaceContextSlot from '@/business/client/WorkspaceContextSlot';-import Loading from '@/components/Loading/BrandTextLoading';+import ContentLoading from '@/components/Loading/ContentLoading';import { isDesktop } from '@/const/version';import { BANNER_HEIGHT } from '@/features/AlertBanner/CloudBanner';import DesktopBrowserGatewayBridge from '@/features/DesktopBrowserGatewayBridge';import DesktopFileMenuBridge from '@/features/DesktopFileMenuBridge';+import DesktopLayoutContainer from '@/features/DesktopLayoutContainer';import DesktopNavigationBridge from '@/features/DesktopNavigationBridge';import AuthRequiredModal from '@/features/Electron/AuthRequiredModal';import OverlayCaptureUploader from '@/features/Electron/ScreenCapture/OverlayCaptureUploader';@@ -35,7 +36,6 @@ import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfiimport DesktopHome from '../home';import DesktopHomeLayout from '../home/_layout';import DesktopAutoOidcOnFirstOpen from './DesktopAutoOidcOnFirstOpen';-import DesktopLayoutContainer from './DesktopLayoutContainer';import RegisterHotkeys from './RegisterHotkeys';import { styles } from './style';@@ -83,7 +83,7 @@ const Layout: FC = () => {<DesktopHomeLayout><DesktopHome /></DesktopHomeLayout>- <Suspense fallback={<Loading debugId="DesktopMainLayout > Outlet" />}>+ <Suspense fallback={<ContentLoading />}><Outlet /></Suspense></DesktopLayoutContainer>diff --git a/src/spa/BootShell/AppShellSkeleton.tsx b/src/spa/BootShell/AppShellSkeleton.tsxnew file mode 100644index 00000000000..eb06ed1dea2--- /dev/null+++ b/src/spa/BootShell/AppShellSkeleton.tsx@@ -0,0 +1,84 @@+'use client';++import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';+import { Flexbox } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';++import { isDesktop } from '@/const/version';+import {+ getInnerCssVariables,+ getOuterCssVariables,+} from '@/features/DesktopLayoutContainer/cssVariables';+import { styles as containerStyles } from '@/features/DesktopLayoutContainer/style';++import { readBootShellGeometry } from './geometry';++// antd emits its design tokens as `.lobe-vars{--ant-*: β¦}` β a plain global+// class rule, not a `:root` one. The shell renders outside `AppTheme`, so it has+// to opt into that class itself or every `var(--ant-*)` below resolves to its+// fallback.+const CSS_VAR_CLASS = 'lobe-vars';++export const APP_SHELL_FALLBACK_ID = 'app-shell-fallback';++const styles = createStaticStyles(({ css }) => ({+ root: css`+ pointer-events: none;++ position: fixed;+ z-index: 99999;+ inset: 0;++ display: flex;+ flex-direction: column;+ `,+}));++interface AppShellSkeletonProps {+ id?: string;+}++const AppShellSkeleton = memo<AppShellSkeletonProps>(({ id }) => {+ const { isDark, navPanelBackground, navPanelWidth, showLeftPanel } = readBootShellGeometry();++ return (+ <div aria-hidden className={`${CSS_VAR_CLASS} ${styles.root}`} id={id}>+ {isDesktop && <div style={{ flexShrink: 0, height: TITLE_BAR_HEIGHT }} />}+ <Flexbox+ horizontal+ height={isDesktop ? `calc(100% - ${TITLE_BAR_HEIGHT}px)` : '100%'}+ width={'100%'}+ >+ {showLeftPanel && (+ <div+ style={{+ background: navPanelBackground,+ flexShrink: 0,+ height: '100%',+ width: navPanelWidth,+ }}+ />+ )}+ <Flexbox+ className={containerStyles.outerContainer}+ height={'100%'}+ padding={8}+ style={getOuterCssVariables({ expand: showLeftPanel })}+ width={'100%'}+ >+ <Flexbox+ className={containerStyles.innerContainer}+ height={'100%'}+ style={getInnerCssVariables({ isDark })}+ width={'100%'}+ />+ </Flexbox>+ </Flexbox>+ </div>+ );+});++AppShellSkeleton.displayName = 'AppShellSkeleton';++export default AppShellSkeleton;diff --git a/src/spa/BootShell/geometry.test.ts b/src/spa/BootShell/geometry.test.tsnew file mode 100644index 00000000000..82dec984d06--- /dev/null+++ b/src/spa/BootShell/geometry.test.ts@@ -0,0 +1,50 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { useGlobalStore } from '@/store/global';+import { INITIAL_STATUS } from '@/store/global/initialState';++import { readBootShellGeometry } from './geometry';++const setStatus = (status: Partial<typeof INITIAL_STATUS>) =>+ useGlobalStore.setState({ status: { ...INITIAL_STATUS, ...status } });++beforeEach(() => {+ setStatus({});+ delete document.documentElement.dataset.theme;+});++afterEach(() => {+ delete document.documentElement.dataset.theme;+});++describe('readBootShellGeometry', () => {+ it('reads the panel layout from the store', () => {+ setStatus({ leftPanelWidth: 320, showLeftPanel: true });++ const geometry = readBootShellGeometry();++ expect(geometry.navPanelWidth).toBe(320);+ expect(geometry.showLeftPanel).toBe(true);+ });++ it('clamps the panel width to the draggable range', () => {+ setStatus({ leftPanelWidth: 9999 });+ expect(readBootShellGeometry().navPanelWidth).toBe(400);++ setStatus({ leftPanelWidth: 10 });+ expect(readBootShellGeometry().navPanelWidth).toBe(240);+ });++ it('falls back to the default width for an unusable persisted value', () => {+ setStatus({ leftPanelWidth: Number.NaN });++ expect(readBootShellGeometry().navPanelWidth).toBe(INITIAL_STATUS.leftPanelWidth);+ });++ it('follows the theme already resolved onto the document', () => {+ expect(readBootShellGeometry().isDark).toBe(false);++ document.documentElement.dataset.theme = 'dark';+ expect(readBootShellGeometry().isDark).toBe(true);+ });+});diff --git a/src/spa/BootShell/geometry.ts b/src/spa/BootShell/geometry.tsnew file mode 100644index 00000000000..f6527f4114e--- /dev/null+++ b/src/spa/BootShell/geometry.ts@@ -0,0 +1,50 @@+import { cssVar } from 'antd-style';++import { isDesktop } from '@/const/version';+import { useGlobalStore } from '@/store/global';+import { INITIAL_STATUS } from '@/store/global/initialState';+import { systemStatusSelectors } from '@/store/global/selectors';+import { isMacOS } from '@/utils/platform';++export interface BootShellGeometry {+ isDark: boolean;+ navPanelBackground: string;+ navPanelWidth: number;+ showLeftPanel: boolean;+}++const readIsDark = () => {+ try {+ return document.documentElement.dataset.theme === 'dark';+ } catch {+ return false;+ }+};++// Mirrors `NavPanelDraggable`'s panel background so the shell hands over to a+// panel of the same color instead of flashing an opaque block over vibrancy.+const readNavPanelBackground = () =>+ isDesktop && isMacOS() ? 'transparent' : cssVar.colorBgLayout;++export const readBootShellGeometry = (): BootShellGeometry => {+ const base = {+ isDark: readIsDark(),+ navPanelBackground: readNavPanelBackground(),+ };++ try {+ const state = useGlobalStore.getState();++ return {+ ...base,+ navPanelWidth: systemStatusSelectors.leftPanelWidth(state),+ showLeftPanel: Boolean(systemStatusSelectors.showLeftPanel(state)),+ };+ } catch {+ return {+ ...base,+ navPanelWidth: INITIAL_STATUS.leftPanelWidth,+ showLeftPanel: Boolean(INITIAL_STATUS.showLeftPanel),+ };+ }+};diff --git a/src/spa/BootShell/index.tsx b/src/spa/BootShell/index.tsxnew file mode 100644index 00000000000..b7ab3e2e328--- /dev/null+++ b/src/spa/BootShell/index.tsx@@ -0,0 +1,20 @@+'use client';++import { memo } from 'react';++import AppShellSkeleton from './AppShellSkeleton';+import { useBootShell } from './useBootShell';++export const BOOT_SHELL_ID = 'boot-shell';++const BootShell = memo(() => {+ const phase = useBootShell();++ if (phase !== 'shell') return null;++ return <AppShellSkeleton id={BOOT_SHELL_ID} />;+});++BootShell.displayName = 'BootShell';++export default BootShell;diff --git a/src/spa/BootShell/phase.test.ts b/src/spa/BootShell/phase.test.tsnew file mode 100644index 00000000000..5a79903a664--- /dev/null+++ b/src/spa/BootShell/phase.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { resolveBootShellPhase } from './phase';++describe('resolveBootShellPhase', () => {+ it('stays hidden before the delay elapses so a warm boot never flashes a shell', () => {+ expect(resolveBootShellPhase({ appPainted: false, appReady: false, delayElapsed: false })).toBe(+ 'hidden',+ );+ });++ it('shows the shell once the delay elapses and the app is still booting', () => {+ expect(resolveBootShellPhase({ appPainted: false, appReady: false, delayElapsed: true })).toBe(+ 'shell',+ );+ });++ it('needs BOTH gates released before it is done', () => {+ expect(resolveBootShellPhase({ appPainted: true, appReady: false, delayElapsed: true })).toBe(+ 'shell',+ );+ expect(resolveBootShellPhase({ appPainted: false, appReady: true, delayElapsed: true })).toBe(+ 'shell',+ );+ });++ it('is done regardless of the delay when the app has painted', () => {+ expect(resolveBootShellPhase({ appPainted: true, appReady: true, delayElapsed: false })).toBe(+ 'done',+ );+ expect(resolveBootShellPhase({ appPainted: true, appReady: true, delayElapsed: true })).toBe(+ 'done',+ );+ });+});diff --git a/src/spa/BootShell/phase.ts b/src/spa/BootShell/phase.tsnew file mode 100644index 00000000000..f96b6f6afc5--- /dev/null+++ b/src/spa/BootShell/phase.ts@@ -0,0 +1,19 @@+export const BOOT_SHELL_DELAY = 200;++export type BootShellPhase = 'done' | 'hidden' | 'shell';++interface ResolveBootShellPhaseOptions {+ appPainted: boolean;+ appReady: boolean;+ delayElapsed: boolean;+}++export const resolveBootShellPhase = ({+ appPainted,+ appReady,+ delayElapsed,+}: ResolveBootShellPhaseOptions): BootShellPhase => {+ if (appReady && appPainted) return 'done';++ return delayElapsed ? 'shell' : 'hidden';+};diff --git a/src/spa/BootShell/routeScope.test.ts b/src/spa/BootShell/routeScope.test.tsnew file mode 100644index 00000000000..de8016dba74--- /dev/null+++ b/src/spa/BootShell/routeScope.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import { desktopRoutes as webDesktopRoutes } from '@/spa/router/desktopRouter.config';+import { desktopRoutes as electronDesktopRoutes } from '@/spa/router/desktopRouter.config.desktop';++import { isMainLayoutLocation } from './routeScope';++const variants: Array<[string, typeof webDesktopRoutes]> = [+ ['Web', webDesktopRoutes],+ ['Electron', electronDesktopRoutes],+];++// Paths that render the nav panel + rounded container the shell imitates.+const MAIN_LAYOUT_PATHS = ['/', '/agent/agent-1', '/settings/memory', '/acme/settings/oauth-apps'];++describe('isMainLayoutLocation', () => {+ it.each(variants)('%s recognises main-layout urls', (_, routes) => {+ for (const pathname of MAIN_LAYOUT_PATHS) {+ expect(isMainLayoutLocation(routes, pathname), `${pathname} is main layout`).toBe(true);+ }+ });++ // The shell would otherwise promise chrome these pages never render β the+ // exact "logo β app-shell skeleton β logo β page" sequence this guards.+ it.each([+ ['Web', webDesktopRoutes, ['/onboarding', '/share/t/topic-1', '/verify', '/verify-im']],+ ['Electron', electronDesktopRoutes, ['/desktop-onboarding']],+ ])('%s excludes standalone routes outside the main layout', (_, routes, paths) => {+ for (const pathname of paths as string[]) {+ expect(isMainLayoutLocation(routes as never, pathname), `${pathname} is standalone`).toBe(+ false,+ );+ }+ });++ it('honours the debug-proxy basename', () => {+ const base = '/_dangerous_local_dev_proxy';++ expect(isMainLayoutLocation(webDesktopRoutes, `${base}/agent/agent-1`, base)).toBe(true);+ // Without it the prefix is eaten as a `:workspaceSlug`, so `/onboarding`+ // stops being recognised as standalone β which is why the entry must pass it.+ expect(isMainLayoutLocation(webDesktopRoutes, `${base}/onboarding`, base)).toBe(false);+ expect(isMainLayoutLocation(webDesktopRoutes, `${base}/onboarding`)).toBe(true);+ });++ // Not a "known route" test: the main area carries a `:workspaceSlug` segment,+ // so an unrecognised path really does render the main layout and the shell is+ // the right placeholder for it.+ it('treats an unrecognised path as a workspace inside the main layout', () => {+ expect(isMainLayoutLocation(webDesktopRoutes, '/_nonexistent_top_level')).toBe(true);+ });+});diff --git a/src/spa/BootShell/routeScope.ts b/src/spa/BootShell/routeScope.tsnew file mode 100644index 00000000000..70b4cf59df3--- /dev/null+++ b/src/spa/BootShell/routeScope.ts@@ -0,0 +1,24 @@+import { matchRoutes, type RouteObject } from 'react-router';++const MAIN_LAYOUT_PATH = '/';++/**+ * Whether the boot url lands inside the main layout.+ *+ * The shell draws the main-app chrome β nav panel column plus the rounded+ * container β so it is only an honest placeholder for routes that actually+ * render that chrome. `/onboarding`, `/share/t/:id` and `/verify` are siblings+ * of the main-layout root, not children: showing them a nav panel that never+ * arrives is worse than showing the brand logo they already fall back to.+ *+ * Note this is not a "known route" test: the main area carries a+ * `:workspaceSlug` segment, so an unrecognised path is read as a workspace and+ * genuinely does render the main layout. Only the explicit siblings are+ * excluded. That also means the basename must be passed β otherwise a+ * `/_dangerous_local_dev_proxy/...` url has its prefix eaten as a slug.+ */+export const isMainLayoutLocation = (+ routes: RouteObject[],+ pathname: string,+ basename?: string,+): boolean => matchRoutes(routes, pathname, basename)?.[0]?.route.path === MAIN_LAYOUT_PATH;diff --git a/src/spa/BootShell/useBootShell.test.ts b/src/spa/BootShell/useBootShell.test.tsnew file mode 100644index 00000000000..85ebf7842ba--- /dev/null+++ b/src/spa/BootShell/useBootShell.test.ts@@ -0,0 +1,106 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { setAppPainted, setAppReady } from '@/spa/atoms/app';++import { BOOT_SHELL_DELAY } from './phase';+import { useBootShell } from './useBootShell';++const queryLoadingScreen = () => document.getElementById('loading-screen');++const seedLoadingScreen = () => {+ const el = document.createElement('div');+ el.id = 'loading-screen';+ document.body.append(el);+};++const finishBoot = () =>+ act(() => {+ setAppReady(true);+ setAppPainted(true);+ });++const elapse = (ms: number) =>+ act(() => {+ vi.advanceTimersByTime(ms);+ });++beforeEach(() => {+ vi.useFakeTimers();+ setAppReady(false);+ setAppPainted(false);+ seedLoadingScreen();+});++afterEach(() => {+ setAppReady(false);+ setAppPainted(false);+ queryLoadingScreen()?.remove();+ vi.useRealTimers();+});++describe('useBootShell', () => {+ it('keeps the static logo up and draws nothing before the delay elapses', () => {+ const { result } = renderHook(() => useBootShell());++ expect(result.current).toBe('hidden');+ expect(queryLoadingScreen()).not.toBeNull();++ elapse(BOOT_SHELL_DELAY - 1);++ expect(result.current).toBe('hidden');+ expect(queryLoadingScreen()).not.toBeNull();+ });++ it('a warm boot never flashes the shell β the logo hands straight over to the app', () => {+ const { result } = renderHook(() => useBootShell());++ finishBoot();++ expect(result.current).toBe('done');+ expect(queryLoadingScreen()).toBeNull();++ // the pending delay timer must not resurrect the shell after the app painted+ elapse(BOOT_SHELL_DELAY * 10);++ expect(result.current).toBe('done');+ });++ it('replaces the logo with the shell on a cold boot, then finishes once painted', () => {+ const { result } = renderHook(() => useBootShell());++ elapse(BOOT_SHELL_DELAY);++ expect(result.current).toBe('shell');+ expect(queryLoadingScreen()).toBeNull();++ finishBoot();++ expect(result.current).toBe('done');+ });++ it('holds the shell until BOTH the ready and painted signals land', () => {+ const { result } = renderHook(() => useBootShell());++ elapse(BOOT_SHELL_DELAY);++ act(() => {+ setAppReady(true);+ });+ expect(result.current).toBe('shell');++ act(() => {+ setAppPainted(true);+ });+ expect(result.current).toBe('done');+ });++ it('tolerates a missing loading screen', () => {+ queryLoadingScreen()!.remove();++ const { result } = renderHook(() => useBootShell());+ elapse(BOOT_SHELL_DELAY);++ expect(result.current).toBe('shell');+ });+});diff --git a/src/spa/BootShell/useBootShell.ts b/src/spa/BootShell/useBootShell.tsnew file mode 100644index 00000000000..546ce4cb42e--- /dev/null+++ b/src/spa/BootShell/useBootShell.ts@@ -0,0 +1,29 @@+import { useEffect, useLayoutEffect, useState } from 'react';++import { useAppPainted, useAppReady } from '@/spa/atoms/app';+import { removeStaticLoadingScreen } from '@/spa/loadingScreen';++import { BOOT_SHELL_DELAY, type BootShellPhase, resolveBootShellPhase } from './phase';++export const useBootShell = (): BootShellPhase => {+ const appReady = useAppReady();+ const appPainted = useAppPainted();+ const [delayElapsed, setDelayElapsed] = useState(false);++ const phase = resolveBootShellPhase({ appPainted, appReady, delayElapsed });++ useEffect(() => {+ if (delayElapsed || phase === 'done') return;++ const timer = setTimeout(() => setDelayElapsed(true), BOOT_SHELL_DELAY);+ return () => clearTimeout(timer);+ }, [delayElapsed, phase]);++ useLayoutEffect(() => {+ if (phase === 'hidden') return;++ removeStaticLoadingScreen();+ }, [phase]);++ return phase;+};diff --git a/src/spa/atoms/app.ts b/src/spa/atoms/app.tsindex 550519046de..b1bd5900019 100644--- a/src/spa/atoms/app.ts+++ b/src/spa/atoms/app.ts@@ -1,6 +1,7 @@import { useSyncExternalStore } from 'react';let appReady = false;+let appPainted = false;let postRenderReady = false;const listeners = new Set<() => void>();@@ -9,6 +10,7 @@ const emit = () => {};export const getAppReady = () => appReady;+export const getAppPainted = () => appPainted;export const getPostRenderReady = () => postRenderReady;export const setAppReady = (ready: boolean) => {@@ -18,6 +20,13 @@ export const setAppReady = (ready: boolean) => {emit();};+export const setAppPainted = (painted: boolean) => {+ if (appPainted === painted) return;++ appPainted = painted;+ emit();+};+export const setPostRenderReady = (ready: boolean) => {if (postRenderReady === ready) return;@@ -34,5 +43,8 @@ export const subscribeAppReady = (listener: () => void) => {export const useAppReady = () => useSyncExternalStore(subscribeAppReady, getAppReady, getAppReady);+export const useAppPainted = () =>+ useSyncExternalStore(subscribeAppReady, getAppPainted, getAppPainted);+export const usePostRenderReady = () =>useSyncExternalStore(subscribeAppReady, getPostRenderReady, getPostRenderReady);diff --git a/src/spa/entry.desktop.test.ts b/src/spa/entry.desktop.test.tsnew file mode 100644index 00000000000..d4b02dbc8df--- /dev/null+++ b/src/spa/entry.desktop.test.ts@@ -0,0 +1,31 @@+import { readFile } from 'node:fs/promises';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++const readEntry = () => readFile(path.join(process.cwd(), 'src/spa/entry.desktop.tsx'), 'utf8');++describe('desktop entry boot order', () => {+ // `useCacheScope` gates the desktop cache partition on `isIdentityResolved`,+ // and preload is the only source that knows it without waiting for the+ // `getUserState()` round-trip. Dropping this call silently downgrades desktop+ // to the optimistic persisted scope β no test fails, the app just hydrates the+ // previous partition and quarantines its writes until the request lands.+ it('applies the preload identity synchronously, before the app initializes', async () => {+ const source = await readEntry();+ const identityAt = source.indexOf('applyDesktopBootstrapIdentity()');+ const initAt = source.indexOf('startAppInitialization()');+ const renderAt = source.indexOf('createSPARoot(');++ expect(identityAt).toBeGreaterThan(-1);+ expect(identityAt).toBeLessThan(initAt);+ expect(identityAt).toBeLessThan(renderAt);+ });++ it('keeps the call out of an effect or callback', async () => {+ const source = await readEntry();++ expect(source).not.toContain('useEffect');+ expect(source).toMatch(/^applyDesktopBootstrapIdentity\(\);$/m);+ });+});diff --git a/src/spa/entry.desktop.tsx b/src/spa/entry.desktop.tsxindex 849a4cea960..0a58fe99935 100644--- a/src/spa/entry.desktop.tsx+++ b/src/spa/entry.desktop.tsx@@ -8,20 +8,31 @@ import { registerLocalDatabaseAdapter } from '@/libs/localDatabase';import { createElectronLocalDatabaseAdapter } from '@/libs/localDatabase/electronAdapter';import { createAppRouter } from '@/utils/router';+import BootShell from './BootShell';+import { isMainLayoutLocation } from './BootShell/routeScope';import { startAppInitialization } from './initialize/bootstrap';import { applyDesktopBootstrapIdentity } from './initialize/desktopIdentity';import { desktopRoutes } from './router/desktopRouter.config';import { createSPARoot } from './runtime';registerLocalDatabaseAdapter(createElectronLocalDatabaseAdapter());+// Must stay synchronous and ahead of the first render: `useCacheScope` reads+// `isIdentityResolved` to pick the cache partition, and on desktop preload is+// the only source that knows it without waiting for `getUserState()`.applyDesktopBootstrapIdentity();bootTiming.mark('bundle-eval');startAppInitialization();const router = createAppRouter(desktopRoutes);+// Mounting is conditional rather than an early return inside the shell: the hook+// also strips the static logo, and a standalone route needs that logo to stay up+// until its own brand-loading fallback takes over.+const showBootShell = isMainLayoutLocation(desktopRoutes, window.location.pathname);+createSPARoot(document.getElementById('root')!).render(<NextThemeProvider>+ {showBootShell && <BootShell />}<RouterProvider router={router} /></NextThemeProvider>,);diff --git a/src/spa/entry.web.tsx b/src/spa/entry.web.tsxindex 2a9c278b2f9..bf334326be6 100644--- a/src/spa/entry.web.tsx+++ b/src/spa/entry.web.tsx@@ -7,6 +7,8 @@ import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';import { bootTiming } from '@/libs/bootTiming';import { createAppRouter } from '@/utils/router';+import BootShell from './BootShell';+import { isMainLayoutLocation } from './BootShell/routeScope';import { startAppInitialization } from './initialize/bootstrap';import { desktopRoutes } from './router/desktopRouter.config';import { createSPARoot } from './runtime';@@ -22,9 +24,15 @@ const basename =const router = createAppRouter(desktopRoutes, { basename });+// Mounting is conditional rather than an early return inside the shell: the hook+// also strips the static logo, and a standalone route needs that logo to stay up+// until its own brand-loading fallback takes over.+const showBootShell = isMainLayoutLocation(desktopRoutes, window.location.pathname, basename);+createSPARoot(document.getElementById('root')!).render(<BootErrorBoundary><NextThemeProvider>+ {showBootShell && <BootShell />}<RouterProvider router={router} /></NextThemeProvider></BootErrorBoundary>,diff --git a/src/spa/loadingScreen.ts b/src/spa/loadingScreen.tsnew file mode 100644index 00000000000..b74811ff5b6--- /dev/null+++ b/src/spa/loadingScreen.ts@@ -0,0 +1,5 @@+export const LOADING_SCREEN_ID = 'loading-screen';++export const removeStaticLoadingScreen = (): void => {+ document.getElementById(LOADING_SCREEN_ID)?.remove();+};diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 72c1ff82de8..046c2d9effd 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -10,7 +10,7 @@ import {Settings,ShapesIcon,} from 'lucide-react';-import type { ReactElement } from 'react';+import { cloneElement, isValidElement, type ReactElement, Suspense } from 'react';import type { RouteObject } from 'react-router';import {@@ -18,6 +18,7 @@ import {BusinessDesktopRoutesWithoutMainLayout,BusinessResourceRoutes,} from '@/business/client/BusinessDesktopRoutes';+import ContentLoading from '@/components/Loading/ContentLoading';import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';@@ -33,6 +34,7 @@ import {} from '@/routes/(main)/agent/features/routeMeta';import { groupProfileRouteMeta, groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';import { settingsRouteMeta } from '@/routes/(main)/settings/features/routeMeta';+import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShellSkeleton';import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';import { routeMeta } from '@/spa/router/routeMeta';import { SettingsTabs } from '@/store/global/initialState';@@ -1130,14 +1132,53 @@ export interface SharedDesktopRouteOptions {* Builds the common Web/Electron top-level route tree. Platform entry files* supply only the root children, runtime-only routes, and onboarding route.*/+/**+ * Swap the brand-loading fallback for a content one across a route subtree.+ *+ * `dynamicElement` / `dynamicLayout` wrap every route element in their own+ * `Suspense`, and that boundary is always nearer the suspending component than+ * any outlet-level one β so a fallback set on the main layout's outlet never+ * fires for route content, and the 100+ call sites would otherwise each need+ * the option. Rewriting the elements once here keeps the main area consistent+ * without touching routes outside it (mobile still wants the full-page brand+ * loading, since its nav bar is inside the same boundary as its outlet).+ */+export const withContentFallback = (routes: RouteObject[]): RouteObject[] =>+ routes.map((route) => {+ const element =+ isValidElement(route.element) && route.element.type === Suspense+ ? // right that this couples to `dynamicElement` returning a bare Suspense.+ // The alternative is the option on all 104 call sites; the coupling is+ // guarded instead β `desktopRouter.sync.test.tsx` asserts every+ // main-area fallback is `ContentLoading`, so if that shape ever changes+ // the rewrite fails loudly rather than silently restoring the logo.+ cloneElement(route.element as ReactElement<{ fallback: ReactElement }>, {+ fallback: <ContentLoading />,+ })+ : route.element;++ // `RouteObject` is a discriminated union of index / non-index routes, and+ // spreading loses the discriminant β the copy keeps the original's shape.+ return {+ ...route,+ ...(route.children && { children: withContentFallback(route.children) }),+ element,+ } as RouteObject;+ });+export const createSharedDesktopRoutes = ({mainAreaChildren,onboardingRoute,platformRoutes = [],}: SharedDesktopRouteOptions): RouteObject[] => [{- children: mainAreaChildren,- element: dynamicLayout(() => import('@/routes/(main)/_layout'), 'Desktop > Main > Layout'),+ children: withContentFallback(mainAreaChildren),+ // `BootShell` unmounts the moment the cache gate releases, which is often+ // before this chunk resolves. Falling back to the same skeleton keeps the+ // handoff invisible instead of flashing the brand logo a second time.+ element: dynamicLayout(() => import('@/routes/(main)/_layout'), 'Desktop > Main > Layout', {+ fallback: <AppShellSkeleton id={APP_SHELL_FALLBACK_ID} />,+ }),errorElement: <ErrorBoundary />,path: '/',},diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex f972bf029f7..0409a3073cd 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -1,11 +1,16 @@import { readFile } from 'node:fs/promises';import path from 'node:path';+import type { ReactElement } from 'react';import type { RouteObject } from 'react-router';import { matchRoutes } from 'react-router';import { describe, expect, it } from 'vitest';+import BrandTextLoading from '@/components/Loading/BrandTextLoading';+import ContentLoading from '@/components/Loading/ContentLoading';import { WORKSPACE_SETTINGS_TABS } from '@/features/Workspace/workspaceAwarePath';+import AppShellSkeleton from '@/spa/BootShell/AppShellSkeleton';+import { createTabRouter } from '@/spa/router/tabRouter';import {createMainAreaChildren as createWebMainAreaChildren,@@ -177,6 +182,46 @@ describe('desktop router shared definition', () => {expect(electronPaths).toContain('/desktop-onboarding');});+ it.each([+ ['Web', webDesktopRoutes],+ ['Electron', electronDesktopRoutes],+ ])('%s hands the boot shell over to the same skeleton, not the brand logo', (_, routes) => {+ const root = routes.find((route) => route.path === '/');+ const { fallback } = (root?.element as ReactElement<{ fallback: ReactElement }>).props;++ expect(fallback.type).toBe(AppShellSkeleton);+ });++ // `dynamicElement` / `dynamicLayout` wrap each route element in their own+ // Suspense, which always beats an outlet-level boundary β so without the+ // rewrite the brand wordmark reappears inside the container for 1β2s on a+ // cold deep link, right after the boot shell hands over.+ const collectFallbacks = (list: RouteObject[]): unknown[] => {+ const fallbacks: unknown[] = [];+ const walk = (routes: RouteObject[]) => {+ for (const route of routes) {+ const element = route.element as ReactElement<{ fallback?: ReactElement }> | undefined;+ if (element?.props?.fallback) fallbacks.push(element.props.fallback.type);+ if (route.children) walk(route.children);+ }+ };+ walk(list);+ return fallbacks;+ };++ it.each([+ // Electron's root tree holds only TabHost stubs β its real content routes+ // live in the per-tab memory routers, which build their own tree.+ ['Web', () => webDesktopRoutes.find((route) => route.path === '/')?.children ?? []],+ ['Electron', () => createTabRouter('/').routes[0]?.children ?? []],+ ])('%s main-area routes load behind the content fallback, not the brand logo', (_, getRoutes) => {+ const fallbacks = collectFallbacks(getRoutes());++ expect(fallbacks.length).toBeGreaterThan(0);+ expect(fallbacks).not.toContain(BrandTextLoading);+ expect(new Set(fallbacks)).toEqual(new Set([ContentLoading]));+ });+it('injects Home only into Electron per-tab content routes', () => {const webChildren = createWebMainAreaChildren();const electronChildren = createElectronMainAreaChildren();diff --git a/src/spa/router/tabRouter.tsx b/src/spa/router/tabRouter.tsxindex adc9e8be191..336bb944723 100644--- a/src/spa/router/tabRouter.tsx+++ b/src/spa/router/tabRouter.tsx@@ -3,14 +3,15 @@import { Suspense } from 'react';import { createMemoryRouter, Outlet } from 'react-router';-import Loading from '@/components/Loading/BrandTextLoading';+import ContentLoading from '@/components/Loading/ContentLoading';import TabLocationReporter from '@/features/Electron/TabHost/TabLocationReporter';import { ErrorBoundary } from '@/utils/router';import { createMainAreaChildren } from './desktopRouter.config';+import { withContentFallback } from './desktopRouter.shared';const TabRootLayout = () => (- <Suspense fallback={<Loading debugId="TabRootLayout > Outlet" />}>+ <Suspense fallback={<ContentLoading />}><Outlet /><TabLocationReporter /></Suspense>@@ -20,7 +21,9 @@ export const createTabRouter = (initialUrl: string) =>createMemoryRouter([{- children: createMainAreaChildren(),+ // Per-tab routers bypass `createSharedDesktopRoutes`, so the main-area+ // fallback rewrite has to be applied here too.+ children: withContentFallback(createMainAreaChildren()),element: <TabRootLayout />,// The error element replaces `TabRootLayout`, so the reporter is repeated// here: the memory router has already advanced to the failing url, anddiff --git a/src/store/global/initialState.test.ts b/src/store/global/initialState.test.tsnew file mode 100644index 00000000000..3eb61fec1c0--- /dev/null+++ b/src/store/global/initialState.test.ts@@ -0,0 +1,46 @@+import { afterEach, describe, expect, it } from 'vitest';++import { createInitialSystemStatus, INITIAL_STATUS } from './initialState';++const STORAGE_KEY = 'LOBE_SYSTEM_STATUS';++const seed = (value: unknown) => localStorage.setItem(STORAGE_KEY, JSON.stringify(value));++afterEach(() => {+ localStorage.removeItem(STORAGE_KEY);+});++describe('createInitialSystemStatus', () => {+ it('restores the shell-defining preferences synchronously', () => {+ seed({ leftPanelWidth: 360, showHomeRail: false, showLeftPanel: false });++ const status = createInitialSystemStatus();++ expect(status.leftPanelWidth).toBe(360);+ expect(status.showHomeRail).toBe(false);+ expect(status.showLeftPanel).toBe(false);+ });++ it('falls back to defaults when nothing is persisted', () => {+ const status = createInitialSystemStatus();++ expect(status.leftPanelWidth).toBe(INITIAL_STATUS.leftPanelWidth);+ expect(status.showHomeRail).toBe(INITIAL_STATUS.showHomeRail);+ expect(status.showLeftPanel).toBe(INITIAL_STATUS.showLeftPanel);+ });++ it('ignores persisted values of the wrong type', () => {+ seed({ leftPanelWidth: '360', showLeftPanel: 'false' });++ const status = createInitialSystemStatus();++ expect(status.leftPanelWidth).toBe(INITIAL_STATUS.leftPanelWidth);+ expect(status.showLeftPanel).toBe(INITIAL_STATUS.showLeftPanel);+ });++ it('survives a corrupted payload', () => {+ localStorage.setItem(STORAGE_KEY, '{not json');++ expect(createInitialSystemStatus().leftPanelWidth).toBe(INITIAL_STATUS.leftPanelWidth);+ });+});diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex 03396ab76bb..c833b0f2abc 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -540,20 +540,30 @@ export const INITIAL_STATUS = {const statusStorage = new AsyncLocalStorage<SystemStatus>('LOBE_SYSTEM_STATUS');/**- * Restore the Home rail before React's first render. The remaining system- * status still follows the existing async initialization path, but this- * layout-affecting preference must not briefly render its default value after- * a page reload.+ * Restore the shell-defining preferences before React's first render. The+ * remaining system status still follows the existing async initialization path,+ * but these must not briefly render their default value after a page reload β+ * the boot shell reads them synchronously to draw a shell that lines up with+ * the real layout, and `NavPanelDraggable` would otherwise size its+ * pre-hydration placeholder to the default width.*/export const createInitialSystemStatus = (): SystemStatus => {const persistedStatus = statusStorage.getFromLocalStorageSync();return {...INITIAL_STATUS,+ leftPanelWidth:+ typeof persistedStatus.leftPanelWidth === 'number'+ ? persistedStatus.leftPanelWidth+ : INITIAL_STATUS.leftPanelWidth,showHomeRail:typeof persistedStatus.showHomeRail === 'boolean'? persistedStatus.showHomeRail: INITIAL_STATUS.showHomeRail,+ showLeftPanel:+ typeof persistedStatus.showLeftPanel === 'boolean'+ ? persistedStatus.showLeftPanel+ : INITIAL_STATUS.showLeftPanel,};};diff --git a/src/utils/router.test.ts b/src/utils/router.test.tsnew file mode 100644index 00000000000..cc10c088f4a--- /dev/null+++ b/src/utils/router.test.ts@@ -0,0 +1,29 @@+import { createElement, type ReactElement } from 'react';+import { describe, expect, it } from 'vitest';++import BrandTextLoading from '@/components/Loading/BrandTextLoading';++import { dynamicElement, dynamicLayout } from './router';++const neverResolves = () => new Promise<{ default: () => null }>(() => {});++const readFallback = (element: ReactElement) =>+ (element as ReactElement<{ fallback: ReactElement }>).props.fallback;++describe('dynamic route helpers', () => {+ it.each([+ ['dynamicLayout', dynamicLayout],+ ['dynamicElement', dynamicElement],+ ])('%s falls back to the brand loading when no fallback is provided', (_, createRouteElement) => {+ expect(readFallback(createRouteElement(neverResolves, 'Test')).type).toBe(BrandTextLoading);+ });++ it.each([+ ['dynamicLayout', dynamicLayout],+ ['dynamicElement', dynamicElement],+ ])('%s suspends on the provided fallback instead', (_, createRouteElement) => {+ const fallback = createElement('div');++ expect(readFallback(createRouteElement(neverResolves, 'Test', { fallback }))).toBe(fallback);+ });+});diff --git a/src/utils/router.tsx b/src/utils/router.tsxindex 8f5ce8d4c99..9e01362639b 100644--- a/src/utils/router.tsx+++ b/src/utils/router.tsx@@ -2,7 +2,7 @@import { ConfigProvider, ThemeProvider } from '@lobehub/ui';import * as m from 'motion/react-m';-import { type ComponentType, type ReactElement } from 'react';+import { type ComponentType, type ReactElement, type ReactNode } from 'react';import { lazy, memo, Suspense } from 'react';import type { RouteObject } from 'react-router';import { Navigate, Outlet, useRouteError } from 'react-router';@@ -39,6 +39,7 @@ function resolveLazyModule<P>(module: { default: ComponentType<P> } | ComponentT}interface DynamicRouteOptions {+ fallback?: ReactNode;preloadId?: string;}@@ -108,7 +109,7 @@ export function dynamicElement<P = NonNullable<unknown>>(// @ts-ignorereturn (- <Suspense fallback={<Loading debugId={debugId || 'dynamicElement'} />}>+ <Suspense fallback={options?.fallback ?? <Loading debugId={debugId || 'dynamicElement'} />}>{/* @ts-ignore */}<Component {...({} as P)} /></Suspense>@@ -129,7 +130,7 @@ export function dynamicLayout<P = NonNullable<unknown>>(// @ts-ignorereturn (- <Suspense fallback={<Loading debugId={debugId || 'dynamicLayout'} />}>+ <Suspense fallback={options?.fallback ?? <Loading debugId={debugId || 'dynamicLayout'} />}>{/* @ts-ignore */}<Component {...({} as P)} /></Suspense>