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(settings,preview): update MSO from the app, and preview the formats a real disk has

Rahman4defd22ea475
diff --git a/.env.example b/.env.example
index 7f5894a3..f1559f96 100644
--- a/.env.example
+++ b/.env.example
@@ -32,6 +32,11 @@ OS_SESSION_SECRET=
# OS_EXEC_ALLOW_DESTRUCTIVE=1
# Append-only audit trail of exec/file/browser/auth actions. Default path below.
# OS_AUDIT_LOG=~/.mso/audit.log
+# Transcript of the last Settings → About "Software update" run — the panel polls
+# this file, and scripts/self-update.sh truncates it on every start. Rarely worth
+# moving; it is here because the updater runs as a transient systemd unit and the
+# path is passed to it explicitly rather than inherited.
+# MSO_UPDATE_LOG=~/.mso/self-update.log
# Number of trusted reverse-proxy hops in front of the app. The login rate
# limiter keys on the (N-from-last) x-forwarded-for hop, so a wrong value
# collapses every client into one bucket (too small N) or trusts spoofed
diff --git a/app/api/v1/sys/update/route.ts b/app/api/v1/sys/update/route.ts
new file mode 100644
index 00000000..64249a34
--- /dev/null
+++ b/app/api/v1/sys/update/route.ts
@@ -0,0 +1,47 @@
+import { NextResponse } from "next/server";
+import { verifyAuth } from "@/lib/agent/server";
+import { apiError, audit, readJson } from "@/lib/host";
+import { getUpdateStatus, startUpdate } from "@/lib/host/self-update";
+
+export const dynamic = "force-dynamic";
+// The GET runs `git fetch`, and the POST hands off to systemd-run. Neither is a
+// static thing and both need the host, so this is Node, never the edge.
+export const runtime = "nodejs";
+
+// GET /sys/update → what version is running, what is on origin/main, and the log of
+// the last run. `?check=0` skips the network round trip, which is what the panel
+// polls with while an update is in flight.
+export async function GET(req: Request) {
+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
+ try {
+ const check = new URL(req.url).searchParams.get("check") !== "0";
+ return NextResponse.json(await getUpdateStatus(check));
+ } catch (e) {
+ return apiError("sys/update", e);
+ }
+}
+
+// POST /sys/update {rebuildOnly?} → pull, verify, build, restart. Audited: this
+// replaces the code the whole cockpit runs, which is the most consequential thing
+// any session can ask for. Body carries no ref and no command — the only knob is a
+// boolean, and `origin/main` is hard-coded in the updater.
+export async function POST(req: Request) {
+ if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
+ try {
+ const body = (await readJson(req).catch(() => ({}))) as { rebuildOnly?: unknown };
+ const rebuildOnly = body.rebuildOnly === true;
+ const status = await startUpdate(rebuildOnly);
+ audit({
+ action: "sys.update",
+ target: rebuildOnly ? "rebuild" : `origin/main (+${status.behind})`,
+ ok: true,
+ detail: `from ${status.current}`,
+ });
+ return NextResponse.json(status);
+ } catch (e) {
+ // A refusal ("already up to date", "an update is already running") is a
+ // HostError → 400 via apiError, and reads as the sentence it is.
+ audit({ action: "sys.update", target: "start", ok: false, detail: String(e).slice(0, 200) });
+ return apiError("sys/update", e);
+ }
+}
diff --git a/bin/mso b/bin/mso
index 51602928..3c39f46f 100755
--- a/bin/mso
+++ b/bin/mso
@@ -74,6 +74,7 @@
# service * status | start | stop | restart | logs
# build Compile HEAD out-of-tree (safe against the live checkout)
# deploy next build, then restart the service
+# update [run] What is on origin/main; `run` pulls, verifies, builds, restarts
#
# Escape hatches
# crud * Generic resource CRUD, incl. editor documents
@@ -239,6 +240,7 @@ U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|u
U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"
U_device="device list|pending|approve <id> [label]|revoke <id>|revoke all --yes"
U_service="service status|start|stop|restart|logs [n]"
+U_update="update status|run [true]|log"
U_threads="threads list|show <id>|save <json>|rm <id>"
U_memory="memory list|add <text>|rm <id>"
U_config="config show|set <json>|rm <provider>"
@@ -490,6 +492,16 @@ case "$cmd" in
# one, and it restarts immediately after.
build) (cd "$ROOT" && bash scripts/verify-build.sh) ;;
deploy) (cd "$ROOT" && npm run build) && sudo systemctl restart mso.service && echo "deployed → $B" ;;
+ # The same self-update Settings → About drives, so both surfaces get the same
+ # preflight and the same transient-unit handoff (a build spawned from the service
+ # would be killed by the restart it performs).
+ update)
+ case "${1:-status}" in
+ status) jget "/api/v1/sys/update" ;;
+ run) jpost "/api/v1/sys/update" "$(jq -n --argjson r "${2:-false}" '{rebuildOnly:$r}')" ;;
+ log) jget "/api/v1/sys/update?check=0" | jq -r .log ;;
+ *) die "usage: mso $U_update" ;;
+ esac ;;
# ── editor-document CRUD (one pattern, all editor features) ──────────────
crud)
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 6e3f4251..370077fc 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
## 2026-08-17
+**Added**
+
+- `settings,preview` update MSO from the app, and preview the formats a real disk has
+
**Fixed**
- `deps` pin nanoid >=3.3.18 — the audit gate has been failing on main
diff --git a/docs/CLI.md b/docs/CLI.md
index 72ad81f2..4b6b7384 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -108,6 +108,7 @@ Commands:
service * status | start | stop | restart | logs
build Compile HEAD out-of-tree (safe against the live checkout)
deploy next build, then restart the service
+ update [run] What is on origin/main; `run` pulls, verifies, builds, restarts
Escape hatches
crud * Generic resource CRUD, incl. editor documents
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 840fc41c..96553c18 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -8,6 +8,69 @@ Running log of what shipped each phase. Newest at top.
> Read those phases as history. **This file is the source of truth for what exists** —
> `ARCHITECTURE.md` is no longer maintained and carries a stale-warning banner.
+## 2026-08-17 — the deploy became a button, and Preview learned the rest of the disk (DONE)
+
+Two PRs from the fork merged first (#2 user bus, #3 dashboard silence), then two
+features on top. The audit gate had been failing on `main` before any of it —
+`GHSA-2v37-7h3g-55p8`, nanoid `<3.3.18` through postcss — so `main` was unpushable
+without `--no-verify`; pinned via `overrides`, which is what the gate's own message
+asks for.
+
+**Software update, in Settings → About.** Prod is systemd with no webhook, so a
+commit on main changed nothing anyone could see until someone with ssh rebuilt. Now
+the panel reports what is on `origin/main`, lists the incoming commits, and runs the
+deploy.
+
+Three things about it are load-bearing:
+
+- **The work does not run in `mso.service`.** Its last step is `systemctl restart
+ mso.service`, and systemd's default KillMode kills the whole cgroup — a detached
+ child included. It would die mid-`next build`, with `.next` already deleted (the
+ build's first act) and nothing to restart into. So `startUpdate()` hands the job to
+ a TRANSIENT unit via `sudo systemd-run --collect --unit=mso-self-update`, which
+ lives in its own cgroup and survives the restart it performs.
+- **It verifies out-of-tree BEFORE building in place.** `scripts/ship.sh` is run by a
+ person who is watching; this is run by an operator who pressed a button and walked
+ away. `scripts/verify-build.sh` proves the pulled HEAD compiles without touching
+ the live `.next`, so a commit that does not build becomes a refusal instead of an
+ outage. An in-place build cannot be undone — there is no old `.next` to put back.
+- **Nothing from the request reaches a shell.** The only knob is a boolean; the ref
+ is hard-coded to `origin/main`. Refusals (dirty checkout, already up to date, one
+ already running) are computed in a pure `blockingReason()` so they happen before
+ anything is touched, and `sys.update` is a new audit action — this replaces the
+ code the whole cockpit runs.
+
+The panel's "Release notes and docs" drawer lists the incoming commits (from
+`git log HEAD..origin/main`, because the CHANGELOG in this checkout is by definition
+the old one — it arrives WITH the update it describes), then the shipped changelog,
+then links to README/CHANGELOG/PROGRESS/CLI. `mso update status|run|log` is the same
+surface from a shell.
+
+**Preview now covers the disk, not four formats.** One table
+(`media-viewer/lib/kinds.ts`) exported through the slice barrel and used by BOTH the
+viewer and Files, so the two can no longer disagree about what a `.heic` is:
+
+- image/video/audio grew the Windows + macOS defaults (heic/heif, tiff, jfif, m4v,
+ wmv, mpg, 3gp, opus, aac, wma…). The server MIME map grew to match — **passive
+ types only**; `text/html` there would make any host file an active document on the
+ cockpit's origin, which is the same hazard the SVG `sandbox` header already exists
+ for.
+- **text, Markdown, CSV/TSV and HTML** render, and their bytes are FETCHED (Range-
+ capped at 512 KB) rather than framed. HTML goes into a `sandbox=""` `srcdoc` frame:
+ no scripts, opaque origin, and therefore no relative assets — the price of not
+ handing a host file the session's origin.
+- **Documents and archives are `none` on purpose** (docx/xlsx/pptx/pages/zip/dmg/exe…).
+ A browser cannot render them, and a viewer that pretends otherwise shows a blank
+ frame that reads as MSO being broken. They get a card that names the format and
+ offers the download.
+- **← → through the folder**, plus the arrow keys, on every previewable file. The
+ sibling list comes from one `fs.list` of the parent, not from the payload, so a
+ window opened by deep link or by the assistant pages exactly like one opened from
+ the grid.
+- Files gained **Preview** in the context menu and **Space** as its shortcut (the
+ macOS Quick Look binding), because a `.md` or `.csv` double-click correctly goes to
+ the editor, and reading it is a different verb from editing it.
+
## 2026-08-11 — shells to their 2026 specs, and a backup for the state that had none (DONE)
Five parallel packages on strictly disjoint file sets, each reviewed against its own
diff --git a/frontend/slices/files-manager/app.tsx b/frontend/slices/files-manager/app.tsx
index 2726bd68..0c12093d 100644
--- a/frontend/slices/files-manager/app.tsx
+++ b/frontend/slices/files-manager/app.tsx
@@ -20,6 +20,7 @@ import { useDnd } from "./hooks/use-dnd";
import { useWindowDrop } from "./hooks/use-window-drop";
import { useTypeahead } from "./hooks/use-typeahead";
import { sortEntries, type SortKey, type ViewMode } from "./lib/types";
+import { canPreview } from "./lib/icons";
// Optional `{ path }` payload (e.g. from Spotlight) opens the manager there.
function initialPath(payload: unknown): string | undefined {
@@ -186,6 +187,8 @@ export default function FilesManager({ payload }: AppProps) {
inTrash={cmd.inTrash}
onClose={() => cmd.setCtx(null)}
onOpen={() => cmd.ctx?.entry && cmd.open(cmd.ctx.entry)}
+ canPreview={!!cmd.ctx?.entry && canPreview(cmd.ctx.entry)}
+ onPreview={() => cmd.ctx?.entry && cmd.preview(cmd.ctx.entry)}
onOpenClaudeCode={() => cmd.ctx?.entry && cmd.openInClaudeCode(cmd.ctx.entry)}
onRename={() => cmd.ctx?.entry && cmd.setRenaming(cmd.ctx.entry.name)}
onNewFolder={cmd.newFolder}
diff --git a/frontend/slices/files-manager/components/file-context-menu.tsx b/frontend/slices/files-manager/components/file-context-menu.tsx
index 9a4bea85..82b685b4 100644
--- a/frontend/slices/files-manager/components/file-context-menu.tsx
+++ b/frontend/slices/files-manager/components/file-context-menu.tsx
@@ -37,8 +37,10 @@ export function FileContextMenu({
hasClipboard,
inTrash,
downloadCount,
+ canPreview,
onClose,
onOpen,
+ onPreview,
onOpenClaudeCode,
onRename,
onNewFolder,
@@ -54,8 +56,12 @@ export function FileContextMenu({
hasClipboard: boolean;
inTrash: boolean;
downloadCount: number;
+ /** Preview can render this entry — hidden for folders and for formats it would
+ * only offer a download for, where "Open" already lands in the same place. */
+ canPreview: boolean;
onClose: () => void;
onOpen: () => void;
+ onPreview: () => void;
onOpenClaudeCode: () => void;
onRename: () => void;
onNewFolder: () => void;
@@ -105,6 +111,7 @@ export function FileContextMenu({
? [
[
{ label: "Open", run: onOpen },
+ ...(canPreview ? [{ label: "Preview", shortcut: "Space", run: onPreview }] : []),
...(ctx.entry.kind === "dir" ? [{ label: "Open with Claude Code", run: onOpenClaudeCode }] : []),
{ label: "Rename", shortcut: "↵", run: onRename },
],
diff --git a/frontend/slices/files-manager/hooks/use-file-commands.ts b/frontend/slices/files-manager/hooks/use-file-commands.ts
index d03b3975..569f92c0 100644
--- a/frontend/slices/files-manager/hooks/use-file-commands.ts
+++ b/frontend/slices/files-manager/hooks/use-file-commands.ts
@@ -50,6 +50,18 @@ export function useFileCommands(fs: UseFiles, sel: UseFileSelection) {
[fs.path, go],
);
+ // "Preview" — the second route for a file whose double-click goes to the editor
+ // (Markdown, CSV, HTML): render it instead of showing its source, and get ← →
+ // through the folder for free.
+ const preview = useCallback(
+ (entry: FsEntry) => {
+ if (entry.kind !== "file") return;
+ const path = joinPath(fs.path, entry.name);
+ openWindow("media-viewer", entry.name, undefined, { path, name: entry.name, kind: mediaKind(entry) });
+ },
+ [fs.path],
+ );
+
// "Open with Claude Code" on a folder → a fresh Claude Code PTY (multi:true so
// each folder gets its own session) cd'd into that folder. Dir-only; the
// terminal only actually runs the CLI in live mode (host-gated).
@@ -190,6 +202,13 @@ export function useFileCommands(fs: UseFiles, sel: UseFileSelection) {
else if (mod && e.key === "x" && names.length) cut(names);
else if (mod && e.key === "v") fs.paste();
else if (e.key === "Enter" && names.length === 1) setRenaming(names[0]);
+ else if (e.key === " " && names.length === 1) {
+ // Quick Look, the macOS binding — and the one the context menu advertises.
+ // preventDefault or the space scrolls the list under the window.
+ e.preventDefault();
+ const entry = fs.entries?.find((x) => x.name === names[0]);
+ if (entry) preview(entry);
+ }
else if ((e.key === "Backspace" || e.key === "Delete") && names.length) {
e.preventDefault();
del(names);
@@ -198,11 +217,11 @@ export function useFileCommands(fs: UseFiles, sel: UseFileSelection) {
fs.setClip(null);
}
},
- [copy, cut, del, fs, renaming, sel],
+ [copy, cut, del, fs, preview, renaming, sel],
);
return {
renaming, setRenaming, ctx, setCtx, inTrash, zipPrompt, setZipPrompt,
- go, open, openInClaudeCode, openPath, onContext, targets, cut, copy, del, download, confirmZip, emptyTrash, doRename, newFolder, onKey,
+ go, open, preview, openInClaudeCode, openPath, onContext, targets, cut, copy, del, download, confirmZip, emptyTrash, doRename, newFolder, onKey,
};
}
diff --git a/frontend/slices/files-manager/lib/icons.ts b/frontend/slices/files-manager/lib/icons.ts
index f7dcb3a2..86414d87 100644
--- a/frontend/slices/files-manager/lib/icons.ts
+++ b/frontend/slices/files-manager/lib/icons.ts
@@ -2,6 +2,7 @@ import {
Folder, FileText, Image, Code2, FileVideo, Music, FileArchive,
FileJson, FileSpreadsheet, Terminal, Globe, type LucideIcon,
} from "lucide-react";
+import { kindForName, isPreviewable, type ViewKind } from "@/features/media-viewer";
import type { FsEntry } from "./host";
const IMAGE = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "avif"]);
@@ -10,13 +11,17 @@ const AUDIO = new Set(["mp3", "wav", "aiff", "m4a", "flac"]);
const CODE = new Set(["ts", "tsx", "js", "jsx", "py", "go", "rs", "css"]);
const ARCHIVE = new Set(["zip", "gz", "tar", "rar", "7z"]);
-// Map an entry to its display icon. Dirs always Folder; files by ext.
+// Map an entry to its display icon. Dirs always Folder; files by kind, then by the
+// few exts that deserve their own glyph. The media families come from the viewer's
+// table so a .heic gets a picture icon and a .m4v a film one — the local sets below
+// only survive for the non-media groupings the viewer has no opinion about.
export function iconFor(entry: FsEntry): LucideIcon {
if (entry.kind === "dir") return Folder;
const ext = entry.ext?.toLowerCase() ?? "";
- if (IMAGE.has(ext)) return Image;
- if (VIDEO.has(ext)) return FileVideo;
- if (AUDIO.has(ext)) return Music;
+ const kind = kindForName(entry.name);
+ if (kind === "image") return Image;
+ if (kind === "video") return FileVideo;
+ if (kind === "audio") return Music;
if (ext === "json") return FileJson;
if (ext === "csv") return FileSpreadsheet;
if (ext === "sh") return Terminal;
@@ -42,27 +47,35 @@ export function colorFor(entry: FsEntry): string {
return "text-muted-foreground";
}
-// Which OS app opens this file (by ext) — used to route openWindow.
+// Which OS app opens this file on a double-click.
+//
+// Text and code go to the EDITOR, not to Preview: for a file you can change, "open"
+// means edit. Everything Preview can render but nothing can edit (media, PDF,
+// documents) goes to Preview — including the formats it can only offer a download
+// for, because a window that names the format beats a double-click that does
+// nothing, which is what an unknown extension used to do.
export function appForFile(entry: FsEntry): "media-viewer" | "code-editor" | null {
if (entry.kind === "dir") return null;
- const ext = entry.ext?.toLowerCase() ?? "";
- if (IMAGE.has(ext) || VIDEO.has(ext) || AUDIO.has(ext) || ext === "pdf") return "media-viewer";
- if (CODE.has(ext) || ["json", "md", "txt", "html", "sh"].includes(ext)) return "code-editor";
- return null;
+ const kind = kindForName(entry.name);
+ if (kind === "text" || kind === "markdown" || kind === "csv" || kind === "html") return "code-editor";
+ return "media-viewer";
}
+/** "Preview" — the OTHER route, offered in the context menu. Rendering is what
+ * Preview is for, so a .md, .csv or .html can be READ without opening an editor,
+ * and the ← → paging works for every previewable file in the folder. */
+export const canPreview = (entry: FsEntry): boolean =>
+ entry.kind === "file" && isPreviewable(kindForName(entry.name));
+
// True for raster/vector image files — used to show a real thumbnail in grid
-// view (rendered via /api/v1/fs/raw) instead of a generic icon.
+// view (rendered via /api/v1/fs/raw) instead of a generic icon. Same table as the
+// viewer: a format it calls an image is one the grid should try to thumbnail, and
+// a browser that cannot decode it falls back to the icon on its own.
export function isImage(entry: FsEntry): boolean {
- return entry.kind === "file" && IMAGE.has(entry.ext?.toLowerCase() ?? "");
+ return entry.kind === "file" && kindForName(entry.name) === "image";
}
-// Media kind for the media-viewer payload (by ext family).
-export type MediaKind = "image" | "video" | "audio" | "pdf";
-export function mediaKind(entry: FsEntry): MediaKind {
- const ext = entry.ext?.toLowerCase() ?? "";
- if (VIDEO.has(ext)) return "video";
- if (AUDIO.has(ext)) return "audio";
- if (ext === "pdf") return "pdf";
- return "image";
-}
+// Media kind for the media-viewer payload — the viewer's OWN table, so Files and
+// Preview can never disagree about what a `.heic` or a `.csv` is. (The viewer
+// re-derives it from the name anyway; this keeps the payload informative.)
+export const mediaKind = (entry: FsEntry): ViewKind => kindForName(entry.name);
diff --git a/frontend/slices/media-viewer/components/fallback-card.tsx b/frontend/slices/media-viewer/components/fallback-card.tsx
new file mode 100644
index 00000000..d615f20f
--- /dev/null
+++ b/frontend/slices/media-viewer/components/fallback-card.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { Download, FileQuestion, Pencil } from "lucide-react";
+import { Button } from "@/components/ui/button";
+
+// The end of the road for bytes no browser renders — .docx, .zip, a codec the
+// build has no decoder for. It names the format instead of showing a blank frame,
+// because a blank frame reads as "MSO is broken" and sends people looking for a
+// fault that is not there. The download is the real answer, so it is the button.
+export function FallbackCard({
+ name,
+ ext,
+ reason,
+ onDownload,
+ editorLabel,
+ onOpenEditor,
+}: {
+ name: string;
+ ext: string;
+ reason: string;
+ onDownload: () => void;
+ editorLabel?: string;
+ onOpenEditor?: () => void;
+}) {
+ return (
+ <div className="flex w-full max-w-md flex-col items-center gap-3 rounded-xl border bg-card/80 p-6 text-center text-muted-foreground shadow-2xl backdrop-blur sm:p-8">
+ <div className="grid size-14 place-items-center rounded-2xl bg-muted text-foreground">
+ <FileQuestion className="size-7" />
+ </div>
+ <div className="w-full break-words text-sm font-semibold text-foreground">{name}</div>
+ <p className="max-w-[320px] text-xs leading-relaxed">
+ {reason}
+ {ext && <span className="ml-1 font-mono uppercase">({ext})</span>}
+ </p>
+ <div className="flex flex-wrap justify-center gap-2">
+ <Button size="sm" onClick={onDownload} className="[@media(pointer:coarse)]:min-h-[44px]">
+ <Download className="size-3.5" />
+ Download
+ </Button>
+ {editorLabel && onOpenEditor && (
+ <Button size="sm" variant="secondary" onClick={onOpenEditor} className="[@media(pointer:coarse)]:min-h-[44px]">
+ <Pencil className="size-3.5" />
+ Open in {editorLabel}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/slices/media-viewer/components/remote-view.tsx b/frontend/slices/media-viewer/components/remote-view.tsx
index 851d0e00..aa5c9297 100644
--- a/frontend/slices/media-viewer/components/remote-view.tsx
+++ b/frontend/slices/media-viewer/components/remote-view.tsx
@@ -1,73 +1,114 @@
"use client";
-import { useEffect, useState } from "react";
-import { ImageIcon, FileText, Film, Music, Pencil } from "lucide-react";
+import { useCallback, useEffect, useState } from "react";
+import { ChevronLeft, ChevronRight, Download, Music, Pencil } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { AppFrame, openWindow, usePublishInspector } from "@/features/os-shell";
import { rawUrl } from "../lib/host";
import { cn } from "@/lib/utils";
import { editorFor } from "../lib/media";
+import { kindForName, isTextual, type ViewKind } from "../lib/kinds";
+import { useSiblings } from "../lib/use-siblings";
+import { TextView } from "./text-view";
+import { FallbackCard } from "./fallback-card";
-export type MediaKind = "image" | "video" | "audio" | "pdf";
-export type RemoteFile = { path: string; name: string; kind: MediaKind };
+export type RemoteFile = { path: string; name: string; kind: ViewKind };
// Checkerboard stage so transparent/letterboxed media reads clearly.
-const STAGE =
- "bg-[repeating-conic-gradient(var(--muted)_0_25%,transparent_0_50%)] bg-[length:24px_24px]";
+const STAGE = "bg-[repeating-conic-gradient(var(--muted)_0_25%,transparent_0_50%)] bg-[length:24px_24px]";
-// Renders a real host file by streaming its bytes from /api/v1/fs/raw (the
-// session cookie authenticates the <img>/<video>/<audio> src directly). Edit
-// hands off to the Image/Video editor by kind (never the code editor); falls
-// back to that handoff if the format can't render.
+// A real host file, streamed from /api/v1/fs/raw (the session cookie authenticates
+// the <img>/<video>/<audio> src directly), with ← → through the rest of the folder.
export function RemoteView({ file }: { file: RemoteFile }) {
- // Remember WHICH path failed — a different file derives back to "no error"
- // without an effect-driven reset (react-hooks/set-state-in-effect).
+ // The window opens on one file and then pages; `current` is what is on screen.
+ // Keyed by path so a NEW payload (a second Open from Files) wins over paging.
+ const [paged, setPaged] = useState<RemoteFile | null>(null);
+ const current = paged?.path && paged.path !== file.path ? paged : file;
+ const { index, items, go } = useSiblings(current.path, current.name);
const [failedPath, setFailedPath] = useState<string | null>(null);
- const failed = failedPath === file.path;
- const setFailed = (v: boolean) => setFailedPath(v ? file.path : null);
- const src = rawUrl(file.path);
- const editor = editorFor(file.kind); // image → Image Editor, video/audio → Video Editor
+ const failed = failedPath === current.path;
- const openInEditor = () => {
+ const kind = current.kind;
+ const src = rawUrl(current.path);
+ const editor = editorFor(kind);
+ const ext = current.name.includes(".") ? (current.name.split(".").pop() ?? "") : "";
+
+ const step = useCallback(
+ (delta: number) => {
+ const next = go(delta);
+ if (next) setPaged({ path: next.path, name: next.name, kind: next.kind });
+ },
+ [go],
+ );
+
+ // ← → anywhere in the window, the way Preview and Photos both behave. Bound on
+ // the window's own document; typing in an input is not a case here (the viewer
+ // has no text field), so no focus guard is needed beyond ignoring modifiers.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ if (e.key === "ArrowLeft") step(-1);
+ else if (e.key === "ArrowRight") step(1);
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [step]);
+
+ const download = useCallback(() => {
+ const a = document.createElement("a");
+ a.href = src;
+ a.download = current.name;
+ a.rel = "noopener";
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ }, [src, current.name]);
+
+ const openInEditor = useCallback(() => {
if (!editor) return;
- openWindow(editor.app, file.name, undefined, {
- path: file.path,
- name: file.name,
- kind: file.kind,
- });
- };
+ openWindow(editor.app, current.name, undefined, { path: current.path, name: current.name, kind });
+ }, [editor, current.path, current.name, kind]);
usePublishInspector(
"media-viewer",
{
- subject: file.name,
+ subject: current.name,
props: [
- { label: "Type", value: file.kind },
- { label: "Source", value: file.path },
+ { label: "Type", value: kind },
+ { label: "Source", value: current.path },
+ ...(items.length > 1 ? [{ label: "In folder", value: `${index + 1} of ${items.length}` }] : []),
+ ],
+ actions: [
+ { id: "download", label: "Download", run: download },
+ ...(editor ? [{ id: "edit", label: `Open in ${editor.label}`, run: openInEditor }] : []),
],
- actions: editor
- ? [{ id: "edit", label: `Open in ${editor.label}`, run: openInEditor }]
- : [],
- context: `Viewing ${file.name} (${file.kind})`,
+ context: `Viewing ${current.name} (${kind})`,
suggestions: ["Describe this", "Suggest edits", "What format is best?"],
},
- [file.path, file.name, file.kind, editor?.app],
+ [current.path, current.name, kind, editor?.app, index, items.length],
);
- const Icon =
- file.kind === "video" ? Film : file.kind === "audio" ? Music : file.kind === "pdf" ? FileText : ImageIcon;
- const isPdf = file.kind === "pdf";
+ const paging = items.length > 1;
+ const fullBleed = kind === "pdf" || isTextual(kind);
return (
<AppFrame
className="bg-background"
header={
<header className="flex items-center gap-2 bg-background/60 px-3 py-2">
- <span className="min-w-0 flex-1 truncate text-sm font-semibold">{file.name}</span>
- <Badge variant="secondary" className="font-mono text-[10px] uppercase">
- {file.kind}
+ <span className="min-w-0 flex-1 truncate text-sm font-semibold">{current.name}</span>
+ {paging && (
+ <span className="hidden shrink-0 text-[11px] tabular-nums text-muted-foreground sm:inline">
+ {index + 1} / {items.length}
+ </span>
+ )}
+ <Badge variant="secondary" className="shrink-0 font-mono text-[10px] uppercase">
+ {kind === "none" ? (ext || "file") : kind}
</Badge>
+ <Button size="sm" variant="ghost" onClick={download} aria-label="Download">
+ <Download className="size-3.5" />
+ </Button>
{editor && (
<Button size="sm" variant="ghost" onClick={openInEditor} aria-label={`Open in ${editor.label}`}>
<Pencil className="size-3.5" />
@@ -77,87 +118,94 @@ export function RemoteView({ file }: { file: RemoteFile }) {
}
bodyClassName="flex flex-col"
>
- {/* PDF fills the window edge-to-edge; visual media sits on a padded
- checkerboard stage and scales to fit (up or down). */}
- <div
- className={cn(
- "flex min-h-0 flex-1",
- isPdf ? "" : cn("items-center justify-center overflow-hidden p-3", STAGE),
- )}
- >
- {failed ? (
- <FallbackCard name={file.name} Icon={Icon} editorLabel={editor?.label} onOpen={openInEditor} />
- ) : file.kind === "image" ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={src}
- alt={file.name}
- onError={() => setFailed(true)}
- className="h-full w-full object-contain"
- />
- ) : file.kind === "video" ? (
- <video
- src={src}
- controls
- onError={() => setFailed(true)}
- className="h-full w-full object-contain"
- />
- ) : file.kind === "audio" ? (
- <div className="flex w-full max-w-lg flex-col items-center gap-4 rounded-2xl border bg-card/80 p-6 shadow-2xl backdrop-blur">
- <div className="grid size-14 place-items-center rounded-xl bg-[var(--accent)]/15 text-[var(--accent)]">
- <Music className="size-7" />
+ <div className="relative flex min-h-0 flex-1">
+ <div
+ className={cn(
+ "flex min-h-0 w-full flex-1",
+ fullBleed && !failed ? "" : cn("items-center justify-center overflow-hidden p-3", STAGE),
+ )}
+ >
+ {failed || kind === "none" ? (
+ <FallbackCard
+ name={current.name}
+ ext={ext}
+ reason={failed ? "This browser could not decode the file." : "No browser can render this format."}
+ onDownload={download}
+ editorLabel={failed ? editor?.label : undefined}
+ onOpenEditor={openInEditor}
+ />
+ ) : kind === "image" ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ key={current.path}
+ src={src}
+ alt={current.name}
+ onError={() => setFailedPath(current.path)}
+ className="h-full w-full object-contain"
+ />
+ ) : kind === "video" ? (
+ <video
+ key={current.path}
+ src={src}
+ controls
+ playsInline
+ onError={() => setFailedPath(current.path)}
+ className="h-full w-full object-contain"
+ />
+ ) : kind === "audio" ? (
+ <div className="flex w-full max-w-lg flex-col items-center gap-4 rounded-2xl border bg-card/80 p-6 shadow-2xl backdrop-blur">
+ <div className="grid size-14 place-items-center rounded-xl bg-[var(--accent)]/15 text-[var(--accent)]">
+ <Music className="size-7" />
+ </div>
+ <div className="w-full truncate text-center text-sm font-semibold">{current.name}</div>
+ <audio key={current.path} src={src} controls onError={() => setFailedPath(current.path)} className="w-full" />
</div>
- <div className="w-full truncate text-center text-sm font-semibold">{file.name}</div>
- <audio src={src} controls onError={() => setFailed(true)} className="w-full" />
- </div>
- ) : (
- // pdf (and anything else routed here) → full-bleed embed
- <iframe src={src} title={file.name} className="h-full w-full border-0 bg-white" />
+ ) : isTextual(kind) ? (
+ <TextView key={current.path} path={current.path} name={current.name} kind={kind} />
+ ) : (
+ <iframe key={current.path} src={src} title={current.name} className="h-full w-full border-0 bg-white" />
+ )}
+ </div>
+
+ {/* Overlaid, not in the toolbar: the arrows belong next to what they page.
+ 44px targets on touch, and they sit above a PDF/HTML frame that swallows
+ its own clicks. */}
+ {paging && (
+ <>
+ <PageButton side="left" onClick={() => step(-1)} />
+ <PageButton side="right" onClick={() => step(1)} />
+ </>
)}
</div>
</AppFrame>
);
}
-function FallbackCard({
- name,
- Icon,
- editorLabel,
- onOpen,
-}: {
- name: string;
- Icon: typeof ImageIcon;
- editorLabel?: string;
- onOpen: () => void;
-}) {
+function PageButton({ side, onClick }: { side: "left" | "right"; onClick: () => void }) {
+ const Icon = side === "left" ? ChevronLeft : ChevronRight;
return (
- <div className="flex w-full max-w-md flex-col items-center gap-3 rounded-xl border bg-card/80 p-8 text-center text-muted-foreground shadow-2xl backdrop-blur">
- <div className="grid size-14 place-items-center rounded-2xl bg-muted text-foreground">
- <Icon className="size-7" />
- </div>
- <div className="text-sm font-semibold text-foreground">{name}</div>
- <p className="max-w-[300px] text-xs leading-relaxed">
- {editorLabel
- ? "Couldn't preview this file here — open it in the editor."
- : "Couldn't preview this file here."}
- </p>
- {editorLabel && (
- <Button size="sm" variant="secondary" onClick={onOpen}>
- <Pencil className="size-3.5" />
- Open in {editorLabel}
- </Button>
+ <button
+ type="button"
+ onClick={onClick}
+ aria-label={side === "left" ? "Previous file" : "Next file"}
+ className={cn(
+ "absolute top-1/2 z-10 grid size-9 -translate-y-1/2 place-items-center rounded-full border bg-background/80 text-foreground shadow-lg backdrop-blur transition-opacity hover:bg-background",
+ "[@media(pointer:coarse)]:size-11",
+ side === "left" ? "left-2" : "right-2",
)}
- </div>
+ >
+ <Icon className="size-5" />
+ </button>
);
}
-// Extract a `{ path, name, kind }` remote-file from the window payload.
+/** Extract a `{ path, name, kind }` remote-file from the window payload. The kind
+ * is derived from the NAME, not trusted from the payload: callers disagreed about
+ * it (Files sent its own four-value enum), and the file's extension is the fact. */
export function remoteFile(payload: unknown): RemoteFile | null {
if (!payload || typeof payload !== "object") return null;
- const p = payload as Partial<RemoteFile>;
+ const p = payload as { path?: unknown; name?: unknown };
if (typeof p.path !== "string" || !p.path) return null;
- const kind: MediaKind = (["image", "video", "audio", "pdf"] as const).includes(p.kind as MediaKind)
- ? (p.kind as MediaKind)
- : "image";
- return { path: p.path, name: p.name ?? p.path, kind };
+ const name = typeof p.name === "string" && p.name ? p.name : (p.path.split("/").pop() ?? p.path);
+ return { path: p.path, name, kind: kindForName(name) };
}
diff --git a/frontend/slices/media-viewer/components/text-view.tsx b/frontend/slices/media-viewer/components/text-view.tsx
new file mode 100644
index 00000000..e21abbd4
--- /dev/null
+++ b/frontend/slices/media-viewer/components/text-view.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Code2, Eye } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { mdToHtml } from "@/features/os-shell";
+import { rawUrl } from "../lib/host";
+import type { ViewKind } from "../lib/kinds";
+
+// Everything the browser cannot render by pointing an element at a URL: text,
+// Markdown, CSV/TSV and HTML. The bytes are FETCHED and rendered here.
+//
+// For HTML that is a security decision, not a convenience: framing
+// /api/v1/fs/raw would make an arbitrary host file an active document on the
+// cockpit's own origin, with the session cookie attached. Instead the source goes
+// into a fully sandboxed `srcdoc` iframe (no allow-scripts, no allow-same-origin),
+// so it renders as layout and nothing more. Relative images inside it will not
+// load — that is the price of not handing a file the origin.
+
+/** One screenful and then some. Enough to read; small enough that a 2 GB log
+ * cannot be pulled into the tab by a double-click. Served by a Range request,
+ * which /api/v1/fs/raw already supports for video seeking. */
+const MAX_BYTES = 512 * 1024;
+const MAX_ROWS = 500;
+
+interface Loaded {
+ path: string;
+ text: string | null;
+ truncated: boolean;
+ error: string | null;
+}
+
+function useFileText(path: string): Omit<Loaded, "path"> {
+ // The load carries WHICH path it is for, so paging to the next file derives back
+ // to "loading" instead of resetting state from inside an effect
+ // (react-hooks/set-state-in-effect) — the same shape remote-view uses for errors.
+ const [loaded, setLoaded] = useState<Loaded | null>(null);
+
+ useEffect(() => {
+ let alive = true;
+ // Range, not a whole-file read: /api/v1/fs/raw already serves 206 for video
+ // seeking, and a 2 GB log must not become a 2 GB string in the tab.
+ fetch(rawUrl(path), { headers: { Range: `bytes=0-${MAX_BYTES - 1}` }, cache: "no-store" })
+ .then(async (res) => {
+ if (!res.ok && res.status !== 206) throw new Error(`HTTP ${res.status}`);
+ const body = await res.text();
+ if (alive) setLoaded({ path, text: body, truncated: body.length >= MAX_BYTES - 1, error: null });
+ })
+ .catch(() => alive && setLoaded({ path, text: null, truncated: false, error: "Could not read this file." }));
+ return () => {
+ alive = false;
+ };
+ }, [path]);
+
+ return loaded?.path === path ? loaded : { text: null, truncated: false, error: null };
+}
+
+/** Split on commas/tabs, honouring "quoted, fields" — the one CSV rule that
+ * actually bites. Anything fancier belongs in a spreadsheet, not a preview. */
+function parseRows(text: string, sep: string): string[][] {
+ return text
+ .split(/\r?\n/)
+ .filter((line) => line.length > 0)
+ .slice(0, MAX_ROWS)
+ .map((line) => {
+ const cells: string[] = [];
+ let cell = "";
+ let quoted = false;
+ for (let i = 0; i < line.length; i++) {
+ const ch = line[i];
+ if (ch === '"') {
+ if (quoted && line[i + 1] === '"') {
+ cell += '"';
+ i++;
+ } else quoted = !quoted;
+ } else if (ch === sep && !quoted) {
+ cells.push(cell);
+ cell = "";
+ } else cell += ch;
+ }
+ cells.push(cell);
+ return cells;
+ });
+}
+
+export function TextView({ path, name, kind }: { path: string; name: string; kind: ViewKind }) {
+ const { text, truncated, error } = useFileText(path);
+ const [source, setSource] = useState(false);
+
+ if (error) return <p className="p-4 text-sm text-muted-foreground">{error}</p>;
+ if (text === null) return <p className="p-4 text-sm text-muted-foreground">Loading…</p>;
+
+ const rendered = kind === "html" && !source ? "html" : kind === "markdown" && !source ? "markdown" : kind === "csv" ? "csv" : "plain";
+
+ return (
+ <div className="flex min-h-0 w-full flex-1 flex-col">
+ {(kind === "html" || kind === "markdown") && (
+ <div className="flex shrink-0 items-center gap-2 border-b px-3 py-1.5">
+ <Button size="sm" variant="ghost" className="h-7 text-xs" onClick={() => setSource((s) => !s)}>
+ {source ? <Eye className="size-3.5" /> : <Code2 className="size-3.5" />}
+ {source ? "Rendered" : "Source"}
+ </Button>
+ {kind === "html" && !source && (
+ <span className="truncate text-[11px] text-muted-foreground">Sandboxed — scripts and relative assets are off</span>
+ )}
+ </div>
+ )}
+
+ {rendered === "html" ? (
+ <iframe
+ // sandbox="" is the strictest value: no scripts, no forms, opaque origin.
+ sandbox=""
+ srcDoc={text}
+ title={name}
+ className="min-h-0 w-full flex-1 border-0 bg-white"
+ />
+ ) : rendered === "markdown" ? (
+ <div
+ className="min-h-0 flex-1 overflow-auto p-4 text-sm leading-relaxed [&_code]:rounded [&_code]:bg-secondary [&_code]:px-1 [&_code]:font-mono [&_h1]:pb-1 [&_h1]:text-lg [&_h1]:font-bold [&_h2]:pt-3 [&_h2]:text-base [&_h2]:font-semibold [&_li]:ml-4 [&_li]:list-disc [&_strong]:font-semibold"
+ dangerouslySetInnerHTML={{ __html: mdToHtml(text) }}
+ />
+ ) : rendered === "csv" ? (
+ <div className="min-h-0 flex-1 overflow-auto">
+ <table className="w-max min-w-full border-collapse text-xs">
+ <tbody>
+ {parseRows(text, name.toLowerCase().endsWith(".tsv") ? "\t" : ",").map((row, r) => (
+ <tr key={r} className={r === 0 ? "sticky top-0 bg-card font-semibold" : "odd:bg-muted/30"}>
+ {row.map((cell, c) => (
+ <td key={c} className="max-w-[28ch] truncate border-b border-r px-2 py-1" title={cell}>
+ {cell}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : (
+ <pre className="min-h-0 flex-1 overflow-auto p-4 font-mono text-xs leading-relaxed whitespace-pre-wrap break-words">
+ {text}
+ </pre>
+ )}
+
+ {truncated && (
+ <p className="shrink-0 border-t px-3 py-1.5 text-[11px] text-muted-foreground">
+ Showing the first {Math.round(MAX_BYTES / 1024)} KB — open it in the Code Editor for the whole file.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/slices/media-viewer/index.ts b/frontend/slices/media-viewer/index.ts
index 70102949..853cb539 100644
--- a/frontend/slices/media-viewer/index.ts
+++ b/frontend/slices/media-viewer/index.ts
@@ -3,6 +3,11 @@ import type { AppDescriptor } from "@/features/os-shell";
// Barrel: app layer imports only this descriptor. The component is lazy-loaded
// via `load`. noDock — opened from the launcher, not pinned to the dock.
+// The format table is part of the slice's public surface: Files decides what to
+// icon and where to route with the SAME map the viewer renders from, so the two can
+// never disagree about what "previewable" means.
+export { kindForName, kindForExt, isPreviewable, isTextual, type ViewKind } from "./lib/kinds";
+
export const mediaViewerApp: AppDescriptor = {
id: "media-viewer",
title: "Preview",
diff --git a/frontend/slices/media-viewer/lib/host.ts b/frontend/slices/media-viewer/lib/host.ts
index 7b3bdbf8..388857b9 100644
--- a/frontend/slices/media-viewer/lib/host.ts
+++ b/frontend/slices/media-viewer/lib/host.ts
@@ -1,4 +1,4 @@
// Single host seam — re-exports the mso raw-bytes URL helper via the shell
// barrel (a legal alias). Lifting the slice swaps this file for an injected one;
// no other file in the slice imports host I/O directly.
-export { rawUrl } from "@/features/os-shell";
+export { rawUrl, useOsApi } from "@/features/os-shell";
diff --git a/frontend/slices/media-viewer/lib/kinds.test.ts b/frontend/slices/media-viewer/lib/kinds.test.ts
new file mode 100644
index 00000000..4dd78430
--- /dev/null
+++ b/frontend/slices/media-viewer/lib/kinds.test.ts
@@ -0,0 +1,57 @@
+// The format table is the contract between Files (what to route, what to icon) and
+// Preview (what to render). These pin the parts that are decisions rather than data:
+// which formats are honestly unrenderable, that HTML is a kind of its own (it is
+// fetched and sandboxed, never framed from the raw URL), and that an unknown
+// extension lands somewhere sane instead of on an empty <img>.
+import { describe, expect, it } from "vitest";
+import { kindForName, kindForExt, isPreviewable, isTextual } from "./kinds";
+
+describe("kindForName", () => {
+ it("covers the formats Windows and macOS actually leave lying around", () => {
+ expect(kindForName("holiday.HEIC")).toBe("image"); // iPhone default
+ expect(kindForName("scan.tiff")).toBe("image");
+ expect(kindForName("clip.m4v")).toBe("video"); // QuickTime export
+ expect(kindForName("recording.wmv")).toBe("video");
+ expect(kindForName("voice memo.m4a")).toBe("audio");
+ expect(kindForName("track.opus")).toBe("audio");
+ expect(kindForName("invoice.PDF")).toBe("pdf");
+ });
+
+ it("calls a document a document instead of pretending to render it", () => {
+ // Every one of these opens as a blank frame if it is treated as previewable —
+ // which reads as MSO being broken rather than as the browser having no decoder.
+ for (const name of ["report.docx", "budget.xlsx", "deck.pptx", "notes.pages", "archive.zip", "Setup.exe", "disk.dmg"]) {
+ expect(kindForName(name)).toBe("none");
+ expect(isPreviewable(kindForName(name))).toBe(false);
+ }
+ });
+
+ it("separates the kinds whose bytes the viewer reads itself", () => {
+ expect(kindForName("index.html")).toBe("html");
+ expect(kindForName("README.md")).toBe("markdown");
+ expect(kindForName("rows.csv")).toBe("csv");
+ expect(kindForName("server.log")).toBe("text");
+ for (const kind of ["html", "markdown", "csv", "text"] as const) expect(isTextual(kind)).toBe(true);
+ // Not textual — these render from a URL, so nothing is fetched.
+ for (const kind of ["image", "video", "audio", "pdf", "none"] as const) expect(isTextual(kind)).toBe(false);
+ });
+
+ it("reads the well-known extension-less files as text", () => {
+ expect(kindForName("Makefile")).toBe("text");
+ expect(kindForName("Dockerfile")).toBe("text");
+ expect(kindForName("LICENSE")).toBe("text");
+ // …but not every extension-less blob: a random binary is not a text file.
+ expect(kindForName("core")).toBe("none");
+ });
+
+ it("takes the extension from the last dot, and the name from the last slash", () => {
+ expect(kindForName("/home/rahman/photos/my.trip.2026.jpg")).toBe("image");
+ expect(kindForName("/var/log/nginx/access.log")).toBe("text");
+ });
+
+ it("is case-insensitive and unknown-safe", () => {
+ expect(kindForExt("JPEG")).toBe("image");
+ expect(kindForExt("wat")).toBe("none");
+ expect(kindForName("no-extension-at-all")).toBe("none");
+ });
+});
diff --git a/frontend/slices/media-viewer/lib/kinds.ts b/frontend/slices/media-viewer/lib/kinds.ts
new file mode 100644
index 00000000..7a5c60d0
--- /dev/null
+++ b/frontend/slices/media-viewer/lib/kinds.ts
@@ -0,0 +1,76 @@
+// What Preview can actually show, keyed by extension — ONE table, used both by the
+// viewer (what to render) and by Files (what to route here, what to icon).
+//
+// The rule for what belongs in which bucket is "what a browser can render from raw
+// bytes", not "what the OS calls a document". So .docx and .zip are `none` — no
+// browser opens them, and a viewer that pretends otherwise renders a blank frame
+// and blames the file. `none` still gets a window: a card that names the format and
+// offers the download, which is the honest end of the road.
+//
+// TEXT IS FETCHED, NOT FRAMED. /api/v1/fs/raw serves unknown types as
+// application/octet-stream on purpose (lib/host/fs.ts), so text and HTML never
+// become an active same-origin document — the viewer reads the bytes and renders
+// them itself, HTML into a fully sandboxed iframe. Do not "fix" that by adding
+// text/html to the server's MIME map.
+
+export type ViewKind = "image" | "video" | "audio" | "pdf" | "markdown" | "csv" | "html" | "text" | "none";
+
+const BY_EXT: Record<string, ViewKind> = {};
+const put = (kind: ViewKind, exts: string) => {
+ for (const ext of exts.split(" ")) BY_EXT[ext] = kind;
+};
+
+// Windows + macOS defaults first, then the web ones. Formats no browser decodes
+// (heic, tiff, wmv, avi on most builds) are still listed: the element tries, fails,
+// and the viewer falls back to the download card — which beats "unsupported file"
+// on a machine whose browser CAN play it (Safari and heic, for one).
+put("image", "png jpg jpeg jfif gif webp avif bmp ico svg tif tiff heic heif");
+put("video", "mp4 m4v mov webm ogv mkv avi wmv mpg mpeg 3gp");
+put("audio", "mp3 wav m4a aac flac ogg oga opus aiff aif wma");
+put("pdf", "pdf");
+put("markdown", "md markdown mdx");
+put("csv", "csv tsv");
+put("html", "html htm xhtml");
+put(
+ "text",
+ "txt log json xml yaml yml toml ini cfg conf env properties " +
+ "js mjs cjs jsx ts tsx css scss sass less " +
+ "py rb php go rs java kt swift c h cpp hpp cs sql " +
+ "sh bash zsh fish ps1 bat cmd " +
+ "srt vtt patch diff lock gitignore gitattributes editorconfig dockerfile makefile plist",
+);
+// Deliberately `none` — a browser cannot render these, so say so and offer the
+// bytes: Office/iWork/OpenDocument, archives, disk images, installers, binaries,
+// design files, fonts and databases.
+put(
+ "none",
+ "doc docx xls xlsx ppt pptx rtf odt ods odp pages numbers key " +
+ "zip rar 7z tar gz tgz bz2 xz dmg iso exe msi deb rpm pkg apk " +
+ "psd ai sketch fig xd ttf otf woff woff2 " +
+ "db sqlite sqlite3 bin dat so dll dylib class jar o a",
+);
+
+/** File name (or path) → what Preview would render. */
+export function kindForName(name: string): ViewKind {
+ const base = name.split("/").pop() ?? name;
+ // Extension-less names that ARE text on every developer machine (Makefile,
+ // Dockerfile, LICENSE, README) — checked before the dot rule so they open as
+ // text rather than as an unknown blob.
+ if (!base.includes(".")) {
+ return /^(makefile|dockerfile|license|licence|readme|changelog|authors|notice|procfile|caddyfile|vagrantfile|gemfile|rakefile)$/i.test(base)
+ ? "text"
+ : "none";
+ }
+ return kindForExt(base.split(".").pop() ?? "");
+}
+
+export function kindForExt(ext: string): ViewKind {
+ return BY_EXT[ext.toLowerCase()] ?? "none";
+}
+
+/** True when Preview has something better than a download card to show. */
+export const isPreviewable = (kind: ViewKind): boolean => kind !== "none";
+
+/** The kinds whose bytes the viewer fetches and renders itself. */
+export const isTextual = (kind: ViewKind): boolean =>
+ kind === "text" || kind === "markdown" || kind === "csv" || kind === "html";
diff --git a/frontend/slices/media-viewer/lib/media.ts b/frontend/slices/media-viewer/lib/media.ts
index 4f4bbca6..5e618487 100644
--- a/frontend/slices/media-viewer/lib/media.ts
+++ b/frontend/slices/media-viewer/lib/media.ts
@@ -1,12 +1,13 @@
// Shared media helpers: editor handoff mapping + time formatting.
-import type { SampleKind } from "./samples";
+import type { ViewKind } from "./kinds";
export type EditorTarget = { app: string; label: string };
// Which editor opens which media kind. Images → image editor (media-studio),
-// timed media (video/audio) → video editor (reel-editor). Others (pdf/text)
-// have no editor.
-export function editorFor(kind: SampleKind): EditorTarget | null {
+// timed media (video/audio) → video editor (reel-editor). Others (pdf/text/
+// documents) have no editor here — the code editor owns text, and nothing in MSO
+// edits a PDF. Takes the viewer's ViewKind, which is a superset of SampleKind.
+export function editorFor(kind: ViewKind): EditorTarget | null {
if (kind === "image") return { app: "media-studio", label: "Image Editor" };
if (kind === "video" || kind === "audio")
return { app: "reel-editor", label: "Video Editor" };
diff --git a/frontend/slices/media-viewer/lib/use-siblings.ts b/frontend/slices/media-viewer/lib/use-siblings.ts
new file mode 100644
index 00000000..1aa282bb
--- /dev/null
+++ b/frontend/slices/media-viewer/lib/use-siblings.ts
@@ -0,0 +1,74 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useOsApi } from "./host";
+import { kindForName, isPreviewable, type ViewKind } from "./kinds";
+
+// ← → through the folder, the way every OS preview works.
+//
+// The sibling list is LISTED, not passed in: a window opened from a deep link, from
+// Spotlight or from the assistant carries one path and no folder, and a viewer that
+// could only page when it was opened from the file grid would be arrows that
+// sometimes exist. One `fs.list` of the parent directory covers every entry point.
+
+export interface Sibling {
+ path: string;
+ name: string;
+ kind: ViewKind;
+}
+
+const parentOf = (path: string): string => {
+ const cut = path.replace(/\/+$/, "").lastIndexOf("/");
+ return cut > 0 ? path.slice(0, cut) : "/";
+};
+
+export function useSiblings(path: string, name: string): {
+ items: Sibling[];
+ index: number;
+ prev: Sibling | null;
+ next: Sibling | null;
+ go: (delta: number) => Sibling | null;
+} {
+ const api = useOsApi();
+ const [items, setItems] = useState<Sibling[]>([]);
+ const dir = useMemo(() => parentOf(path), [path]);
+
+ useEffect(() => {
+ let alive = true;
+ api.fs
+ .list(dir)
+ .then((res) => {
+ if (!alive) return;
+ // Only files this viewer can actually show — paging onto a .zip would be a
+ // download card between two photos.
+ const base = res.path || dir;
+ setItems(
+ res.entries
+ .filter((e) => e.kind === "file" && isPreviewable(kindForName(e.name)))
+ .map((e) => ({
+ path: `${base.replace(/\/+$/, "")}/${e.name}`,
+ name: e.name,
+ kind: kindForName(e.name),
+ })),
+ );
+ })
+ .catch(() => {
+ // A folder we cannot list (bounds, permissions) simply has no arrows.
+ if (alive) setItems([]);
+ });
+ return () => {
+ alive = false;
+ };
+ }, [api, dir]);
+
+ const index = items.findIndex((i) => i.path === path || i.name === name);
+ const at = useCallback(
+ (delta: number): Sibling | null => {
+ if (items.length < 2 || index < 0) return null;
+ return items[(index + delta + items.length) % items.length] ?? null;
+ },
+ [items, index],
+ );
+
+ return { items, index, prev: at(-1), next: at(1), go: at };
+}
diff --git a/frontend/slices/os-settings/components/about-section.tsx b/frontend/slices/os-settings/components/about-section.tsx
index 10da668e..1ad9f73e 100644
--- a/frontend/slices/os-settings/components/about-section.tsx
+++ b/frontend/slices/os-settings/components/about-section.tsx
@@ -10,6 +10,7 @@ import { IS_DEMO } from "@/lib/demo";
import { SettingsSection, SettingsValueRow, SettingsActionRow } from "@/features/shell-settings";
import { MsoMark } from "@/components/shared/mso-mark";
import { WhatsNew } from "./whats-new";
+import { UpdateSection } from "./update-section";
import pkg from "../../../../package.json";
import { openOnboarding } from "@/features/auth";
@@ -90,6 +91,10 @@ export function AboutSection() {
))}
</SettingsSection>
+ {/* Above "What's new": the update is the thing to ACT on, the changelog is the
+ thing to read. Renders nothing in demo, or where the host cannot self-update. */}
+ <UpdateSection />
+
<WhatsNew />
<SettingsSection icon={<RotateCcw />} title="Reset">
diff --git a/frontend/slices/os-settings/components/update-notes.tsx b/frontend/slices/os-settings/components/update-notes.tsx
new file mode 100644
index 00000000..87a1de44
--- /dev/null
+++ b/frontend/slices/os-settings/components/update-notes.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { GitCommitHorizontal } from "lucide-react";
+import { FormDrawer, mdToHtml } from "@/features/os-shell";
+import type { UpdateCommit } from "@/lib/host/self-update";
+
+// The docs behind the update button: what is ABOUT to land, then what already has.
+//
+// Two different sources on purpose. The incoming list comes from the update check
+// (`git log HEAD..origin/main`) because docs/CHANGELOG.md in this checkout is, by
+// definition, the OLD one — it is generated at ship time and arrives WITH the update
+// it would describe. The shipped list is that file, the same one "What's new" shows.
+
+const REPO = "https://github.com/rahmanef63/mso";
+
+export function UpdateNotes({ commits }: { commits: UpdateCommit[] }) {
+ const [shipped, setShipped] = useState<string | null>(null);
+
+ useEffect(() => {
+ let alive = true;
+ fetch("/api/changelog", { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((d: { markdown?: string } | null) => alive && setShipped(d?.markdown?.slice(0, 12_000) ?? ""))
+ .catch(() => alive && setShipped(""));
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ return (
+ <FormDrawer.Body className="space-y-4">
+ {commits.length > 0 && (
+ <section className="space-y-1.5">
+ <h3 className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Incoming</h3>
+ <ul className="space-y-1.5">
+ {commits.map((c) => (
+ <li key={c.sha} className="flex gap-2 text-xs">
+ <GitCommitHorizontal className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0">
+ <span className="break-words text-foreground">{c.subject}</span>{" "}
+ <span className="whitespace-nowrap font-mono text-[10px] text-muted-foreground">
+ {c.sha} · {c.date}
+ </span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
+ <section className="space-y-1.5">
+ <h3 className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
+ {commits.length > 0 ? "Already shipped here" : "Shipped"}
+ </h3>
+ {shipped === null ? (
+ <p className="text-xs text-muted-foreground">Loading…</p>
+ ) : shipped ? (
+ <div
+ className="space-y-1 text-xs leading-relaxed [&_code]:rounded [&_code]:bg-secondary [&_code]:px-1 [&_code]:font-mono [&_h2]:pt-2 [&_h2]:text-[11px] [&_h2]:font-semibold [&_h2]:text-muted-foreground [&_strong]:font-semibold [&_strong]:text-foreground"
+ dangerouslySetInnerHTML={{ __html: mdToHtml(shipped) }}
+ />
+ ) : (
+ <p className="text-xs text-muted-foreground">No changelog in this checkout yet.</p>
+ )}
+ </section>
+
+ <section className="space-y-1 border-t pt-3 text-xs">
+ <h3 className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Docs</h3>
+ {/* Real links, so ⌘-click and long-press-share behave. The repo is public;
+ everything here is already in the commit history it points at. */}
+ <ul className="space-y-1">
+ {[
+ ["README — what MSO is, and the security model", `${REPO}#readme`],
+ ["Full changelog", `${REPO}/blob/main/docs/CHANGELOG.md`],
+ ["Progress log — why each change happened", `${REPO}/blob/main/docs/PROGRESS.md`],
+ ["CLI reference", `${REPO}/blob/main/docs/CLI.md`],
+ ].map(([label, href]) => (
+ <li key={href}>
+ <a href={href} target="_blank" rel="noreferrer" className="text-info underline-offset-2 hover:underline">
+ {label}
+ </a>
+ </li>
+ ))}
+ </ul>
+ </section>
+ </FormDrawer.Body>
+ );
+}
diff --git a/frontend/slices/os-settings/components/update-section.tsx b/frontend/slices/os-settings/components/update-section.tsx
new file mode 100644
index 00000000..eb160b9d
--- /dev/null
+++ b/frontend/slices/os-settings/components/update-section.tsx
@@ -0,0 +1,192 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { ArrowDownToLine, BookOpen, CheckCircle2, RefreshCw } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { FormDrawer } from "@/features/os-shell";
+import { SettingsSection, SettingsActionRow, SettingsBlock } from "@/features/shell-settings";
+import { IS_DEMO } from "@/lib/demo";
+import type { UpdateStatus } from "@/lib/host/self-update";
+import { UpdateNotes } from "./update-notes";
+
+// Settings → About → Software update. The button the whole deploy hangs off:
+// prod is systemd with no webhook, so a commit on main is invisible in the running
+// app until someone rebuilds — which used to mean someone with ssh.
+//
+// `import type` only: lib/host/self-update is "server-only" and the type is erased
+// at compile time, so the shape stays shared without the module reaching the bundle.
+
+const POLL_MS = 3_000;
+const OK_MARKER = "UPDATE OK";
+
+async function readStatus(check: boolean): Promise<UpdateStatus | null> {
+ const res = await fetch(`/api/v1/sys/update${check ? "" : "?check=0"}`, { cache: "no-store" });
+ return res.ok ? ((await res.json()) as UpdateStatus) : null;
+}
+
+export function UpdateSection() {
+ const [info, setInfo] = useState<UpdateStatus | null>(null);
+ const [checking, setChecking] = useState(true);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [notes, setNotes] = useState(false);
+ // "An update ran in THIS tab (or was running when we looked)" — the outcome below
+ // is derived from it rather than stored, so nothing has to be reset on the next run.
+ const [sawRunning, setSawRunning] = useState(false);
+
+ const refresh = useCallback(async (check: boolean) => {
+ // A poll that lands while the service is restarting simply fails; keeping the
+ // last known state is the honest render, and the next tick recovers.
+ const next = await readStatus(check).catch(() => null);
+ if (next) {
+ setInfo(next);
+ if (next.running) setSawRunning(true);
+ }
+ return next;
+ }, []);
+
+ // The first read asks the remote; every later one is the poll below. Written as a
+ // subscription-shaped effect (start an external call, set state in ITS callback)
+ // rather than calling `refresh` here — the two are the same work, but only this
+ // shape is honestly "synchronise with an external system".
+ useEffect(() => {
+ if (IS_DEMO) return;
+ let alive = true;
+ readStatus(true)
+ .catch(() => null)
+ .then((next) => {
+ if (!alive) return;
+ if (next) {
+ setInfo(next);
+ if (next.running) setSawRunning(true);
+ }
+ setChecking(false);
+ });
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ // Poll only while an update is in flight — including across the restart it ends
+ // with, which is the one moment the API is briefly gone.
+ useEffect(() => {
+ if (!info?.running) return;
+ const id = setInterval(() => void refresh(false), POLL_MS);
+ return () => clearInterval(id);
+ }, [info?.running, refresh]);
+
+ const start = async (rebuildOnly: boolean) => {
+ setBusy(true);
+ setError(null);
+ setSawRunning(true);
+ try {
+ const res = await fetch("/api/v1/sys/update", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ rebuildOnly }),
+ });
+ const body = (await res.json()) as UpdateStatus & { error?: string };
+ if (!res.ok) setError(body.error ?? `update refused (${res.status})`);
+ else setInfo(body);
+ } catch {
+ setError("could not reach the host");
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ if (IS_DEMO || (!info && !checking)) return null;
+ const behind = info?.behind ?? 0;
+ const running = info?.running ?? false;
+ // Derived, never stored: an update we watched, that is no longer running, either
+ // left its marker in the log or stopped before deploying.
+ const finished = sawRunning && !running && info ? (info.log.includes(OK_MARKER) ? "ok" : "failed") : null;
+
+ return (
+ <SettingsSection
+ icon={<ArrowDownToLine />}
+ title="Software update"
+ footnote={
+ info?.supported === false
+ ? (info.reason ?? undefined)
+ : "Pulls origin/main, proves it compiles out-of-tree, then builds and restarts. The out-of-tree check runs first because an in-place build cannot be undone."
+ }
+ >
+ <SettingsBlock className="space-y-2">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-xs">
+ <span className="font-medium text-foreground">
+ {checking ? "Checking for updates…" : behind > 0 ? `${behind} update${behind > 1 ? "s" : ""} available` : "Up to date"}
+ </span>
+ <span className="font-mono text-[11px] text-muted-foreground">running {info?.current ?? "—"}</span>
+ </div>
+ {info?.currentSubject && <p className="line-clamp-2 text-[11px] text-muted-foreground">{info.currentSubject}</p>}
+ {info && !info.remoteChecked && !running && (
+ <p className="text-[11px] text-amber-500">
+ Could not reach the remote — this is what was last fetched, not necessarily what is on main now.
+ </p>
+ )}
+ {error && <p className="text-[11px] text-destructive-text">{error}</p>}
+ {finished === "ok" && !running && (
+ <p className="flex items-center gap-1.5 text-[11px] text-emerald-500">
+ <CheckCircle2 className="size-3.5" /> Updated and restarted — reload to run the new build.
+ </p>
+ )}
+ {finished === "failed" && !running && (
+ <p className="text-[11px] text-destructive-text">The update stopped before deploying. The running build was left untouched — see the log.</p>
+ )}
+ {running && (
+ <pre className="max-h-48 overflow-auto rounded-md bg-secondary/60 p-2 text-[10px] leading-relaxed whitespace-pre-wrap break-words">
+ {info?.log?.trim() || "starting…"}
+ </pre>
+ )}
+ {finished === "ok" && !running && (
+ <Button type="button" size="sm" className="w-full [@media(pointer:coarse)]:min-h-[44px]" onClick={() => window.location.reload()}>
+ <RefreshCw className="size-4" /> Reload MSO
+ </Button>
+ )}
+ </SettingsBlock>
+
+ {behind > 0 && info?.supported !== false && (
+ <SettingsActionRow
+ label={running ? "Updating…" : `Update to ${info?.commits[0]?.sha ?? "latest"} and restart`}
+ icon={<ArrowDownToLine />}
+ busy={busy || running}
+ disabled={running}
+ onClick={() => void start(false)}
+ />
+ )}
+ {info?.supported !== false && (
+ <SettingsActionRow
+ label="Release notes and docs"
+ icon={<BookOpen />}
+ onClick={() => setNotes(true)}
+ trailing={behind > 0 ? <span className="text-[11px] text-muted-foreground">{behind} new</span> : undefined}
+ />
+ )}
+ {info?.supported !== false && behind === 0 && (
+ <SettingsActionRow
+ label="Rebuild and restart"
+ icon={<RefreshCw />}
+ busy={busy || running}
+ disabled={running}
+ onClick={() => void start(true)}
+ />
+ )}
+
+ <FormDrawer open={notes} onOpenChange={setNotes} size="lg">
+ <FormDrawer.Header>
+ <FormDrawer.Title>{behind > 0 ? `What's in this update (${behind})` : "Release notes"}</FormDrawer.Title>
+ <FormDrawer.Description>
+ Incoming commits first, then everything already shipped to this deployment.
+ </FormDrawer.Description>
+ </FormDrawer.Header>
+ <UpdateNotes commits={info?.commits ?? []} />
+ <FormDrawer.Footer>
+ <Button type="button" variant="ghost" onClick={() => setNotes(false)}>
+ Close
+ </Button>
+ </FormDrawer.Footer>
+ </FormDrawer>
+ </SettingsSection>
+ );
+}
diff --git a/lib/host/audit.ts b/lib/host/audit.ts
index fe5fd385..e747fa4a 100644
--- a/lib/host/audit.ts
+++ b/lib/host/audit.ts
@@ -22,6 +22,8 @@ export type AuditAction =
| "fs.upload"
| "fs.zip"
| "sys.cleanup"
+ /** The cockpit replacing its own code (Settings → About, or `mso update run`). */
+ | "sys.update"
| "managed-app.action"
| "camoufox.power"
/** An MCP token asked for a tool above its scope. Not an error — it is the
diff --git a/lib/host/fs.ts b/lib/host/fs.ts
index 26a0d789..08d58290 100644
--- a/lib/host/fs.ts
+++ b/lib/host/fs.ts
@@ -151,13 +151,25 @@ export async function usage(requested: string): Promise<FsUsage> {
// --- raw byte serving (images / video / audio / pdf preview) ---
+// PASSIVE MEDIA TYPES ONLY. Everything absent from this table is served as
+// application/octet-stream, which browsers download instead of executing — and that
+// is doing real work: `text/html` here would turn any host file into an ACTIVE
+// document on the cockpit's own origin, with the session cookie attached (the exact
+// hazard the SVG sandbox header below exists for). The Preview app reads text and
+// HTML with fetch() and renders it in a sandboxed frame precisely so this table
+// never has to grow an executable type. Do not add html/xhtml/xml here.
const MIME: Record<string, string> = {
- png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif",
- webp: "image/webp", svg: "image/svg+xml", avif: "image/avif", bmp: "image/bmp",
- ico: "image/x-icon", mp4: "video/mp4", webm: "video/webm", mov: "video/quicktime",
+ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", jfif: "image/jpeg",
+ gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", avif: "image/avif",
+ bmp: "image/bmp", ico: "image/x-icon", tif: "image/tiff", tiff: "image/tiff",
+ heic: "image/heic", heif: "image/heif",
+ mp4: "video/mp4", m4v: "video/x-m4v", webm: "video/webm", mov: "video/quicktime",
mkv: "video/x-matroska", avi: "video/x-msvideo", ogv: "video/ogg",
+ mpg: "video/mpeg", mpeg: "video/mpeg", "3gp": "video/3gpp", wmv: "video/x-ms-wmv",
mp3: "audio/mpeg", wav: "audio/wav", m4a: "audio/mp4", flac: "audio/flac",
- aiff: "audio/aiff", ogg: "audio/ogg", oga: "audio/ogg", pdf: "application/pdf",
+ aiff: "audio/aiff", aif: "audio/aiff", ogg: "audio/ogg", oga: "audio/ogg",
+ opus: "audio/opus", aac: "audio/aac", wma: "audio/x-ms-wma",
+ pdf: "application/pdf",
};
export function mimeFor(p: string): string {
diff --git a/lib/host/self-update.test.ts b/lib/host/self-update.test.ts
new file mode 100644
index 00000000..ba394f48
--- /dev/null
+++ b/lib/host/self-update.test.ts
@@ -0,0 +1,73 @@
+// The two decisions in self-update that are not plumbing: what `git log` said, and
+// whether the update may start at all. Both are pure, and both are the difference
+// between "nothing happened, here is why" and a half-finished deploy — `next build`
+// deletes the .next the live service is serving from, so a refusal has to happen
+// BEFORE anything is touched.
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+const { parseCommits, blockingReason } = await import("./self-update");
+
+const status = (over: Partial<Parameters<typeof blockingReason>[0]> = {}) => ({
+ supported: true,
+ reason: null,
+ current: "abc1234",
+ currentSubject: "feat: something",
+ behind: 3,
+ commits: [],
+ dirty: false,
+ running: false,
+ remoteChecked: true,
+ log: "",
+ ...over,
+});
+
+describe("parseCommits", () => {
+ it("splits the unit-separated format git is asked for", () => {
+ const out = ["9f3c9ee\x1ffix(deps): pin nanoid\x1f2026-08-17", "ecce676\x1fMerge pull request #3\x1f2026-08-16"].join("\n");
+ expect(parseCommits(out)).toEqual([
+ { sha: "9f3c9ee", subject: "fix(deps): pin nanoid", date: "2026-08-17" },
+ { sha: "ecce676", subject: "Merge pull request #3", date: "2026-08-16" },
+ ]);
+ });
+
+ it("survives a subject containing the characters a naive split would choke on", () => {
+ // Real subjects in this repo carry colons, em dashes and parentheses. \x1f is
+ // the separator precisely because none of them can appear in one.
+ const [commit] = parseCommits("abc1234\x1ffix(ship): amend on retry — and collapse: a subject\x1f2026-08-14");
+ expect(commit.subject).toBe("fix(ship): amend on retry — and collapse: a subject");
+ });
+
+ it("returns nothing for the up-to-date case rather than an empty-shaped row", () => {
+ expect(parseCommits("")).toEqual([]);
+ expect(parseCommits("\n \n")).toEqual([]);
+ });
+});
+
+describe("blockingReason", () => {
+ it("lets a normal update through", () => {
+ expect(blockingReason(status(), false)).toBeNull();
+ });
+
+ it("refuses when there is nothing to pull, unless a rebuild was asked for", () => {
+ expect(blockingReason(status({ behind: 0 }), false)).toBe("already up to date");
+ expect(blockingReason(status({ behind: 0 }), true)).toBeNull();
+ });
+
+ it("refuses a dirty checkout — the fast-forward would fail anyway", () => {
+ expect(blockingReason(status({ dirty: true }), false)).toContain("uncommitted changes");
+ // Also for a rebuild: the point of refusing is that we do not know what is in
+ // the tree we are about to compile and serve.
+ expect(blockingReason(status({ dirty: true }), true)).toContain("uncommitted changes");
+ });
+
+ it("refuses a second run while one is in flight", () => {
+ expect(blockingReason(status({ running: true }), false)).toBe("an update is already running");
+ });
+
+ it("passes the unsupported reason through verbatim", () => {
+ const reason = "this deployment is not a git checkout, so there is nothing to pull";
+ expect(blockingReason(status({ supported: false, reason }), true)).toBe(reason);
+ });
+});
diff --git a/lib/host/self-update.ts b/lib/host/self-update.ts
new file mode 100644
index 00000000..f19f7dfe
--- /dev/null
+++ b/lib/host/self-update.ts
@@ -0,0 +1,224 @@
+import "server-only";
+import { execFile } from "node:child_process";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { HostError } from "./host-error";
+
+// SERVER-ONLY. "Is there a newer MSO, and pull it in" — the deploy that CLAUDE.md
+// describes (`git pull` → build → restart), driven from Settings instead of from a
+// terminal the owner may not have open.
+//
+// Prod is systemd with NO webhook, so a commit on main changes nothing anyone can
+// see until someone rebuilds. That someone was always a person with ssh. This makes
+// it a button.
+//
+// THE UPDATE DOES NOT RUN IN THIS PROCESS, and that is not a style choice: the last
+// step is `systemctl restart mso.service`, and systemd's default KillMode kills
+// everything in the unit's cgroup — including a child we spawned. A detached child
+// is still in that cgroup, so it would be killed mid-`next build`, with `.next`
+// already deleted (the build's first act) and nothing to restart into. So the work
+// is handed to a TRANSIENT unit via `systemd-run`, which lives in its own cgroup and
+// survives the restart it performs.
+const UNIT = "mso-self-update";
+const LOG_TAIL = 12_000;
+const GIT_TIMEOUT_MS = 20_000;
+const FETCH_TIMEOUT_MS = 45_000;
+/** Enough to see what is coming without turning the panel into a git log. */
+const MAX_COMMITS = 25;
+
+export interface UpdateCommit {
+ sha: string;
+ subject: string;
+ date: string;
+}
+
+export interface UpdateStatus {
+ /** False when this deployment cannot self-update (not a checkout, no systemd). */
+ supported: boolean;
+ /** Why not, when `supported` is false — shown to the operator verbatim. */
+ reason: string | null;
+ current: string;
+ currentSubject: string;
+ behind: number;
+ commits: UpdateCommit[];
+ /** Uncommitted work in the checkout: a `--ff-only` merge would fail, so refuse early. */
+ dirty: boolean;
+ running: boolean;
+ /** False when `git fetch` could not reach the remote — `behind` is then only local knowledge. */
+ remoteChecked: boolean;
+ log: string;
+}
+
+export const updateLogPath = (): string => {
+ const override = process.env.MSO_UPDATE_LOG?.trim();
+ return override || path.join(os.homedir(), ".mso", "self-update.log");
+};
+
+const repoRoot = (): string => process.cwd();
+
+interface Ran {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+function run(command: string, args: readonly string[], timeout = GIT_TIMEOUT_MS): Promise<Ran> {
+ return new Promise((resolve) => {
+ execFile(
+ command,
+ [...args],
+ { cwd: repoRoot(), timeout, maxBuffer: 1024 * 1024, windowsHide: true, shell: false },
+ (error, stdout, stderr) => {
+ const code = typeof (error as { code?: number } | null)?.code === "number" ? (error as { code: number }).code : error ? 1 : 0;
+ resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
+ },
+ );
+ });
+}
+
+const git = (args: readonly string[], timeout?: number) => run("git", args, timeout);
+
+/** `<sha>\x1f<subject>\x1f<iso date>` per line — a separator no subject can contain. */
+export function parseCommits(stdout: string): UpdateCommit[] {
+ return stdout
+ .split("\n")
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .slice(0, MAX_COMMITS)
+ .map((line) => {
+ const [sha = "", subject = "", date = ""] = line.split("\x1f");
+ return { sha, subject: subject.slice(0, 200), date: date.slice(0, 10) };
+ })
+ .filter((c) => c.sha);
+}
+
+/**
+ * Why this update must not start, or `null` when it may.
+ *
+ * Pure, and separate from the doing, because every one of these is a refusal an
+ * operator has to be able to read — "nothing happened and here is why" beats a
+ * build that fails halfway through with the live `.next` already deleted.
+ */
+export function blockingReason(status: UpdateStatus, rebuildOnly: boolean): string | null {
+ if (!status.supported) return status.reason ?? "this deployment cannot update itself";
+ if (status.running) return "an update is already running";
+ if (status.dirty) {
+ return "the checkout has uncommitted changes — commit or stash them on the host first, a fast-forward would refuse anyway";
+ }
+ if (!rebuildOnly && status.behind === 0) return "already up to date";
+ return null;
+}
+
+async function isRunning(): Promise<boolean> {
+ // `is-active` on a transient unit that has been collected exits non-zero, which
+ // is the same answer as "never ran" — both mean "not running", so the code is
+ // all we need here.
+ const result = await run("systemctl", ["is-active", `${UNIT}.service`], 10_000);
+ return result.code === 0;
+}
+
+async function readLog(): Promise<string> {
+ const raw = await fs.readFile(updateLogPath(), "utf8").catch(() => "");
+ return raw.length > LOG_TAIL ? raw.slice(-LOG_TAIL) : raw;
+}
+
+/**
+ * @param fetchRemote when true, ask the remote first. A check costs a network
+ * round trip, so the panel asks for one and the poller during an update does not.
+ */
+export async function getUpdateStatus(fetchRemote = true): Promise<UpdateStatus> {
+ const base: UpdateStatus = {
+ supported: false,
+ reason: null,
+ current: "unknown",
+ currentSubject: "",
+ behind: 0,
+ commits: [],
+ dirty: false,
+ running: false,
+ remoteChecked: false,
+ log: await readLog(),
+ };
+
+ const inside = await git(["rev-parse", "--is-inside-work-tree"]);
+ if (inside.code !== 0 || inside.stdout.trim() !== "true") {
+ return { ...base, reason: "this deployment is not a git checkout, so there is nothing to pull" };
+ }
+
+ const running = await isRunning();
+ const [head, subject, status] = await Promise.all([
+ git(["rev-parse", "--short", "HEAD"]),
+ git(["log", "-1", "--format=%s"]),
+ git(["status", "--porcelain"]),
+ ]);
+
+ let remoteChecked = false;
+ if (fetchRemote && !running) {
+ // Quiet + a hard timeout: an unreachable remote must degrade to "could not
+ // check", never hang the Settings panel that is waiting on this.
+ const fetched = await git(["fetch", "--quiet", "origin", "main"], FETCH_TIMEOUT_MS);
+ remoteChecked = fetched.code === 0;
+ }
+
+ const [count, log] = await Promise.all([
+ git(["rev-list", "--count", "HEAD..origin/main"]),
+ git(["log", "--format=%h%x1f%s%x1f%cs", `-${MAX_COMMITS}`, "HEAD..origin/main"]),
+ ]);
+
+ return {
+ ...base,
+ supported: true,
+ current: head.stdout.trim() || "unknown",
+ currentSubject: subject.stdout.trim(),
+ behind: count.code === 0 ? Number(count.stdout.trim()) || 0 : 0,
+ commits: log.code === 0 ? parseCommits(log.stdout) : [],
+ dirty: status.stdout.trim().length > 0,
+ running,
+ remoteChecked,
+ log: await readLog(),
+ };
+}
+
+/**
+ * Hand the update to a transient systemd unit and return immediately.
+ *
+ * Nothing from the request reaches a shell: the only knob is a boolean, and the
+ * ref is hard-coded to `origin/main`.
+ */
+export async function startUpdate(rebuildOnly = false): Promise<UpdateStatus> {
+ const status = await getUpdateStatus(true);
+ const blocked = blockingReason(status, rebuildOnly);
+ if (blocked) throw new HostError(blocked);
+
+ const script = path.join(repoRoot(), "scripts", "self-update.sh");
+ if (!(await fs.stat(script).catch(() => null))) throw new HostError(`missing ${script}`);
+
+ const started = await run(
+ "sudo",
+ [
+ "-n",
+ "systemd-run",
+ "--collect",
+ `--unit=${UNIT}`,
+ `--property=User=${os.userInfo().username}`,
+ `--property=WorkingDirectory=${repoRoot()}`,
+ // A build on a small VPS is minutes, not seconds; the default 90s start
+ // timeout would kill it exactly at the point of no return.
+ "--property=TimeoutStartSec=3600",
+ `--setenv=MSO_UPDATE_LOG=${updateLogPath()}`,
+ "/bin/bash",
+ script,
+ ...(rebuildOnly ? ["--rebuild-only"] : []),
+ ],
+ 30_000,
+ );
+ if (started.code !== 0) {
+ // The common causes are both fixable and neither is obvious from "exit 1":
+ // no passwordless sudo, or no systemd-run on the host.
+ throw new HostError(
+ `could not start the updater: ${(started.stderr || started.stdout).trim().slice(0, 300) || `exit ${started.code}`}`,
+ );
+ }
+ return { ...status, running: true };
+}
diff --git a/scripts/self-update.sh b/scripts/self-update.sh
new file mode 100755
index 00000000..5b30029b
--- /dev/null
+++ b/scripts/self-update.sh
@@ -0,0 +1,80 @@
+#!/usr/bin/env bash
+# self-update.sh — pull main, prove it compiles, build, restart. The body of the
+# Settings → About update button.
+#
+# RUN BY systemd-run, NOT by mso.service (lib/host/self-update.ts explains why: the
+# last step restarts mso.service, and systemd kills the whole cgroup — a child of the
+# service would die mid-build with .next already deleted).
+#
+# Order is the same load-bearing order as scripts/ship.sh, with ONE addition: the
+# out-of-tree verification. ship.sh is run by a human who is watching; this is run by
+# an operator who pressed a button and walked away, so a commit that does not compile
+# must be found BEFORE `next build` deletes the .next the live service is serving
+# from. That build is unrecoverable in place — there is no old .next to put back.
+set -uo pipefail
+
+cd "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+
+LOG="${MSO_UPDATE_LOG:-$HOME/.mso/self-update.log}"
+mkdir -p "$(dirname "$LOG")"
+# Truncate, then take over both streams: the panel polls this file, and a log that
+# grew forever would eventually be the biggest thing in ~/.mso.
+exec >"$LOG" 2>&1
+
+# systemd hands a unit /usr/local/sbin:…:/usr/bin and nothing else. bun lives in
+# ~/.bun/bin — the same gap that made managed apps read as "not installed".
+export PATH="$HOME/.bun/bin:$HOME/.local/bin:$PATH"
+export NO_COLOR=1 TERM=dumb
+
+step() { printf '\n[%s] == %s\n' "$(date -Is)" "$*"; }
+die() { printf '\n[%s] FAILED: %s\n' "$(date -Is)" "$*"; printf 'the running MSO was left untouched.\n'; exit 1; }
+
+REBUILD_ONLY=0
+[ "${1:-}" = "--rebuild-only" ] && REBUILD_ONLY=1
+
+step "self-update starting (rebuild-only=$REBUILD_ONLY)"
+git rev-parse --short HEAD | sed 's/^/at /'
+
+if [ "$REBUILD_ONLY" -eq 0 ]; then
+ step "fetching origin/main"
+ git fetch --quiet origin main || die "could not reach the remote"
+ step "fast-forwarding"
+ # --ff-only, never a merge: this checkout must stay a mirror of main. A refusal
+ # here means someone committed on the host, and silently merging their work into
+ # a deploy is worse than stopping.
+ git merge --ff-only origin/main || die "cannot fast-forward — the checkout has diverged from origin/main"
+ git log -1 --format='now at %h — %s'
+
+ step "installing dependencies"
+ # Cheap when nothing changed (~250ms), and a pulled commit may have moved a
+ # dependency. node-pty is in trustedDependencies, so its native build runs here.
+ bun install || die "bun install failed"
+ node -e "require('node-pty')" || die "node-pty did not load after install — every /api/v1 route imports it"
+fi
+
+step "verifying the build out-of-tree (this does not touch the live .next)"
+bash scripts/verify-build.sh >/dev/null || die "HEAD does not compile — nothing was deployed"
+
+step "building in place"
+bun run build >/dev/null || die "build failed after it had already passed out-of-tree — check disk space"
+
+step "restarting mso.service"
+sudo -n systemctl restart mso.service || die "could not restart mso.service"
+sleep 4
+
+# The chunk-mismatch check CLAUDE.md warns about, verified rather than remembered —
+# the same check scripts/ship.sh ends with. If the HTML references a chunk the
+# restarted process does not serve, every asset 404s and the UI comes up unstyled.
+PORT="${PORT:-4005}"
+CSS=$(curl -fsS --max-time 10 "http://127.0.0.1:$PORT/" | grep -o '/_next/static/[^"]*\.css' | head -1)
+if [ -z "$CSS" ]; then
+ die "no CSS reference in the served HTML — recover with: rm -rf .next && bun run build && sudo systemctl restart mso.service"
+fi
+TYPE=$(curl -fsSI --max-time 10 "http://127.0.0.1:$PORT$CSS" | tr -d '\r' | awk -F': ' 'tolower($1)=="content-type"{print $2}')
+case "$TYPE" in
+ text/css*) ;;
+ *) die "chunk mismatch: $CSS served as '${TYPE:-nothing}'. Recover with: rm -rf .next && bun run build && sudo systemctl restart mso.service" ;;
+esac
+
+step "done — now at $(git rev-parse --short HEAD)"
+printf 'UPDATE OK\n'