fix(startup): reduce initial loading and unblock app restoration

This commit is contained in:
t8y2 committed 2026-09-25 09:03:15 +08:00
1 parent 55c07f5852
commit 48d66d04d0
23 files changed
+745 -123

No files matched your search

@@ -0,0 +1,34 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from "vitest";
import { checkStartupAuthentication } from "@/lib/startup/startupAuthentication";
afterEach(() => vi.unstubAllGlobals());
describe("startup authentication", () => {
it("preserves authenticated, disabled-auth and setup-required states", async () => {
for (const state of [
{ required: true, authenticated: true, setup_required: false },
{ required: false, authenticated: false, setup_required: false },
{ required: true, authenticated: false, setup_required: true },
]) {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => state });
vi.stubGlobal("fetch", fetchMock);
expect(await checkStartupAuthentication()).toEqual(state);
expect(fetchMock).toHaveBeenCalledWith("/api/auth/check", expect.objectContaining({ credentials: "same-origin" }));
}
});
it.each([null, [], "invalid", {}, { required: "false", authenticated: true }, { required: false, authenticated: "true" }])("fails closed for malformed authentication data: %j", async (state) => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => state }));
await expect(checkStartupAuthentication()).rejects.toThrow("AUTH_CHECK_FAILED");
});
it("fails closed on unsuccessful responses and forwards cancellation", async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: false });
vi.stubGlobal("fetch", fetchMock);
const controller = new AbortController();
await expect(checkStartupAuthentication(controller.signal)).rejects.toThrow("AUTH_CHECK_FAILED");
expect(fetchMock.mock.calls[0]?.[1].signal).toBe(controller.signal);
});
});
@@ -0,0 +1,23 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { markStartupPhase } from "@/lib/startup/startupTiming";
afterEach(() => vi.unstubAllGlobals());
describe("startup phase marks", () => {
it("records each phase once without confusing gate mount with app readiness", () => {
const entries = new Set<string>();
const mark = vi.fn((name: string) => entries.add(name));
vi.stubGlobal("performance", { mark, getEntriesByName: (name: string) => (entries.has(name) ? [{}] : []) });
markStartupPhase("gate-mounted");
markStartupPhase("gate-mounted");
expect(mark).toHaveBeenCalledTimes(1);
expect(entries.has("dbx:startup:app-mounted")).toBe(false);
markStartupPhase("app-mounted");
expect(mark).toHaveBeenCalledTimes(2);
});
it("does not block startup when performance marks are unavailable", () => {
vi.stubGlobal("performance", {});
expect(() => markStartupPhase("bootstrap")).not.toThrow();
});
});
+1 -5
View File
@@ -27,11 +27,7 @@ interface InitializeOpenTabsOptions {
}
export async function initializeOpenTabs({ initializeOptionalState, restoreOpenTabs, onOptionalStateError }: InitializeOpenTabsOptions): Promise<void> {
try {
await initializeOptionalState();
} catch (error) {
onOptionalStateError(error);
}
void Promise.resolve().then(initializeOptionalState).catch(onOptionalStateError);
await restoreOpenTabs();
}
@@ -0,0 +1,48 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
settingsImported: vi.fn(),
migrationStatus: vi.fn(),
listInstalledAgents: vi.fn(),
installAgent: vi.fn(),
upgradeAllAgents: vi.fn(),
reinstallJre: vi.fn(),
}));
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => true }));
vi.mock("@/lib/backend/tauri", () => mocks);
vi.mock("@/lib/backend/debugLog", () => ({ appendDebugLog: vi.fn() }));
const settings = { editorSettings: { updateDownloadSource: "github" } };
beforeEach(() => {
vi.resetModules();
vi.resetAllMocks();
settings.editorSettings.updateDownloadSource = "github";
vi.doMock("@/stores/settingsStore", () => {
mocks.settingsImported();
return { useSettingsStore: () => settings };
});
});
describe("startup API dependency boundary", () => {
it("does not import the business settings store for migration preflight", async () => {
mocks.migrationStatus.mockResolvedValue({ state: "not_required" });
const api = await import("../api");
await expect(api.migrationStatus()).resolves.toEqual({ state: "not_required" });
expect(mocks.settingsImported).not.toHaveBeenCalled();
});
it("continues using the current configured source for agent operations", async () => {
const api = await import("../api");
await api.listInstalledAgents();
expect(mocks.listInstalledAgents).toHaveBeenCalledWith("github");
settings.editorSettings.updateDownloadSource = "cloudflare";
await api.installAgent("mysql", "install-1");
await api.upgradeAllAgents("upgrade-1");
await api.reinstallJre("java-21", "jre-1");
expect(mocks.installAgent).toHaveBeenCalledWith("mysql", "cloudflare", "install-1");
expect(mocks.upgradeAllAgents).toHaveBeenCalledWith("cloudflare", "upgrade-1");
expect(mocks.reinstallJre).toHaveBeenCalledWith("java-21", "cloudflare", "jre-1");
expect(mocks.settingsImported).toHaveBeenCalledTimes(1);
});
});
+4 -1
View File
@@ -1,7 +1,6 @@
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import type * as TauriModule from "@/lib/backend/tauri";
import { appendDebugLog } from "@/lib/backend/debugLog";
import { useSettingsStore } from "@/stores/settingsStore";
import type { AiConfigItem } from "@/types/ai";
// ---------------------------------------------------------------------------
@@ -135,6 +134,7 @@ export const uninstallJdbcPlugin = forward("uninstallJdbcPlugin");
export const listInstalledAgentsLocal = forward("listInstalledAgentsLocal");
export async function listInstalledAgents() {
const backend = await getBackend();
const { useSettingsStore } = await import("@/stores/settingsStore");
return backend.listInstalledAgents(useSettingsStore().editorSettings.updateDownloadSource);
}
export const isAgentInstalled = forward("isAgentInstalled");
@@ -145,10 +145,12 @@ export const stopDriverRuntime = forward("stopDriverRuntime");
export const restartDriverRuntime = forward("restartDriverRuntime");
export async function installAgent(dbType: string, operationId?: string) {
const backend = await getBackend();
const { useSettingsStore } = await import("@/stores/settingsStore");
return backend.installAgent(dbType, useSettingsStore().editorSettings.updateDownloadSource, operationId);
}
export async function upgradeAllAgents(operationId?: string) {
const backend = await getBackend();
const { useSettingsStore } = await import("@/stores/settingsStore");
return backend.upgradeAllAgents(useSettingsStore().editorSettings.updateDownloadSource, operationId);
}
export const cancelAgentInstall = forward("cancelAgentInstall");
@@ -168,6 +170,7 @@ export const importAgentDriver = forward("importAgentDriver");
export const importAgentJar = importAgentDriver;
export async function reinstallJre(jreKey?: string, operationId?: string) {
const backend = await getBackend();
const { useSettingsStore } = await import("@/stores/settingsStore");
return backend.reinstallJre(jreKey, useSettingsStore().editorSettings.updateDownloadSource, operationId);
}
export const uninstallJre = forward("uninstallJre");
@@ -0,0 +1,21 @@
import { apiUrl } from "@/lib/common/webPath";
export interface StartupAuthentication {
required: boolean;
authenticated: boolean;
setup_required: boolean;
}
export async function checkStartupAuthentication(signal?: AbortSignal): Promise<StartupAuthentication> {
const response = await fetch(apiUrl("/api/auth/check"), { credentials: "same-origin", signal });
if (!response.ok) throw new Error("AUTH_CHECK_FAILED");
const result: unknown = await response.json();
if (!result || typeof result !== "object" || !("required" in result) || !("authenticated" in result) || typeof result.required !== "boolean" || typeof result.authenticated !== "boolean") {
throw new Error("AUTH_CHECK_FAILED");
}
return {
required: result.required,
authenticated: result.authenticated,
setup_required: "setup_required" in result && result.setup_required === true,
};
}
@@ -0,0 +1,8 @@
export type StartupPhase = "bootstrap" | "gate-mounted" | "locale-ready" | "auth-ready" | "migration-ready" | "app-mounted" | "settings-ready" | "connections-ready" | "tabs-restored";
export function markStartupPhase(phase: StartupPhase): void {
const name = `dbx:startup:${phase}`;
const clock = globalThis.performance;
if (typeof clock?.mark !== "function" || typeof clock.getEntriesByName !== "function") return;
if (!clock.getEntriesByName(name, "mark").length) clock.mark(name);
}