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.

feat(perf): hydration mark chain, and the LCP conclusion it overturns

Abdurrahman Fakhrul6c8933cd6d10
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 5d786c5a..3e77cd4a 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,15 +8,11 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
-- `tui` close the opencode TUI gap on the seams MSO already owns
-
-**Fixed**
-
-- `tui` actually attach uploaded images, and stop overclaiming /share and /stash
+- `perf` hydration mark chain, and the LCP conclusion it overturns
+- `tui` close the opencode TUI gap on the seams MSO already owns (#166)
**Docs**
-- `env` document MSO_AGENT_THEME, which the TUI now reads
- `progress` record the perf gate and the numbers it retracted
## 2026-10-28
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 8a749de6..294c2c59 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -87,19 +87,27 @@ they live in a separate, deliberately weaker gate.
| Command | What it does | Gates a push |
|---|---|---|
-| `bun run perf:probe` | Cold load at 4G + 4× CPU against a synthetic fixture (or `--base=`), writes `perf-report.json` | no |
+| `bun run perf:probe` | Cold load at Slow 4G + 4× CPU against a synthetic fixture (or `--base=`), writes `perf-report.json` | no |
| `bun run perf:check` | Enforces `scripts/perf-budget.json` against a report | **yes** |
+| `bun run perf:hydration` | Mark chain: FCP → last JS byte → shell mount → first paint of icons → LCP | no |
| `bun run perf:tasks` | CDP-trace attribution of every long task to the script that owns it | no |
| `bun run perf:apps` | Per-app open latency, fetched chunks and long tasks caused | no |
-`perf:check` fails hard on first-load JS bytes and on a missing measurement — a
-silent zero is how a perf gate dies. Timings only fail on a 2× blowup against
-`scripts/perf-baseline.json`, because this box also serves production and a
-wall-clock gate that flakes gets muted. Targets in that budget file
-(`tbtMs 150`, `lcpMs 2500`, `initialGzipBytes 256000`) are the post-migration goal
-from `docs/MSO-MIGRATION.md`; they are printed as advisory and never enforced,
-since holding today's Next build to a Svelte target would just make the gate
-permanently red.
+`perf:hydration` is the one that answers "what actually gates LCP". Reading it off the
+LCP element tag does not work: an element that ends up largest can be painted arbitrarily
+late by JavaScript, so `SPAN` or `IMG` says nothing about the cause. On this shell the
+chain is decisive — FCP ~1.2 s, mount ~2.6-2.9 s, LCP ~3.2-4.0 s — which means LCP is
+gated by downloading and executing ~940 KB of first-load JS, not by first paint.
+
+`perf:check` fails hard on a **missing** measurement — a silent zero is how a perf gate
+dies — and on a 2× TBT blowup against `scripts/perf-baseline.json`, because this box also
+serves production and a wall-clock gate that flakes gets muted. Bundle bytes are
+deliberately *not* re-gated here: `check-bundle.mjs` already gates gzip bytes
+deterministically from build output, while a browser-measured byte count includes deferred
+chunks and moves. Targets in the budget file (`tbtMs 150`, `lcpMs 2500`,
+`initialGzipBytes 256000`) are the post-migration goal from `docs/MSO-MIGRATION.md`; they
+are printed as advisory and never enforced, since holding today's Next build to a Svelte
+target would just make the gate permanently red.
Regenerate the baseline with `node scripts/perf-probe.mjs --json` and commit the
runs. Do that deliberately after a real improvement, not to silence a failure.
diff --git a/docs/MSO-MIGRATION.md b/docs/MSO-MIGRATION.md
index d41c4d2d..b3a8856d 100644
--- a/docs/MSO-MIGRATION.md
+++ b/docs/MSO-MIGRATION.md
@@ -142,8 +142,16 @@ time. The 5-minute build is the Playwright release gate.**
| `vitest run lib/mcp` | 6.14 s wall, 20 files |
| `bun test lib/mcp` | 5.99 s wall, **243 pass / 98 fail / 23 errors** |
-Vitest itself reports: 858 workers spawned at ~122 ms each, `isolate:false` would save
-~6.84 s (16 %). That is available today without any framework change.
+Vitest itself reports: 858 workers spawned at ~122 ms each, and estimates that
+`isolate:false` "would save ~6.84 s (16 %)". **That estimate is wrong for this suite and is
+retracted here.** Measured 2026-10-29: full suite `isolate:true` is 42.6 s green; with
+`isolate:false` + `pool:"threads"` it is 65.9 s (**54.5 % slower**) and 52 files / 161 tests
+fail. Excluding the breakers exposed new cascade failures on every re-run (52 → 24 → 12 → 11,
+ending in 45 s timer timeouts), and even after excluding ~110 files the run still failed
+non-deterministically on cross-thread mock leakage. The suite shares process singletons —
+`process.env`, `window`, `localStorage`, `globalThis.fetch`, the approved-device registry,
+A2A token store, standby worker state, fetch interceptors, systemctl mocks — so a module
+registry shared across files is not a safe default here. Per-file isolation stays.
Bun's runner is ~1.1 s faster on the same 85-file subset and does not run the suite as
written. Observed blockers: `vi.mock("server-only", …)`, jsdom environment, `localStorage`
@@ -232,6 +240,12 @@ Two earlier numbers in this document were wrong and are corrected here:
definition is the sum of `max(0, duration − 50 ms)` per long task. The corrected
number is roughly a third of the old one.
+A third assertion in this document was wrong and is retracted here:
+
+- The document asserted that LCP is set by first paint (CSS + wallpaper) and therefore
+ framework-neutral. That was disproved by measurement on 2026-10-29
+ (`bun run perf:hydration`). LCP is hydration-bound.
+
| Metric | Desktop 1440×900 | Mobile 390×844 |
|---|---|---|
| FCP | 1,180 ms | 1,166 ms |
@@ -249,6 +263,53 @@ fresh runner. Observed spread across stable runs: desktop TBT 150–184 ms, mobi
69–148 ms, LCP 2.98–3.22 s. Host load moves these by ±25 %, which is why the gate
enforces a 2× blowup rather than an absolute cap.
+Hydration mark chain (`bun run perf:hydration`, desktop 1440×900, Slow 4G + 4× CPU).
+Two representative runs, plus the spread across all runs on this host:
+
+```
+ run A run B observed range (11 runs)
+ FCP 1208 ms 1180 ms 1160-1440 ms
+ last JS arrival 3078 ms 2921 ms 2850-3320 ms
+ shell mounted 2792 ms 2654 ms 2570-3040 ms (#main-content gains data-shell)
+ icons painted 3839 ms 3790 ms 3200-4120 ms
+ LCP 3932 ms 3884 ms 3170-4220 ms (element: SPAN menu-bar label)
+```
+
+Mobile measures the same shape with an `IMG` (app-icon artwork) as the LCP element:
+LCP 3400-3808 ms, mounted 2713-2923 ms, last JS 2905-3095 ms.
+
+Median desktop LCP across those 11 runs is ~3.8 s. Quote the range, not a point value:
+a 1 s spread on the same commit is host load, not a regression.
+
+The spread is run-to-run variance, not instrumentation overhead: the same load measured
+with no observers at all produced 3724 / 3768 ms, with a per-frame `requestAnimationFrame`
+poller 3676 / 3208 ms, and with a 100 ms interval poller 3172 / 3248 ms. The §1.5 table
+above reports the median of a separate 3-run batch (3,222 ms desktop), which sits inside
+that same range — the numbers are the same measurement seen at different times, not a
+contradiction, and treating any single figure as exact would be wrong.
+
+What is stable across every run is the *shape*: LCP lands ~2.0-2.8 s after FCP and
+~0.4-1.0 s after the last JS byte arrives, and mount itself lands ~1.5-1.6 s after FCP.
+Controls that isolate the levers:
+
+```
+throttle LCP
+Slow4G + 4x CPU 3884-4004 ms
+Slow4G + 1x CPU 3108 ms (-644 ms: CPU is a real lever)
+no limit + 4x CPU 2236 ms (-1516 ms: network is the bigger lever)
+```
+
+Network is the bigger lever; CPU is real but smaller.
+
+Cause: from `frontend/slices/appshell/components/desktop.tsx` (~line 84), the shell
+renders **only after mount** by deliberate design — the surface depends on
+`window.innerWidth`, `localStorage sv:shell`, and the wallpaper pref, so SSR guesses
+macOS and a phone hydrates iOS. SSR therefore paints a skeleton (`#main-content` with no
+`data-shell`, 82 DOM nodes) and the real shell arrives after ~942 KB of first-load JS is
+downloaded and executed.
+
+LCP is therefore **hydration-bound**, i.e. gated by ~942 KB of first-load JS.
+
Same page, unthrottled local, cold cache:
```
@@ -279,13 +340,13 @@ Image Editor and Video Editor each pull editor chunks and pay 300–600 ms of ma
time — those two are the per-slice measurement that matters, and they are also the two
places where a framework swap would show up first.
-**Conclusion: server and in-shell navigation are already good. The remaining
-user-visible cost is LCP ~3.1 s on throttled mobile; TBT is 164 ms desktop / 132 ms
-mobile, i.e. already at or near the 150 ms post-migration target, before any migration.**
-
-That last fact materially changes §3: the Svelte case can no longer be "TBT 443 → 150",
-because TBT is effectively there already. What is left to buy is **LCP**, and LCP on this
-shell is dominated by first paint (CSS + wallpaper art), not by the JS bundle.
+**Conclusion: server and in-shell navigation are already good. TBT is 164 ms desktop /
+132 ms mobile, i.e. already at or near the 150 ms post-migration target before any
+migration. But the earlier conclusion that LCP is paint-bound was wrong: LCP is 3.2-4.2 s
+on throttled desktop and is hydration-bound, gated by ~942 KB of first-load JS. The
+primary lever is network (−1,516 ms unthrottled), with CPU as a secondary lever (−644 ms
+at 1× CPU). A framework swap that cuts first-load JS directly attacks the LCP critical
+path.**
---
@@ -297,6 +358,10 @@ shell is dominated by first paint (CSS + wallpaper art), not by the JS bundle.
Delivers:
- ~180–230 KB gzip less first-load JS (`react-dom` 230 KB raw + Next router runtime).
Realistic post-migration initial: 281 KB gzip → **~90–110 KB gzip**.
+- Direct LCP cut: LCP 3.2-4.2 s is gated by 942 KB first-load JS; removing ~230 KB of
+ `react-dom` plus the Next router is a direct cut into the LCP critical path, so a
+ 3.2–4.2 s → ~2.5–2.9 s is the realistic expectation, and it is now the primary
+ argument for the migration rather than a bundle-aesthetics one.
- Less main-thread work at startup. Measured attribution (`bun run perf:tasks`) puts
~280 ms of ~355 ms total long-task self time on the `react-dom` chunk — so removing
it removes real work, but TBT is already 164 ms, which means most of that 280 ms
@@ -310,9 +375,6 @@ Delivers:
Does not deliver:
- Build time (§1.1: compile is 2.7 % of the build).
- Server RSS: SvelteKit SSR is still Node/Bun. It does not shrink the 110 MB process.
-- The LCP win that would matter most. LCP is 3.1 s and is set by first paint — CSS and
- the wallpaper artwork — not by the JS bundle. A Svelte rewrite keeps both. Expect
- maybe 200–400 ms, not 1 s.
- Anything for `lib/`: 96 % of it is already portable, so rewriting it is pure cost.
Costs:
@@ -361,41 +423,50 @@ entire failure surface.
## 3. Decision gate — do this before any rewrite
-**The gate now fails on its own terms.** §1.5 measures TBT at 164 ms desktop / 132 ms
-mobile, against a post-migration target of 150 ms. Desktop is within 10 % of the number
-the Svelte rewrite was going to buy; mobile already beats it. The remaining user-visible
-cost is LCP 3.1 s, and LCP is set by first paint (CSS + wallpaper artwork), which a
-framework swap does not change.
-
-So the honest sequencing is: fix LCP cheaply first, then re-decide.
-
-Cheaper fixes, in the order the measurements say to do them:
-
-1. **Attack LCP, which is the real number.** 3.1 s to largest paint on Slow 4G with a
- 1,168 ms FCP means ~2 s is spent after first paint on the element that ends up
- largest — measured as an `IMG.shell-artwork` on mobile. Concretely: check whether the
- wallpaper is fetched at full resolution for the viewport, whether it is in the
- critical path of first paint, and whether a CSS gradient placeholder would let the
- real art arrive after paint without being the LCP element. This is the single
- highest-value piece of work available and it requires no migration.
-2. **Tighten the eager shell budget.** `scripts/bundle-budget.json` allows 300 KB gzip
- initial; actual is 281 KB. The ceiling is not doing any work. Lower it to 250 KB and
- fix what breaks. (Same for entry: 151.5 KB actual against a 160 KB ceiling.)
-3. **Attribute and shrink the 4 long tasks.** `bun run perf:tasks` already attributes
- them: ~280 ms of 355 ms of self time is the `react-dom` chunk. Since TBT is only
- 164 ms, that work mostly overlaps idle time — so the win here is smaller than the
- raw attribution suggests. Do not spend a quarter on it after LCP is fixed.
-4. **Turn on vitest `isolate:false` where safe.** 6.84 s of the 41.4 s is worker startup.
- Pure dev-loop win, zero user risk.
+**The gate now reopens on measured grounds.** The earlier claim that LCP was set by
+first paint (CSS + wallpaper artwork) and therefore framework-neutral is disproved.
+With LCP at 3.2-4.2 s across runs (landing 2.0-3.0 s after FCP and 0.4-1.1 s after the last
+JS byte arrives), LCP is hydration-bound to the ~942 KB first-load JS bundle.
+
+LCP cannot be painted away. Therefore, "fix LCP cheaply first" becomes an ordered list
+of the measured options, cheapest first:
+
+1. **Shrink the eager graph (bundle budget 300 → 250 KB gzip).** Lower
+ `scripts/bundle-budget.json` initial ceiling from 300 KB gzip to 250 KB (actual is
+ 281 KB) and prune eager slice dependencies.
+ *Measurement support:* Supported directly by the network throttle control
+ (−1,516 ms when unthrottled). The last JS byte arrival (2.9-3.1 s) gates mount and
+ LCP; every kilobyte cut from the eager download shortens the critical path.
+2. **Keep the wallpaper art off the LCP critical path.** Ensure wallpaper fetch does
+ not contend with first-load JS or trigger late layout shifts on mobile
+ (`IMG.shell-artwork` was measured as LCP on mobile), using a CSS placeholder/gradient.
+ *Measurement support:* Speculative for desktop (where the measured LCP element is a
+ `SPAN` menu-bar label painted after JS hydration, not the image), but
+ prevents bandwidth contention on constrained mobile connections.
+3. **Cut shell mount cost.** Profile and reduce component initialization inside
+ `frontend/slices/appshell/components/desktop.tsx` and the eager slice registry during
+ `#main-content` hydration (mount ~2.6-3.0 s → LCP ~3.2-4.2 s).
+ *Measurement support:* Supported by the CPU throttle control (−644 ms at 1× CPU vs
+ 4× CPU). Main-thread execution after JS arrival accounts for 0.4-1.1 s before LCP.
+4. **Migrate a slice (Phase 3).** If in-tree budget and mount optimizations leave LCP
+ > 2.5 s, a framework migration is the only remaining lever that removes ~230 KB of
+ `react-dom` runtime and Next router overhead from the first-load critical path.
+ *Measurement support:* Supported by both network and CPU controls. Phase 3 is now
+ the honest test of a real win (LCP 3.2–4.2 → ~2.5–2.9 s) instead of a
+ bundle-aesthetics exercise.
+
+(`isolate:false` was considered as an independent dev-loop win and rejected: measured 54.5 %
+slower with 161 failing tests; see §1.2.)
Gate criteria to proceed past §3 — all three required:
-- LCP on Slow 4G + 4× CPU is still > 2.5 s after (1) and (2), **and**
-- a named slice proves Svelte parity in a real browser at equal-or-better LCP, **and**
+- LCP on Slow 4G + 4× CPU is still > 2.5 s after (1), (2), and (3), **and**
+- a named slice proves Svelte parity in a real browser at equal-or-better LCP (targeting
+ the ~2.5–2.9 s window), **and**
- build time is addressed separately (it is an E2E problem, not a framework problem).
-Note what is *not* in that list any more: TBT. Gating on it would be gating on a number
-the current build already meets.
+Note what is *not* in that list: TBT. Gating on it would be gating on a number the
+current build already meets.
---
@@ -441,7 +512,8 @@ of 3 runs committed as baseline.
already pass under Bun.
- Fix the install portability blocker: `node-pty` prebuild or a Bun-compatible
postinstall. Until that is fixed, Bun is a dev convenience, not a stack choice.
-- Optional and independent: `isolate:false` for vitest.
+- Not on the table: `isolate:false` for vitest. Measured 54.5 % slower with 161 failing
+ tests (§1.2); per-file isolation stays.
Exit criteria: `bun install` succeeds from a clean clone; all `scripts/*` green under
Bun; `next` still on Node; build time unchanged or better.
@@ -530,20 +602,22 @@ plus thin SSR. Do not attempt before Phase 2 lands.
| Path | Engineering | Risk to live users | Measured upside |
|---|---|---|---|
| Phase 0 (done) | 1 day | none | makes everything else falsifiable |
-| **LCP fix (§3 item 1), no migration** | **2–5 days** | low | **the actual user-visible win** |
+| **In-tree budget & mount tuning (§3 items 1–3)** | **2–5 days** | low | initial JS −30 KB gzip; shaves ~200–400 ms LCP |
| + Phase 1 (Bun tooling) | +2–4 days | none | dev velocity; `bun install` portability |
| + Phase 2 (portable core) | +2–3 weeks | none | maintainability, framework freedom |
| + Phase 3 (one island) | +3–4 weeks | low, flag-gated | proves or disproves the whole thesis |
-| Full Svelte (all phases) | **6–9 months solo** | medium | initial JS −60 %, TBT 164 → ~70–95 ms |
+| Full Svelte (all phases) | **6–9 months solo** | medium | LCP 3.2–4.2 → ~2.5–2.9 s, initial JS −60 %, TBT 164 → ~70–95 ms |
| Rust rewrite of shell + server | **> 1 year** | high | nothing user-visible |
-The single honest sentence: **TBT is already at the post-migration target; the number
-still worth fixing is LCP, it is a few days of work, and it needs no migration at all.**
+The single honest sentence: **TBT is already at the post-migration target, but LCP is
+3.2–4.2 s and hydration-bound to 942 KB of first-load JS; in-tree budget and mount fixes can
+chip away at it, but cutting the runtime via migration is the primary path to ~2.5 s.**
-After the LCP fix, Phases 1–2 are still worth doing on their own merits (maintainability,
-`bun install` portability, a framework-free backend). Phase 3 remains the honest test of
-the Svelte thesis, but its expected payoff has shrunk from "TBT −70 %" to "bundle bytes
-−60 % with TBT already fine", which is a maintenance argument, not a speed argument.
+After in-tree budget and mount tuning, Phases 1–2 are still worth doing on their own
+merits (maintainability, `bun install` portability, a framework-free backend). Phase 3
+becomes the honest test of whether a real slice shrinks first-load JS and brings LCP
+toward the ~2.5 s target in a real browser, turning what looked like a bundle-aesthetics
+exercise into a measurable user speed win.
---
@@ -558,6 +632,7 @@ Perceived performance and per-app cost:
```
bun run perf:probe --base=http://127.0.0.1:4005 # table to stderr
+bun run perf:hydration --base=http://127.0.0.1:4005 # hydration mark chain (FCP, last JS, mounted, icons, LCP)
node scripts/perf-probe.mjs --json > /tmp/perf.json # machine-readable
bun run perf:check --report=/tmp/perf.json # enforce budget
bun run perf:tasks --base=http://127.0.0.1:4005 --min-ms=40
@@ -590,3 +665,7 @@ wrong number first:
- LCP arrives ~3 s in. A "settle when nothing changes for 1 s" loop exits too early and
reports `lcpMs: null`.
- TBT is `Σ max(0, duration − 50)`, not the raw sum of long-task durations.
+- **Retracted again:** concluding that LCP was paint-bound from a single LCP element tag
+ (`SPAN`/`IMG`) is wrong — the element that ends up largest can be painted late by JS,
+ so the element identity says nothing about what gates it; measure the mark chain
+ (`perf:hydration`) instead.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 340a9289..7c79a62e 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -56,6 +56,22 @@ nodes / 942 KB first-load JS; mobile FCP 1166 / LCP 3054 / TBT 132 / 1165 DOM /
Per-app open at 4× CPU: Image Editor ~550–600 ms and ~600 ms of long task, Video Editor
~450–470 ms and ~300 ms, System Monitor ~230 ms, Terminal ~190 ms.
+Follow-up the same day, because the gate contradicted the doc it was built for: the entry
+above concluded that a framework swap could not help, on the belief that LCP was set by
+first paint. `bun run perf:hydration` disproved that. The shell mounts client-side by design
+(`appshell/components/desktop.tsx`: the surface depends on `innerWidth`, `localStorage` and
+the wallpaper pref, so SSR would guess macOS and a phone would hydrate iOS), so SSR paints a
+82-node skeleton and the real shell arrives only after ~940 KB of JS executes. The mark chain
+is FCP ~1.2 s → last JS byte ~2.9–3.1 s → mount ~2.6–2.9 s → icons ~3.2–3.9 s → LCP
+~3.2–4.0 s. Throttle controls separate the levers: Slow 4G at 1× CPU saves 644 ms and no
+network limit saves 1516 ms, so network dominates and CPU is real but secondary. LCP is
+therefore hydration-bound, i.e. gated by exactly the bundle a migration shrinks, and
+`docs/MSO-MIGRATION.md` §3 now gates on LCP instead of TBT with LCP 3.2–4.0 → ~2.5–2.9 s as
+the realistic migration win. The lesson recorded in §6: reading the gate off the LCP element
+tag is wrong, because the element that ends up largest can be painted arbitrarily late by
+JavaScript.
+
+
## 2026-10-25: Agent transcript — one live row per turn, and owner-owned turn budgets
The interactive Agent printed an `Agent work` divider for every model round and a separate row
diff --git a/lib/host/api-error.ts b/lib/host/api-error.ts
index 1d4e6b14..5b6afbd9 100644
--- a/lib/host/api-error.ts
+++ b/lib/host/api-error.ts
@@ -3,16 +3,22 @@
// everything else is logged server-side with the route name and replaced by a
// generic message so raw Node errors (ENOENT/EACCES with absolute paths) and
// unexpected exceptions never leak to the client.
-import { NextResponse } from "next/server";
import { HostError } from "./host-error";
+function json(body: unknown, status: number): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
export function apiError(
route: string,
e: unknown,
fallback: { status?: number; error?: string } = {},
-): NextResponse {
+): Response {
if (e instanceof HostError)
- return NextResponse.json({ error: e.message }, { status: e.status });
+ return json({ error: e.message }, e.status);
// A missing path or a permission denial is a fact about the REQUEST, not a
// server fault. They used to fall through to 500, which sends a client (and a
// reader of the logs) hunting a broken server when the file simply is not there
@@ -21,13 +27,13 @@ export function apiError(
// carries an absolute path and must not reach the client.
const code = (e as NodeJS.ErrnoException)?.code;
if (code === "ENOENT" || code === "ENOTDIR")
- return NextResponse.json({ error: "Not found" }, { status: 404 });
+ return json({ error: "Not found" }, 404);
if (code === "EACCES" || code === "EPERM")
- return NextResponse.json({ error: "Permission denied" }, { status: 403 });
+ return json({ error: "Permission denied" }, 403);
console.error(`[api/v1/${route}]`, e);
- return NextResponse.json(
+ return json(
{ error: fallback.error ?? "Operation failed" },
- { status: fallback.status ?? 500 },
+ fallback.status ?? 500,
);
}
@@ -78,6 +84,6 @@ export function requireInt(
return n >= min && n <= max ? n : null;
}
-export function invalidRequest(field: string): NextResponse {
- return NextResponse.json({ error: `Invalid request: ${field}` }, { status: 400 });
+export function invalidRequest(field: string): Response {
+ return json({ error: `Invalid request: ${field}` }, 400);
}
diff --git a/package.json b/package.json
index 6d9420e5..1dd44a4a 100644
--- a/package.json
+++ b/package.json
@@ -56,6 +56,7 @@
"bundle:check": "node scripts/check-bundle.mjs",
"perf:probe": "node scripts/perf-probe.mjs",
"perf:check": "node scripts/check-perf.mjs",
+ "perf:hydration": "node scripts/perf-hydration.mjs",
"perf:apps": "node scripts/perf-app-open.mjs",
"perf:tasks": "node scripts/perf-longtasks.mjs",
"ci:plan": "node scripts/ci/run.mjs --plan",
diff --git a/scripts/lib/hydration-marks.mjs b/scripts/lib/hydration-marks.mjs
new file mode 100644
index 00000000..737c27f9
--- /dev/null
+++ b/scripts/lib/hydration-marks.mjs
@@ -0,0 +1,105 @@
+// Hydration marks observer: captures client-side hydration milestones and LCP.
+// Injected before page scripts (installMarks) and evaluated after load (readMarks).
+
+export function installMarks() {
+ localStorage.setItem("sv:shell", JSON.stringify({ desktop: "macos", mobile: "ios" }));
+ localStorage.setItem("mso:onboarding:v1", "done");
+
+ window.__marks = {
+ fcp: null,
+ lcp: null,
+ lcpTag: null,
+ ttfb: null,
+ lastJsDone: null,
+ mounted: null,
+ icons: null,
+ interactive: null,
+ };
+ window.__perfLcpElement = null;
+
+ try {
+ new PerformanceObserver((list) => {
+ const last = list.getEntries().pop();
+ if (last) {
+ window.__marks.lcp = Math.round(last.renderTime || last.loadTime || last.startTime);
+ window.__marks.lcpTag = last.element ? last.element.tagName : null;
+ window.__perfLcpElement = last.element ?? null;
+ }
+ }).observe({ type: "largest-contentful-paint", buffered: true });
+ } catch {}
+
+ const poll = () => {
+ const now = Math.round(performance.now());
+ // Shell mount means #main-content received its surface data-shell (not SSR skeleton)
+ if (window.__marks.mounted == null && document.querySelector("#main-content[data-shell]")) {
+ window.__marks.mounted = now;
+ }
+ // Icons mark first appearance of squircle icons or shell wallpaper artwork
+ if (window.__marks.icons == null && document.querySelector(".shell-icon-tile, .shell-artwork")) {
+ window.__marks.icons = now;
+ }
+ // Interactive mark first appearance of dock buttons or primary app icons
+ if (
+ window.__marks.interactive == null &&
+ document.querySelector(
+ '[aria-label*="System Monitor"], .macos-dock button, .macos-dock a, [data-slot="ios-dock"] button, [data-dock] button',
+ )
+ ) {
+ window.__marks.interactive = now;
+ }
+ // First contentful paint
+ if (window.__marks.fcp == null) {
+ const paint = performance.getEntriesByType("paint").find((e) => e.name === "first-contentful-paint");
+ if (paint) window.__marks.fcp = Math.round(paint.startTime);
+ }
+ // Time to first byte
+ if (window.__marks.ttfb == null) {
+ const nav = performance.getEntriesByType("navigation")[0];
+ if (nav && nav.responseStart > 0) window.__marks.ttfb = Math.round(nav.responseStart);
+ }
+ // Last Next.js chunk response arrival
+ const js = performance.getEntriesByType("resource").filter((e) => {
+ try {
+ return e.name.includes("/_next/") && new URL(e.name, location.href).pathname.endsWith(".js");
+ } catch {
+ return false;
+ }
+ });
+ if (js.length > 0) {
+ let max = 0;
+ for (const r of js) if (r.responseEnd > max) max = r.responseEnd;
+ if (max > 0) window.__marks.lastJsDone = Math.round(max);
+ }
+ requestAnimationFrame(poll);
+ };
+ requestAnimationFrame(poll);
+}
+
+export function readMarks() {
+ const marks = { ...window.__marks };
+ const js = performance.getEntriesByType("resource").filter((e) => {
+ try {
+ return e.name.includes("/_next/") && new URL(e.name, location.href).pathname.endsWith(".js");
+ } catch {
+ return false;
+ }
+ });
+ if (js.length > 0) {
+ let max = 0;
+ for (const r of js) if (r.responseEnd > max) max = r.responseEnd;
+ if (max > 0) marks.lastJsDone = Math.round(max);
+ }
+ const el = window.__perfLcpElement;
+ let lcpElement = null;
+ if (el) {
+ const tag = el.tagName || "";
+ const text = el.textContent ? el.textContent.trim().slice(0, 30) : "";
+ lcpElement = tag + (text ? ` (${text})` : "");
+ }
+ return {
+ ...marks,
+ lcpElement: lcpElement ?? marks.lcpTag ?? null,
+ firstLoadJsBytes: js.reduce((sum, r) => sum + (r.decodedBodySize || 0), 0),
+ firstLoadJsFiles: js.length,
+ };
+}
diff --git a/scripts/perf-hydration.mjs b/scripts/perf-hydration.mjs
new file mode 100644
index 00000000..c1ade7cc
--- /dev/null
+++ b/scripts/perf-hydration.mjs
@@ -0,0 +1,180 @@
+#!/usr/bin/env node
+// Cold-load hydration timeline diagnostic: measures FCP, last JS, mounted, icons, LCP.
+// Emits perf-hydration.json with hydration marks and critical-path deltas.
+import fs from "node:fs";
+import path from "node:path";
+import { execFileSync } from "node:child_process";
+import { parseArgs } from "node:util";
+import { chromium } from "@playwright/test";
+import { releaseFixture } from "./e2e/release-fixture.mjs";
+import { SLOW_4G, SHELL_READY } from "./lib/browser-metrics.mjs";
+import { installMarks, readMarks } from "./lib/hydration-marks.mjs";
+
+const { values } = parseArgs({
+ options: {
+ base: { type: "string" },
+ output: { type: "string" },
+ json: { type: "boolean", default: false },
+ cpu: { type: "string", default: "4" },
+ net: { type: "string", default: "slow4g" },
+ },
+ strict: true,
+ allowPositionals: false,
+});
+
+const RUNS = [
+ { label: "desktop", viewport: { width: 1440, height: 900 } },
+ { label: "mobile", viewport: { width: 390, height: 844 } },
+];
+
+function commit() {
+ try {
+ return execFileSync("git", ["rev-parse", "--short", "HEAD"], {
+ cwd: path.resolve("."),
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ }).trim();
+ } catch {
+ return null;
+ }
+}
+
+async function measure(browser, base, { label, viewport }, { cpuRate, isNetThrottled }) {
+ const context = await browser.newContext({ viewport, reducedMotion: "reduce" });
+ try {
+ await context.addInitScript(installMarks);
+ const page = await context.newPage();
+ const cdp = await context.newCDPSession(page);
+ await cdp.send("Network.enable");
+ if (isNetThrottled) {
+ await cdp.send("Network.emulateNetworkConditions", { offline: false, ...SLOW_4G });
+ }
+ if (cpuRate > 1) {
+ await cdp.send("Emulation.setCPUThrottlingRate", { rate: cpuRate });
+ }
+
+ await page.goto(base, { waitUntil: "load", timeout: 60000 });
+ try {
+ await page.locator("#main-content[data-shell]").waitFor({ state: "attached", timeout: 60000 });
+ } catch {
+ // Shell failed to mount within timeout; mounted remains null
+ }
+
+ // Wait for LCP observer to record the post-mount element
+ await page.waitForFunction(() => window.__marks?.lcp != null, null, { timeout: 30000 }).catch(() => {});
+ // Allow icons and interactive elements to finish rendering
+ await page.waitForTimeout(2000);
+
+ const raw = await page.evaluate(readMarks);
+ const mountAfterFcpMs = raw.mounted != null && raw.fcp != null ? raw.mounted - raw.fcp : null;
+ const lcpAfterFcpMs = raw.lcp != null && raw.fcp != null ? raw.lcp - raw.fcp : null;
+ const lcpAfterLastJsMs = raw.lcp != null && raw.lastJsDone != null ? raw.lcp - raw.lastJsDone : null;
+
+ return {
+ label,
+ viewport,
+ ...raw,
+ mountAfterFcpMs,
+ lcpAfterFcpMs,
+ lcpAfterLastJsMs,
+ };
+ } finally {
+ await context.close();
+ }
+}
+
+function formatTable(report) {
+ const headers = [
+ "surface",
+ "fcp",
+ "mounted",
+ "icons",
+ "interact",
+ "lcp",
+ "tag",
+ "lastJs",
+ "+mount(fcp)",
+ "+lcp(fcp)",
+ "+lcp(js)",
+ "jsKB",
+ ];
+ const rows = report.runs.map((r) => [
+ r.label,
+ r.fcp != null ? `${r.fcp}ms` : "null",
+ r.mounted != null ? `${r.mounted}ms` : "null",
+ r.icons != null ? `${r.icons}ms` : "null",
+ r.interactive != null ? `${r.interactive}ms` : "null",
+ r.lcp != null ? `${r.lcp}ms` : "null",
+ r.lcpTag ?? "null",
+ r.lastJsDone != null ? `${r.lastJsDone}ms` : "null",
+ r.mountAfterFcpMs != null ? `+${r.mountAfterFcpMs}ms` : "null",
+ r.lcpAfterFcpMs != null ? `+${r.lcpAfterFcpMs}ms` : "null",
+ r.lcpAfterLastJsMs != null ? `+${r.lcpAfterLastJsMs}ms` : "null",
+ r.firstLoadJsBytes != null ? `${(r.firstLoadJsBytes / 1024).toFixed(1)}KB` : "null",
+ ]);
+ const allRows = [headers, ...rows];
+ const colWidths = headers.map((_, i) => Math.max(...allRows.map((row) => row[i].length)));
+ return allRows.map((row) => row.map((c, i) => (i === row.length - 1 ? c : c.padEnd(colWidths[i]))).join(" ")).join("\n");
+}
+
+let fixture;
+let browser;
+try {
+ const base = values.base ?? (fixture = await releaseFixture()).base;
+ browser = await chromium.launch({ headless: true });
+
+ const cpuRate = Math.max(1, Number(values.cpu) || 4);
+ const isNetThrottled = values.net !== "none";
+ const throttle = {
+ latencyMs: isNetThrottled ? SLOW_4G.latency : 0,
+ downloadKbps: isNetThrottled ? 1600 : 0,
+ cpuRate,
+ };
+
+ // Warm-up boot, discarded, same reason as perf-probe: a session's first cold load pays
+ // disk-cache misses for ~940 KB of chunks and inflates every mark by a few hundred ms,
+ // which would publish numbers that disagree with perf:probe for the same commit.
+ const warm = await browser.newContext({ viewport: RUNS[0].viewport, reducedMotion: "reduce" });
+ try {
+ await warm.addInitScript(installMarks);
+ const page = await warm.newPage();
+ await page.goto(base, { waitUntil: "load", timeout: 60000 });
+ await page.locator(SHELL_READY).waitFor({ state: "visible", timeout: 60000 });
+ } finally {
+ await warm.close();
+ }
+
+ const runs = [];
+ for (const config of RUNS) {
+ runs.push(await measure(browser, base, config, { cpuRate, isNetThrottled }));
+ }
+
+ const report = {
+ schemaVersion: 1,
+ createdAt: new Date().toISOString(),
+ commit: commit(),
+ throttle,
+ runs,
+ };
+
+ if (values.output) {
+ fs.mkdirSync(values.output, { recursive: true, mode: 0o700 });
+ fs.writeFileSync(path.join(values.output, "perf-hydration.json"), JSON.stringify(report, null, 2), { mode: 0o600 });
+ }
+
+ if (values.json) {
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
+ } else {
+ process.stdout.write(`${formatTable(report)}\n`);
+ }
+
+ if (runs.some((r) => r.mounted == null)) {
+ process.exitCode = 1;
+ }
+} catch (error) {
+ console.error(`perf-hydration: ${error instanceof Error ? error.message : String(error)}`);
+ process.exitCode = 1;
+} finally {
+ await browser?.close();
+ await fixture?.close();
+}