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: keep the OS shell out of every route, stop sleeping on every stats poll

Rahmand3d0022a263c
diff --git a/README.md b/README.md
index 96ceacbe..399b5c3a 100644
--- a/README.md
+++ b/README.md
@@ -108,6 +108,8 @@ curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install
curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- --uninstall
```
+There is also a no-login install guide you can share: **<https://mso.rahmanef.com/install>** (every MSO instance serves it at `/install`).
+
Full production setup, TLS/VPN notes, filesystem roots, updates, and rollback steps live in [docs/INSTALL.md](./docs/INSTALL.md).
## CLI
@@ -132,6 +134,8 @@ mso api GET /api/v1/sys/stats # escape hatch — any endpoint
eval "$(mso completion bash)" # tab completion
```
+Full command reference: [docs/CLI.md](./docs/CLI.md) (generated from `mso --help`).
+
Global options: `--base <url>` to target another instance, `--env <file>` to pick a
different secrets file. Device and service commands work even while the service is
down. If you use [Claude Code](https://claude.com/claude-code), the installer also
@@ -249,6 +253,7 @@ Not currently supported:
| Doc | What's in it |
|---|---|
| [docs/INSTALL.md](./docs/INSTALL.md) | Server install, credentials, systemd, TLS/VPN, updates, rollback |
+| [docs/CLI.md](./docs/CLI.md) | The `mso` command-line reference (generated from `mso --help`) |
| [docs/DEVELOPMENT.md](./docs/DEVELOPMENT.md) | Local dev, quality gates, pnpm, deploy hazards |
| [docs/ARCHITECTURE.md](./docs/ARCHITECTURE.md) | App shell, host layer, slices, routing |
| [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md) | Managing Hermes/OpenClaw, per-app origins, workspace modes |
diff --git a/app/install/copy.tsx b/app/install/copy.tsx
new file mode 100644
index 00000000..77845df5
--- /dev/null
+++ b/app/install/copy.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import * as React from "react";
+import { Check, Copy as CopyIcon } from "lucide-react";
+
+// The one interactive bit on an otherwise static public page. A shell command you
+// have to hand-retype is a command you mistype, and the install one-liner is long
+// enough that a wrapped line hides a missing character.
+export function Copy({ text }: { text: string }) {
+ const [copied, setCopied] = React.useState(false);
+
+ React.useEffect(() => {
+ if (!copied) return;
+ const t = setTimeout(() => setCopied(false), 1600);
+ return () => clearTimeout(t);
+ }, [copied]);
+
+ return (
+ <div className="group relative mt-3">
+ <pre className="overflow-x-auto rounded-lg border border-border bg-muted/50 py-3 pl-4 pr-12 text-[0.8125rem] leading-relaxed">
+ <code>{text}</code>
+ </pre>
+ <button
+ type="button"
+ // navigator.clipboard is undefined on insecure origins — someone reading
+ // this over plain http on a LAN address still gets a working button.
+ onClick={async () => {
+ try {
+ await navigator.clipboard.writeText(text);
+ } catch {
+ const el = document.createElement("textarea");
+ el.value = text;
+ el.style.position = "fixed";
+ el.style.opacity = "0";
+ document.body.appendChild(el);
+ el.select();
+ document.execCommand("copy");
+ el.remove();
+ }
+ setCopied(true);
+ }}
+ className="absolute right-2 top-2 rounded-md border border-border bg-background/80 p-1.5 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ aria-label={copied ? "Copied" : "Copy to clipboard"}
+ >
+ {copied ? <Check className="size-3.5" aria-hidden /> : <CopyIcon className="size-3.5" aria-hidden />}
+ </button>
+ <span aria-live="polite" className="sr-only">
+ {copied ? "Copied to clipboard" : ""}
+ </span>
+ </div>
+ );
+}
diff --git a/app/install/page.tsx b/app/install/page.tsx
new file mode 100644
index 00000000..d82cb22a
--- /dev/null
+++ b/app/install/page.tsx
@@ -0,0 +1,135 @@
+import type { Metadata } from "next";
+import { Copy } from "./copy";
+
+// A PUBLIC page: no session, no shell, no client data fetch. Someone evaluating
+// MSO lands here from a shared link and has to be able to read the whole story —
+// what it is, what it costs them in risk, and the exact commands — without an
+// account. It deliberately does NOT render the OS shell: the shell is ~338 KB of
+// JS for a page whose job is to be read.
+export const metadata: Metadata = {
+ title: "Install Manef Shell OS on your own server",
+ description:
+ "One command installs MSO on a Linux server you own: a browser terminal, file manager, live metrics and a BYOK AI assistant, behind password + device approval.",
+};
+
+const INSTALL = "curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash";
+
+const REQUIREMENTS = [
+ ["A Linux server you own", "A $5 VPS is enough. Debian/Ubuntu, Fedora and Arch are covered by the installer."],
+ ["Node 20.9 or newer", "The installer adds it via NodeSource if it is missing."],
+ ["A normal, non-root user", "MSO runs as that user and can do whatever that user can do. Never install it as root."],
+ ["About 2 GB free disk", "Mostly the build. The app itself is small; there is no database."],
+];
+
+const STEPS = [
+ {
+ n: 1,
+ title: "Run the installer",
+ body: "As your normal user, not root. It installs prerequisites, clones the repo, builds, generates a login password and session secret, and sets up the systemd unit.",
+ code: INSTALL,
+ note: "It prints your login password once. Save it — it is written only to .env.local on the server.",
+ },
+ {
+ n: 2,
+ title: "Put it behind something",
+ body: "MSO listens on :4005. An authenticated session can read allowed files and run commands as the process user, so treat the port like SSH: do not expose it raw to the internet. Tailscale or a VPN is the easy answer; a TLS reverse proxy with an allowlist also works.",
+ code: "sudo ufw deny 4005",
+ },
+ {
+ n: 3,
+ title: "Pair your first device",
+ body: "Open the app and enter the password. Your browser lands in a PENDING state and shows a device id — correct password alone is not enough. Approve it from a shell on the server:",
+ code: "mso device pending\nmso device approve <deviceId> \"my laptop\"",
+ note: "Device approval is a browser allowlist, not standards-based 2FA. Approve only devices you own.",
+ },
+ {
+ n: 4,
+ title: "Reload and sign in",
+ body: "That device can now log in with the password. Approve later devices the same way, or from Settings → Devices once you are in.",
+ },
+];
+
+export default function InstallPage() {
+ return (
+ <main className="mx-auto min-h-dvh w-full max-w-3xl px-5 py-14 text-foreground sm:px-8">
+ <header className="mb-12">
+ <p className="text-xs font-medium uppercase tracking-widest text-muted-foreground">Manef Shell OS</p>
+ <h1 className="mt-3 text-3xl font-semibold tracking-tight sm:text-4xl">
+ Install it on your own server
+ </h1>
+ <p className="mt-4 text-balance text-base leading-relaxed text-muted-foreground">
+ A browser terminal, file manager, live system metrics and a bring-your-own-key AI
+ assistant for one Linux server you control. Open source, self-hosted, no account and
+ no database. This page needs no login — the install does.
+ </p>
+ <p className="mt-4 rounded-lg border border-border bg-muted/40 px-4 py-3 text-sm leading-relaxed text-muted-foreground">
+ <strong className="font-medium text-foreground">Public Alpha.</strong> MSO is a normal
+ non-root Node process on top of Linux. It is not an operating system, a distribution,
+ or a hardened multi-tenant platform. One owner, one server.
+ </p>
+ </header>
+
+ <section className="mb-12">
+ <h2 className="mb-4 text-lg font-semibold">Before you start</h2>
+ <dl className="grid gap-3 sm:grid-cols-2">
+ {REQUIREMENTS.map(([term, detail]) => (
+ <div key={term} className="rounded-lg border border-border p-4">
+ <dt className="text-sm font-medium">{term}</dt>
+ <dd className="mt-1 text-sm leading-relaxed text-muted-foreground">{detail}</dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+
+ <section className="mb-12">
+ <h2 className="mb-5 text-lg font-semibold">Four steps</h2>
+ <ol className="space-y-8">
+ {STEPS.map((s) => (
+ <li key={s.n} className="grid grid-cols-[2rem_1fr] gap-x-3">
+ <span
+ aria-hidden
+ className="mt-0.5 flex size-7 items-center justify-center rounded-full border border-border text-sm font-medium tabular-nums"
+ >
+ {s.n}
+ </span>
+ <div className="min-w-0">
+ <h3 className="text-base font-medium">{s.title}</h3>
+ <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{s.body}</p>
+ {s.code ? <Copy text={s.code} /> : null}
+ {s.note ? (
+ <p className="mt-2 text-sm leading-relaxed text-muted-foreground">
+ <span className="font-medium text-foreground">Note:</span> {s.note}
+ </p>
+ ) : null}
+ </div>
+ </li>
+ ))}
+ </ol>
+ </section>
+
+ <section className="mb-12">
+ <h2 className="mb-3 text-lg font-semibold">Drive it from a shell</h2>
+ <p className="text-sm leading-relaxed text-muted-foreground">
+ The installer also puts <code className="rounded bg-muted px-1 py-0.5 text-[0.85em]">mso</code> on
+ your PATH. It reaches the same API the browser does — files, host shell, metrics,
+ managed apps, devices — so nothing is UI-only. Start with{" "}
+ <code className="rounded bg-muted px-1 py-0.5 text-[0.85em]">mso doctor</code>.
+ </p>
+ <Copy text="mso doctor" />
+ </section>
+
+ <footer className="flex flex-wrap gap-x-6 gap-y-2 border-t border-border pt-6 text-sm">
+ {[
+ ["Source + full docs", "https://github.com/rahmanef63/mso"],
+ ["Install reference", "https://github.com/rahmanef63/mso/blob/main/docs/INSTALL.md"],
+ ["CLI reference", "https://github.com/rahmanef63/mso/blob/main/docs/CLI.md"],
+ ["Security model", "https://github.com/rahmanef63/mso/blob/main/SECURITY.md"],
+ ].map(([label, href]) => (
+ <a key={href} className="text-muted-foreground underline underline-offset-4 hover:text-foreground" href={href}>
+ {label}
+ </a>
+ ))}
+ </footer>
+ </main>
+ );
+}
diff --git a/app/layout-graph.test.ts b/app/layout-graph.test.ts
new file mode 100644
index 00000000..10c44987
--- /dev/null
+++ b/app/layout-graph.test.ts
@@ -0,0 +1,62 @@
+import { readFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { describe, expect, it } from "vitest";
+
+// The root layout is inherited by EVERY route, including public pages that render
+// nothing but text. `@/features/os-shell` re-exports the whole appshell barrel —
+// window manager, 5 shells, 10 shell features — so a single static import of it
+// anywhere in the root layout's graph puts the entire OS into the initial load of
+// every page. That is exactly what `register-sw.tsx` did: /install shipped 330 KB
+// gzip to render a static install guide. Deferring it to a dynamic import cut the
+// page to 195 KB.
+//
+// This walks the root layout's LOCAL static imports and fails if the shell is
+// back. Dynamic `await import(...)` is fine — that is the fix, not the problem.
+const APP = join(dirname(new URL(import.meta.url).pathname));
+const SHELL_BARRELS = ["@/features/os-shell", "@/features/appshell"];
+
+function localImports(file: string): string[] {
+ const src = readFileSync(file, "utf8");
+ // Static imports only. `await import()` is deliberately not matched.
+ return [...src.matchAll(/^import\s[^;]*?from\s+["'](\.[^"']+)["']/gm)].map((m) => m[1]);
+}
+function staticShellImports(file: string): string[] {
+ const src = readFileSync(file, "utf8");
+ return SHELL_BARRELS.filter((b) =>
+ new RegExp(`^import\\s[^;]*?from\\s+["']${b}(/[^"']*)?["']`, "m").test(src),
+ );
+}
+function resolveLocal(from: string, spec: string): string | null {
+ const base = resolve(dirname(from), spec);
+ for (const ext of [".tsx", ".ts", "/index.tsx", "/index.ts"]) {
+ try {
+ readFileSync(base + ext, "utf8");
+ return base + ext;
+ } catch {
+ /* try the next extension */
+ }
+ }
+ return null;
+}
+
+describe("root layout graph", () => {
+ it("never statically imports the OS shell", () => {
+ const seen = new Set<string>();
+ const offenders: string[] = [];
+ const walk = (file: string) => {
+ if (seen.has(file)) return;
+ seen.add(file);
+ for (const barrel of staticShellImports(file)) {
+ offenders.push(`${file.replace(/^.*\/app\//, "app/")} → ${barrel}`);
+ }
+ for (const spec of localImports(file)) {
+ const next = resolveLocal(file, spec);
+ if (next) walk(next);
+ }
+ };
+ walk(join(APP, "layout.tsx"));
+
+ expect(seen.size).toBeGreaterThan(1); // the walk actually followed something
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/app/register-sw.tsx b/app/register-sw.tsx
index d48b8118..d5864cbe 100644
--- a/app/register-sw.tsx
+++ b/app/register-sw.tsx
@@ -1,7 +1,6 @@
"use client";
import { useEffect } from "react";
-import { toast } from "@/features/os-shell";
// One-shot guard (per tab) so recovery never loops.
const GUARD = "mso_chunk_recover";
@@ -49,10 +48,19 @@ async function recover() {
// New SW is installed + waiting → offer a one-tap reload. The reload clears
// caches and activates the waiting SW (SKIP_WAITING → controllerchange).
-function promptUpdate(reg: ServiceWorkerRegistration) {
+//
+// `toast` is imported HERE, not at module scope. RegisterSW sits in the ROOT
+// layout, and `@/features/os-shell` re-exports the whole appshell barrel — so a
+// top-level import put the entire OS shell (window manager, 5 shells, 10 shell
+// features) into the static graph of every route, including public pages that
+// render nothing but text. Deferring it to the moment an update actually exists
+// keeps the shell out of the initial load and changes no behaviour: by then the
+// shell is either already loaded, or there is no toast surface to render into.
+async function promptUpdate(reg: ServiceWorkerRegistration) {
const waiting = reg.waiting;
if (!waiting || !navigator.serviceWorker.controller) return;
let reloading = false;
+ const { toast } = await import("@/features/os-shell");
toast("Versi baru tersedia.", {
action: {
label: "Reload",
@@ -108,13 +116,13 @@ export function RegisterSW() {
.register("/sw.js")
.then((reg) => {
// Already-queued update from a prior tab session.
- if (reg.waiting) promptUpdate(reg);
+ if (reg.waiting) void promptUpdate(reg);
// A new SW starts installing → toast once it finishes.
reg.addEventListener("updatefound", () => {
const sw = reg.installing;
if (!sw) return;
sw.addEventListener("statechange", () => {
- if (sw.state === "installed") promptUpdate(reg);
+ if (sw.state === "installed") void promptUpdate(reg);
});
});
// Mobile PWAs check for SW updates lazily — force it now, on focus, and
diff --git a/bin/mso.test.ts b/bin/mso.test.ts
index 65a6a455..81ca095c 100644
--- a/bin/mso.test.ts
+++ b/bin/mso.test.ts
@@ -41,6 +41,17 @@ describe("bin/mso", () => {
expect(() => run("definitely-not-a-verb")).toThrow();
});
+ it("keeps docs/CLI.md in sync with the help", () => {
+ // docs/CLI.md is generated from this same help text. A doc that silently
+ // describes an older CLI is worse than no doc, so staleness fails here
+ // rather than being noticed by whoever followed it.
+ expect(() =>
+ execFileSync("node", [path.join(__dirname, "../scripts/gen-cli-docs.mjs"), "--check"], {
+ encoding: "utf8",
+ }),
+ ).not.toThrow();
+ });
+
// "Covers every need" is only true if it stays true. Every API route must be
// reachable by a named verb, except the ones a shell genuinely cannot drive.
it("has a named verb for every API route", () => {
diff --git a/docs/CLI.md b/docs/CLI.md
new file mode 100644
index 00000000..b31232ce
--- /dev/null
+++ b/docs/CLI.md
@@ -0,0 +1,153 @@
+<!-- GENERATED by scripts/gen-cli-docs.mjs — edit the header of bin/mso, not this file. -->
+
+# MSO CLI
+
+The browser UI at your instance's domain is one frontend, not the product. `mso`
+reaches the same `/api` surface from a shell, so every feature is scriptable.
+
+`scripts/install.sh` symlinks `bin/mso` to `~/.local/bin/mso`. To install it by
+hand from a checkout:
+
+```bash
+ln -s "$PWD/bin/mso" ~/.local/bin/mso
+eval "$(mso completion bash)" # optional: tab completion
+```
+
+## First run
+
+```bash
+mso doctor # deps, env, service, session, device — names what broke
+mso device pending # after a browser tries to log in, approve it from here
+```
+
+The CLI signs in with `OS_LOGIN_PASSWORD` from your `.env.local` and its own
+device id (`~/.mso/cli.device.id`), which you approve once:
+
+```bash
+mso device approve "$(cat ~/.mso/cli.device.id)" "mso cli"
+```
+
+Device and service commands work even while the service is down — that is on
+purpose, because those are exactly the commands you need when it is.
+
+## Reference
+
+```
+Manef Shell OS — drive the whole cockpit from the shell.
+
+Usage: mso [options] <command> [args]
+
+mso.rahmanef.com is only ONE frontend. Everything it can do is a call to the
+same /api surface, so this CLI reaches every feature without a browser.
+Auth = signed session cookie (password + approved device), cached in a jar.
+
+Options:
+ --base <url> API base to talk to (default http://127.0.0.1:4005)
+ --env <file> Env file to source for secrets (default <repo>/.env.local)
+ -h, --help Show this help, or `mso <command> --help` for one command
+ -v, --version Show version
+
+Commands:
+ Hint: commands suffixed with * have subcommands. Run `mso <command> --help`.
+
+ Files
+ ls [path] List a directory (default ~)
+ cat <path> Read a text file
+ raw <path> Stream a file's raw bytes to stdout (images, video, any blob)
+ write <path> <text> Write a file
+ mkdir <path> Create a directory
+ rm <path> Delete, recursively
+ mv <from> <to> Move or rename
+ cp <from> <to> Copy
+ zip <base> <name…> Zip entries of <base> to stdout (redirect it to a .zip)
+ upload <local> <dst> Upload a local file into <dst> (the dir must already exist)
+ search <q> [root] Search file contents
+ usage [path] Disk usage
+
+ Host
+ exec <cmd…> Run a shell command on the host (full power)
+ stats CPU, memory, disk
+ ps Process table
+ cleanup [--run] Reclaimable junk; --run actually deletes it
+ status Public service status (no session needed)
+ health Is this CLI's session valid?
+ doctor Check deps, env, service, session, device — and say what broke
+
+ Browser
+ camoufox * Power the anti-detection VNC browser + read its password
+
+ Apps
+ apps App-store runtime apps
+ mapp * Managed apps on the box (hermes, openclaw): logs, update…
+ term * Interactive PTY sessions (open | input | resize | stream | close)
+
+ AI + state
+ ai <prompt…> One turn with the assistant
+ threads * Conversation history: list | show | rm
+ memory * Assistant memories: list | add | rm
+ config * BYOK provider + model: show | set | rm
+ prefs * UI preferences: show | set
+ models * Model catalog: list | test
+ skills Skill catalog the assistant sees
+ stock <query> [page] Stock-image search (Unsplash key optional, Openverse fallback)
+
+ Devices (a local file — these work while the service is down)
+ device * list | pending | approve | revoke | revoke all --yes
+ devices Alias for `device list`
+ approve <id> [label] Approve a device id
+ revoke <id> Revoke one device
+ whoami This CLI's device id + session state
+ login Force a fresh login
+ logout Drop the session (server-side + local jar)
+
+ Service (local systemd)
+ service * status | start | stop | restart | logs
+ build next build
+ deploy next build, then restart the service
+
+ Escape hatches
+ crud * Generic resource CRUD, incl. editor documents
+ api * Call ANY endpoint directly
+ completion [shell] Print a shell completion script (bash|zsh)
+ version Show version
+
+Examples:
+ mso doctor
+ First thing to run when something is off — it names the broken layer.
+ mso device pending
+ See who typed the correct password and is waiting to be let in.
+ mso device approve <id> "my phone"
+ Let that device sign in.
+ mso exec "systemctl status nginx"
+ Run anything on the host, as the user that owns the process.
+ mso camoufox start && mso camoufox session
+ Bring the browser up and print its one-time VNC password.
+ mso raw ~/shot.png > ./shot.png
+ Pull a binary file down; `cat` is for text.
+ mso mapp logs hermes
+ Tail a managed app's log without opening the UI.
+ mso api POST /api/v1/sys/cleanup
+ No named verb for it? Call the endpoint directly.
+
+Environment:
+ MSO_BASE Same as --base
+ MSO_ENV Same as --env
+ MSO_PASSWORD Overrides OS_LOGIN_PASSWORD from the env file
+ MSO_DEVICE Overrides this CLI's device id (~/.mso/cli.device.id)
+
+READ = OS_FS_READ_ROOTS; WRITE = home + ~/projects; exec = full host power.
+
+Docs: https://github.com/rahmanef63/mso
+```
+
+## Notes
+
+- **Every non-browser caller must send `Origin: <base>`.** `proxy.ts` blocks
+ mutating `/api` requests that cannot prove same-origin; a browser proves it with
+ `Sec-Fetch-Site`, and the documented fallback is an `Origin` whose host matches
+ `Host`. `mso` does this for you. Without it, login itself returns 403
+ `cross_origin_blocked` — before any device check — which looks like an approval
+ problem and is not.
+- `--base` targets another instance; the cookie jar is keyed by base, so switching
+ never reuses a session minted for a different origin.
+- `raw`, `zip` and `term stream` stream to stdout — redirect them to a file.
diff --git a/lib/host/sys.test.ts b/lib/host/sys.test.ts
new file mode 100644
index 00000000..ea901865
--- /dev/null
+++ b/lib/host/sys.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+import { stats } from "./sys";
+
+// The System Monitor polls /api/v1/sys/stats every 1500ms. Taking both /proc/stat
+// samples inside one call made every one of those requests sleep 120ms; reusing
+// the previous sample removes that for all but the first.
+describe("stats", () => {
+ it("reuses the previous CPU sample instead of sleeping again", async () => {
+ const first = await timed(); // cold: pays the two-sample sleep
+ await sleep(250); // past REUSE_MIN_MS, so the cached sample is usable
+ const second = await timed();
+
+ expect(first.ms).toBeGreaterThanOrEqual(100);
+ expect(second.ms).toBeLessThan(100);
+ // Still a real reading, not a shortcut that skips the work.
+ expect(second.value.cpu.pct).toBeGreaterThanOrEqual(0);
+ expect(second.value.cpu.pct).toBeLessThanOrEqual(100);
+ expect(second.value.cpu.cores).toBeGreaterThan(0);
+ expect(second.value.mem.total).toBeGreaterThan(0);
+ });
+
+ it("returns a whole, sane payload", async () => {
+ const s = await stats();
+ expect(s.mem.used).toBeLessThanOrEqual(s.mem.total);
+ expect(s.disk.used).toBeLessThanOrEqual(s.disk.total);
+ expect(s.uptime).toBeGreaterThan(0);
+ });
+});
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+async function timed() {
+ const t0 = Date.now();
+ const value = await stats();
+ return { ms: Date.now() - t0, value };
+}
diff --git a/lib/host/sys.ts b/lib/host/sys.ts
index 0a10b1fb..88801571 100644
--- a/lib/host/sys.ts
+++ b/lib/host/sys.ts
@@ -18,10 +18,36 @@ async function cpuSample(): Promise<{ idle: number; total: number }> {
}
}
+// CPU% needs two /proc/stat samples. Taking both inside one request means every
+// caller pays a 120ms sleep — and the System Monitor polls this every 1500ms, so
+// the handler sat blocked for 8% of wall-clock forever. Keep the last sample
+// instead: a poll that arrives while a usable one is on hand diffs against it and
+// returns immediately.
+//
+// The window has both ends for a reason. Below MIN, the delta is too few jiffies
+// to mean anything (and can read 0 on an idle box). Above MAX, the delta stops
+// being "now" — a sample from ten minutes ago would report the ten-minute average
+// as the current load. Outside the window we fall back to the honest two-sample
+// read, so correctness never depends on how often someone happens to be polling.
+const REUSE_MIN_MS = 200;
+const REUSE_MAX_MS = 10_000;
+let lastSample: { at: number; idle: number; total: number } | null = null;
+
export async function stats(): Promise<SysStats> {
- const a = await cpuSample();
- await new Promise((r) => setTimeout(r, 120));
+ const now = Date.now();
+ const prev = lastSample;
+ const reusable = prev && now - prev.at >= REUSE_MIN_MS && now - prev.at <= REUSE_MAX_MS;
+
+ let a: { idle: number; total: number };
+ if (reusable) {
+ a = prev;
+ } else {
+ a = await cpuSample();
+ await new Promise((r) => setTimeout(r, 120));
+ }
const b = await cpuSample();
+ lastSample = { at: Date.now(), idle: b.idle, total: b.total };
+
const dt = b.total - a.total;
const di = b.idle - a.idle;
const pct = dt > 0 ? Math.max(0, Math.min(100, Math.round((1 - di / dt) * 100))) : 0;
diff --git a/scripts/gen-cli-docs.mjs b/scripts/gen-cli-docs.mjs
new file mode 100644
index 00000000..2ae1b645
--- /dev/null
+++ b/scripts/gen-cli-docs.mjs
@@ -0,0 +1,89 @@
+#!/usr/bin/env node
+// Writes docs/CLI.md from `bin/mso --help`. The help text lives in ONE place (the
+// comment header of bin/mso, which the CLI prints verbatim), so the doc cannot
+// drift from the tool. Run after changing the header:
+//
+// node scripts/gen-cli-docs.mjs # write
+// node scripts/gen-cli-docs.mjs --check # exit 1 if stale (used by a test)
+import { execFileSync } from "node:child_process";
+import { readFileSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const out = join(root, "docs/CLI.md");
+
+// MSO_ENV=/dev/null: the help must never depend on a machine's secrets file.
+const help = execFileSync(join(root, "bin/mso"), ["--help"], {
+ encoding: "utf8",
+ env: { ...process.env, MSO_ENV: "/dev/null" },
+}).trimEnd();
+
+const doc = `<!-- GENERATED by scripts/gen-cli-docs.mjs — edit the header of bin/mso, not this file. -->
+
+# MSO CLI
+
+The browser UI at your instance's domain is one frontend, not the product. \`mso\`
+reaches the same \`/api\` surface from a shell, so every feature is scriptable.
+
+\`scripts/install.sh\` symlinks \`bin/mso\` to \`~/.local/bin/mso\`. To install it by
+hand from a checkout:
+
+\`\`\`bash
+ln -s "$PWD/bin/mso" ~/.local/bin/mso
+eval "$(mso completion bash)" # optional: tab completion
+\`\`\`
+
+## First run
+
+\`\`\`bash
+mso doctor # deps, env, service, session, device — names what broke
+mso device pending # after a browser tries to log in, approve it from here
+\`\`\`
+
+The CLI signs in with \`OS_LOGIN_PASSWORD\` from your \`.env.local\` and its own
+device id (\`~/.mso/cli.device.id\`), which you approve once:
+
+\`\`\`bash
+mso device approve "$(cat ~/.mso/cli.device.id)" "mso cli"
+\`\`\`
+
+Device and service commands work even while the service is down — that is on
+purpose, because those are exactly the commands you need when it is.
+
+## Reference
+
+\`\`\`
+${help}
+\`\`\`
+
+## Notes
+
+- **Every non-browser caller must send \`Origin: <base>\`.** \`proxy.ts\` blocks
+ mutating \`/api\` requests that cannot prove same-origin; a browser proves it with
+ \`Sec-Fetch-Site\`, and the documented fallback is an \`Origin\` whose host matches
+ \`Host\`. \`mso\` does this for you. Without it, login itself returns 403
+ \`cross_origin_blocked\` — before any device check — which looks like an approval
+ problem and is not.
+- \`--base\` targets another instance; the cookie jar is keyed by base, so switching
+ never reuses a session minted for a different origin.
+- \`raw\`, \`zip\` and \`term stream\` stream to stdout — redirect them to a file.
+`;
+
+if (process.argv.includes("--check")) {
+ const current = (() => {
+ try {
+ return readFileSync(out, "utf8");
+ } catch {
+ return "";
+ }
+ })();
+ if (current !== doc) {
+ console.error("docs/CLI.md is stale — run: node scripts/gen-cli-docs.mjs");
+ process.exit(1);
+ }
+ console.log("docs/CLI.md is current");
+} else {
+ writeFileSync(out, doc);
+ console.log(`wrote ${out}`);
+}