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
test(e2e): a browser that actually loads the page — and the three bugs it found
Rahmanf2001d94ed3e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 3c029533..3674f47b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -240,16 +240,18 @@ to `resources/` (rr) and drive any project from one manifest:`fs`/`child_process` straight from a route.- Solo-dev: push direct to `main` once `bun run verify` is green (typecheck + lint +test + check + audit). Conventional commits + Claude co-author.-- **The gates live in an UNTRACKED `.git/hooks/pre-push`**, so no commit can carry- them and an sc-git hook reinstall silently drops them. Four guards run, ~70 s per- push: sc-git `ci.js --skip build` (typecheck/lint/test, Guard 1), `check-cycles.mjs`- (1b), `scripts/audit.mjs` (1c), `scripts/verify-build.sh` (1d). A fifth, Guard 2, is- a self-hosted-Convex auto-deploy that is a silent no-op here — there is no `convex/`- dir — so don't be surprised to find it in the file. A healthy push prints- `audit: clean at high/critical.` and `build: HEAD compiles (out-of-tree).` — **if- those two lines are missing, the wiring is gone.** The `--skip build` is deliberate- safety, not laziness (see Deploy/ops). A reinstall also re-adds a- `scripts/check-slices.mjs` line; that script was deleted, so it blocks every push.+- **The gates live in `scripts/gates.sh`, which IS committed.** `.git/hooks/pre-push`+ is a one-line shim that execs it; reinstall with `bash scripts/gates.sh --install`.+ They used to live in the untracked hook itself, which meant a fresh clone had NO+ gates and an sc-git hook reinstall silently dropped the audit + build guards while+ re-adding a `check-slices.mjs` line for a script deleted on 2026-08-03. Four guards+ run, ~70 s per push: sc-git `ci.js --skip build` (Guard 1, falling back to `bun run+ verify` when that shared runner is not on the machine — a fresh clone must not skip+ it silently), `check-cycles.mjs` (1b), `scripts/audit.mjs` (1c),+ `scripts/verify-build.sh` (1d). Guard 2 is a self-hosted-Convex auto-deploy that is+ a silent no-op here. A healthy push prints `audit: clean at high/critical.` and+ `build: HEAD compiles (out-of-tree).` — **if those two lines are missing, the wiring+ is gone.** The `--skip build` is deliberate safety, not laziness (see Deploy/ops).- **`bun run audit` ≠ `bun audit`.** The script is `scripts/audit.mjs`, which wraps`bun audit --json` because raw `bun audit` fails CLOSED — offline it exits 1, thesame code as a real advisory, which would turn every network blip into a fakediff --git a/frontend/slices/code-editor/lib/use-editor.ts b/frontend/slices/code-editor/lib/use-editor.tsindex 75c0f8cd..93d5cb7d 100644--- a/frontend/slices/code-editor/lib/use-editor.ts+++ b/frontend/slices/code-editor/lib/use-editor.ts@@ -27,6 +27,13 @@ export function useEditor() {const seed = disk[path] ?? SEED_FILES[path] ?? "";return { ...b, [path]: seed };});+ // A SEED path is fictional demo content — `/Projects/counter.tsx` and friends+ // exist only in seed.ts. Asking the host for one always fails, and it did:+ // opening the editor on a live server fired GET /api/v1/fs/read for a path+ // that cannot exist, logging an error on every open. The catch below hid it+ // from the user but not from the console, and a browser e2e caught it.+ // openPath() (a real cross-app "open this file") still always reads.+ if (path in SEED_FILES) return;// Best-effort live hydrate; ignore failures (mock / missing file).api.fs.read(path)diff --git a/lib/host/api-error.test.ts b/lib/host/api-error.test.tsnew file mode 100644index 00000000..80c42baa--- /dev/null+++ b/lib/host/api-error.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it, vi } from "vitest";+import { apiError } from "./api-error";+import { HostError } from "./host-error";++describe("apiError", () => {+ const errno = (code: string) => Object.assign(new Error(`${code}: nope, realpath '/secret/path'`), { code });++ it("passes a curated HostError through as a 400 — those messages are UX", async () => {+ const r = apiError("fs/read", new HostError("Outside the read roots"));+ expect(r.status).toBe(400);+ expect(await r.json()).toEqual({ error: "Outside the read roots" });+ });++ it("maps ENOENT to 404 — a missing file is not a broken server", async () => {+ // Caught by the browser e2e as `500 GET /api/v1/fs/read` for a path the code+ // editor had opened out of MOCK data. A 500 sends everyone hunting the server.+ const r = apiError("fs/read", errno("ENOENT"));+ expect(r.status).toBe(404);+ expect(await r.json()).toEqual({ error: "Not found" });+ });++ it("maps ENOTDIR to 404 and EACCES/EPERM to 403", () => {+ expect(apiError("fs/list", errno("ENOTDIR")).status).toBe(404);+ expect(apiError("fs/read", errno("EACCES")).status).toBe(403);+ expect(apiError("fs/read", errno("EPERM")).status).toBe(403);+ });++ it("still 500s anything it does not recognise", () => {+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});+ expect(apiError("fs/read", new Error("boom")).status).toBe(500);+ spy.mockRestore();+ });++ it("never echoes the raw Node message — it carries an absolute path", async () => {+ const body = JSON.stringify(await apiError("fs/read", errno("ENOENT")).json());+ expect(body).not.toContain("/secret/path");+ expect(body).not.toContain("nope");+ });+});diff --git a/lib/host/api-error.ts b/lib/host/api-error.tsindex dd28f9f3..29085708 100644--- a/lib/host/api-error.ts+++ b/lib/host/api-error.ts@@ -13,6 +13,17 @@ export function apiError(): NextResponse {if (e instanceof HostError)return NextResponse.json({ error: e.message }, { status: 400 });+ // 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+ // — a browser e2e caught it as `500 GET /api/v1/fs/read` for a path that had+ // been opened from mock data. The message stays generic: the raw Node error+ // 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 });+ if (code === "EACCES" || code === "EPERM")+ return NextResponse.json({ error: "Permission denied" }, { status: 403 });console.error(`[api/v1/${route}]`, e);return NextResponse.json({ error: fallback.error ?? "Operation failed" },diff --git a/package.json b/package.jsonindex 680a6d0a..e6823c90 100644--- a/package.json+++ b/package.json@@ -15,7 +15,8 @@"coverage": "vitest run --coverage","check": "node scripts/check-cycles.mjs && node scripts/check-contrast.mjs","audit": "node scripts/audit.mjs",- "verify": "bun run typecheck && bun run lint && bun run test && bun run check && bun run audit",+ "verify": "bun run typecheck && bun run lint && bun run coverage && bun run check && bun run audit",+ "e2e": "node scripts/e2e/shell.mjs","smoke": "E2E_BASE_URL=http://localhost:4005 vitest run scripts/e2e/smoke.test.ts"},"dependencies": {diff --git a/scripts/e2e/shell.mjs b/scripts/e2e/shell.mjsnew file mode 100644index 00000000..b2081bdc--- /dev/null+++ b/scripts/e2e/shell.mjs@@ -0,0 +1,206 @@+#!/usr/bin/env node+// Browser e2e for the shell. THE detector this repo did not have.+//+// Every bug found in the 2026-08-10 audits was found by READING code — an+// `apps.list` that always answered "no apps installed", a file listing that+// rendered "(0b)" for everything, a MOCK banner that was false, four hydration+// mismatches. All of them are invisible to a unit test and obvious the moment a+// browser actually loads the page. So: load the page.+//+// node scripts/e2e/shell.mjs # against http://127.0.0.1:4005+// E2E_BASE_URL=… E2E_PASSWORD=… node scripts/e2e/shell.mjs+//+// Playwright lives under os-browser/node_modules (the repo's only install, CJS) —+// see CLAUDE.md. Requires an APPROVED device id, which is seeded into localStorage+// before first paint rather than clicking through an approval flow.+import { createRequire } from "node:module";+import { readFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";++const require = createRequire(import.meta.url);+const { chromium } = require(path.join(process.cwd(), "os-browser/node_modules/playwright"));++const BASE = process.env.E2E_BASE_URL ?? "http://localhost:4005";+const HEADLESS = process.env.E2E_HEADED !== "1";++function env(key) {+ const raw = readFileSync(path.join(process.cwd(), ".env.local"), "utf8");+ return new RegExp(`^${key}=(.*)$`, "m").exec(raw)?.[1]?.trim().replace(/^["']|["']$/g, "");+}+function approvedDevice() {+ const file = process.env.OS_DEVICE_STORE ?? path.join(os.homedir(), ".mso", "auth-devices.json");+ const ids = Object.keys(JSON.parse(readFileSync(file, "utf8")).approved ?? {});+ if (!ids.length) throw new Error(`no approved device in ${file} — run: mso device approve <id> "e2e"`);+ return ids[0];+}++const PASSWORD = process.env.E2E_PASSWORD ?? env("OS_LOGIN_PASSWORD");+const DEVICE = process.env.E2E_DEVICE ?? approvedDevice();++/** Log in ONCE and hand back the raw signed cookie value.+ * Cached: the login route rate-limits per IP, and minting one session per viewport+ * 429s the second run of the day. */+let sessionValue = null;+async function mintSession() {+ if (sessionValue) return sessionValue;+ const r = await fetch(`${BASE}/api/auth/login`, {+ method: "POST",+ headers: { "content-type": "application/json", origin: BASE },+ body: JSON.stringify({ password: PASSWORD, deviceId: DEVICE, deviceLabel: "e2e" }),+ });+ if (!r.ok) throw new Error(`login failed (${r.status}) — is the device approved? ${DEVICE}`);+ const raw = r.headers.get("set-cookie") ?? "";+ const value = /(?:^|,\s*)session=([^;]+)/.exec(raw)?.[1];+ if (!value) throw new Error(`login 200 but no session cookie in: ${raw.slice(0, 120)}`);+ sessionValue = value;+ return value;+}++const failures = [];+const fail = (m) => { failures.push(m); console.log(` ✗ ${m}`); };+const pass = (m) => console.log(` ✓ ${m}`);+const check = (cond, m) => (cond ? pass(m) : fail(m));++// Noise we do not control and that does not indicate a broken shell.+// App titles, for the mobile home where tiles are buttons rather than links.+const TITLES = {+ files: "Files", monitor: "System Monitor", settings: "Settings",+ code: "Code", terminal: "Terminal",+};++const IGNORE = [+ /favicon/i,+ /Download the React DevTools/i,+ /net::ERR_INTERNET_DISCONNECTED/i,+ // The stock image search reaches third-party hosts; offline that is not our bug.+ /openverse|unsplash/i,+];++async function session(browser, { width, height, label }) {+ console.log(`\n▶ ${label} (${width}×${height})`);+ const ctx = await browser.newContext({+ viewport: { width, height },+ deviceScaleFactor: 2,+ hasTouch: width < 768,+ isMobile: width < 768,+ });+ const errors = [];+ ctx.on("console", (m) => {+ if (m.type() !== "error") return;+ const t = m.text();+ if (!IGNORE.some((re) => re.test(t))) errors.push(t);+ });+ ctx.on("weberror", (e) => errors.push(String(e.error()?.message ?? e.error())));+ // Track failed requests WITH their URL. A bare "401 (Unauthorized)" in the console+ // is unactionable; the URL is the whole finding.+ const http = [];+ ctx.on("response", (r) => {+ if (r.status() >= 400) http.push(`${r.status()} ${r.request().method()} ${new URL(r.url()).pathname}`);+ });++ // Sign in by INSTALLING the session cookie, not by driving the form.+ //+ // The cookie the server issues is `Secure` — correct, prod is HTTPS — and Chromium+ // refuses to STORE a Secure cookie that arrives over plain http, even on loopback.+ // The consequence is nastier than a failed login: the shell renders for signed-out+ // visitors too, backed by mock data (auth-gate.tsx, "signed-in AND signed-out →+ // the shell"), so the form appears to work, the desktop appears, and every+ // assertion below would pass against fakes. The first version of this file did+ // exactly that and reported green.+ //+ // Browsers only enforce Secure when RECEIVING a cookie, so a cookie we install+ // ourselves with secure:false is sent over http and is byte-identical to the+ // server's on the way back. The login FORM is covered by unit tests; what this+ // file exists to exercise is the shell behind it.+ await ctx.addCookies([{ name: "session", value: await mintSession(), url: BASE, sameSite: "Strict" }]);++ const page = await ctx.newPage();+ // Seed BEFORE first paint: the device id is read during the auth gate's first+ // render, so an addInitScript is the only place it lands in time.+ await page.addInitScript(+ ([id, key, onboarding]) => {+ localStorage.setItem(key, id);+ localStorage.setItem(onboarding, "done"); // skip the first-run tour+ },+ [DEVICE, "mso.device.id", "mso:onboarding:v1"],+ );++ await page.goto(BASE, { waitUntil: "domcontentloaded" });++ // `#main-content[data-shell]` — the attribute is ON the element, not a descendant.+ await page.waitForSelector("#main-content[data-shell]", { timeout: 20_000 }).catch(() => {});+ const shell = await page.getAttribute("#main-content", "data-shell");+ check(shell != null, `shell resolved (${shell})`);++ // ASSERT THE SESSION, do not assume it. The shell renders for signed-OUT visitors+ // too, backed by mock data — so "the desktop appeared" proves nothing about auth,+ // and a run that quietly tested mocks would report green forever.+ const me = await page.evaluate(async () => (await fetch("/api/auth/me", { cache: "no-store" })).json());+ check(me?.authenticated === true, `really signed in (authenticated=${me?.authenticated})`);+ if (!me?.authenticated) fail("everything below this line is testing MOCK data — fix auth first");+ check(+ width < 768 ? ["ios", "android"].includes(shell) : ["macos", "windows", "dashboard"].includes(shell),+ `${shell} is the right shell for this viewport`,+ );++ // ── no horizontal overflow. A shell that scrolls sideways is broken on a phone+ // and nothing in a unit test can see it.+ const overflow = await page.evaluate(() =>+ document.documentElement.scrollWidth - document.documentElement.clientWidth,+ );+ check(overflow <= 1, `no horizontal overflow (${overflow}px)`);++ // ── open every app by DEEP LINK rather than by clicking the dock.+ //+ // Deliberate: the URL is the documented contract ("the OS is addressable" —+ // CLAUDE.md), so this exercises the same routing a bookmark or a shared link+ // uses, and it does not depend on dock geometry. Clicking was tried first and was+ // hopelessly flaky: macOS magnifies icons on hover so the hit box moves under the+ // pointer, and the iOS home paginates so half the grid is off-screen. A launcher+ // that cannot be clicked is a real finding, but it is a DIFFERENT test from "does+ // this app render", and conflating them made both unreliable.+ for (const slug of ["files", "monitor", "settings", "code", "terminal"]) {+ await page.goto(`${BASE}/${slug}`, { waitUntil: "domcontentloaded" });+ await page.waitForTimeout(1200);+ // Desktop puts the app in a [data-window]; iOS/Android render it full-screen in+ // the shell, with no window chrome at all. Assert the surface-appropriate thing+ // rather than a window that is correctly absent on a phone.+ check(page.url().endsWith(`/${slug}`), `/${slug} deep-link kept the URL`);+ if (width >= 768) {+ check((await page.locator("[data-window]").count()) > 0, `/${slug} opened a window`);+ }+ // A spinner that never resolves is the exact failure window-content.tsx used to+ // sit in forever when a chunk import rejected.+ check((await page.locator(".animate-spin").count()) === 0, `/${slug} rendered without a stuck spinner`);+ }++ // ── the regression that shipped for months: a tool/list that renders every file+ // as "(0b)" because fs.list does not report sizes.+ const zeroBytes = await page.locator("text=/\\(0b\\)/").count();+ check(zeroBytes === 0, "no bogus (0b) file sizes rendered");++ // /api/prefs 401s once before sign-in BY DESIGN: the appearance + quicklinks+ // providers mount outside AuthGate so persisted UI state applies on first paint,+ // and the pull is silent when it fails. Any OTHER 4xx/5xx is a real finding, so it+ // is excluded by exact path rather than by status.+ const badHttp = [...new Set(http)].filter((h) => h !== "401 GET /api/prefs");+ check(badHttp.length === 0, `no unexpected failed requests${badHttp.length ? ` — ${badHttp.join(", ")}` : ""}`);++ const realErrors = errors.filter((e) => !/401 \(Unauthorized\)/.test(e) || badHttp.length > 0);+ check(realErrors.length === 0, `zero console errors${realErrors.length ? ` — first: ${realErrors[0].slice(0, 160)}` : ""}`);+ for (const e of realErrors.slice(0, 5)) console.log(` · ${e.slice(0, 200)}`);++ await ctx.close();+}++const browser = await chromium.launch({ headless: HEADLESS });+try {+ await session(browser, { width: 1280, height: 800, label: "desktop" });+ await session(browser, { width: 390, height: 844, label: "mobile" });+} finally {+ await browser.close();+}++console.log(`\n${failures.length === 0 ? "✅ shell e2e passed" : `❌ ${failures.length} failure(s)`}`);+process.exit(failures.length === 0 ? 0 : 1);diff --git a/scripts/gates.sh b/scripts/gates.shnew file mode 100755index 00000000..3253bb27--- /dev/null+++ b/scripts/gates.sh@@ -0,0 +1,88 @@+#!/usr/bin/env bash+# The push gates. THIS FILE IS THE SOURCE OF TRUTH — the git hook is a one-liner+# that execs it.+#+# Why it lives here and not in .git/hooks/pre-push: a hook is untracked, so a fresh+# clone had NO gates at all, and re-running an sc-git hook installer silently+# overwrote the file — dropping the audit and build guards and re-adding a+# `check-slices.mjs` line for a script deleted on 2026-08-03, which blocks every+# push. Both failure modes were documented in CLAUDE.md, and a doc is not a control.+#+# Install (idempotent): bash scripts/gates.sh --install+# Run by hand: bash scripts/gates.sh+#+# A healthy run ends with BOTH of these lines. If either is missing, the wiring is+# gone — do not trust the push:+# audit: clean at high/critical.+# build: HEAD compiles (out-of-tree).+set -e++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+cd "$ROOT"++if [ "${1-}" = "--install" ]; then+ HOOK="$ROOT/.git/hooks/pre-push"+ mkdir -p "$(dirname "$HOOK")"+ printf '#!/usr/bin/env bash\n# Thin shim — the gates live in scripts/gates.sh, which is committed.\nexec bash "$(git rev-parse --show-toplevel)/scripts/gates.sh"\n' > "$HOOK"+ chmod +x "$HOOK"+ echo "installed $HOOK → scripts/gates.sh"+ exit 0+fi++fail() { echo ""; echo "❌ $1 push blocked."; [ -n "${2-}" ] && echo " $2"; exit 1; }++# ── Guard 1 — typecheck + lint + test.+# sc-git's ci.js is used when present (it is the shared runner across this owner's+# repos) but must not be REQUIRED: a fresh clone on another machine has no such+# path, and silently skipping the whole guard there is exactly the hole this file+# exists to close. `bun run verify` is the in-repo equivalent.+SC_CI="/home/rahman/projects/opensource/si-coder-agent/skills/sc-git/scripts/ci.js"+if [ -f "$SC_CI" ]; then+ node "$SC_CI" --skip build || fail "sc-git ci failed." "override (NOT recommended): git push --no-verify"+else+ echo "▶ sc-git ci.js not present — running \`bun run verify\` instead"+ bun run verify || fail "verify failed." "reproduce: bun run verify"+fi++# ── Guard 1b — architecture. check-contrast is informational (a WCAG palette audit+# is a design task, not a push blocker), so it is allowed to exit non-zero.+# NOTE: check-slices.mjs used to run here. It and all 20 slice.json were deleted on+# 2026-08-03 (commit 844eef3) — do NOT let a hook reinstall re-add that line.+node scripts/check-cycles.mjs || fail "check-cycles: new import cycle introduced."+node scripts/check-contrast.mjs || true++# ── Guard 1c — dependency audit, high/critical only.+# Must live HERE rather than lean on ci.js: that runner has a hardcoded+# STEPS=['typecheck','lint','test','build'] and never invokes `verify`. The wrapper+# skips (exit 0) when the registry is unreachable, so a network blip cannot fake a+# CVE and block a push.+node scripts/audit.mjs || fail "audit: unignored high/critical advisory."++# ── Guard 1d — build. ci.js above keeps `--skip build` ON PURPOSE: it would build in+# THIS directory, and `next build` wipes .next before compiling — which is what the+# live :4005 process is serving from. verify-build.sh compiles a throwaway copy of+# HEAD instead. Adds ~35 s to a push; if that ever becomes intolerable, DELETE this+# guard rather than "fixing" it by letting ci.js build in place.+bash scripts/verify-build.sh >/dev/null 2>&1 \+ && echo "build: HEAD compiles (out-of-tree)." \+ || fail "build failed." "reproduce: bash scripts/verify-build.sh"++# ── Guard 2 — self-hosted Convex auto-deploy. A silent no-op in this repo (there is+# no convex/ directory); kept so the file matches the shared sc-git shape and a+# future backend does not have to rediscover the ordering rule: backend first, or+# the frontend lands ahead of it.+if [ -d convex ] && [ -f .env.local ] \+ && grep -q "^CONVEX_SELF_HOSTED_URL=" .env.local 2>/dev/null \+ && grep -q "^CONVEX_SELF_HOSTED_ADMIN_KEY=" .env.local 2>/dev/null; then+ LOCAL_SHA=$(git rev-parse HEAD 2>/dev/null || true)+ REMOTE_SHA=$(git rev-parse origin/main 2>/dev/null || echo "")+ if [ -n "$REMOTE_SHA" ] && [ "$LOCAL_SHA" != "$REMOTE_SHA" ] \+ && [ -n "$(git diff --name-only "$REMOTE_SHA"..HEAD -- convex/ 2>/dev/null || true)" ]; then+ echo ""+ echo "▶ convex/ changed → deploying self-hosted Convex FIRST"+ set -a; . ./.env.local; set +a+ pnpm exec convex deploy --yes \+ || fail "Convex self-hosted deploy failed." "do NOT --no-verify — the frontend would land ahead of the backend."+ echo "✓ Convex deploy complete. Continuing push."+ fi+fidiff --git a/vitest.config.mts b/vitest.config.mtsindex 12af9814..ea2da45c 100644--- a/vitest.config.mts+++ b/vitest.config.mts@@ -33,9 +33,13 @@ export default defineConfig({"proxy-websocket.test.ts",],environment: "node",- // `pnpm coverage`. @vitest/coverage-v8 is installed (package.json), so the- // thresholds below are real gates, not aspirations — this comment used to say- // the block was inert pending an install that had already happened.+ // `bun run coverage`, and it IS in `verify`, so these are gates.+ //+ // The numbers are the CURRENT floor minus a hair, not a target. They used to+ // read 50/40/50/50 with a comment calling them "real gates" while real coverage+ // was 19% and nothing ran them — an aspiration written as a fact, which is the+ // worse of the two failure modes: it reads as covered. Raise these when you add+ // tests; never lower them to make a push go through.coverage: {provider: "v8",reporter: ["text", "json-summary"],@@ -47,10 +51,10 @@ export default defineConfig({"**/.next/**",],thresholds: {- statements: 50,- branches: 40,- functions: 50,- lines: 50,+ statements: 19,+ branches: 18,+ functions: 14,+ lines: 19,},},},