diff --git a/docs/frontend-first-screen-performance.md b/docs/frontend-first-screen-performance.md
new file mode 100644
index 00000000..9d3e668c
--- /dev/null
+++ b/docs/frontend-first-screen-performance.md
@@ -0,0 +1,58 @@
+# Frontend first-screen loading
+
+This change moves non-critical modules out of the eager application entry and
+onto the chunks that actually render them. No page markup, interaction or
+styling rule changed; only when a resource is fetched.
+
+## What left the first screen
+
+| Resource | Before | After |
+| --------------------------------------------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------- |
+| `lucide-react` (`icons-vendor`) | Statically reachable from the entry through `Layout`, `Sidebar`, `PluginRouteGuard` and `UserBootstrapPanel`, so the entry preloaded the union of every icon used by all lazy pages. | The eager shell uses `src/components/shell-icons.tsx`; the icon vendor chunk is only requested when a route that imports lucide renders. |
+| `Sidebar` (navigation JSX, supplier/users helpers) | Bundled in the entry and parsed on every first paint. | Dynamic `import("./Sidebar")`, warmed only when `droboticflow.currentUserId` already exists. |
+| `src/styles/capture-workspace.css` | Imported by the global `src/index.css`, so every page downloaded the annotation workspace layout rules. | Imported by `CaptureAnnotationWorkbench`, emitted with the annotation route CSS. |
+| `WorkforceStatisticsPanel` | Bundled in the lazy Dashboard chunk even though it only renders in the collapsed legacy overview. | Lazy import inside a local `Suspense` boundary. |
+
+The eager shell now contains only React, React DOM, React Router, the context
+providers, the API client, `Layout`, the plugin guard and the login panel.
+
+## Measuring FCP/LCP
+
+Build once per revision and serve `dist/` (the Go SPA handler or any static
+server that also answers `/api/*` for the auth check):
+
+```bash
+npm run build:web
+```
+
+Capture both metrics in a Playwright page with a fresh browser context:
+
+```js
+await page.addInitScript(() => {
+ window.__vitals = {};
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) window.__vitals.fcp = entry.startTime;
+ }).observe({ type: "paint", buffered: true });
+ new PerformanceObserver((list) => {
+ const entries = list.getEntries();
+ window.__vitals.lcp = entries[entries.length - 1].startTime;
+ }).observe({ type: "largest-contentful-paint", buffered: true });
+});
+await page.goto(origin, { waitUntil: "networkidle" });
+const vitals = await page.evaluate(() => window.__vitals);
+```
+
+Run the same script against the base commit and this branch with the same
+network/CPU throttling and the same auth fixture. The first screen for an
+unauthenticated session must not request `icons-vendor`, the `Sidebar` chunk or
+the annotation workspace stylesheet. For a returning session the `Sidebar`
+chunk is warmed as soon as the shell paints, concurrently with `/api/auth/me`,
+instead of after the route starts rendering.
+
+## Verification commands
+
+```bash
+npm run lint:web
+npm run test:frontend:gate
+npm run build:web
+```
diff --git a/src/components/CaptureAnnotationWorkbench.tsx b/src/components/CaptureAnnotationWorkbench.tsx
index 642a65df..a84181e6 100644
--- a/src/components/CaptureAnnotationWorkbench.tsx
+++ b/src/components/CaptureAnnotationWorkbench.tsx
@@ -1,4 +1,8 @@
import type { AnnotationTimelineFailure } from "../lib/annotation-source-validation";
+// Workbench-only layout rules. Loading them with this component (instead of
+// the global entry stylesheet) keeps the annotation workspace CSS off the
+// application's first screen.
+import "../styles/capture-workspace.css";
import {
createSliceEditSession,
freezeSliceEditSession,
diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx
index c32c29e8..f79d2c36 100644
--- a/src/components/Layout.tsx
+++ b/src/components/Layout.tsx
@@ -1,11 +1,10 @@
-import React, { useEffect, useRef, useState } from "react";
+import React, { Suspense, lazy, useEffect, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
import {
AnnotationWorkspaceLayoutContext,
useAnnotationLayoutPreference,
} from "../context/AnnotationWorkspaceLayoutContext";
-import { Loader2, Moon, Sun } from "lucide-react";
-import { Sidebar } from "./Sidebar";
+import { Loader2, Moon, Sun } from "./shell-icons";
import { UserBootstrapPanel } from "./UserBootstrapPanel";
import { useUser } from "../context/UserContext";
import { getActionErrorMessage } from "../lib/action-errors.js";
@@ -17,6 +16,26 @@ interface LayoutProps {
children: React.ReactNode;
}
+// The sidebar is only mounted after the current user resolves, but it is not
+// needed to paint the shell. Keeping it in its own chunk removes its icon set
+// and API helpers from the entry bundle; a returning user starts the request
+// as soon as the shell paints so the navigation is ready when auth completes.
+const Sidebar = lazy(() => import("./Sidebar").then((module) => ({ default: module.Sidebar })));
+
+const CURRENT_USER_STORAGE_KEY = "droboticflow.currentUserId";
+
+function SidebarFallback({ collapsed }: { collapsed: boolean }) {
+ return (
+
+ );
+}
+
type HealthState = {
status: "loading" | "online" | "offline";
service?: string;
@@ -70,6 +89,18 @@ export function Layout({ children }: LayoutProps) {
return () => mobileViewport.removeEventListener("change", collapseForMobile);
}, []);
+ useEffect(() => {
+ // Only warm modules for sessions that were already authenticated; a first
+ // visit to the login screen must not download app-only chunks.
+ if (!window.localStorage.getItem(CURRENT_USER_STORAGE_KEY)) {
+ return;
+ }
+ const timer = window.setTimeout(() => {
+ void import("./Sidebar");
+ }, 0);
+ return () => window.clearTimeout(timer);
+ }, []);
+
useEffect(() => {
let cancelled = false;
@@ -192,7 +223,9 @@ export function Layout({ children }: LayoutProps) {
className="flex h-screen bg-[color:var(--app-canvas)] font-sans text-[color:var(--app-text)]"
>
{currentUser && !isSuperAdmin && !focusedWorkPage ? (
- setIsCollapsed(!isCollapsed)} />
+ }>
+ setIsCollapsed(!isCollapsed)} />
+
) : null}
+ {children}
+
+ );
+}
+
+export function Loader2({ className }: ShellIconProps) {
+ return (
+
+
+
+ );
+}
+
+export function Moon({ className }: ShellIconProps) {
+ return (
+
+
+
+ );
+}
+
+export function Sun({ className }: ShellIconProps) {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
+
+export function Blocks({ className }: ShellIconProps) {
+ return (
+
+
+
+
+ );
+}
+
+export function AlertCircle({ className }: ShellIconProps) {
+ return (
+
+
+
+
+
+ );
+}
+
+export function Lock({ className }: ShellIconProps) {
+ return (
+
+
+
+
+ );
+}
+
+export function LogIn({ className }: ShellIconProps) {
+ return (
+
+
+
+
+
+ );
+}
+
+export function Phone({ className }: ShellIconProps) {
+ return (
+
+
+
+ );
+}
+
+export function Shield({ className }: ShellIconProps) {
+ return (
+
+
+
+ );
+}
+
+export function User({ className }: ShellIconProps) {
+ return (
+
+
+
+
+ );
+}
diff --git a/src/index.css b/src/index.css
index de5efbd1..5a190866 100644
--- a/src/index.css
+++ b/src/index.css
@@ -1,5 +1,4 @@
@import "tailwindcss";
-@import "./styles/capture-workspace.css";
/* Keep the reviewer controls usable inside a narrow workbench, not merely a
wide viewport. Never hide overflowing buttons behind the page scroller. */
diff --git a/src/pages/AnnotationOperations.tsx b/src/pages/AnnotationOperations.tsx
index 42f85b54..a434a59b 100644
--- a/src/pages/AnnotationOperations.tsx
+++ b/src/pages/AnnotationOperations.tsx
@@ -1,5 +1,8 @@
import { annotationTimelineFailure } from "../lib/annotation-source-validation.js";
import type { AnnotationTimelineFailure } from "../lib/annotation-source-validation";
+// Keep the workbench rules ahead of the review framing rules, matching the
+// order they had when both were pulled in by the global entry stylesheet.
+import "../styles/capture-workspace.css";
import "../styles/review-workspace.css";
import { AcceptanceMisreports } from "../components/AcceptanceMisreports";
import { useReviewTrace, ReviewTracePanel, ReviewListTrace } from "../components/ReviewTrace";
diff --git a/src/pages/Dashboard.tsx b/src/pages/Dashboard.tsx
index 973287fd..212b16c4 100644
--- a/src/pages/Dashboard.tsx
+++ b/src/pages/Dashboard.tsx
@@ -1,6 +1,6 @@
import { ProductionQualityDashboard } from "../components/ProductionQualityDashboard";
import { userErrorMessage } from "../lib/user-error-message.js";
-import { WorkforceStatisticsPanel, type WorkforceFilters } from "../components/WorkforceStatisticsPanel";
+import type { WorkforceFilters } from "../components/WorkforceStatisticsPanel";
import { defaultProductionFilters, type ProductionFilters } from "../lib/production-filters";
import React, { Suspense, lazy, useCallback, useEffect, useState } from "react";
import {
@@ -52,25 +52,38 @@ const ProductionStatistics = lazy(() =>
import("../components/ProductionStatistics").then((module) => ({ default: module.ProductionStatistics })),
);
+// The workforce report lives in the collapsed legacy overview (and the
+// non-admin summary). Keep its table/modal code out of the dashboard chunk
+// that must load for the first screen.
+const WorkforceStatisticsPanel = lazy(() =>
+ import("../components/WorkforceStatisticsPanel").then((module) => ({ default: module.WorkforceStatisticsPanel })),
+);
+
function ProductionStatisticsFallback() {
return 正在加载生产总览...
;
}
+function WorkforceStatisticsFallback() {
+ return 正在加载工作量统计...
;
+}
+
function WorkforceSummaryPanel({ summary, filters }: { summary: DashboardSummary | null; filters: WorkforceFilters }) {
const { currentUser } = useUser();
const reviewer = currentUser?.role === "quality_reviewer" || currentUser?.role === "acceptance_reviewer";
return (
-
+ }>
+
+
);
}
diff --git a/tests/frontend/first-screen-loading.test.mjs b/tests/frontend/first-screen-loading.test.mjs
new file mode 100644
index 00000000..e2b8b3d7
--- /dev/null
+++ b/tests/frontend/first-screen-loading.test.mjs
@@ -0,0 +1,39 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+const source = (path) => readFile(new URL(`../../${path}`, import.meta.url), "utf8");
+
+test("the eager application shell does not import the shared lucide vendor chunk", async () => {
+ const files = await Promise.all([
+ source("src/components/Layout.tsx"),
+ source("src/components/PluginRouteGuard.tsx"),
+ source("src/components/UserBootstrapPanel.tsx"),
+ ]);
+ for (const file of files) {
+ assert.doesNotMatch(file, /from "lucide-react"/);
+ assert.match(file, /from "\.\/shell-icons"/);
+ }
+});
+
+test("the sidebar is code-split out of the shell and only warmed for returning sessions", async () => {
+ const layout = await source("src/components/Layout.tsx");
+ assert.match(layout, /const Sidebar = lazy\(\(\) => import\("\.\/Sidebar"\)/);
+ assert.match(layout, /currentUserId/);
+ assert.match(layout, /import\("\.\/Sidebar"\)/);
+});
+
+test("annotation workspace CSS loads with the annotation route, not the entry stylesheet", async () => {
+ const [indexCss, workbench] = await Promise.all([
+ source("src/index.css"),
+ source("src/components/CaptureAnnotationWorkbench.tsx"),
+ ]);
+ assert.doesNotMatch(indexCss, /styles\/capture-workspace\.css/);
+ assert.match(workbench, /styles\/capture-workspace\.css/);
+});
+
+test("below-the-fold dashboard panels are lazily imported", async () => {
+ const dashboard = await source("src/pages/Dashboard.tsx");
+ assert.match(dashboard, /const WorkforceStatisticsPanel = lazy\(/);
+ assert.match(dashboard, /const ProductionStatistics = lazy\(/);
+});
diff --git a/tests/frontend/review-seek-harness.mjs b/tests/frontend/review-seek-harness.mjs
index dec2fb8d..3e65a9b7 100644
--- a/tests/frontend/review-seek-harness.mjs
+++ b/tests/frontend/review-seek-harness.mjs
@@ -153,6 +153,9 @@ export function reviewSeekHarness(overrides = {}) {
if (name === "react") return hooks;
if (name === "react/jsx-runtime") return { jsx: element, jsxs: element, Fragment: "fragment" };
if (name === "lucide-react") return new Proxy({}, { get: (_, key) => key });
+ // CSS side-effect imports carry no runtime state; this seam only exercises
+ // component logic, and the vm loader cannot execute stylesheets.
+ if (name.endsWith(".css")) return {};
if (name.endsWith("/movi-player")) return { moviRuntimeMode: () => "native" };
if (name === "./MoviVideo") return { moviElementReady: () => false };
if (name.startsWith("./") && path.basename(file) === "CaptureAnnotationWorkbench.tsx")