Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

perf(shell): defer optional surfaces and bound cold-load bundles

Rahman1526439ddf7a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b30bf8fc..7cde3123 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -66,12 +66,18 @@ jobs:
- name: Production build
run: bun run build
+ - name: Bundle budget
+ run: bun run bundle:check
+
- name: Install browser
run: node_modules/.bin/playwright install --with-deps chromium
- name: Required browser journeys
run: bun run e2e:release
+ - name: Deferred shell performance journeys
+ run: node scripts/e2e/bundle-performance.mjs
+
dependency-watch:
name: Scheduled dependency audit
if: github.event_name == 'schedule'
diff --git a/app/globals.css b/app/globals.css
index 71403329..0d56bebb 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -1,6 +1,5 @@
@import "tailwindcss";
@import "tw-animate-css";
-@import "@xyflow/react/dist/style.css";
/* Dark is driven by [data-theme=dark] (os-rr convention), so shadcn `dark:`
utilities key off the same attribute. */
diff --git a/app/layout.tsx b/app/layout.tsx
index af311ba2..6559d087 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -1,7 +1,7 @@
import type { Metadata, Viewport } from "next";
import { headers } from "next/headers";
import { GeistSans } from "geist/font/sans";
-import { GeistMono } from "geist/font/mono";
+import { GeistMono } from "./mono-font";
import { RegisterSW } from "./register-sw";
import { InstallPrompt } from "./install-prompt";
import "./globals.css";
diff --git a/app/mono-font.test.ts b/app/mono-font.test.ts
new file mode 100644
index 00000000..e7b4bcf4
--- /dev/null
+++ b/app/mono-font.test.ts
@@ -0,0 +1,11 @@
+import { readFileSync, existsSync } from "node:fs";
+import { expect, it } from "vitest";
+it("keeps the same local mono typeface and root variable without global preloading", () => {
+ const source = readFileSync("app/mono-font.ts", "utf8");
+ expect(source).toContain("preload: false");
+ expect(source).toContain('variable: "--font-geist-mono"');
+ expect(source).toContain('display: "swap"');
+ expect(source).not.toContain("next/font/google");
+ expect(existsSync("node_modules/geist/dist/fonts/geist-mono/GeistMono-Variable.woff2")).toBe(true);
+ expect(readFileSync("app/layout.tsx", "utf8")).toContain("GeistMono.variable");
+});
diff --git a/app/mono-font.ts b/app/mono-font.ts
new file mode 100644
index 00000000..0b05e881
--- /dev/null
+++ b/app/mono-font.ts
@@ -0,0 +1,14 @@
+import localFont from "next/font/local";
+
+// Same locally installed font and CSS variable, but only fetch when text uses it.
+// Do not preload 71 KB of monospace on login/install or a sans-only shell.
+export const GeistMono = localFont({
+ src: "../node_modules/geist/dist/fonts/geist-mono/GeistMono-Variable.woff2",
+ variable: "--font-geist-mono",
+ weight: "100 900",
+ display: "swap",
+ preload: false,
+ adjustFontFallback: false,
+ fallback: ["ui-monospace", "SFMono-Regular", "Roboto Mono", "Menlo", "Monaco",
+ "Liberation Mono", "DejaVu Sans Mono", "Courier New", "monospace"],
+});
diff --git a/components/shared/graph-canvas.tsx b/components/shared/graph-canvas.tsx
index 3ba86b87..8829eb8d 100644
--- a/components/shared/graph-canvas.tsx
+++ b/components/shared/graph-canvas.tsx
@@ -1,6 +1,9 @@
"use client";
-import { useCallback, useEffect, useId, useState } from "react";
+// Owned by the lazy graph boundary, not every page in the cockpit.
+import "@xyflow/react/dist/style.css";
+
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import {
Background,
BackgroundVariant,
@@ -11,6 +14,8 @@ import {
ReactFlowProvider,
SelectionMode,
useReactFlow,
+ useNodesInitialized,
+ useStore,
type Edge,
type MiniMapProps,
type Node,
@@ -18,7 +23,7 @@ import {
} from "@xyflow/react";
import { Hand, LayoutGrid, Maximize2, MousePointer2, ZoomIn, ZoomOut } from "lucide-react";
import { cn } from "@/lib/utils";
-import { useContainer } from "@/features/appshell";
+import { compactGraphViewport } from "./graph-fit";
export type GraphCanvasMode = "select" | "pan";
type MiniMapNodeColor = MiniMapProps["nodeColor"];
@@ -50,19 +55,33 @@ function GraphCanvasInner<NodeType extends Node = Node, EdgeType extends Edge =
const [mode, setMode] = useState<GraphCanvasMode>(initialMode);
const instanceId = useId().replace(/[^a-zA-Z0-9_-]/g, "");
const flowId = props.id || `mso-graph-${instanceId}`;
- const [containerRef, pane] = useContainer<HTMLDivElement>();
- const compact = pane === "xs" || pane === "sm";
+ // Use the graph's measured viewport, including height: landscape panes can be
+ // wide but far too short to fit a complete graph at a readable scale.
+ const width = useStore((state) => state.width);
+ const height = useStore((state) => state.height);
+ const initialized = useNodesInitialized();
+ const compact = compactGraphViewport(width, height);
+ const fitted = useRef(false);
+ const [fitRevision, requestFit] = useState(0);
+ // Node selection/movement may recreate the array without changing the focus set.
+ const focusKey = JSON.stringify(compactFitNodeIds ?? []);
+ const focusNodes = useMemo(() => (JSON.parse(focusKey) as string[]).map((id) => ({ id })), [focusKey]);
const { fitView, zoomIn, zoomOut } = useReactFlow<NodeType, EdgeType>();
const fit = useCallback(() => void fitView({ padding: fitPadding, duration: 220, ...fitViewOptions }), [fitPadding, fitView, fitViewOptions]);
- const fitResponsive = useCallback(() => {
- const nodes = compact && compactFitNodeIds?.length ? compactFitNodeIds.map((id) => ({ id })) : undefined;
- void fitView({ padding: compact ? Math.min(fitPadding, 0.14) : fitPadding, duration: 220, ...fitViewOptions, ...(nodes ? { nodes, maxZoom: compactFitMaxZoom } : {}) });
- }, [compact, compactFitMaxZoom, compactFitNodeIds, fitPadding, fitView, fitViewOptions]);
+ const fitResponsive = useCallback((duration: number) => {
+ const nodes = compact && focusNodes.length ? focusNodes : undefined;
+ void fitView({ padding: compact ? Math.min(fitPadding, 0.14) : fitPadding, duration, ...fitViewOptions, ...(nodes ? { nodes, maxZoom: compactFitMaxZoom } : {}) });
+ }, [compact, compactFitMaxZoom, focusNodes, fitPadding, fitView, fitViewOptions]);
useEffect(() => {
- const raf = requestAnimationFrame(() => requestAnimationFrame(fitResponsive));
- return () => cancelAnimationFrame(raf);
- }, [fitResponsive, pane]);
- const tidy = useCallback(() => { onTidy?.(); requestAnimationFrame(() => requestAnimationFrame(fitResponsive)); }, [fitResponsive, onTidy]);
+ if (!initialized || width <= 0 || height <= 0) return;
+ // A single owner fits only after lazy CSS and node measurement are ready.
+ // Cancel whichever frame is pending on resize/unmount, including the inner one.
+ let frame = requestAnimationFrame(() => {
+ frame = requestAnimationFrame(() => { fitResponsive(fitted.current ? 220 : 0); fitted.current = true; });
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [initialized, width, height, fitResponsive, fitRevision]);
+ const tidy = useCallback(() => { onTidy?.(); requestFit((revision) => revision + 1); }, [onTidy]);
const keyboard = (event: React.KeyboardEvent<HTMLDivElement>) => {
onKeyDown?.(event); if (event.defaultPrevented) return;
const target = event.target as HTMLElement;
@@ -74,13 +93,12 @@ function GraphCanvasInner<NodeType extends Node = Node, EdgeType extends Edge =
if (key === "+" || key === "=") { event.preventDefault(); void zoomIn({ duration: 160 }); }
if (key === "-") { event.preventDefault(); void zoomOut({ duration: 160 }); }
};
- return <div ref={containerRef} className="h-full min-h-0 w-full min-w-0 outline-none" tabIndex={0} onKeyDown={keyboard}>
+ return <div className="h-full min-h-0 w-full min-w-0 outline-none" tabIndex={0} onKeyDown={keyboard}>
<ReactFlow<NodeType, EdgeType>
{...props}
id={flowId}
aria-label={ariaLabel}
className={cn("mso-graph-flow h-full w-full", className)}
- fitView fitViewOptions={{ padding: fitPadding, duration: 220, ...fitViewOptions }}
minZoom={props.minZoom ?? 0.18} maxZoom={props.maxZoom ?? 2.5}
selectionMode={SelectionMode.Partial} selectionOnDrag={mode === "select"}
panOnDrag={mode === "pan" ? true : [1, 2]} panOnScroll={mode === "select"}
diff --git a/components/shared/graph-fit.ts b/components/shared/graph-fit.ts
new file mode 100644
index 00000000..75a3bd5f
--- /dev/null
+++ b/components/shared/graph-fit.ts
@@ -0,0 +1,4 @@
+/** Width and height belong to the canvas, not the device or browser window. */
+export function compactGraphViewport(width: number, height: number): boolean {
+ return width > 0 && height > 0 && (width < 600 || height < 240);
+}
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 3e23a025..aa13f6da 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -70,6 +70,48 @@ claim that every feature is covered. Two-instance tests independently load origi
widget CSP and external app catalogs. The literal guard is supporting evidence,
not a substitute for runtime isolation tests.
+## Bundle boundaries and performance verification
+
+`bun run bundle:report` reads an existing production build; `bun run bundle:check`
+enforces `scripts/bundle-budget.json`. `scripts/verify-build.sh` runs the budget
+and `scripts/e2e/bundle-performance.mjs` on its isolated committed build; CI runs
+the same checks after its production build. The
+browser journey checks all five shells, absence of graph/editor/terminal/ONNX
+runtime chunks on cold startup, delayed first-open/close/reopen Search, eager
+clipboard capture, and retained Inspector tab state. It uses synthetic stores.
+
+The report deduplicates eager catch-all entry chunks plus the framework runtime.
+It lists `nomodule` polyfills separately: charging them to modern browsers would
+overstate first-load bytes. Gzip/Brotli values are compression estimates, not
+network timings or an LCP/INP benchmark. Actual selected-shell and feature-driven
+lazy downloads are checked separately in the browser. Font limits apply to
+preloaded files, not to fonts subsequently needed by visible monospace text.
+
+Keep app descriptors cheap. Organization retains its public `OrganizationView`
+through a lazy facade; its graph engine and shared canvas stylesheet must not be
+reachable eagerly from the shell manifest. Settings navigation/access checks stay
+eager, but section bodies load only after selection and their existing role gate.
+`DeferredSurface` uses the window host's effect/state loader rather than relying
+on a Suspense retry from an external-store update. Retain mounted presentation
+when local tab state or exit animations require it. Auto-lock, shortcut listeners,
+notifications and clipboard capture remain eager; only noncritical UI is deferred.
+
+Dock/Launcher keep Next link `prefetch={false}`. Their separate app-module warming
+waits 250 ms for hover/keyboard intent, cancels pending timers on leave/blur/close,
+checks online/visibility/Save-Data/slow-network state, and deduplicates in-flight
+loads. Expensive descriptors opt out with `prefetch: "never"`; explicit app opens
+still use the normal loader. No project-specific app-id blacklist lives in AppShell.
+
+Shared graph fitting waits for node measurements and uses both canvas width and
+height so short landscape windows keep their trigger readable. Only the responsive
+fit controller owns initial fitting; explicit Fit still shows the full graph.
+Geist Mono keeps its original local font, fallback stack and root CSS variable,
+with `preload: false`; no font CDN or external runtime dependency is introduced.
+
+Optional background-removal engines/models, model quality defaults, production
+artifact packaging and build-cache retention are unchanged. Do not delete WASM
+or enable site-wide cross-origin isolation just to make a size number smaller.
+
## Comparison governance
`docs/comparison-data.json` is the only hand-edited comparison source. It records criterion
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 3a9c5849..64ff7864 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,11 @@
+## 2026-09-17 — Isolated shell bundle and first-open performance improvements
+
+Reduced eager shell work without removing applications or changing authorization, persistence, native terminal sessions, service-worker recovery, or deployment behavior. Organization's public view now has a lazy facade (the descriptor stays cheap); ReactFlow CSS follows the shared graph canvas rather than the root stylesheet. Search, Inspector, mobile Alfa/Control Center and clipboard presentation load on demand through an effect/state boundary, while lock protection, capture, hotkeys and notifications remain active from startup. The Inspector keeps its selected tab across close/reopen. Settings section bodies are split behind the existing selection and Owner-role checks. App-module prefetch now requires 250 ms of intent, cancels pending requests on leave/blur/close, respects constrained connections, deduplicates loads, and lets expensive app descriptors opt out. The existing local Geist Mono stays available without global preloading.
+
+The exact production build at baseline `866ec61` and the optimized candidate, using the same lockfile and Next 16.3.4, measured eager modern-browser JS at 340,067 → 269,498 gzip bytes (20.8% reduction), shell-entry JS 208,982 → 138,413 (33.8%), CSS 31,158 → 28,887 (7.3%), and preloaded font files 141,020 → 69,652 raw bytes. These are build-manifest measurements, not a claimed page-speed percentage; legacy nomodule polyfills and optional lazy downloads are separate. Added fail-closed bundle limits, import-boundary/prefetch regression tests and a five-shell synthetic browser journey to both the existing isolated build gate and CI. Heavy background-removal assets, quality defaults and runtime/cache deployment layout are intentionally untouched in this phase.
+
+The mandatory Workflow landscape journey exposed an existing readability bug: the unchanged `866ec61` build also shrank a trigger to ~67 pixels in an 826 × 122 canvas. Shared graph fitting now considers canvas height as well as width, waits for measured nodes, cancels pending frames correctly and has a single initial-fit owner. Manual full-graph Fit and zoom remain available. The browser test retains its original size thresholds but samples settled geometry rather than transient animation frames.
+
## 2026-09-17 — Gateway core becomes deployment/provider/supervisor agnostic
Refactored the gateway reliability boundary without removing the existing Cloudflare lifecycle or process-ownership protections. The new read-only classifier separates local, public, provider and process health from ownership/supervisor state and reports `managed-running`, `external-running`, `degraded`, `recovering`, `stopped` or `unknown`. A configured public origin is healthy only when its structured MSO health identity matches the selected local runtime, including `buildSha` when present; this fixes the real case where a healthy externally supervised public route was previously displayed as stopped. Added `mso gateway status --json`, capability-based provider metadata, external duplicate-start protection, and provider-neutral non-mutating doctor diagnostics. Cloudflare remains the current managed/default adapter; external reverse proxies/tunnels are detected but never adopted, stopped or restarted. Existing PID/start-ticks/executable/argv/runtime-instance, atomic private state, update locks and recovery markers remain authoritative. No generic `gateway supervise` daemon was added because the current external-supervisor model already covers systemd/s6/container/Kubernetes/PaaS ownership without duplicating supervisor semantics. Added provider-neutral regression coverage and a dedicated `docs/GATEWAY.md` architecture/operations reference.
diff --git a/frontend/slices/appshell/components/app-launcher.tsx b/frontend/slices/appshell/components/app-launcher.tsx
index 08647c39..76c69ddc 100644
--- a/frontend/slices/appshell/components/app-launcher.tsx
+++ b/frontend/slices/appshell/components/app-launcher.tsx
@@ -1,6 +1,7 @@
"use client";
import Link from "next/link";
+import { useIntentPrefetch } from "../hooks/use-intent-prefetch";
import { useEffect, useRef, useState } from "react";
import { Search } from "lucide-react";
import { cn } from "@/lib/utils";
@@ -18,6 +19,7 @@ import { QuicklinkIcon } from "./quicklink-icon";
// overlay (8500) — overlays opened on top of Launchpad must win.
export function AppLauncher() {
const open = useLauncherOpen();
+ const prefetch = useIntentPrefetch(open);
const apps = useApps();
const { items: links, open: openLink } = useQuickLinks();
const [q, setQ] = useState("");
@@ -76,7 +78,10 @@ export function AppLauncher() {
key={app.id}
href={"/" + (app.slug ?? app.id)}
prefetch={false}
- onPointerEnter={() => void app.load?.().catch(() => {})}
+ onPointerEnter={(event) => { if (open) prefetch.schedule(app, event.pointerType); }}
+ onPointerLeave={prefetch.cancel}
+ onFocus={() => { if (open) prefetch.schedule(app, "keyboard"); }}
+ onBlur={prefetch.cancel}
onClick={(e) => {
if (e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey) {
e.preventDefault();
diff --git a/frontend/slices/appshell/components/dock-parts.tsx b/frontend/slices/appshell/components/dock-parts.tsx
index ceaea83d..e6fd2c06 100644
--- a/frontend/slices/appshell/components/dock-parts.tsx
+++ b/frontend/slices/appshell/components/dock-parts.tsx
@@ -5,6 +5,7 @@
BASE is the resting icon size the magnification math in dock.tsx shares. */
import { Button } from "@/components/ui/button";
import Link from "next/link";
+import { useIntentPrefetch } from "../hooks/use-intent-prefetch";
import { Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import { openWindow, focusApp, restoreWindow, closeWindow } from "../lib/store";
@@ -51,6 +52,7 @@ export function DockIcon({
slotRef: (el: HTMLDivElement | null) => void;
zoneRef: (el: HTMLDivElement | null) => void;
}) {
+ const prefetch = useIntentPrefetch();
const running = windows.length > 0;
const href = "/" + (app.slug ?? app.id);
const hasMenu = windows.length > 0 || !!app.multi;
@@ -109,7 +111,10 @@ export function DockIcon({
<Link
href={href}
prefetch={false}
- onPointerEnter={() => void app.load?.().catch(() => {})}
+ onPointerEnter={(event) => prefetch.schedule(app, event.pointerType)}
+ onPointerLeave={prefetch.cancel}
+ onFocus={() => prefetch.schedule(app, "keyboard")}
+ onBlur={prefetch.cancel}
onContextMenu={ctx.open}
onClick={(e) => {
if (e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey) {
diff --git a/frontend/slices/appshell/features/clipboard/components/clipboard-overlay.tsx b/frontend/slices/appshell/features/clipboard/components/clipboard-overlay.tsx
index 15395b3e..b5d4fcdf 100644
--- a/frontend/slices/appshell/features/clipboard/components/clipboard-overlay.tsx
+++ b/frontend/slices/appshell/features/clipboard/components/clipboard-overlay.tsx
@@ -1,22 +1,17 @@
"use client";
-import { useEffect, useState } from "react";
-import { Pin, Trash2, X } from "lucide-react";
-import { cn } from "@/lib/utils";
-import { Button } from "@/components/ui/button";
+import { useEffect } from "react";
import {
- clearClips,
- copyClip,
- removeClip,
setClipboardOpen,
startClipboardCapture,
toggleClipboard,
- togglePinClip,
useClipboardOpen,
- useClips,
} from "../../../lib/clipboard";
import { inEditable } from "../../../lib/use-focused-hotkey";
+import { DeferredSurface } from "../../../primitives/deferred-surface";
+const loadPanel = () => import("./clipboard-panel").then((module) => ({ default: module.ClipboardPanel }));
+
// ⌘⇧V clipboard history — pinned entries stick, click copies back to the
// system clipboard. Capture (document copy/cut) starts with this feature.
// The panel MOUNTS per open, so the search query starts fresh every time
@@ -40,75 +35,5 @@ export function ClipboardOverlay() {
return () => window.removeEventListener("keydown", onKey);
}, []);
- return open ? <ClipboardPanel /> : null;
-}
-
-function ClipboardPanel() {
- const clips = useClips();
- const [q, setQ] = useState("");
- const list = clips.filter((c) => c.text.toLowerCase().includes(q.toLowerCase()));
-
- return (
- <div className="absolute inset-0 z-[var(--z-clipboard)] flex items-start justify-center bg-black/20 pt-[16vh]" onClick={() => setClipboardOpen(false)}>
- <div className="glass flex max-h-[60vh] w-full max-w-lg flex-col overflow-hidden rounded-2xl border border-border shadow-2xl" onClick={(e) => e.stopPropagation()}>
- <header className="flex items-center gap-2 border-b border-border px-4 py-2.5">
- <span className="text-xs font-semibold text-muted-foreground">Clipboard history</span>
- {clips.length > 0 && (
- <Button type="button" variant="ghost" onClick={clearClips} className="ml-auto h-auto p-0 text-xs font-normal text-muted-foreground hover:bg-transparent hover:underline">
- Clear unpinned
- </Button>
- )}
- </header>
- <input
- autoFocus
- value={q}
- onChange={(e) => setQ(e.target.value)}
- placeholder="Search clips…"
- className="w-full bg-transparent px-4 py-2.5 text-sm outline-none placeholder:text-muted-foreground"
- />
- <ul className="min-h-0 flex-1 overflow-y-auto border-t border-border p-2">
- {list.length === 0 && (
- <li className="px-3 py-4 text-sm text-muted-foreground">
- {clips.length === 0 ? "Nothing copied yet — ⌘C anywhere in the OS lands here." : "No matches."}
- </li>
- )}
- {list.map((c) => (
- <li key={c.id} className="group flex items-center gap-1 rounded-lg px-1 hover:bg-primary/10">
- <Button
- type="button"
- variant="ghost"
- onClick={() => {
- copyClip(c.text);
- setClipboardOpen(false);
- }}
- className="h-auto min-w-0 flex-1 justify-start truncate p-2 text-left text-sm font-normal hover:bg-transparent"
- >
- {c.text}
- </Button>
- <Button
- type="button" variant="ghost" aria-label={c.pinned ? "Unpin" : "Pin"}
- onClick={() => togglePinClip(c.id)}
- className={cn("h-auto shrink-0 p-1 font-normal hover:bg-muted", c.pinned ? "text-primary" : "text-muted-foreground opacity-0 group-hover:opacity-100")}
- >
- <Pin className="size-3.5" />
- </Button>
- <Button
- type="button" variant="ghost" aria-label="Remove"
- onClick={() => removeClip(c.id)}
- className="h-auto shrink-0 p-1 font-normal text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100"
- >
- <Trash2 className="size-3.5" />
- </Button>
- </li>
- ))}
- </ul>
- <footer className="flex items-center border-t border-border px-4 py-1.5 text-[11px] text-muted-foreground">
- ⌘⇧V toggles · click copies
- <Button type="button" variant="ghost" aria-label="Close" onClick={() => setClipboardOpen(false)} className="ml-auto h-auto p-1 font-normal hover:bg-muted">
- <X className="size-3" />
- </Button>
- </footer>
- </div>
- </div>
- );
+ return <DeferredSurface active={open} load={loadPanel} label="Clipboard history" />;
}
diff --git a/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx b/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx
new file mode 100644
index 00000000..23ed482b
--- /dev/null
+++ b/frontend/slices/appshell/features/clipboard/components/clipboard-panel.tsx
@@ -0,0 +1,76 @@
+"use client";
+import { useState } from "react";
+import { Pin, Trash2, X } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import { clearClips, copyClip, removeClip, setClipboardOpen, togglePinClip, useClips } from "../../../lib/clipboard";
+
+export function ClipboardPanel() {
+ const clips = useClips();
+ const [q, setQ] = useState("");
+ const list = clips.filter((c) => c.text.toLowerCase().includes(q.toLowerCase()));
+
+ return (
+ <div className="absolute inset-0 z-[var(--z-clipboard)] flex items-start justify-center bg-black/20 pt-[16vh]" onClick={() => setClipboardOpen(false)}>
+ <div className="glass flex max-h-[60vh] w-full max-w-lg flex-col overflow-hidden rounded-2xl border border-border shadow-2xl" onClick={(e) => e.stopPropagation()}>
+ <header className="flex items-center gap-2 border-b border-border px-4 py-2.5">
+ <span className="text-xs font-semibold text-muted-foreground">Clipboard history</span>
+ {clips.length > 0 && (
+ <Button type="button" variant="ghost" onClick={clearClips} className="ml-auto h-auto p-0 text-xs font-normal text-muted-foreground hover:bg-transparent hover:underline">
+ Clear unpinned
+ </Button>
+ )}
+ </header>
+ <input
+ autoFocus
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ placeholder="Search clips…"
+ className="w-full bg-transparent px-4 py-2.5 text-sm outline-none placeholder:text-muted-foreground"
+ />
+ <ul className="min-h-0 flex-1 overflow-y-auto border-t border-border p-2">
+ {list.length === 0 && (
+ <li className="px-3 py-4 text-sm text-muted-foreground">
+ {clips.length === 0 ? "Nothing copied yet — ⌘C anywhere in the OS lands here." : "No matches."}
+ </li>
+ )}
+ {list.map((c) => (
+ <li key={c.id} className="group flex items-center gap-1 rounded-lg px-1 hover:bg-primary/10">
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => {
+ copyClip(c.text);
+ setClipboardOpen(false);
+ }}
+ className="h-auto min-w-0 flex-1 justify-start truncate p-2 text-left text-sm font-normal hover:bg-transparent"
+ >
+ {c.text}
+ </Button>
+ <Button
+ type="button" variant="ghost" aria-label={c.pinned ? "Unpin" : "Pin"}
+ onClick={() => togglePinClip(c.id)}
+ className={cn("h-auto shrink-0 p-1 font-normal hover:bg-muted", c.pinned ? "text-primary" : "text-muted-foreground opacity-0 group-hover:opacity-100")}
+ >
+ <Pin className="size-3.5" />
+ </Button>
+ <Button
+ type="button" variant="ghost" aria-label="Remove"
+ onClick={() => removeClip(c.id)}
+ className="h-auto shrink-0 p-1 font-normal text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100"
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ </li>
+ ))}
+ </ul>
+ <footer className="flex items-center border-t border-border px-4 py-1.5 text-[11px] text-muted-foreground">
+ ⌘⇧V toggles · click copies
+ <Button type="button" variant="ghost" aria-label="Close" onClick={() => setClipboardOpen(false)} className="ml-auto h-auto p-1 font-normal hover:bg-muted">
+ <X className="size-3" />
+ </Button>
+ </footer>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/slices/appshell/features/control-center/deferred.tsx b/frontend/slices/appshell/features/control-center/deferred.tsx
new file mode 100644
index 00000000..f46c85d3
--- /dev/null
+++ b/frontend/slices/appshell/features/control-center/deferred.tsx
@@ -0,0 +1,8 @@
+"use client";
+import { useShellUI } from "../../registry/shell-ui";
+import { DeferredSurface } from "../../primitives/deferred-surface";
+const load = () => import("./components/control-center").then((module) => ({ default: module.ControlCenter }));
+export function DeferredControlCenter() {
+ const { controlCenterOpen } = useShellUI();
+ return <DeferredSurface active={controlCenterOpen} load={load} label="Control Center" keepMounted />;
+}
diff --git a/frontend/slices/appshell/features/control-center/index.ts b/frontend/slices/appshell/features/control-center/index.ts
index fc19b273..0a3873eb 100644
--- a/frontend/slices/appshell/features/control-center/index.ts
+++ b/frontend/slices/appshell/features/control-center/index.ts
@@ -1,5 +1,5 @@
import { defineFeature } from "../../registry/types";
-import { ControlCenter } from "./components/control-center";
+import { DeferredControlCenter } from "./deferred";
import { ControlCenterDesktop } from "./components/control-center-desktop";
// Control Center — the SAME real toggles on both surfaces: an iOS-style pull-down
@@ -8,5 +8,5 @@ import { ControlCenterDesktop } from "./components/control-center-desktop";
// owned by the mobile surface via the shell-UI context; the desktop popover is local.
export const controlCenterFeature = defineFeature({
id: "control-center",
- slots: { controlCenter: ControlCenter, menuBarStatus: ControlCenterDesktop },
+ slots: { controlCenter: DeferredControlCenter, menuBarStatus: ControlCenterDesktop },
});
diff --git a/frontend/slices/appshell/features/inspector/deferred.tsx b/frontend/slices/appshell/features/inspector/deferred.tsx
new file mode 100644
index 00000000..d72d8e79
--- /dev/null
+++ b/frontend/slices/appshell/features/inspector/deferred.tsx
@@ -0,0 +1,15 @@
+"use client";
+import { useInspectorOpen } from "../../hooks/use-shell";
+import { useIsMobile } from "../../responsive/use-is-mobile";
+import { DeferredSurface } from "../../primitives/deferred-surface";
+const loadInspector = () => import("./components/inspector").then((module) => ({ default: module.Inspector }));
+const loadAlfa = () => import("./components/alfa-sheet").then((module) => ({ default: module.AlfaSheet }));
+export function DeferredInspector() {
+ const open = useInspectorOpen();
+ return <DeferredSurface active={open} load={loadInspector} label="Inspector" keepMounted />;
+}
+export function DeferredAlfaSheet() {
+ const open = useInspectorOpen();
+ const mobile = useIsMobile();
+ return <DeferredSurface active={open && mobile} load={loadAlfa} label="Alfa" keepMounted />;
+}
diff --git a/frontend/slices/appshell/features/inspector/index.ts b/frontend/slices/appshell/features/inspector/index.ts
index 0d183b80..f4e4f01a 100644
--- a/frontend/slices/appshell/features/inspector/index.ts
+++ b/frontend/slices/appshell/features/inspector/index.ts
@@ -1,6 +1,5 @@
import { defineFeature } from "../../registry/types";
-import { Inspector } from "./components/inspector";
-import { AlfaSheet } from "./components/alfa-sheet";
+import { DeferredInspector, DeferredAlfaSheet } from "./deferred";
// Inspector — the app-context panel + Alfa. The publish bus (usePublishInspector)
// stays in appshell core so apps publish state without depending on this feature.
@@ -11,5 +10,5 @@ import { AlfaSheet } from "./components/alfa-sheet";
// phone. Each returns null on the surface it is not for, so only one ever mounts.
export const inspectorFeature = defineFeature({
id: "inspector",
- slots: { rightPanel: Inspector, overlay: AlfaSheet },
+ slots: { rightPanel: DeferredInspector, overlay: DeferredAlfaSheet },
});
diff --git a/frontend/slices/appshell/features/search/deferred.tsx b/frontend/slices/appshell/features/search/deferred.tsx
new file mode 100644
index 00000000..7cadda21
--- /dev/null
+++ b/frontend/slices/appshell/features/search/deferred.tsx
@@ -0,0 +1,8 @@
+"use client";
+import { useSpotlightOpen } from "../../hooks/use-shell";
+import { DeferredSurface } from "../../primitives/deferred-surface";
+const load = () => import("./components/spotlight").then((module) => ({ default: module.Spotlight }));
+export function DeferredSpotlight() {
+ const open = useSpotlightOpen();
+ return <DeferredSurface active={open} load={load} label="Search" />;
+}
diff --git a/frontend/slices/appshell/features/search/index.ts b/frontend/slices/appshell/features/search/index.ts
index e4f47f45..79791425 100644
--- a/frontend/slices/appshell/features/search/index.ts
+++ b/frontend/slices/appshell/features/search/index.ts
@@ -1,8 +1,8 @@
import { defineFeature } from "../../registry/types";
-import { Spotlight } from "./components/spotlight";
+import { DeferredSpotlight } from "./deferred";
// Search — the ⌘K command palette, mounted into the shell's full-screen overlay.
export const searchFeature = defineFeature({
id: "search",
- slots: { overlay: Spotlight },
+ slots: { overlay: DeferredSpotlight },
});
diff --git a/frontend/slices/appshell/hooks/use-intent-prefetch.ts b/frontend/slices/appshell/hooks/use-intent-prefetch.ts
new file mode 100644
index 00000000..496137c5
--- /dev/null
+++ b/frontend/slices/appshell/hooks/use-intent-prefetch.ts
@@ -0,0 +1,14 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { createIntentPrefetch } from "../lib/intent-prefetch";
+
+/** One pending intent per surface; cancel on close, pointer leave, blur or unmount. */
+export function useIntentPrefetch(enabled = true) {
+ const [prefetch] = useState(() => createIntentPrefetch());
+ useEffect(() => {
+ if (!enabled) prefetch.cancel();
+ return prefetch.cancel;
+ }, [enabled, prefetch]);
+ return prefetch;
+}
diff --git a/frontend/slices/appshell/lib/intent-prefetch.test.ts b/frontend/slices/appshell/lib/intent-prefetch.test.ts
new file mode 100644
index 00000000..9e2ac961
--- /dev/null
+++ b/frontend/slices/appshell/lib/intent-prefetch.test.ts
@@ -0,0 +1,62 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { canIntentPrefetch, createIntentPrefetch, PREFETCH_INTENT_MS, type PrefetchEnvironment } from "./intent-prefetch";
+
+const app = () => ({ load: vi.fn(async () => ({ default: () => null })) });
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
+
+describe("intent-only app warming", () => {
+ it("waits for deliberate intent, then warms once", async () => {
+ const target = app(); const prefetch = createIntentPrefetch(() => ({}));
+ prefetch.schedule(target);
+ await vi.advanceTimersByTimeAsync(PREFETCH_INTENT_MS - 1);
+ expect(target.load).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(target.load).toHaveBeenCalledTimes(1);
+ prefetch.schedule(target);
+ await vi.advanceTimersByTimeAsync(PREFETCH_INTENT_MS);
+ expect(target.load).toHaveBeenCalledTimes(1);
+ });
+ it("cancels on leave/blur/unmount without loading the app", async () => {
+ const target = app(); const prefetch = createIntentPrefetch(() => ({}));
+ prefetch.schedule(target); prefetch.cancel(); prefetch.cancel();
+ await vi.runAllTimersAsync(); expect(target.load).not.toHaveBeenCalled();
+ });
+ it("replaces pending intent during a launcher sweep", async () => {
+ const first = app(); const last = app(); const prefetch = createIntentPrefetch(() => ({}));
+ prefetch.schedule(first); await vi.advanceTimersByTimeAsync(100); prefetch.schedule(last);
+ await vi.runAllTimersAsync(); expect(first.load).not.toHaveBeenCalled(); expect(last.load).toHaveBeenCalledTimes(1);
+ });
+ it("never warms expensive opt-out apps or touch-hover events", async () => {
+ const target = app(); const prefetch = createIntentPrefetch(() => ({}));
+ prefetch.schedule({ ...target, prefetch: "never" }); await vi.runAllTimersAsync();
+ prefetch.schedule(target, "touch"); await vi.runAllTimersAsync(); expect(target.load).not.toHaveBeenCalled();
+ });
+ it.each<PrefetchEnvironment>([{ hidden: true }, { online: false }, { saveData: true }, { effectiveType: "2g" }, { effectiveType: "slow-2g" }])("respects constrained state %j", async (environment) => {
+ const target = app(); const prefetch = createIntentPrefetch(() => environment);
+ expect(canIntentPrefetch(environment)).toBe(false);
+ prefetch.schedule(target); await vi.runAllTimersAsync(); expect(target.load).not.toHaveBeenCalled();
+ });
+ it("rechecks visibility/network when intent expires", async () => {
+ const target = app(); let environment: PrefetchEnvironment = {};
+ const prefetch = createIntentPrefetch(() => environment);
+ prefetch.schedule(target); environment = { hidden: true };
+ await vi.runAllTimersAsync(); expect(target.load).not.toHaveBeenCalled();
+ });
+ it("deduplicates an in-flight module across independent surfaces", async () => {
+ let resolve!: (value: { default: () => null }) => void;
+ const target = { load: vi.fn(() => new Promise<{ default: () => null }>(done => { resolve = done; })) };
+ createIntentPrefetch(() => ({})).schedule(target);
+ createIntentPrefetch(() => ({})).schedule(target, "keyboard");
+ await vi.advanceTimersByTimeAsync(PREFETCH_INTENT_MS);
+ expect(target.load).toHaveBeenCalledTimes(1); resolve({ default: () => null });
+ await Promise.resolve();
+ });
+ it("does not poison real loading after speculative rejection", async () => {
+ const target = app(); target.load.mockRejectedValueOnce(new Error("offline"));
+ const prefetch = createIntentPrefetch(() => ({}));
+ prefetch.schedule(target); await vi.runAllTimersAsync();
+ prefetch.schedule(target); await vi.runAllTimersAsync();
+ expect(target.load).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/frontend/slices/appshell/lib/intent-prefetch.ts b/frontend/slices/appshell/lib/intent-prefetch.ts
new file mode 100644
index 00000000..3deae40f
--- /dev/null
+++ b/frontend/slices/appshell/lib/intent-prefetch.ts
@@ -0,0 +1,38 @@
+import type { AppDescriptor } from "./types";
+
+type PrefetchApp = Pick<AppDescriptor, "load" | "prefetch">;
+export type PrefetchEnvironment = { hidden?: boolean; online?: boolean; saveData?: boolean; effectiveType?: string };
+export const PREFETCH_INTENT_MS = 250;
+const warmed = new WeakSet<PrefetchApp["load"]>();
+const pending = new WeakSet<PrefetchApp["load"]>();
+
+function browserEnvironment(): PrefetchEnvironment {
+ if (typeof navigator === "undefined") return { online: false };
+ const connection = (navigator as Navigator & { connection?: PrefetchEnvironment }).connection;
+ return { hidden: typeof document !== "undefined" && document.hidden, online: navigator.onLine,
+ saveData: connection?.saveData, effectiveType: connection?.effectiveType };
+}
+
+export function canIntentPrefetch(environment: PrefetchEnvironment): boolean {
+ return !environment.hidden && environment.online !== false && !environment.saveData &&
+ !["slow-2g", "2g"].includes(environment.effectiveType ?? "");
+}
+
+/** Cancel the intent timer, not an already-started import. Failed warming may retry. */
+export function createIntentPrefetch(environment = browserEnvironment) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const cancel = () => { if (timer !== undefined) clearTimeout(timer); timer = undefined; };
+ const schedule = (app: PrefetchApp, pointerType = "mouse") => {
+ cancel();
+ if (pointerType === "touch" || app.prefetch === "never" || !canIntentPrefetch(environment())) return;
+ timer = setTimeout(() => {
+ timer = undefined;
+ if (!canIntentPrefetch(environment()) || warmed.has(app.load) || pending.has(app.load)) return;
+ pending.add(app.load);
+ // A speculative error must not reload an active editor or poison the real app loader.
+ void Promise.resolve().then(() => app.load()).then(() => warmed.add(app.load))
+ .catch(() => undefined).finally(() => pending.delete(app.load));
+ }, PREFETCH_INTENT_MS);
+ };
+ return { schedule, cancel };
+}
diff --git a/frontend/slices/appshell/lib/types.ts b/frontend/slices/appshell/lib/types.ts
index 1936b602..bfb79838 100644
--- a/frontend/slices/appshell/lib/types.ts
+++ b/frontend/slices/appshell/lib/types.ts
@@ -86,6 +86,8 @@ export type AppDescriptor = {
iconFill?: boolean;
/** Lazy-loaded so a window only pulls its app bundle when opened. */
load: () => Promise<{ default: ComponentType<AppProps> }>;
+ /** Warm after deliberate hover/focus, or only load on open for expensive apps. */
+ prefetch?: "intent" | "never";
defaultSize?: { w: number; h: number };
/** Hide from the dock (still launchable via launcher). */
noDock?: boolean;
diff --git a/frontend/slices/appshell/primitives/deferred-surface.test.tsx b/frontend/slices/appshell/primitives/deferred-surface.test.tsx
new file mode 100644
index 00000000..c00969fb
--- /dev/null
+++ b/frontend/slices/appshell/primitives/deferred-surface.test.tsx
@@ -0,0 +1,24 @@
+import { createElement } from "react";
+import { renderToString } from "react-dom/server";
+import { describe, expect, it, vi } from "vitest";
+import { DeferredSurface, loadDeferredSurface } from "./deferred-surface";
+
+describe("deferred shell surfaces", () => {
+ it("does not start importing a closed surface, even with retention enabled", () => {
+ const load = vi.fn(async () => ({ default: () => null }));
+ expect(renderToString(createElement(DeferredSurface, { active: false, load, label: "Inspector", keepMounted: true }))).toBe("");
+ expect(load).not.toHaveBeenCalled();
+ });
+ it("deduplicates the loader while importing and after success", async () => {
+ const load = vi.fn(async () => ({ default: () => null }));
+ const first = loadDeferredSurface(load); const second = loadDeferredSurface(load);
+ expect(second).toBe(first); await first;
+ expect(loadDeferredSurface(load)).toBe(first); expect(load).toHaveBeenCalledTimes(1);
+ });
+ it("clears a failed import so a new intent can retry", async () => {
+ const load = vi.fn(async () => ({ default: () => null })).mockRejectedValueOnce(new Error("missing chunk"));
+ await expect(loadDeferredSurface(load)).rejects.toThrow("missing chunk");
+ await expect(loadDeferredSurface(load)).resolves.toHaveProperty("default");
+ expect(load).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/frontend/slices/appshell/primitives/deferred-surface.tsx b/frontend/slices/appshell/primitives/deferred-surface.tsx
new file mode 100644
index 00000000..966d3e1c
--- /dev/null
+++ b/frontend/slices/appshell/primitives/deferred-surface.tsx
@@ -0,0 +1,47 @@
+"use client";
+
+import { useEffect, useState, type ComponentType } from "react";
+import { Button } from "@/components/ui/button";
+
+type SurfaceModule = { default: ComponentType };
+type SurfaceLoader = () => Promise<SurfaceModule>;
+const modules = new WeakMap<SurfaceLoader, Promise<SurfaceModule>>();
+
+export function loadDeferredSurface(load: SurfaceLoader): Promise<SurfaceModule> {
+ const cached = modules.get(load);
+ if (cached) return cached;
+ const pending = Promise.resolve().then(load).catch((error: unknown) => { modules.delete(load); throw error; });
+ modules.set(load, pending);
+ return pending;
+}
+
+/** Keep essential hooks in the caller; defer only presentation until requested.
+ * Uses the window host's effect/state pattern: an external-store open must not
+ * depend on a Suspense retry ping. Retention preserves tabs and exit animations.
+ */
+export function DeferredSurface({ active, load, label, keepMounted = false }: {
+ active: boolean; load: SurfaceLoader; label: string; keepMounted?: boolean;
+}) {
+ const [result, setResult] = useState<{ load: SurfaceLoader; Comp?: ComponentType; failed?: boolean } | null>(null);
+ const [attempt, retry] = useState(0);
+ const current = result?.load === load ? result : null;
+ const Comp = current?.Comp;
+ useEffect(() => {
+ if (!active || Comp) return;
+ let alive = true;
+ void loadDeferredSurface(load).then((module) => {
+ if (alive) setResult({ load, Comp: module.default });
+ }).catch((error: unknown) => {
+ if (alive) setResult({ load, failed: true });
+ // Preserve the global service-worker stale-chunk recovery path.
+ throw error;
+ });
+ return () => { alive = false; };
+ }, [active, load, Comp, attempt]);
+ if (!active && (!keepMounted || !Comp)) return null;
+ if (Comp) return <Comp />;
+ if (current?.failed) return <div role="alert" className="p-3 text-sm text-muted-foreground">
+ Could not load {label}. <Button variant="secondary" size="sm" onClick={() => retry((value) => value + 1)}>Retry loading {label}</Button>
+ </div>;
+ return <span role="status" className="sr-only">Loading {label}…</span>;
+}
diff --git a/frontend/slices/code-editor/index.ts b/frontend/slices/code-editor/index.ts
index 532277ec..8ee1e5b3 100644
--- a/frontend/slices/code-editor/index.ts
+++ b/frontend/slices/code-editor/index.ts
@@ -8,6 +8,7 @@ export const codeEditorApp: AppDescriptor = {
title: "Code",
icon: Code2,
gradient: "linear-gradient(160deg,#ff5f8f,#b5179e)",
+ prefetch: "never",
load: () => import("./app"),
defaultSize: { w: 820, h: 560 },
};
diff --git a/frontend/slices/managed-apps/index.ts b/frontend/slices/managed-apps/index.ts
index d63120e6..bc0fc28f 100644
--- a/frontend/slices/managed-apps/index.ts
+++ b/frontend/slices/managed-apps/index.ts
@@ -31,6 +31,7 @@ function managedDescriptor(app: ManagedApp): AppDescriptor {
title: look.title,
icon: look.icon,
gradient: look.gradient,
+ prefetch: "never",
load: async () => {
const loaded = await import("./app");
return { default: loaded[look.loader as "HermesApp" | "OpenClawApp" | "NineRouterApp"] };
diff --git a/frontend/slices/media-studio/index.ts b/frontend/slices/media-studio/index.ts
index b3e27d83..5b545701 100644
--- a/frontend/slices/media-studio/index.ts
+++ b/frontend/slices/media-studio/index.ts
@@ -8,6 +8,7 @@ export const mediaStudioApp: AppDescriptor = {
title: "Image Editor",
icon: Image,
gradient: "linear-gradient(160deg,#ff9f43,#ee5253)",
+ prefetch: "never",
load: () => import("./app"),
defaultSize: { w: 1180, h: 760 },
};
diff --git a/frontend/slices/organization/bundle-boundary.test.ts b/frontend/slices/organization/bundle-boundary.test.ts
new file mode 100644
index 00000000..7c0b309b
--- /dev/null
+++ b/frontend/slices/organization/bundle-boundary.test.ts
@@ -0,0 +1,34 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+const read = (path: string) => readFileSync(path, "utf8");
+describe("shell graph loading boundaries", () => {
+ it("preserves the public Organization API without eagerly exporting the canvas view", () => {
+ const barrel = read("frontend/slices/organization/index.ts");
+ expect(barrel).toContain('load: () => import("./app")');
+ expect(barrel).toContain('from "./lazy-view"');
+ expect(barrel).not.toContain('from "./components/organization-view"');
+ expect(read("frontend/slices/organization/lazy-view.tsx")).toContain('import("./components/organization-view")');
+ });
+ it("loads graph CSS at the shared canvas boundary rather than in global CSS", () => {
+ expect(read("app/globals.css")).not.toContain("@xyflow/react");
+ expect(read("components/shared/graph-canvas.tsx")).toContain('import "@xyflow/react/dist/style.css"');
+ });
+ it("keeps lock protection, notification plumbing and clipboard capture eager", () => {
+ expect(read("frontend/slices/appshell/features/lock-screen/index.ts")).toContain('from "./components/lock-screen"');
+ expect(read("frontend/slices/appshell/features/notifications/index.ts")).toContain('from "./components/toast-host"');
+ const clipboard = read("frontend/slices/appshell/features/clipboard/components/clipboard-overlay.tsx");
+ expect(clipboard).toContain("useEffect(() => startClipboardCapture(), [])");
+ expect(clipboard).toContain('window.addEventListener("keydown", onKey)');
+ expect(clipboard).toContain('import("./clipboard-panel")');
+ });
+ it("keeps native links, normal app loading and restrictive prefetch guards", () => {
+ for (const name of ["dock-parts", "app-launcher"]) {
+ const source = read(`frontend/slices/appshell/components/${name}.tsx`);
+ expect(source).toContain("prefetch={false}");
+ expect(source).toContain("onPointerLeave={prefetch.cancel}");
+ expect(source).toContain("onBlur={prefetch.cancel}");
+ expect(source).not.toContain("onPointerEnter={() => void app.load");
+ }
+ expect(read("frontend/slices/appshell/components/window-content.tsx")).toContain(".load()");
+ });
+});
diff --git a/frontend/slices/organization/index.ts b/frontend/slices/organization/index.ts
index 49ea0ea8..eb9eff51 100644
--- a/frontend/slices/organization/index.ts
+++ b/frontend/slices/organization/index.ts
@@ -6,8 +6,9 @@ export const organizationApp: AppDescriptor = {
title: "Organization",
icon: Network,
gradient: "linear-gradient(160deg,#2563eb,#0f172a)",
+ prefetch: "never",
load: () => import("./app"),
defaultSize: { w: 1120, h: 720 },
};
-export { OrganizationView } from "./components/organization-view";
+export { OrganizationView } from "./lazy-view";
diff --git a/frontend/slices/organization/lazy-view.tsx b/frontend/slices/organization/lazy-view.tsx
new file mode 100644
index 00000000..dd57acb4
--- /dev/null
+++ b/frontend/slices/organization/lazy-view.tsx
@@ -0,0 +1,10 @@
+"use client";
+
+import dynamic from "next/dynamic";
+
+// Preserve the public API without eagerly importing the graph through the app descriptor.
+// Used by Alfa's Organization tab; the standalone app still loads its own view directly.
+export const OrganizationView = dynamic(
+ () => import("./components/organization-view").then((module) => module.OrganizationView),
+ { ssr: false, loading: () => <p role="status" className="p-4 text-sm text-muted-foreground">Loading organization…</p> },
+);
diff --git a/frontend/slices/os-settings/components/sections.tsx b/frontend/slices/os-settings/components/sections.tsx
index 169af547..32592ed5 100644
--- a/frontend/slices/os-settings/components/sections.tsx
+++ b/frontend/slices/os-settings/components/sections.tsx
@@ -1,5 +1,6 @@
"use client";
import Link from "next/link";
+import dynamic from "next/dynamic";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
@@ -9,18 +10,23 @@ import { SettingsSection } from "@/features/shell-settings";
import { cn } from "@/lib/utils";
import { Lock, ShieldCheck } from "lucide-react";
import { SECTIONS, type SectionId } from "../lib/sections";
-import { A2ASection } from "./a2a-section";
-import { AboutSection } from "./about-section";
-import { AiSection } from "./ai-section";
-import { AppearanceSection } from "./appearance-section";
+
import { AutoLockRow } from "./auto-lock-row";
-import { BackupSection } from "./backup-section";
-import { CleanupSection } from "./cleanup-section";
-import { McpSection } from "./mcp-section";
-import { MemorySection } from "./memory-section";
-import { QuicklinksSection } from "./quicklinks-section";
-import { ServerSection } from "./server-section";
-import { ThemeSection } from "./theme-section";
+
+// Metadata/navigation and access checks stay eager. No private panel mounts or
+// fetches before its existing role gate allows it; inactive sections stay deferred.
+const loadingSection = () => <p role="status" className="p-3 text-sm text-muted-foreground">Loading settings…</p>;
+const A2ASection = dynamic(() => import("./a2a-section").then((module) => module.A2ASection), { loading: loadingSection });
+const AboutSection = dynamic(() => import("./about-section").then((module) => module.AboutSection), { loading: loadingSection });
+const AiSection = dynamic(() => import("./ai-section").then((module) => module.AiSection), { loading: loadingSection });
+const AppearanceSection = dynamic(() => import("./appearance-section").then((module) => module.AppearanceSection), { loading: loadingSection });
+const BackupSection = dynamic(() => import("./backup-section").then((module) => module.BackupSection), { loading: loadingSection });
+const CleanupSection = dynamic(() => import("./cleanup-section").then((module) => module.CleanupSection), { loading: loadingSection });
+const McpSection = dynamic(() => import("./mcp-section").then((module) => module.McpSection), { loading: loadingSection });
+const MemorySection = dynamic(() => import("./memory-section").then((module) => module.MemorySection), { loading: loadingSection });
+const QuicklinksSection = dynamic(() => import("./quicklinks-section").then((module) => module.QuicklinksSection), { loading: loadingSection });
+const ServerSection = dynamic(() => import("./server-section").then((module) => module.ServerSection), { loading: loadingSection });
+const ThemeSection = dynamic(() => import("./theme-section").then((module) => module.ThemeSection), { loading: loadingSection });
// The section content — one functional panel per SectionId, shared verbatim by
// every shell's Settings layout (the per-shell seam only swaps the navigation
diff --git a/frontend/slices/os-terminal/index.ts b/frontend/slices/os-terminal/index.ts
index d63e9006..4a79b4b6 100644
--- a/frontend/slices/os-terminal/index.ts
+++ b/frontend/slices/os-terminal/index.ts
@@ -21,6 +21,7 @@ export const osTerminalApp: AppDescriptor = {
title: "Terminal",
icon: SquareTerminal,
gradient: "linear-gradient(160deg,#3a3a40,#111114)",
+ prefetch: "never",
load: () => import("./app"),
defaultSize: { w: 640, h: 400 },
};
@@ -31,6 +32,7 @@ export const claudeCodeApp: AppDescriptor = {
title: "Claude Code",
icon: Bot,
gradient: "linear-gradient(160deg,#d97757,#8a4a30)",
+ prefetch: "never",
load: () => import("./claude-code"),
defaultSize: { w: 760, h: 480 },
};
diff --git a/frontend/slices/reel-editor/index.ts b/frontend/slices/reel-editor/index.ts
index 5c8ee77d..cdef4b48 100644
--- a/frontend/slices/reel-editor/index.ts
+++ b/frontend/slices/reel-editor/index.ts
@@ -8,6 +8,7 @@ export const reelEditorApp: AppDescriptor = {
title: "Video Editor",
icon: Clapperboard,
gradient: "linear-gradient(160deg,#7a5cff,#5b2fe0)",
+ prefetch: "never",
load: () => import("./app"),
defaultSize: { w: 920, h: 600 },
};
diff --git a/frontend/slices/workflows/index.ts b/frontend/slices/workflows/index.ts
index 4430cf16..d9dc05bb 100644
--- a/frontend/slices/workflows/index.ts
+++ b/frontend/slices/workflows/index.ts
@@ -6,6 +6,7 @@ export const workflowsApp: AppDescriptor = {
title: "Workflows",
icon: Workflow,
gradient: "var(--primary)",
+ prefetch: "never",
load: () => import("./app"),
defaultSize: { w: 1180, h: 760 },
};
diff --git a/package.json b/package.json
index 5b882aa0..7d5209d2 100644
--- a/package.json
+++ b/package.json
@@ -45,7 +45,9 @@
"test:features": "node scripts/test-features.mjs",
"screenshot:cli": "node scripts/capture-cli.mjs",
"check:instance-literals": "bun scripts/check-instance-literals.mjs",
- "e2e:release": "node scripts/e2e/release.mjs"
+ "e2e:release": "node scripts/e2e/release.mjs",
+ "bundle:report": "node scripts/check-bundle.mjs --report-only",
+ "bundle:check": "node scripts/check-bundle.mjs"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.120.0",
diff --git a/scripts/bundle-budget.json b/scripts/bundle-budget.json
new file mode 100644
index 00000000..443356aa
--- /dev/null
+++ b/scripts/bundle-budget.json
@@ -0,0 +1,4 @@
+{
+ "gzipBytes": { "initial": 307200, "entry": 163840, "css": 30720 },
+ "preloadedFontBytes": 81920
+}
diff --git a/scripts/bundle-report.test.ts b/scripts/bundle-report.test.ts
new file mode 100644
index 00000000..ed222a44
--- /dev/null
+++ b/scripts/bundle-report.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { parseClientManifest, bundleViolations } from "./lib/bundle-report.mjs";
+
+describe("fail-closed production bundle budget", () => {
+ it("reads the generated assignment as JSON, without executing scripts", () => {
+ expect(parseClientManifest('globalThis.__RSC_MANIFEST = {}; globalThis.__RSC_MANIFEST["/[[...slug]]/page"] = {"entryJSFiles":{}};')).toEqual({ entryJSFiles: {} });
+ expect(() => parseClientManifest('process.exit(0)')).toThrow("Unsupported");
+ expect(() => parseClientManifest('globalThis.__RSC_MANIFEST["/route"] = {"x":(()=>42)()};')).toThrow();
+ });
+ it("rejects missing measurements, over-budget bytes and eager heavy engines", () => {
+ const report = { initial: { gzip: 100 }, fonts: { bytes: 10 }, initialHeavyModules: [] };
+ const budget = { gzipBytes: { initial: 100 }, preloadedFontBytes: 10 };
+ expect(bundleViolations(report, budget)).toEqual([]);
+ expect(bundleViolations({ ...report, initial: { gzip: 101 } }, budget)).toHaveLength(1);
+ expect(bundleViolations({ ...report, initial: null }, budget)).toHaveLength(1);
+ expect(bundleViolations({ ...report, fonts: { bytes: 11 }, initialHeavyModules: ["ReactFlow"] }, budget)).toHaveLength(2);
+ });
+ it("fails closed on missing fonts, missing engine scan and invalid thresholds", () => {
+ const report = { initial: { gzip: 10 }, fonts: { bytes: 1 }, initialHeavyModules: [] };
+ const budget = { gzipBytes: { initial: 100 }, preloadedFontBytes: 10 };
+ expect(bundleViolations({ ...report, fonts: null }, budget)).toContain("preloaded fonts: missing measurement");
+ expect(bundleViolations({ ...report, initialHeavyModules: undefined }, budget)).toContain("Missing eager engine scan");
+ expect(bundleViolations(report, { ...budget, gzipBytes: { initial: Number.NaN } })).toContain("initial: invalid budget");
+ expect(bundleViolations(report, {})).toContain("Missing gzip bundle budgets");
+ });
+
+});
diff --git a/scripts/check-bundle.mjs b/scripts/check-bundle.mjs
new file mode 100644
index 00000000..9f5c9d81
--- /dev/null
+++ b/scripts/check-bundle.mjs
@@ -0,0 +1,19 @@
+#!/usr/bin/env node
+import fs from 'node:fs';
+import { readBundleReport, bundleViolations } from './lib/bundle-report.mjs';
+
+try {
+ const report = readBundleReport();
+ if (process.argv.includes('--json')) console.log(JSON.stringify(report, null, 2));
+ else for (const key of ['initial', 'entry', 'css', 'fonts']) {
+ console.log(`bundle ${key}: ${(report[key].bytes / 1024).toFixed(1)} KiB raw / ${(report[key].gzip / 1024).toFixed(1)} KiB gzip (${report[key].files} files)`);
+ }
+ if (!process.argv.includes('--report-only')) {
+ const failures = bundleViolations(report, JSON.parse(fs.readFileSync('scripts/bundle-budget.json', 'utf8')));
+ if (failures.length) throw new Error(failures.join('\n'));
+ console.log('bundle: eager shell budget passed; optional engines remain deferred.');
+ }
+} catch (error) {
+ console.error(`bundle: ${error instanceof Error ? error.message : String(error)}`);
+ process.exitCode = 1;
+}
diff --git a/scripts/e2e/bundle-performance.mjs b/scripts/e2e/bundle-performance.mjs
new file mode 100644
index 00000000..74ff3aac
--- /dev/null
+++ b/scripts/e2e/bundle-performance.mjs
@@ -0,0 +1,122 @@
+#!/usr/bin/env node
+// Cold-load and first-open regressions against synthetic stores, never live state.
+import fs from 'node:fs';
+import path from 'node:path';
+import { chromium, expect as assertion } from '@playwright/test';
+import { releaseFixture } from './release-fixture.mjs';
+
+const expect = assertion.configure({ timeout: 15000 });
+const chunks = new Map(fs.readdirSync('.next/static/chunks').filter(file => file.endsWith('.js'))
+ .map(file => [file, fs.readFileSync(path.join('.next/static/chunks', file), 'utf8')]));
+const heavyMarkers = ['react-flow__renderer', 'Konva error', 'xterm-screen', 'ort-wasm-simd-threaded'];
+const output = process.argv.find(arg => arg.startsWith('--output='))?.slice(9);
+if (output) fs.mkdirSync(output, { recursive: true, mode: 0o700 });
+const fixture = await releaseFixture();
+let browser;
+const results = [];
+try {
+ browser = await chromium.launch({ headless: true });
+ for (const shell of ['macos', 'windows', 'dashboard', 'ios', 'android']) {
+ const mobile = ['ios', 'android'].includes(shell);
+ const viewport = mobile ? { width: 390, height: 844 } : { width: 1363, height: 936 };
+ const context = await browser.newContext({ viewport, reducedMotion: 'reduce' });
+ await context.addInitScript(({ shell, mobile }) => {
+ localStorage.setItem('sv:shell', JSON.stringify({ desktop: mobile ? 'macos' : shell, mobile: mobile ? shell : 'ios' }));
+ localStorage.setItem('mso:onboarding:v1', 'done');
+ }, { shell, mobile });
+ const page = await context.newPage();
+ const errors = [];
+ const pendingScripts = new Set();
+ const requestedScripts = new Set();
+ let lastScriptAt = Date.now();
+ const isScript = request => /\/_next\/static\/.*\.js(?:\?|$)/.test(request.url());
+ page.on('request', request => {
+ if (isScript(request)) { pendingScripts.add(request); requestedScripts.add(new URL(request.url()).pathname.split('/').at(-1)); lastScriptAt = Date.now(); }
+ });
+ const settled = request => { if (isScript(request)) { pendingScripts.delete(request); lastScriptAt = Date.now(); } };
+ page.on('requestfinished', settled); page.on('requestfailed', settled);
+ page.on('pageerror', error => errors.push(error.message));
+ await page.route('**/_next/static/chunks/*.js', async route => {
+ const file = new URL(route.request().url()).pathname.split('/').at(-1);
+ // First-open must settle by itself even when the deferred panel arrives late.
+ if (chunks.get(file)?.includes('Spotlight search')) await new Promise(resolve => setTimeout(resolve, 350));
+ await route.continue();
+ });
+ await page.goto(fixture.base);
+ await expect(page.locator(`#main-content[data-shell="${shell}"]`)).toBeVisible();
+ await expect(page.getByLabel('Server connection mode')).toBeVisible();
+ // Telemetry/SSE/SW traffic is intentionally long-lived. Wait only for the
+ // local startup JavaScript, not an impossible globally idle network.
+ await expect.poll(() => pendingScripts.size === 0 && Date.now() - lastScriptAt > 500).toBe(true);
+ const resources = await page.evaluate(() => performance.getEntriesByType('resource')
+ .filter(entry => entry.name.includes('/_next/static/') && new URL(entry.name).pathname.endsWith('.js'))
+ .map(entry => ({ file: new URL(entry.name).pathname.split('/').at(-1), decodedBytes: entry.decodedBodySize, transferBytes: entry.transferSize })));
+ const heavy = [...requestedScripts].filter(file => heavyMarkers.some(marker => chunks.get(file)?.includes(marker)));
+ expect(heavy).toEqual([]);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);
+ if (output) await page.screenshot({ path: path.join(output, `${shell}-cold.png`) });
+ const search = page.getByRole('combobox', { name: 'Spotlight search' });
+ if (shell === 'macos') {
+ const delayed = page.waitForResponse(response => {
+ const file = new URL(response.url()).pathname.split('/').at(-1);
+ return Boolean(chunks.get(file)?.includes('Spotlight search'));
+ });
+ const requested = page.waitForRequest(request => {
+ const file = new URL(request.url()).pathname.split('/').at(-1);
+ return Boolean(chunks.get(file)?.includes('Spotlight search'));
+ });
+ await page.keyboard.press('Control+k'); await requested;
+ await page.keyboard.press('Control+k'); await delayed;
+ await expect(search).not.toBeVisible();
+ }
+ await page.keyboard.press('Control+k');
+ await expect(search).toBeVisible(); await expect(search).toBeFocused();
+ await search.fill('Terminal'); await expect(page.getByRole('listbox')).toContainText('Terminal');
+ await page.keyboard.press('Escape'); await expect(search).not.toBeVisible();
+ await page.keyboard.press('Control+k'); await expect(search).toHaveValue('');
+ await expect(search).toBeFocused();
+ await page.keyboard.press('Escape'); await expect(search).not.toBeVisible();
+ // Capture a copy BEFORE ever importing clipboard presentation.
+ const capturedSelection = await page.evaluate(() => {
+ const node = document.createElement('p'); node.style.userSelect = 'text'; node.textContent = 'bundle-capture-before-open'; document.body.appendChild(node);
+ const range = document.createRange(); range.selectNodeContents(node);
+ getSelection().removeAllRanges(); getSelection().addRange(range);
+ const selected = getSelection().toString();
+ document.dispatchEvent(new Event('copy')); getSelection().removeAllRanges(); node.remove();
+ return selected;
+ });
+ expect(capturedSelection).toBe('bundle-capture-before-open');
+ await page.keyboard.press('Control+Shift+v');
+ await expect(page.getByText('Clipboard history', { exact: true })).toBeVisible();
+ await expect(page.getByRole('button', { name: 'bundle-capture-before-open', exact: true })).toBeVisible();
+ await page.keyboard.press('Escape');
+ if (shell === 'macos' || shell === 'windows') {
+ await page.keyboard.press('Control+i');
+ const close = page.getByRole('button', { name: 'Close inspector (⌘I)', exact: true });
+ await expect(close).toBeVisible();
+ const inspector = page.locator('aside').filter({ has: close });
+ await inspector.getByRole('button', { name: 'AI', exact: true }).click();
+ await close.click(); await expect(close).not.toBeVisible();
+ await page.keyboard.press('Control+i');
+ await expect(inspector.getByRole('button', { name: 'AI', exact: true })).toHaveClass(/bg-secondary/);
+ await close.click();
+ } else if (mobile) {
+ await page.keyboard.press('Control+i');
+ const close = page.getByRole('button', { name: 'Close Alfa', exact: true });
+ await expect(close).toBeVisible(); await close.click(); await expect(close).not.toBeVisible();
+ }
+ expect(errors).toEqual([]);
+ results.push({ shell, viewport, coldJsRequests: resources.length,
+ coldJsDecodedBytes: resources.reduce((n, row) => n + row.decodedBytes, 0),
+ coldJsTransferBytes: resources.reduce((n, row) => n + row.transferBytes, 0),
+ heavyEnginesLoadedOnColdStart: heavy.length, pageErrors: errors.length,
+ firstOpenSearch: 'pass', eagerClipboardCapture: 'pass', resources });
+ await context.close();
+ console.log(`PASS ${shell}: no cold graph/editor/terminal/ONNX engines, deferred search, clipboard and inspector lifecycle`);
+ }
+ if (output) fs.writeFileSync(path.join(output, 'browser-report.json'), JSON.stringify({ synthetic: true, results }, null, 2));
+} finally {
+ await browser?.close();
+ await fixture.close();
+}
+console.log('bundle performance E2E: all five shells passed');
diff --git a/scripts/e2e/workflow-canvas.mjs b/scripts/e2e/workflow-canvas.mjs
index 3601aaef..6b22750e 100644
--- a/scripts/e2e/workflow-canvas.mjs
+++ b/scripts/e2e/workflow-canvas.mjs
@@ -61,8 +61,14 @@ export async function workflowCanvasJourney(page, fixture) {
await expect(page.getByLabel("Workflow name")).toBeVisible();
const trigger = canvas.locator(".react-flow__node", { hasText: "Manual Trigger" });
await expect(trigger).toBeVisible();
- const box = await trigger.boundingBox();
- expect(box?.width ?? 0).toBeGreaterThan(viewport.width < 700 ? 140 : 95);
+ // Measure settled geometry, not a lucky intermediate fit animation frame.
+ let previousWidth = 0, stableSamples = 0;
+ await expect.poll(async () => {
+ const width = (await trigger.boundingBox())?.width ?? 0;
+ stableSamples = Math.abs(width - previousWidth) < 0.5 ? stableSamples + 1 : 0;
+ previousWidth = width;
+ return stableSamples >= 3 ? width : 0;
+ }, { timeout: 10000, intervals: [100] }).toBeGreaterThan(viewport.width < 700 ? 140 : 95);
if (viewport.width < 700) {
await expect(page.getByRole("button", { name: "New workflow" })).toBeVisible();
await expect(page.getByRole("button", { name: "More actions" })).toBeVisible();
diff --git a/scripts/graph-fit.test.ts b/scripts/graph-fit.test.ts
new file mode 100644
index 00000000..305115f6
--- /dev/null
+++ b/scripts/graph-fit.test.ts
@@ -0,0 +1,25 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+import { compactGraphViewport } from "../components/shared/graph-fit";
+
+describe("readable measured graph viewport", () => {
+ it("handles portrait, narrow desktop panes and short landscape independently", () => {
+ expect(compactGraphViewport(390, 600)).toBe(true);
+ expect(compactGraphViewport(550, 800)).toBe(true);
+ expect(compactGraphViewport(826, 122)).toBe(true);
+ expect(compactGraphViewport(1200, 239)).toBe(true);
+ expect(compactGraphViewport(600, 240)).toBe(false);
+ expect(compactGraphViewport(1000, 700)).toBe(false);
+ });
+ it("does not classify an unmeasured canvas", () => {
+ expect(compactGraphViewport(0, 0)).toBe(false);
+ expect(compactGraphViewport(826, 0)).toBe(false);
+ });
+ it("waits for node measurements and avoids competing initial fit controllers", () => {
+ const source = readFileSync("components/shared/graph-canvas.tsx", "utf8");
+ expect(source).toContain("useNodesInitialized()");
+ expect(source).toContain("state.height");
+ expect(source).toContain("cancelAnimationFrame(frame)");
+ expect(source).not.toContain("fitView fitViewOptions=");
+ });
+});
diff --git a/scripts/lib/bundle-report.mjs b/scripts/lib/bundle-report.mjs
new file mode 100644
index 00000000..f7a93a49
--- /dev/null
+++ b/scripts/lib/bundle-report.mjs
@@ -0,0 +1,71 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { gzipSync, brotliCompressSync, constants } from 'node:zlib';
+
+const ROUTE = '/[[...slug]]/page';
+const ENTRY = '[project]/app' + ROUTE;
+const sum = rows => ({ files: rows.length, bytes: rows.reduce((n, r) => n + r.bytes, 0),
+ gzip: rows.reduce((n, r) => n + r.gzip, 0), brotli: rows.reduce((n, r) => n + r.brotli, 0) });
+
+export function parseClientManifest(source) {
+ // Read the generated JSON assignment without evaluating JavaScript from the build.
+ const match = source.match(/globalThis\.__RSC_MANIFEST\["[^" ]+"\]\s*=\s*(\{[\s\S]*\});?\s*$/);
+ if (!match) throw new Error('Unsupported client manifest format; update the parser, do not skip the budget');
+ return JSON.parse(match[1]);
+}
+
+export function readBundleReport(root = process.cwd()) {
+ const build = path.resolve(root, '.next');
+ const readJson = file => JSON.parse(fs.readFileSync(path.join(build, file), 'utf8'));
+ const manifest = parseClientManifest(fs.readFileSync(path.join(build, 'server/app' + ROUTE + '_client-reference-manifest.js'), 'utf8'));
+ const main = readJson('build-manifest.json');
+ const entryPaths = manifest.entryJSFiles?.[ENTRY];
+ const cssPaths = manifest.entryCSSFiles?.[ENTRY]?.map(row => row.path);
+ if (!entryPaths?.length || !cssPaths?.length || !main.rootMainFiles?.length) throw new Error('Missing shell entry chunks or styles');
+ const normalize = asset => {
+ if (typeof asset !== 'string') throw new Error('Invalid bundle asset path');
+ const relative = asset.replace(/^\/_next\//, '');
+ const resolved = path.resolve(build, relative);
+ if (!relative.startsWith('static/') || !resolved.startsWith(build + path.sep)) throw new Error('Bundle asset escaped static build root');
+ return relative;
+ };
+ const measure = paths => [...new Set(paths.map(normalize))].map(file => {
+ const data = fs.readFileSync(path.join(build, file));
+ return { path: file, bytes: data.length, gzip: gzipSync(data).length,
+ brotli: brotliCompressSync(data, { params: { [constants.BROTLI_PARAM_QUALITY]: 6 } }).length };
+ });
+ const runtime = measure(main.rootMainFiles);
+ const entry = measure(entryPaths);
+ const chunks = measure([...main.rootMainFiles, ...entryPaths]);
+ const styles = measure(cssPaths);
+ const fontFiles = measure(readJson('server/next-font-manifest.json').app?.[ENTRY] ?? []);
+ const contents = chunks.map(row => fs.readFileSync(path.join(build, row.path), 'utf8'));
+ const signatures = {
+ ReactFlow: 'react-flow__renderer',
+ Konva: 'Konva error',
+ Xterm: 'xterm-screen',
+ ONNX: 'ort-wasm-simd-threaded',
+ };
+ const initialHeavyModules = Object.entries(signatures).filter(([, marker]) => contents.some(text => text.includes(marker))).map(([name]) => name);
+ return { schemaVersion: 1, next: JSON.parse(fs.readFileSync(path.join(root, 'node_modules/next/package.json'), 'utf8')).version,
+ measurement: 'Unique eager catch-all chunks plus framework runtime. Nomodule polyfills and runtime-triggered lazy downloads are separate. Compression is estimated, not network transfer.',
+ initial: sum(chunks), entry: sum(entry), runtime: sum(runtime), css: sum(styles), fonts: sum(fontFiles),
+ polyfills: measure(main.polyfillFiles ?? []), initialHeavyModules, chunks, styles, fontFiles };
+}
+
+export function bundleViolations(report, budget) {
+ const failures = [];
+ const validBytes = value => Number.isFinite(value) && value >= 0;
+ if (!budget?.gzipBytes || !Object.keys(budget.gzipBytes).length) return ['Missing gzip bundle budgets'];
+ for (const [name, cap] of Object.entries(budget.gzipBytes)) {
+ if (!validBytes(cap)) failures.push(`${name}: invalid budget`);
+ if (!validBytes(report?.[name]?.gzip)) failures.push(`${name}: missing measurement`);
+ else if (validBytes(cap) && report[name].gzip > cap) failures.push(`${name}: ${report[name].gzip} gzip bytes > ${cap}`);
+ }
+ if (!validBytes(budget.preloadedFontBytes)) failures.push('preloaded fonts: invalid budget');
+ if (!validBytes(report?.fonts?.bytes)) failures.push('preloaded fonts: missing measurement');
+ else if (validBytes(budget.preloadedFontBytes) && report.fonts.bytes > budget.preloadedFontBytes) failures.push(`preloaded fonts: ${report.fonts.bytes} > ${budget.preloadedFontBytes}`);
+ if (!Array.isArray(report?.initialHeavyModules)) failures.push('Missing eager engine scan');
+ else for (const name of report.initialHeavyModules) failures.push(`${name} runtime leaked into the eager shell graph`);
+ return failures;
+}
diff --git a/scripts/verify-build.sh b/scripts/verify-build.sh
index 332803a7..5ef090e7 100755
--- a/scripts/verify-build.sh
+++ b/scripts/verify-build.sh
@@ -46,6 +46,9 @@ if grep -Ei "(^|[[:space:]])warnings?[: ]|⚠" "$MSO_VERIFY_BUILD_LOG"; then
exit 41
fi
+echo "== verify: eager shell bundle budget"
+node scripts/check-bundle.mjs
+
echo "== verify 2/3: Playwright Chromium runtime"
if ! node scripts/ensure-playwright-browser.mjs; then
echo "verification failed while preparing the browser required by release E2E" >&2
@@ -71,6 +74,12 @@ if ! node scripts/e2e/shell-status.mjs; then
exit 43
fi
+echo "== verify deferred shell performance"
+if ! node scripts/e2e/bundle-performance.mjs; then
+ echo "verification failed during deferred shell performance E2E" >&2
+ exit 43
+fi
+
# Optional deeper media/native acceptance, using the same isolated built tree.
if [ "${1:-}" = "--extended" ]; then
echo "== verify extended: desktop native acceptance"
diff --git a/scripts/worktree-gates.test.ts b/scripts/worktree-gates.test.ts
index a0e0c6a3..4c8bb752 100644
--- a/scripts/worktree-gates.test.ts
+++ b/scripts/worktree-gates.test.ts
@@ -53,6 +53,13 @@ function fixture(script: string) {
path.join(repo, "scripts/e2e/shell-status.mjs"),
"import fs from 'node:fs'; if (!fs.existsSync('.build-verified') || fs.existsSync('.env.local')) throw Error('unsafe status fixture'); console.log('isolated shell status fixture passed');",
);
+ for (const [file, label] of [
+ ["scripts/check-bundle.mjs", "bundle budget"],
+ ["scripts/e2e/bundle-performance.mjs", "deferred performance"],
+ ]) {
+ writeFileSync(path.join(repo, file),
+ `import fs from 'node:fs'; if (!fs.existsSync('.build-verified') || fs.existsSync('.env.local')) throw Error('unsafe bundle fixture'); console.log('isolated ${label} fixture passed');`);
+ }
git("init", "-q");
git("add", "scripts");
git(
@@ -123,6 +130,8 @@ describe("isolated worktree release guards", () => {
expect(run.stdout).toContain("isolated E2E fixture passed");
expect(run.stdout).toContain("isolated shell fixture passed");
expect(run.stdout).toContain("isolated shell status fixture passed");
+ expect(run.stdout).toContain("isolated bundle budget fixture passed");
+ expect(run.stdout).toContain("isolated deferred performance fixture passed");
expect(readFileSync(path.join(repo, ".next/keep"), "utf8")).toBe(
"live marker",
);