Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 登录后白屏不再被附件清扫堵住

Dash630c90dd674b
diff --git a/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts b/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts
index f934bd6cee..d325fcf8c3 100644
--- a/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts
@@ -48,4 +48,15 @@ describe('model pricing prewarm ordering', () => {
expect(nextIpc).toBeGreaterThan(earlyUsageIpc);
expect(source.slice(earlyUsageIpc, nextIpc)).not.toContain('prewarmModelPricing');
});
+
+ it('does not block owner ensureReady on staged attachment bookkeeping', () => {
+ const onReady = source.slice(
+ source.indexOf('onReady: async (userId) => {'),
+ source.indexOf('onReadyError:'),
+ );
+ expect(onReady).toContain('void sweepStagedChatAttachmentsOnStartup({');
+ expect(onReady).toContain('loadProtectedPaths: listPersistedChatAttachmentPaths');
+ expect(onReady).not.toMatch(/await listPersistedChatAttachmentPaths\(\)/);
+ expect(onReady).not.toMatch(/await sweepStagedChatAttachmentsOnStartup\(/);
+ });
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b9cca600ef..e0069b40e2 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -6884,25 +6884,33 @@ app.on('ready', async () => {
// Phase 1.1: file worker 接管 DB 连接后,释放 main 端的 _db + optimize 定时器。
// 如果 worker takeover 失败并进入 inproc fallback,main _db 必须继续保留,
// 否则 fallback 会拿到已关闭的连接。
- try {
- const protectedPaths = await listPersistedChatAttachmentPaths();
- const result = await sweepStagedChatAttachmentsOnStartup({
- ownerId: userId,
- protectedPaths,
- createdBeforeMs: PROCESS_STARTED_AT_MS,
- });
- if (result.removed > 0 || result.protected > 0) {
- dbClientLog.info('[ChatAttachment] startup staged attachment sweep completed', {
- ...result,
+ //
+ // Staged-attachment bookkeeping is not first-paint readiness. The persisted-path
+ // lookup is a LIKE + json_tree scan over every retained message body; on a
+ // multi-GB owner DB that blocked LocalDbGate for ~24s after splash had already
+ // unmounted, leaving a white window. Sweep is fire-and-forget and only queries
+ // the DB when the owner cache already has stale files.
+ void sweepStagedChatAttachmentsOnStartup({
+ ownerId: userId,
+ createdBeforeMs: PROCESS_STARTED_AT_MS,
+ loadProtectedPaths: listPersistedChatAttachmentPaths,
+ canContinue: () =>
+ getActiveAppSession().dataOwnerId === userId && !isAppSessionBoundaryPending(),
+ })
+ .then((result) => {
+ if (result.removed > 0 || result.protected > 0) {
+ dbClientLog.info('[ChatAttachment] startup staged attachment sweep completed', {
+ ...result,
+ ownerId: userId,
+ });
+ }
+ })
+ .catch((err) => {
+ dbClientLog.warn('[ChatAttachment] startup staged attachment sweep failed (non-fatal)', {
ownerId: userId,
+ error: err instanceof Error ? err.message : String(err),
});
- }
- } catch (err) {
- dbClientLog.warn('[ChatAttachment] startup staged attachment sweep failed (non-fatal)', {
- ownerId: userId,
- error: err instanceof Error ? err.message : String(err),
});
- }
logStartupPhase('chat-attachment-sweep');
if (dbClientTakeover.shouldReleaseMainDb && process.env.XDT_DB_INPROC !== 'true') {
// 只把连接交给 worker,不能释放 shared-passive schema reader lease:worker
diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts
index bf6e1e9112..6fe3a5fc9a 100644
--- a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheStaging.test.ts
@@ -114,6 +114,83 @@ describe('chat attachment staging cache', () => {
await expect(fs.stat(otherOwnerPath)).resolves.toBeDefined();
});
+ it('does not load persisted paths when the owner cache has no stale files', async () => {
+ const loadProtectedPaths = vi.fn(async () => {
+ throw new Error('must not query message bodies when there is nothing to sweep');
+ });
+
+ await expect(
+ sweepStagedChatAttachmentsOnStartup({
+ ownerId: 'owner-empty',
+ createdBeforeMs: Date.now() - 1_000,
+ loadProtectedPaths,
+ }),
+ ).resolves.toMatchObject({ inspected: 0, removed: 0, protected: 0 });
+ expect(loadProtectedPaths).not.toHaveBeenCalled();
+
+ const ownerRoot = getChatAttachmentOwnerCacheRoot('owner-fresh');
+ await fs.mkdir(ownerRoot, { recursive: true });
+ const freshPath = path.join(ownerRoot, 'fresh.bin');
+ await fs.writeFile(freshPath, 'fresh');
+
+ await expect(
+ sweepStagedChatAttachmentsOnStartup({
+ ownerId: 'owner-fresh',
+ createdBeforeMs: Date.now() - 1_000,
+ loadProtectedPaths,
+ }),
+ ).resolves.toMatchObject({ inspected: 1, removed: 0, protected: 0 });
+ expect(loadProtectedPaths).not.toHaveBeenCalled();
+ await expect(fs.stat(freshPath)).resolves.toBeDefined();
+ });
+
+ it('loads persisted paths only after it finds stale cache files', async () => {
+ const ownerId = 'owner-stale';
+ const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);
+ await fs.mkdir(ownerRoot, { recursive: true });
+ const orphanPath = path.join(ownerRoot, 'orphan.bin');
+ const protectedPath = path.join(ownerRoot, 'protected.bin');
+ await Promise.all([fs.writeFile(orphanPath, 'orphan'), fs.writeFile(protectedPath, 'kept')]);
+ const oldTime = new Date(Date.now() - 60_000);
+ await Promise.all([
+ fs.utimes(orphanPath, oldTime, oldTime),
+ fs.utimes(protectedPath, oldTime, oldTime),
+ ]);
+ const loadProtectedPaths = vi.fn(async () => [protectedPath]);
+
+ await expect(
+ sweepStagedChatAttachmentsOnStartup({
+ ownerId,
+ createdBeforeMs: Date.now() - 1_000,
+ loadProtectedPaths,
+ }),
+ ).resolves.toMatchObject({ inspected: 2, removed: 1, protected: 1 });
+ expect(loadProtectedPaths).toHaveBeenCalledOnce();
+ await expect(fs.stat(orphanPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fs.stat(protectedPath)).resolves.toBeDefined();
+ });
+
+ it('stops before deleting when the owner is no longer current', async () => {
+ const ownerId = 'owner-switch';
+ const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);
+ await fs.mkdir(ownerRoot, { recursive: true });
+ const orphanPath = path.join(ownerRoot, 'orphan.bin');
+ await fs.writeFile(orphanPath, 'orphan');
+ await fs.utimes(orphanPath, new Date(Date.now() - 60_000), new Date(Date.now() - 60_000));
+ const loadProtectedPaths = vi.fn(async () => []);
+
+ await expect(
+ sweepStagedChatAttachmentsOnStartup({
+ ownerId,
+ createdBeforeMs: Date.now() - 1_000,
+ loadProtectedPaths,
+ canContinue: () => false,
+ }),
+ ).resolves.toMatchObject({ inspected: 1, removed: 0, protected: 0 });
+ expect(loadProtectedPaths).not.toHaveBeenCalled();
+ await expect(fs.stat(orphanPath)).resolves.toBeDefined();
+ });
+
it('renderer cleanup removes only current-owner files not retained by messages', async () => {
const ownerId = 'owner-a';
const ownerRoot = getChatAttachmentOwnerCacheRoot(ownerId);
diff --git a/apps/desktop/src/main/file-browser/remote-file-cache.ts b/apps/desktop/src/main/file-browser/remote-file-cache.ts
index cb673bc2ca..2d156e69e0 100644
--- a/apps/desktop/src/main/file-browser/remote-file-cache.ts
+++ b/apps/desktop/src/main/file-browser/remote-file-cache.ts
@@ -134,20 +134,27 @@ export interface StartupStagedChatAttachmentSweepResult {
* created by an earlier process and not referenced by persisted messages is
* unreachable after restart. Files created by this process are left alone to
* avoid racing a draft that is still being assembled.
+ *
+ * Filesystem is the source of work: persisted-path lookup only runs when the
+ * owner cache already has stale `.bin` / `.bin.part` files. A LIKE + json_tree
+ * scan over a multi-GB message table otherwise blocks startup for tens of
+ * seconds even when the cache directory does not exist.
*/
export async function sweepStagedChatAttachmentsOnStartup(params: {
ownerId: string;
- protectedPaths: readonly string[];
createdBeforeMs: number;
+ protectedPaths?: readonly string[];
+ loadProtectedPaths?: () => Promise<readonly string[]>;
+ canContinue?: () => boolean;
}): Promise<StartupStagedChatAttachmentSweepResult> {
const result: StartupStagedChatAttachmentSweepResult = {
inspected: 0,
removed: 0,
protected: 0,
};
- const protectedPaths = new Set(params.protectedPaths.map(normalizePathForComparison));
const ownerDir = chatAttachmentOwnerCacheDir(params.ownerId);
const entries = await fs.readdir(ownerDir, { withFileTypes: true }).catch(() => []);
+ const stalePaths: string[] = [];
for (const entry of entries) {
if (!entry.isFile() && !entry.isSymbolicLink()) continue;
if (!entry.name.endsWith('.bin') && !entry.name.endsWith('.bin.part')) continue;
@@ -157,10 +164,33 @@ export async function sweepStagedChatAttachmentsOnStartup(params: {
try {
const stat = await fs.lstat(filePath);
if (stat.mtimeMs >= params.createdBeforeMs) continue;
- if (protectedPaths.has(normalizePathForComparison(filePath))) {
- result.protected += 1;
- continue;
+ stalePaths.push(filePath);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ if (code !== 'ENOENT') {
+ log.warn('startup staged chat attachment sweep failed for file', {
+ filePath,
+ error: String(err),
+ });
}
+ }
+ }
+ if (stalePaths.length === 0) return result;
+ if (params.canContinue && !params.canContinue()) return result;
+
+ const protectedList =
+ params.protectedPaths ??
+ (params.loadProtectedPaths ? await params.loadProtectedPaths() : []);
+ if (params.canContinue && !params.canContinue()) return result;
+ const protectedPaths = new Set(protectedList.map(normalizePathForComparison));
+
+ for (const filePath of stalePaths) {
+ if (protectedPaths.has(normalizePathForComparison(filePath))) {
+ result.protected += 1;
+ continue;
+ }
+ try {
+ if (params.canContinue && !params.canContinue()) return result;
await fs.unlink(filePath);
result.removed += 1;
} catch (err) {
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index d134b771f0..63ec5cd939 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -9,6 +9,7 @@ import { ThemeProvider } from '@/hooks/useTheme';
import { FontSettingsProvider } from '@/hooks/useFontSettings';
import { LocaleProvider } from '@/hooks/useLocale';
import { AuthProvider, useAuth } from '@/contexts/AuthContext';
+import { AppShellCoverProvider, useAppShellCover } from '@/contexts/AppShellCoverContext';
import { LoginHandoffProvider } from '@/contexts/LoginHandoffContext';
import { EnvCheckProvider, EnvCheckGuard } from '@/contexts/EnvCheckContext';
import { WorktreeProvider } from '@/contexts/WorktreeContext';
@@ -71,10 +72,12 @@ import { router } from './router';
*/
function LoginHandoffHost({ children }: { children: React.ReactNode }) {
const { isInitializing, isAuthenticated, canEnterApp } = useAuth();
+ const { coverHeld } = useAppShellCover();
return (
<LoginHandoffProvider
authResolved={!isInitializing}
authenticated={isAuthenticated || canEnterApp}
+ coverHeld={coverHeld}
>
{/* 认证恢复后已登录(直进受保护路由、LoginPage 不挂载)时结束首启亮色门,
避免 renderer localStorage 被清空但主进程仍持有会话时整个已登录会话
@@ -330,8 +333,9 @@ export function App() {
<ConfirmDialogProvider>
<EnvCheckProvider>
<AuthProvider>
- <WorktreeProvider>
- <PrRefsProvider>
+ <AppShellCoverProvider>
+ <WorktreeProvider>
+ <PrRefsProvider>
<Tooltip.Provider>
{/* LoginHandoffProvider 包 SplashScreen + RouterProvider(Step 3b
WHAT2 宿主契约):Splash→登录/主界面衔接动画状态机。
@@ -366,8 +370,9 @@ export function App() {
<LegacyMigrationDialog />
)}
</Tooltip.Provider>
- </PrRefsProvider>
- </WorktreeProvider>
+ </PrRefsProvider>
+ </WorktreeProvider>
+ </AppShellCoverProvider>
</AuthProvider>
</EnvCheckProvider>
</ConfirmDialogProvider>
diff --git a/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx b/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx
index df384e7e4f..94d126414e 100644
--- a/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx
+++ b/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { Outlet, useNavigate } from 'react-router-dom';
+import { useAppShellCover } from '@/contexts/AppShellCoverContext';
import { useAuth } from '@/contexts/AuthContext';
import { LocalDbFatalScreen } from '@/components/error/LocalDbFatalScreen';
import { createLogger } from '@/lib/logger';
@@ -36,6 +37,7 @@ const DECISION_RETRY_DELAY_MS = 1_000;
export function LocalDbGate() {
const { dataOwnerId, mode, logout, exitLocalMode } = useAuth();
+ const { reportLocalDbGate } = useAppShellCover();
const navigate = useNavigate();
const [decision, setDecision] = useState<GateDecision>({ phase: 'checking' });
const [retryNonce, setRetryNonce] = useState(0);
@@ -115,8 +117,22 @@ export function LocalDbGate() {
// retryNonce 驱动失败后的有限重试重跑。
}, [dataOwnerId, retryNonce]);
+ useEffect(() => {
+ if (!dataOwnerId || decision.phase === 'checking') {
+ reportLocalDbGate('pending');
+ } else if (decision.phase === 'fatal') {
+ reportLocalDbGate('fatal');
+ } else {
+ reportLocalDbGate('ready');
+ }
+ return () => {
+ reportLocalDbGate('pending');
+ };
+ }, [dataOwnerId, decision, reportLocalDbGate]);
+
if (!dataOwnerId || decision.phase === 'checking') {
- // 短暂检查窗口(通常 < 100ms);返回 null 即可,App 已有 splash 兜底视觉
+ // 主界面还不能画。视觉盖由 AppShellCover + Splash / 品牌层承接
+ // (DESIGN.md §10),这里返回 null 避免先露出空壳再盖上。
return null;
}
diff --git a/apps/desktop/src/renderer/components/splash/SplashScreen.tsx b/apps/desktop/src/renderer/components/splash/SplashScreen.tsx
index 83e29ecc65..006c0d3f12 100644
--- a/apps/desktop/src/renderer/components/splash/SplashScreen.tsx
+++ b/apps/desktop/src/renderer/components/splash/SplashScreen.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
@@ -8,6 +8,7 @@ import {
useSplash,
type SplashPhase,
} from '@/hooks/useSplash';
+import { useAppShellCover } from '@/contexts/AppShellCoverContext';
import { useEnvCheck } from '@/contexts/EnvCheckContext';
import { useLoginHandoff } from '@/contexts/LoginHandoffContext';
import { WindowControls } from '@/components/title-bar/WindowControls';
@@ -91,14 +92,23 @@ export function SplashScreen() {
const { t } = useTranslation();
const splash = useSplash();
const { step, totalSteps } = useEnvCheck();
+ const { coverHeld } = useAppShellCover();
const handoff = useLoginHandoff();
+ const [shellCoverFading, setShellCoverFading] = useState(false);
+ const prevCoverHeldRef = useRef(coverHeld);
const { width, height } = useViewportSize();
const { scale } = desktopScale(width, height);
// dev fixture 只改显示 phase(附录 A splash 行;PROD 恒 null)。
const fixture = readSplashPhaseFixture();
- const displayPhase: SplashPhase = fixture ? splashPhaseForFixture(fixture) : splash.phase;
const realPhase = splash.phase;
+ const holdAfterDone =
+ coverHeld && (realPhase === 'splash_done' || realPhase === 'splash_skipped');
+ const displayPhase: SplashPhase = fixture
+ ? splashPhaseForFixture(fixture)
+ : holdAfterDone || shellCoverFading
+ ? 'splash_passed'
+ : realPhase;
const {
isDownloading: realIsDownloading,
@@ -123,13 +133,27 @@ export function SplashScreen() {
prevResetRef.current = resetSignal;
});
+ const splashLifecycleActive =
+ realPhase !== 'fading_out' &&
+ realPhase !== 'splash_done' &&
+ realPhase !== 'splash_skipped';
+
+ useEffect(() => {
+ if (prevCoverHeldRef.current && !coverHeld && (realPhase === 'splash_done' || realPhase === 'splash_skipped')) {
+ setShellCoverFading(true);
+ const timer = window.setTimeout(() => setShellCoverFading(false), 500);
+ prevCoverHeldRef.current = coverHeld;
+ return () => window.clearTimeout(timer);
+ }
+ if (holdAfterDone) setShellCoverFading(false);
+ prevCoverHeldRef.current = coverHeld;
+ }, [coverHeld, holdAfterDone, realPhase]);
+
+ const shellCoverVisible = holdAfterDone || shellCoverFading;
+
useEffect(() => {
const root = document.documentElement;
- if (
- realPhase !== 'fading_out' &&
- realPhase !== 'splash_done' &&
- realPhase !== 'splash_skipped'
- ) {
+ if (splashLifecycleActive || shellCoverVisible) {
root.setAttribute('data-splash-active', '1');
} else {
root.removeAttribute('data-splash-active');
@@ -137,7 +161,7 @@ export function SplashScreen() {
return () => {
root.removeAttribute('data-splash-active');
};
- }, [realPhase]);
+ }, [shellCoverVisible, splashLifecycleActive]);
// handoff 推进锚之一:Splash 开始退场(fading_out/done/skipped)即上报。
const splashExitReportedRef = useRef(false);
@@ -155,7 +179,9 @@ export function SplashScreen() {
// dev fixture 激活时冻结停留:真实生命周期跑完也不退场,供状态遍历/视觉走查
// (readSplashPhaseFixture 在 PROD 恒 null,本分支不可达)。
- if (!fixture && (realPhase === 'splash_done' || realPhase === 'splash_skipped')) return null;
+ if (!fixture && (realPhase === 'splash_done' || realPhase === 'splash_skipped') && !shellCoverVisible) {
+ return null;
+ }
const isMac = window.electronAPI?.platform === 'darwin';
@@ -194,7 +220,9 @@ export function SplashScreen() {
<div
className={cn(
'fixed inset-0 z-[9999] overflow-hidden',
- realPhase === 'fading_out' && !fixture ? 'opacity-0' : 'opacity-100',
+ (realPhase === 'fading_out' || shellCoverFading) && !fixture
+ ? 'opacity-0'
+ : 'opacity-100',
)}
style={
{
diff --git a/apps/desktop/src/renderer/components/splash/__tests__/SplashScreen.test.tsx b/apps/desktop/src/renderer/components/splash/__tests__/SplashScreen.test.tsx
index 0ecff95e33..c745b3b94d 100644
--- a/apps/desktop/src/renderer/components/splash/__tests__/SplashScreen.test.tsx
+++ b/apps/desktop/src/renderer/components/splash/__tests__/SplashScreen.test.tsx
@@ -43,6 +43,7 @@ const mocks = vi.hoisted(() => ({
skipSplash: vi.fn(),
},
env: { step: undefined as 1 | 2 | undefined, totalSteps: undefined as 2 | undefined },
+ coverHeld: false,
}));
vi.mock('react-i18next', () => ({
@@ -74,6 +75,10 @@ vi.mock('@/contexts/EnvCheckContext', () => ({
useEnvCheck: () => ({ step: mocks.env.step, totalSteps: mocks.env.totalSteps }),
}));
+vi.mock('@/contexts/AppShellCoverContext', () => ({
+ useAppShellCover: () => ({ coverHeld: mocks.coverHeld, reportLocalDbGate: () => {} }),
+}));
+
vi.mock('@/components/title-bar/WindowControls', () => ({
WindowControls: () => <div data-testid="window-controls" />,
}));
@@ -126,6 +131,7 @@ beforeEach(() => {
mocks.splash.downloadProgress = 0;
mocks.splash.downloadInfo = { progress: 0 };
mocks.splash.resetSignal = 0;
+ mocks.coverHeld = false;
setPhase('splash_checking');
document.documentElement.removeAttribute('data-splash-active');
(window as unknown as { electronAPI: { platform: string } }).electronAPI = {
@@ -366,4 +372,13 @@ describe('SplashScreen wave4 统一面板', () => {
view.rerender(<SplashScreen />);
expect(view.container.firstElementChild).toBeNull();
});
+
+ it('LocalDbGate 未就绪时 splash_done 仍保持加载面板(登录后不得露白底)', () => {
+ mocks.coverHeld = true;
+ renderSplash('splash_done');
+ expect(screen.getByTestId('splash-panel')).toBeTruthy();
+ expectSpinner();
+ expect(screen.getByText('splash.tips.waking')).toBeTruthy();
+ expect(document.documentElement.getAttribute('data-splash-active')).toBe('1');
+ });
});
diff --git a/apps/desktop/src/renderer/contexts/AppShellCoverContext.tsx b/apps/desktop/src/renderer/contexts/AppShellCoverContext.tsx
new file mode 100644
index 0000000000..2c1de9bc72
--- /dev/null
+++ b/apps/desktop/src/renderer/contexts/AppShellCoverContext.tsx
@@ -0,0 +1,65 @@
+import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react';
+
+import { useAuth } from '@/contexts/AuthContext';
+import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';
+import { isSecondaryWindow } from '@/lib/secondaryWindow';
+import { isSidebarWindow } from '@/lib/sidebarWindow';
+
+/**
+ * AppShellCover — 启动 / 登录后进入主界面之前的不透明加载盖。
+ *
+ * DESIGN.md §10: splash 必须完全遮蔽已挂载 UI,直到加载完成。LocalDbGate 以前
+ * 假定这段等待 <100ms、交给 splash 兜底;一旦 ensureReady 慢于 splash 3s 地板,
+ * 品牌层卸掉后 gate 仍返回 null,窗口就露出默认白底。
+ *
+ * 本 context 把「已可进应用但主功能区还不能画」收成一个 coverHeld:
+ * splash / 品牌层在 coverHeld 期间不得退场;副窗不走 splash,也不持盖。
+ */
+export type LocalDbGateStatus = 'pending' | 'ready' | 'fatal';
+
+export interface AppShellCoverContextValue {
+ /** 主界面还不能画,启动 / 登录加载盖必须留着。 */
+ coverHeld: boolean;
+ localDbGateStatus: LocalDbGateStatus;
+ reportLocalDbGate: (status: LocalDbGateStatus) => void;
+}
+
+const AppShellCoverContext = createContext<AppShellCoverContextValue | null>(null);
+
+const FALLBACK_VALUE: AppShellCoverContextValue = Object.freeze({
+ coverHeld: false,
+ localDbGateStatus: 'pending',
+ reportLocalDbGate: () => {},
+});
+
+function isDerivedWindow(): boolean {
+ return isSecondaryWindow() || isSidebarWindow() || isGhostPanelWindow();
+}
+
+export function AppShellCoverProvider({ children }: { children: ReactNode }) {
+ const { isInitializing, canEnterApp } = useAuth();
+ const [localDbGateStatus, setLocalDbGateStatus] = useState<LocalDbGateStatus>('pending');
+
+ const reportLocalDbGate = useCallback((status: LocalDbGateStatus) => {
+ setLocalDbGateStatus(status);
+ }, []);
+
+ const value = useMemo<AppShellCoverContextValue>(() => {
+ const coverHeld =
+ !isDerivedWindow() &&
+ !isInitializing &&
+ canEnterApp &&
+ localDbGateStatus === 'pending';
+ return {
+ coverHeld,
+ localDbGateStatus,
+ reportLocalDbGate,
+ };
+ }, [canEnterApp, isInitializing, localDbGateStatus, reportLocalDbGate]);
+
+ return <AppShellCoverContext.Provider value={value}>{children}</AppShellCoverContext.Provider>;
+}
+
+export function useAppShellCover(): AppShellCoverContextValue {
+ return useContext(AppShellCoverContext) ?? FALLBACK_VALUE;
+}
diff --git a/apps/desktop/src/renderer/contexts/LoginHandoffContext.tsx b/apps/desktop/src/renderer/contexts/LoginHandoffContext.tsx
index c5fbb4d0f5..f9a2121b5c 100644
--- a/apps/desktop/src/renderer/contexts/LoginHandoffContext.tsx
+++ b/apps/desktop/src/renderer/contexts/LoginHandoffContext.tsx
@@ -129,12 +129,15 @@ export function LoginHandoffProvider({
children,
authResolved,
authenticated,
+ coverHeld = false,
}: {
children: ReactNode;
/** auth 初始化完成(= !isInitializing;App.tsx 内层 host 从 useAuth 取,避免本模块传递性引入 AuthContext 重依赖)。 */
authResolved: boolean;
/** auth 初始化结果分支(仅在 authResolved 后读)。 */
authenticated: boolean;
+ /** 已登录但 LocalDbGate 还不能画主界面时由 App 壳下传,避免本模块 import AppShellCover/Auth。 */
+ coverHeld?: boolean;
}) {
const [phase, setPhase] = useState<LoginHandoffPhase>('boot');
const [branch, setBranch] = useState<LoginHandoffBranch>(null);
@@ -235,12 +238,12 @@ export function LoginHandoffProvider({
panelBottomReserve,
isPlaying,
// startup 期(含 boot/播放中/brand-exit)恒挂以维持不透明白底全盖;done 后
- // 一律跟随登录面板存在:authenticated 淡出完成且无面板 → 卸载;之后登出
- // 回 /login,LoginPage 上报面板挂载 → 品牌层重挂(phase 恒 done = 终态:
- // 品牌固定登录位、Slogan 直落可见、无过渡不重播——playedRef 语义不变)。
+ // 跟随登录面板或 AppShellCover:登录页要品牌底;已登录但 LocalDbGate 还在
+ // checking 时也要留着,避免登录成功卸面板后露出默认白底。登出回 /login
+ // 由 LoginPage 上报面板挂载重挂(phase 恒 done = 终态,不重播)。
// 判定刻意不绑 branch:绑死会让 authenticated 冷启动后登出的 /login 永久
// 丢失品牌层(登录页只剩悬空白面板,2026-07-20 对抗 review P1)。
- brandStageMounted: phase !== 'done' ? true : panelMounted,
+ brandStageMounted: phase !== 'done' ? true : panelMounted || coverHeld,
brandExiting: phase === 'brand-exit',
panelRevealed: phase === 'panel' || phase === 'slogan' || phase === 'done',
sloganRevealed: phase === 'slogan' || phase === 'done',
@@ -254,6 +257,7 @@ export function LoginHandoffProvider({
phase,
branch,
panelMounted,
+ coverHeld,
panelBottomReserve,
reportBrandAssetsReady,
reportSplashExited,
diff --git a/apps/desktop/src/renderer/contexts/__tests__/AppShellCoverContext.test.tsx b/apps/desktop/src/renderer/contexts/__tests__/AppShellCoverContext.test.tsx
new file mode 100644
index 0000000000..457d1443bf
--- /dev/null
+++ b/apps/desktop/src/renderer/contexts/__tests__/AppShellCoverContext.test.tsx
@@ -0,0 +1,94 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from '@testing-library/react';
+import { act } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const auth = vi.hoisted(() => ({
+ isInitializing: false,
+ canEnterApp: false,
+}));
+
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => auth,
+}));
+
+vi.mock('@/lib/secondaryWindow', () => ({
+ isSecondaryWindow: () => false,
+}));
+vi.mock('@/lib/sidebarWindow', () => ({
+ isSidebarWindow: () => false,
+}));
+vi.mock('@/lib/ghostPanelWindow', () => ({
+ isGhostPanelWindow: () => false,
+}));
+
+import { AppShellCoverProvider, useAppShellCover } from '../AppShellCoverContext';
+
+function Probe() {
+ const { coverHeld, localDbGateStatus } = useAppShellCover();
+ return (
+ <div>
+ <span data-testid="cover">{coverHeld ? 'held' : 'open'}</span>
+ <span data-testid="gate">{localDbGateStatus}</span>
+ </div>
+ );
+}
+
+function renderCover() {
+ return render(
+ <AppShellCoverProvider>
+ <Probe />
+ </AppShellCoverProvider>,
+ );
+}
+
+describe('AppShellCover', () => {
+ afterEach(() => {
+ cleanup();
+ auth.isInitializing = false;
+ auth.canEnterApp = false;
+ });
+
+ it('未登录不持盖,让 splash 退到登录页', () => {
+ auth.canEnterApp = false;
+ renderCover();
+ expect(screen.getByTestId('cover').textContent).toBe('open');
+ });
+
+ it('已可进应用且 LocalDbGate 仍 pending 时持盖', () => {
+ auth.canEnterApp = true;
+ renderCover();
+ expect(screen.getByTestId('cover').textContent).toBe('held');
+ expect(screen.getByTestId('gate').textContent).toBe('pending');
+ });
+
+ it('LocalDbGate ready 后放行', () => {
+ auth.canEnterApp = true;
+ function ReadyProbe() {
+ const { reportLocalDbGate, coverHeld } = useAppShellCover();
+ return (
+ <button type="button" onClick={() => reportLocalDbGate('ready')}>
+ {coverHeld ? 'held' : 'open'}
+ </button>
+ );
+ }
+ render(
+ <AppShellCoverProvider>
+ <ReadyProbe />
+ </AppShellCoverProvider>,
+ );
+ expect(screen.getByRole('button').textContent).toBe('held');
+ act(() => {
+ screen.getByRole('button').click();
+ });
+ expect(screen.getByRole('button').textContent).toBe('open');
+ });
+
+ it('auth 仍在初始化时不持盖,交给 splash 自己的 auth 锚', () => {
+ auth.isInitializing = true;
+ auth.canEnterApp = true;
+ renderCover();
+ expect(screen.getByTestId('cover').textContent).toBe('open');
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useSplashPhases.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useSplashPhases.test.tsx
index ef3dd59608..b75c6d11ac 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useSplashPhases.test.tsx
+++ b/apps/desktop/src/renderer/hooks/__tests__/useSplashPhases.test.tsx
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({
totalSteps: undefined as 2 | undefined,
checkEnvironment: vi.fn(async () => undefined),
authInitializing: false,
+ coverHeld: false,
updateErrorCode: undefined as string | undefined,
}));
@@ -45,6 +46,10 @@ vi.mock('@/hooks/useUpdateStatus', () => ({
useUpdateStatus: () => ({ errorCode: mocks.updateErrorCode }),
}));
+vi.mock('@/contexts/AppShellCoverContext', () => ({
+ useAppShellCover: () => ({ coverHeld: mocks.coverHeld, reportLocalDbGate: () => {} }),
+}));
+
import { useSplash } from '../useSplash';
describe('useSplash phase 表', () => {
@@ -54,6 +59,7 @@ describe('useSplash phase 表', () => {
mocks.step = undefined;
mocks.totalSteps = undefined;
mocks.authInitializing = false;
+ mocks.coverHeld = false;
mocks.updateErrorCode = undefined;
mocks.checkEnvironment.mockClear();
(
@@ -137,6 +143,16 @@ describe('useSplash phase 表', () => {
expect(result.current.phase).toBe('splash_passed');
});
+ it('LocalDbGate 仍在 checking 时 passed 不淡出(启动盖必须留到主界面可画)', () => {
+ mocks.envStatus = 'passed';
+ mocks.coverHeld = true;
+ const { result } = renderHook(() => useSplash());
+ act(() => {
+ vi.advanceTimersByTime(10_000);
+ });
+ expect(result.current.phase).toBe('splash_passed');
+ });
+
it('三失败弹窗 booleans 与 phase 一一对应且互斥', () => {
for (const [envStatus, key] of [
['manifest_failed', 'showManifestFailedDialog'],
diff --git a/apps/desktop/src/renderer/hooks/useSplash.ts b/apps/desktop/src/renderer/hooks/useSplash.ts
index 3435ee8ecc..37e95bd0a3 100644
--- a/apps/desktop/src/renderer/hooks/useSplash.ts
+++ b/apps/desktop/src/renderer/hooks/useSplash.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useAppShellCover } from '@/contexts/AppShellCoverContext';
import { useEnvCheck } from '@/contexts/EnvCheckContext';
import { useAuth } from '@/contexts/AuthContext';
import { useUpdateStatus } from '@/hooks/useUpdateStatus';
@@ -98,6 +99,7 @@ export function useSplash() {
checkEnvironment,
} = useEnvCheck();
const { isInitializing: authInitializing } = useAuth();
+ const { coverHeld } = useAppShellCover();
const { errorCode: updateErrorCode } = useUpdateStatus();
const [phase, setPhase] = useState<SplashPhase>('init');
@@ -158,11 +160,13 @@ export function useSplash() {
}, [updateErrorCode, phase]);
// ── Effect 3: fade-out trigger ──
+ // coverHeld:已登录但 LocalDbGate 还不能画主界面。splash 必须继续盖住
+ // (DESIGN.md §10),否则 3s 地板一过会露出默认白底。
useEffect(() => {
- if (phase === 'splash_passed' && minTimeElapsed && !authInitializing) {
+ if (phase === 'splash_passed' && minTimeElapsed && !authInitializing && !coverHeld) {
setPhase('fading_out');
}
- }, [phase, minTimeElapsed, authInitializing]);
+ }, [phase, minTimeElapsed, authInitializing, coverHeld]);
// ── Effect 4: fading_out fallback ──
useEffect(() => {