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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
perf: get the shell chrome and the Alfa catalog out of first load
Rahman421ab7fe30ba
diff --git a/frontend/slices/appshell/components/chat-composer.tsx b/frontend/slices/appshell/components/chat-composer.tsxindex dcbce486..c7e45e5b 100644--- a/frontend/slices/appshell/components/chat-composer.tsx+++ b/frontend/slices/appshell/components/chat-composer.tsx@@ -1,12 +1,12 @@"use client";-import { useRef, useState, type KeyboardEvent } from "react";+import { useRef, useState, useSyncExternalStore, type KeyboardEvent } from "react";import { ArrowUp, Send, Sparkles, Square } from "lucide-react";import { Button } from "@/components/ui/button";import { Textarea } from "@/components/ui/textarea";import { cn } from "@/lib/utils";import { useActiveShell } from "../registry/shells";-import { alfaSources } from "../lib/alfa-sources";+import { alfaSources, subscribeAlfaSources, alfaSourcesVersion } from "../lib/alfa-sources";import { mentionAt, applyMention, rankMentions, type MentionItem } from "../lib/mentions";// THE composer. Every AI input in MSO renders this one — the Assistant app, the@@ -39,6 +39,11 @@ export function ChatComposer({const ref = useRef<HTMLTextAreaElement>(null);const canSend = value.trim().length > 0 && !streaming;const ios = useActiveShell().id === "ios";+ // Re-render when a source's data lands asynchronously: the consumer module is+ // imported on this component's first render, and its skills fetch starts on the+ // first `/`. `items` below is computed during render, so without this the new+ // rows would only appear on the user's next keystroke.+ useSyncExternalStore(subscribeAlfaSources, alfaSourcesVersion, () => 0);const agentName = alfaSources().activeAgentName?.() ?? null;const query = dismissed ? null : mentionAt(value, caret);diff --git a/frontend/slices/appshell/components/desktop.tsx b/frontend/slices/appshell/components/desktop.tsxindex 8a36ff52..091bde81 100644--- a/frontend/slices/appshell/components/desktop.tsx+++ b/frontend/slices/appshell/components/desktop.tsx@@ -1,33 +1,15 @@"use client";import { Suspense, useEffect, useMemo, useState, type ComponentType } from "react";-import { Monitor, Smartphone, Grid3x3, Minimize2, Maximize2, X } from "lucide-react";import { useResponsive } from "../responsive/use-responsive";-import { useWindowOrder, useWindowsMap } from "../hooks/use-shell";-import { stackByZ } from "../lib/store";import { inEditable } from "../lib/use-focused-hotkey";import { usePersistLayout } from "../hooks/use-persist-layout";-import { useOverviewKey } from "../hooks/use-overview-key";-import { MenuBar } from "./menu-bar";-import { Dock } from "./dock";-import { AppLauncher } from "./app-launcher";-import { HotCorners } from "./hot-corners";import { Wallpaper } from "./wallpaper";-import { MobileShell } from "./mobile-shell";-import { Window } from "./window";import { Slot } from "../registry/feature-registry";-import { toggleSpotlight, toggleInspector, snapWindow, cycleSnap, toggleMaximize, minimizeWindow, minimizeAll, restoreWindow, closeAll, shellStore } from "../lib/store";-import { WindowOverview } from "./shells/window-overview";-import { ForceQuitDialog } from "../features/force-quit/force-quit";-import { DesktopIcons, useDesktopMarquee } from "../features/desktop-icons";-import { NotificationCenter } from "./notification-center";-import { AppSwitcher } from "./app-switcher";-import { ShellContextMenu, useShellContextMenu, type MenuItem } from "./shells/context-menu";+import { toggleSpotlight, toggleInspector, snapWindow, cycleSnap, toggleMaximize, minimizeWindow, shellStore } from "../lib/store";import { ContextMenuHost } from "./shells/context-menu-host";-import { registerShell, resolveShell, useShellPrefs, ActiveShellProvider } from "../registry/shells";-import { useShellAppearance } from "../registry/capabilities";-import { cn } from "@/lib/utils";-// side-effects: shell registrations (windows/android/dashboard lazy) + palette commands+import { resolveShell, useShellPrefs, ActiveShellProvider } from "../registry/shells";+// side-effects: all five shell registrations (lazy) + palette commandsimport "../registry/register-shells";import "../lib/window-commands";import "../lib/spaces";@@ -177,71 +159,3 @@ function useWindowSnapKeys(enabled: boolean) {return () => window.removeEventListener("keydown", onKey);}, [enabled]);}--function DesktopChrome() {- const order = useWindowOrder();- const winMap = useWindowsMap();- // Paint windows in z-order (focus recency) so the visible stack matches the- // store's MRU — unfocused windows share one CSS z tier, so DOM order is the- // tiebreak. winMap re-identifies on any window patch (incl. focus z bump).- const stacked = useMemo(() => stackByZ(order, winMap), [order, winMap]);- const [overview, setOverview] = useState(false);- const menu = useShellContextMenu("macos");- const marquee = useDesktopMarquee();- // An interactive live wallpaper needs empty-desktop clicks to reach it: the- // window layer goes transparent to hit-testing, its windows stay clickable.- const interactive = !!useShellAppearance().liveWallpaper?.interactive;- useOverviewKey(() => setOverview(true));- // Built-in items — passed at open time so they read current state. Registry- // items (consumer/app, dynamic per shell) merge after these.- const baseItems: MenuItem[] = [- { label: "Mission Control", icon: Grid3x3, onClick: () => setOverview(true) },- { type: "sep" },- { label: "Show all windows", icon: Maximize2, disabled: order.length === 0, onClick: () => order.forEach((id) => shellStore.getWindow(id)?.minimized && restoreWindow(id)) },- { label: "Minimize all", icon: Minimize2, disabled: order.length === 0, onClick: () => minimizeAll() },- { label: "Close all", icon: X, disabled: order.length === 0, onClick: () => closeAll() },- ];- return (- <>- <MenuBar />- <section- className={cn("absolute inset-x-0 bottom-0 top-[30px] z-[10]", interactive && "pointer-events-none [&>*]:pointer-events-auto")}- // Open the desktop menu for any right-click NOT inside a window. Icons +- // widgets stopPropagation their own menus (never reach here); windows are- // excluded via [data-window]. The old `target===currentTarget` guard- // silently missed clicks whose target was a background descendant.- onContextMenu={(e) => { if (!(e.target as HTMLElement).closest("[data-window]")) menu.open(e, baseItems); }}- onPointerDown={marquee.onPointerDown}- >- {/* Icons + widgets live INSIDE the section (behind windows: z-[4]/z-[5] <- window z-10+) so their own right-click / drag beats the desktop menu +- marquee, which only fire on the bare surface. */}- <DesktopIcons />- <Slot region="desktopWidgets" />- {marquee.rect && (- <div- className="pointer-events-none absolute z-[6] rounded-sm border border-primary bg-primary/15"- style={{ left: marquee.rect.x, top: marquee.rect.y, width: marquee.rect.w, height: marquee.rect.h }}- />- )}- {stacked.map((id) => (- <Window key={id} id={id} />- ))}- </section>- <Slot region="rightPanel" />- <NotificationCenter />- <AppSwitcher />- <AppLauncher />- <Dock onMissionControl={() => setOverview(true)} />- <HotCorners onMissionControl={() => setOverview(true)} />- {overview && <WindowOverview onClose={() => setOverview(false)} label="Mission Control" />}- <ForceQuitDialog />- <ShellContextMenu state={menu.state} onClose={menu.close} />- </>- );-}--// The two built-in shells. Later phases register windows / dashboard / android /-// mobile-dashboard into the same registry.-registerShell({ id: "macos", label: "macOS", icon: Monitor, surface: "desktop", group: "Desktop", windowed: true, wallpaper: "aurora", render: DesktopChrome });-registerShell({ id: "ios", label: "iOS", icon: Smartphone, surface: "mobile", group: "Mobile", wallpaper: "ios", render: MobileShell });diff --git a/frontend/slices/appshell/components/shells/macos/macos-shell.tsx b/frontend/slices/appshell/components/shells/macos/macos-shell.tsxnew file mode 100644index 00000000..2d78ca89--- /dev/null+++ b/frontend/slices/appshell/components/shells/macos/macos-shell.tsx@@ -0,0 +1,96 @@+"use client";++// The macOS chrome — menu bar, desktop surface + window layer, dock, launcher,+// Mission Control. Split out of desktop.tsx so it can be React.lazy()'d in+// register-shells.tsx: it used to sit in the same module as Surface, which put+// every byte of it (and, through the same file, the whole iOS shell) in the+// first-load chunk of every visitor regardless of which shell they resolve to.++import { useMemo, useState } from "react";+import { Grid3x3, Minimize2, Maximize2, X } from "lucide-react";+import { useWindowOrder, useWindowsMap } from "../../../hooks/use-shell";+import { useOverviewKey } from "../../../hooks/use-overview-key";+import {+ stackByZ,+ shellStore,+ minimizeAll,+ restoreWindow,+ closeAll,+} from "../../../lib/store";+import { MenuBar } from "../../menu-bar";+import { Dock } from "../../dock";+import { AppLauncher } from "../../app-launcher";+import { HotCorners } from "../../hot-corners";+import { Window } from "../../window";+import { NotificationCenter } from "../../notification-center";+import { AppSwitcher } from "../../app-switcher";+import { WindowOverview } from "../window-overview";+import { ShellContextMenu, useShellContextMenu, type MenuItem } from "../context-menu";+import { Slot } from "../../../registry/feature-registry";+import { useShellAppearance } from "../../../registry/capabilities";+import { ForceQuitDialog } from "../../../features/force-quit/force-quit";+import { DesktopIcons, useDesktopMarquee } from "../../../features/desktop-icons";+import { cn } from "@/lib/utils";++export function DesktopChrome() {+ const order = useWindowOrder();+ const winMap = useWindowsMap();+ // Paint windows in z-order (focus recency) so the visible stack matches the+ // store's MRU — unfocused windows share one CSS z tier, so DOM order is the+ // tiebreak. winMap re-identifies on any window patch (incl. focus z bump).+ const stacked = useMemo(() => stackByZ(order, winMap), [order, winMap]);+ const [overview, setOverview] = useState(false);+ const menu = useShellContextMenu("macos");+ const marquee = useDesktopMarquee();+ // An interactive live wallpaper needs empty-desktop clicks to reach it: the+ // window layer goes transparent to hit-testing, its windows stay clickable.+ const interactive = !!useShellAppearance().liveWallpaper?.interactive;+ useOverviewKey(() => setOverview(true));+ // Built-in items — passed at open time so they read current state. Registry+ // items (consumer/app, dynamic per shell) merge after these.+ const baseItems: MenuItem[] = [+ { label: "Mission Control", icon: Grid3x3, onClick: () => setOverview(true) },+ { type: "sep" },+ { label: "Show all windows", icon: Maximize2, disabled: order.length === 0, onClick: () => order.forEach((id) => shellStore.getWindow(id)?.minimized && restoreWindow(id)) },+ { label: "Minimize all", icon: Minimize2, disabled: order.length === 0, onClick: () => minimizeAll() },+ { label: "Close all", icon: X, disabled: order.length === 0, onClick: () => closeAll() },+ ];+ return (+ <>+ <MenuBar />+ <section+ className={cn("absolute inset-x-0 bottom-0 top-[30px] z-[10]", interactive && "pointer-events-none [&>*]:pointer-events-auto")}+ // Open the desktop menu for any right-click NOT inside a window. Icons ++ // widgets stopPropagation their own menus (never reach here); windows are+ // excluded via [data-window]. The old `target===currentTarget` guard+ // silently missed clicks whose target was a background descendant.+ onContextMenu={(e) => { if (!(e.target as HTMLElement).closest("[data-window]")) menu.open(e, baseItems); }}+ onPointerDown={marquee.onPointerDown}+ >+ {/* Icons + widgets live INSIDE the section (behind windows: z-[4]/z-[5] <+ window z-10+) so their own right-click / drag beats the desktop menu ++ marquee, which only fire on the bare surface. */}+ <DesktopIcons />+ <Slot region="desktopWidgets" />+ {marquee.rect && (+ <div+ className="pointer-events-none absolute z-[6] rounded-sm border border-primary bg-primary/15"+ style={{ left: marquee.rect.x, top: marquee.rect.y, width: marquee.rect.w, height: marquee.rect.h }}+ />+ )}+ {stacked.map((id) => (+ <Window key={id} id={id} />+ ))}+ </section>+ <Slot region="rightPanel" />+ <NotificationCenter />+ <AppSwitcher />+ <AppLauncher />+ <Dock onMissionControl={() => setOverview(true)} />+ <HotCorners onMissionControl={() => setOverview(true)} />+ {overview && <WindowOverview onClose={() => setOverview(false)} label="Mission Control" />}+ <ForceQuitDialog />+ <ShellContextMenu state={menu.state} onClose={menu.close} />+ </>+ );+}diff --git a/frontend/slices/appshell/lib/alfa-sources.test.ts b/frontend/slices/appshell/lib/alfa-sources.test.tsnew file mode 100644index 00000000..c1f0035d--- /dev/null+++ b/frontend/slices/appshell/lib/alfa-sources.test.ts@@ -0,0 +1,66 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++// Module-level state, so each case gets a fresh copy.+async function fresh() {+ vi.resetModules();+ return import("./alfa-sources");+}++const ITEM = { id: "tool:x", label: "x", insert: "x", kind: "command" as const };++describe("alfa-sources loader", () => {+ beforeEach(() => vi.resetModules());++ it("returns empty sources and starts nothing when no loader is registered", async () => {+ const m = await fresh();+ expect(m.alfaSources().commands()).toEqual([]);+ expect(m.alfaSources().agents()).toEqual([]);+ });++ it("runs the loader on the FIRST alfaSources() call and never again", async () => {+ const m = await fresh();+ const load = vi.fn();+ m.registerAlfaLoader(load);+ m.alfaSources();+ m.alfaSources();+ m.alfaSources();+ expect(load).toHaveBeenCalledTimes(1);+ });++ it("serves what the loader registered, and notifies so the composer re-renders", async () => {+ const m = await fresh();+ const seen = vi.fn();+ m.subscribeAlfaSources(seen);+ // Mirrors production: the real loader awaits a dynamic import first.+ m.registerAlfaLoader(async () => {+ await Promise.resolve();+ m.registerAlfaSources({ agents: () => [], commands: () => [ITEM] });+ });+ expect(m.alfaSources().commands()).toEqual([]); // first paint: chunk not in yet+ await vi.waitFor(() => expect(m.alfaSources().commands()).toEqual([ITEM]));+ expect(seen).toHaveBeenCalled();+ });++ it("re-arms after a failed load, so a dead chunk is not permanent", async () => {+ const m = await fresh();+ const load = vi.fn().mockRejectedValueOnce(new Error("ChunkLoadError"));+ m.registerAlfaLoader(load);+ m.alfaSources();+ await vi.waitFor(() => expect(load).toHaveBeenCalledTimes(1));+ m.alfaSources();+ expect(load).toHaveBeenCalledTimes(2);+ });++ it("bumps the version on every notify, and stops after unsubscribe", async () => {+ const m = await fresh();+ const seen = vi.fn();+ const off = m.subscribeAlfaSources(seen);+ const before = m.alfaSourcesVersion();+ m.notifyAlfaSources();+ expect(m.alfaSourcesVersion()).toBe(before + 1);+ expect(seen).toHaveBeenCalledTimes(1);+ off();+ m.notifyAlfaSources();+ expect(seen).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/slices/appshell/lib/alfa-sources.ts b/frontend/slices/appshell/lib/alfa-sources.tsindex 55885859..537e3dab 100644--- a/frontend/slices/appshell/lib/alfa-sources.ts+++ b/frontend/slices/appshell/lib/alfa-sources.ts@@ -22,11 +22,51 @@ export type AlfaSources = {const NO_SOURCES: AlfaSources = { agents: () => [], commands: () => [] };let sources: AlfaSources = NO_SOURCES;+const subs = new Set<() => void>();+let version = 0;++// The consumer's source module is worth ~88 KB of chunk (tool catalog, its run()+// closures, agent presets) and NOTHING renders it until an AI composer exists. So+// the consumer registers a LOADER instead of importing eagerly, and the first+// composer render is what pulls it in.+let loader: (() => void | Promise<void>) | null = null;+let loaderStarted = false;++export function registerAlfaLoader(fn: () => void | Promise<void>): void {+ loader = fn;+}+export function registerAlfaSources(next: AlfaSources): void {sources = next;+ notifyAlfaSources();+}++/** Call when a getter's data lands asynchronously (the skills fetch). The composer+ * computes its item list DURING render — deliberately, see chat-composer — so+ * without this the new rows only appear on the user's next keystroke. */+export function notifyAlfaSources(): void {+ version++;+ for (const cb of subs) cb();+}++export function subscribeAlfaSources(cb: () => void): () => void {+ subs.add(cb);+ return () => {+ subs.delete(cb);+ };+}++export function alfaSourcesVersion(): number {+ return version;}export function alfaSources(): AlfaSources {+ if (loader && !loaderStarted) {+ loaderStarted = true;+ // Fire and forget: the loader calls registerAlfaSources, which notifies.+ void Promise.resolve(loader()).catch(() => {+ loaderStarted = false; // a failed chunk may succeed on the next open+ });+ }return sources;}-diff --git a/frontend/slices/appshell/registry/register-shells.tsx b/frontend/slices/appshell/registry/register-shells.tsxindex b0b26d44..510afcb8 100644--- a/frontend/slices/appshell/registry/register-shells.tsx+++ b/frontend/slices/appshell/registry/register-shells.tsx@@ -1,16 +1,40 @@"use client";-// Lazy shell registration. The non-default shells (Windows / Android / Dashboard)-// register their METADATA eagerly here — so resolveShell() + the shell switcher-// work at startup — but their COMPONENT is React.lazy, so each becomes its own-// chunk: a phone never downloads the desktop chrome it can't reach by default.-// The Surface (desktop.tsx) wraps the shell in <Suspense>, so SSR renders the-// fallback rather than a client-only shell (also removes the #418 hydration-// mismatch). macOS + iOS stay EAGER in desktop.tsx (zero-flash defaults; their-// components share desktop.tsx with the Surface, so they can't split cleanly here).+// Lazy shell registration. Every shell registers its METADATA eagerly here — so+// resolveShell() + the shell switcher work at startup — but its COMPONENT is+// React.lazy, so each becomes its own chunk: a phone never downloads the desktop+// chrome it cannot reach, and a desktop never downloads the phone chrome.+//+// macOS + iOS used to be EAGER, registered inside desktop.tsx because DesktopChrome+// shared that module with Surface. The measured cost of that convenience was one+// 267 KB first-load chunk carrying BOTH chromes plus every shell feature to every+// visitor. DesktopChrome now lives in components/shells/macos/, so all five split+// the same way. Surface wraps the shell in <Suspense fallback={null}> and paints+// the wallpaper outside it, so the pre-chrome frame shows the themed background —+// the same trade the post-mount render already makes for hydration correctness.import { lazy } from "react";-import { AppWindow, Bot, Activity } from "lucide-react";+import { AppWindow, Bot, Activity, Monitor, Smartphone } from "lucide-react";import { registerShell } from "./shells";+registerShell({+ id: "macos",+ label: "macOS",+ icon: Monitor,+ surface: "desktop",+ group: "Desktop",+ windowed: true,+ wallpaper: "aurora",+ render: lazy(() => import("../components/shells/macos/macos-shell").then((m) => ({ default: m.DesktopChrome }))),+});+registerShell({+ id: "ios",+ label: "iOS",+ icon: Smartphone,+ surface: "mobile",+ group: "Mobile",+ wallpaper: "ios",+ render: lazy(() => import("../components/mobile-shell").then((m) => ({ default: m.MobileShell }))),+});+registerShell({id: "windows",label: "Windows",diff --git a/frontend/slices/assistant/lib/alfa-sources.ts b/frontend/slices/assistant/lib/alfa-sources.tsindex 36a7e48b..6e06aae6 100644--- a/frontend/slices/assistant/lib/alfa-sources.ts+++ b/frontend/slices/assistant/lib/alfa-sources.ts@@ -1,6 +1,6 @@"use client";-import { registerAlfaSources, type MentionItem } from "@/features/os-shell";+import { notifyAlfaSources, registerAlfaSources, type MentionItem } from "@/features/os-shell";import { HOST_TOOLS } from "../host-tools/catalog";import { activeAgent, agentList, setActiveAgentId } from "./store";@@ -14,8 +14,11 @@ import { activeAgent, agentList, setActiveAgentId } from "./store";// exists — `skills.read` is a tool, so naming a skill is enough for Alfa to go and// read it. No new endpoint, no attachment plumbing, no second execution path.//-// Skills are fetched ONCE and cached for the tab. There are ~88 of them and the-// menu filters on every keystroke; refetching per keystroke would be absurd.+// Skills are fetched ONCE and cached for the tab, and NOT until the first `/`.+// There are ~88 of them, the read is ~600 KB of SKILL.md off disk server-side, and+// nothing renders them until that menu opens — it used to run on every signed-in+// page load. There are ~88 and the menu filters on every keystroke; refetching per+// keystroke would be absurd.type SkillRow = { name: string; description?: string };@@ -41,6 +44,7 @@ function loadSkills(): void {}).finally(() => {inflight = null;+ notifyAlfaSources(); // the composer computes its list during render});}@@ -56,13 +60,14 @@ const toolItems: MentionItem[] = HOST_TOOLS.map((t) => ({}));/**- * Publish @ and / to the shared composer. Called ONCE from os-shell/integrations,- * not from the Assistant app: neither source needs that app to be open (HOST_TOOLS- * is a static array, skills are one fetch), and requiring it would leave the menus- * empty in exactly the surface that needs them most — the per-app Alfa sheet.+ * Publish @ and / to the shared composer. Registered as a LOADER from+ * os-shell/integrations rather than called at module scope, so this module (tool+ * catalog + its run() closures + agent presets, ~88 KB) stays out of first load;+ * the first composer render pulls it in. Not called from the Assistant app either:+ * requiring that app to be open would leave the menus empty in exactly the surface+ * that needs them most — the per-app Alfa sheet.*/export function installAlfaSources(): void {- loadSkills();registerAlfaSources({agents: () =>agentList().map((a) => ({@@ -80,7 +85,10 @@ export function installAlfaSources(): void {// 8 rows — skills-first meant a bare "/" only ever showed skills and the// executable tools were unreachable without typing their name. Filtering still// reaches everything; this only decides what an empty query shows.- commands: () => [...toolItems, ...(skillCache ?? [])],+ commands: () => {+ loadSkills(); // first `/` starts the fetch; tools render immediately+ return [...toolItems, ...(skillCache ?? [])];+ },activeAgentName: () => activeAgent()?.name ?? null,});}diff --git a/frontend/slices/os-shell/integrations.ts b/frontend/slices/os-shell/integrations.tsindex f943b445..1ef94e8a 100644--- a/frontend/slices/os-shell/integrations.ts+++ b/frontend/slices/os-shell/integrations.ts@@ -9,6 +9,7 @@ import {lock,openWindow,registerCommands,+ registerAlfaLoader,registerContextMenu,resetDesktopIcons,setAddDialog,@@ -18,12 +19,16 @@ import {toast,type MenuItem,} from "@/features/appshell";-import { installAlfaSources } from "@/features/assistant";// @ agents and / skills+tools for every AI composer. Registered here rather than// from the Assistant app so the menus work in the per-app Alfa sheet before that-// app has ever been opened. Pulls only the tool catalog + presets, not the UI.-installAlfaSources();+// app has ever been opened — but as a LOADER, not an eager import: the catalog and+// presets are ~88 KB that nothing renders until a composer exists, and the module+// also fired a /api/skills read (90 files, ~600 KB off disk) on every page load.+registerAlfaLoader(async () => {+ const { installAlfaSources } = await import("@/features/assistant");+ installAlfaSources();+});// Unlock = the signed session cookie is still valid. A dead session falls// through to false; the user reloads and lands on the login gate instead.