Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
refactor: one download helper, one path helper, and gates for the drifts they hid
Rahmane87dabc6fb27
diff --git a/.env.example b/.env.exampleindex f1559f96..2924134c 100644--- a/.env.example+++ b/.env.example@@ -54,6 +54,12 @@ OS_SESSION_SECRET=# Bring your own Anthropic key. Can also be set in the OS via Settings → AI# (stored in ~/.mso/config.json). If unset, the assistant returns 501.# ANTHROPIC_API_KEY=+#+# Provider-run tools the Codex backend may use, comma/space separated (currently+# only `image_generation`). OFF by default and deliberately opt-in: a built-in runs+# on the provider's side, BILLS TO YOUR ChatGPT account, and returns content this+# shell does not render yet — none of which should be a surprise on the next reply.+# OS_CODEX_BUILTIN_TOOLS=image_generation# --- Managed apps: Hermes / OpenClaw (optional) ---# The OS lists an upstream app's own dashboard pages by reading that app's built@@ -157,8 +163,11 @@ OS_SESSION_SECRET=# CAMOUFOX_VNC_PASSWD_TEXT=~/.vnc/passwd.txt# --- Build metadata (optional) ----# Shown in Settings → About. Set at BUILD time (NEXT_PUBLIC_ is inlined into the-# client bundle), e.g. NEXT_PUBLIC_COMMIT_SHA=$(git rev-parse --short HEAD) bun run build+# Shown in Settings → About, and compared against the checkout's HEAD by the+# Software-update panel to tell "a build is pending" from "up to date". Set at BUILD+# time (NEXT_PUBLIC_ is inlined into the client bundle). You do NOT normally set it:+# next.config.mjs fills it from `git rev-parse --short HEAD` when it is unset. Set it+# only where the build has no .git (a tarball, a container build stage).# NEXT_PUBLIC_COMMIT_SHA=## The ONLY way to emit a ?dpl= query on static chunk URLs. Leave UNSET unless you arediff --git a/app/api/v1/sys/update/route.test.ts b/app/api/v1/sys/update/route.test.tsnew file mode 100644index 00000000..0a959b97--- /dev/null+++ b/app/api/v1/sys/update/route.test.ts@@ -0,0 +1,116 @@+// Integration tests for /api/v1/sys/update — the route that REPLACES THE CODE THE+// WHOLE COCKPIT RUNS. It shipped with no test at all, which is the wrong end of the+// risk scale to leave uncovered: a regression here does not render a panel wrong,+// it pulls and rebuilds the running deployment.+//+// The route's own job is thin and entirely about refusing: auth, then the boolean,+// then handing off. lib/host/self-update is stubbed so these exercise the WIRING —+// that a signed-out caller gets nothing, that a refusal is a 4xx carrying its+// sentence, and that both outcomes reach the audit trail (this action is the one an+// operator would most want to find in ~/.mso/audit.log afterwards).+import { beforeEach, describe, expect, it, vi } from "vitest";++const authed = { current: true };+vi.mock("@/lib/agent/server", () => ({+ verifyAuth: vi.fn(async () => authed.current),+}));++const getStatus = vi.fn();+const startUpdate = vi.fn();+vi.mock("@/lib/host/self-update", () => ({+ getUpdateStatus: (...args: unknown[]) => getStatus(...args),+ startUpdate: (...args: unknown[]) => startUpdate(...args),+}));++const auditMock = vi.fn();+vi.mock("@/lib/host", async () => {+ const real = await vi.importActual<typeof import("@/lib/host")>("@/lib/host");+ return { ...real, audit: (...args: unknown[]) => auditMock(...args) };+});++const { GET, POST } = await import("./route");+const { HostError } = await import("@/lib/host/host-error");++const status = (over: Record<string, unknown> = {}) => ({+ supported: true,+ reason: null,+ current: "abc1234",+ currentSubject: "feat: x",+ buildSha: "abc1234",+ pendingBuild: false,+ behind: 2,+ commits: [],+ dirty: false,+ running: false,+ remoteChecked: true,+ log: "",+ ...over,+});++const get = (url = "http://localhost/api/v1/sys/update") => new Request(url);+const post = (body: unknown) =>+ new Request("http://localhost/api/v1/sys/update", {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ });++beforeEach(() => {+ authed.current = true;+ getStatus.mockReset().mockResolvedValue(status());+ startUpdate.mockReset().mockResolvedValue(status({ running: true }));+ auditMock.mockReset();+});++describe("/api/v1/sys/update", () => {+ it("tells a signed-out caller nothing, on either verb", async () => {+ authed.current = false;+ expect((await GET(get())).status).toBe(401);+ expect((await POST(post({}))).status).toBe(401);+ // Not merely unauthorised — it must not have looked at the host either.+ expect(getStatus).not.toHaveBeenCalled();+ expect(startUpdate).not.toHaveBeenCalled();+ });++ it("asks the remote by default, and skips it for the poller", async () => {+ await GET(get());+ expect(getStatus).toHaveBeenLastCalledWith(true);+ // `?check=0` is what the panel polls with WHILE an update runs — a git fetch+ // every 3s during a build is pure noise.+ await GET(get("http://localhost/api/v1/sys/update?check=0"));+ expect(getStatus).toHaveBeenLastCalledWith(false);+ });++ it("passes rebuildOnly through only when it is exactly true", async () => {+ await POST(post({ rebuildOnly: true }));+ expect(startUpdate).toHaveBeenLastCalledWith(true);+ // A truthy string from a hand-rolled client must not silently mean "rebuild".+ await POST(post({ rebuildOnly: "yes" }));+ expect(startUpdate).toHaveBeenLastCalledWith(false);+ await POST(post({}));+ expect(startUpdate).toHaveBeenLastCalledWith(false);+ });++ it("surfaces a refusal as its sentence, not as a 500", async () => {+ startUpdate.mockRejectedValue(new HostError("already up to date"));+ const res = await POST(post({}));+ expect(res.status).toBe(400);+ expect((await res.json()).error).toContain("already up to date");+ });++ it("audits both the start and the refusal", async () => {+ await POST(post({}));+ expect(auditMock).toHaveBeenCalledWith(expect.objectContaining({ action: "sys.update", ok: true }));++ auditMock.mockReset();+ startUpdate.mockRejectedValue(new HostError("an update is already running"));+ await POST(post({}));+ // A failed attempt is the more interesting line in the log, not the less.+ expect(auditMock).toHaveBeenCalledWith(expect.objectContaining({ action: "sys.update", ok: false }));+ });++ it("does not audit a read", async () => {+ await GET(get());+ expect(auditMock).not.toHaveBeenCalled();+ });+});diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 66421f0f..e63d8ed0 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -24,6 +24,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.- `managed-apps` one-click install died, and installed apps read as "not installed", under systemd- `install` bind loopback by default, and restart the service on re-run+**Changed**++- one download helper, one path helper, and gates for the drifts they hid+**Tests**- `e2e` a committed browser check for Preview and the update paneldiff --git a/frontend/slices/appshell/index.ts b/frontend/slices/appshell/index.tsindex 2e3557e8..9f73c089 100644--- a/frontend/slices/appshell/index.ts+++ b/frontend/slices/appshell/index.ts@@ -82,6 +82,9 @@ export * from "./lib/window-title";export * from "./lib/spaces";export * from "./lib/window-tabs";export * from "./lib/clipboard";+// Browser-generic, brand-free: every app that writes a file to disk uses this one+// rather than re-deriving the two rules that make a download actually land.+export { saveAs } from "./lib/download";export * from "./lib/lock";export * from "./lib/profiles";export * from "./lib/shortcuts";diff --git a/frontend/slices/appshell/lib/download.test.ts b/frontend/slices/appshell/lib/download.test.tsnew file mode 100644index 00000000..770d1384--- /dev/null+++ b/frontend/slices/appshell/lib/download.test.ts@@ -0,0 +1,84 @@+// Two rules, one helper, and both of them shipped WRONG somewhere before it+// existed: an anchor that is never inserted (Firefox ignores `download` on a+// detached element, so Settings → Backup saved nothing there) and a blob: URL+// revoked in the click's own tick (0-byte file in Firefox/Safari).+import { afterEach, describe, expect, it, vi } from "vitest";+import { saveAs } from "./download";++interface FakeAnchor {+ href: string;+ download: string;+ rel: string;+ clicked: boolean;+ /** Was the element in the document AT THE MOMENT of the click? */+ inDocumentAtClick: boolean | null;+ removed: boolean;+}++function fakeDoc(): { doc: Document; anchor: () => FakeAnchor } {+ let made: FakeAnchor | null = null;+ const attached = new Set<object>();+ const doc = {+ createElement: () => {+ const a: FakeAnchor & { remove: () => void; click: () => void } = {+ href: "",+ download: "",+ rel: "",+ clicked: false,+ inDocumentAtClick: null,+ removed: false,+ click() {+ a.clicked = true;+ a.inDocumentAtClick = attached.has(a);+ },+ remove() {+ a.removed = true;+ attached.delete(a);+ },+ };+ made = a;+ return a;+ },+ body: { appendChild: (el: object) => attached.add(el) },+ } as unknown as Document;+ return { doc, anchor: () => made as unknown as FakeAnchor };+}++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe("saveAs", () => {+ it("clicks an anchor that is IN the document, then removes it", () => {+ const { doc, anchor } = fakeDoc();+ saveAs("/api/v1/fs/raw?path=%2Ftmp%2Fa.png", "a.png", doc);+ const a = anchor();+ expect(a.clicked).toBe(true);+ expect(a.inDocumentAtClick).toBe(true); // the whole reason this helper exists+ expect(a.removed).toBe(true);+ expect(a.download).toBe("a.png");+ expect(a.rel).toBe("noopener");+ });++ it("revokes a blob: URL LATER, never in the click's own tick", () => {+ vi.useFakeTimers();+ const revoke = vi.fn();+ vi.stubGlobal("URL", { revokeObjectURL: revoke });+ const { doc } = fakeDoc();+ saveAs("blob:http://localhost/abc", "state.json", doc);+ expect(revoke).not.toHaveBeenCalled(); // same tick = 0-byte download+ vi.advanceTimersByTime(5_000);+ expect(revoke).toHaveBeenCalledWith("blob:http://localhost/abc");+ });++ it("does not pretend to revoke a URL it never created", () => {+ vi.useFakeTimers();+ const revoke = vi.fn();+ vi.stubGlobal("URL", { revokeObjectURL: revoke });+ const { doc } = fakeDoc();+ saveAs("data:image/png;base64,iVBORw0KGgo=", "shot.png", doc);+ vi.advanceTimersByTime(5_000);+ expect(revoke).not.toHaveBeenCalled();+ });+});diff --git a/frontend/slices/appshell/lib/download.ts b/frontend/slices/appshell/lib/download.tsnew file mode 100644index 00000000..37644053--- /dev/null+++ b/frontend/slices/appshell/lib/download.ts@@ -0,0 +1,38 @@+// Save a URL to disk the way a browser actually requires — one implementation.+//+// There were SIX of these, and they disagreed on the two details that decide+// whether the file arrives:+//+// 1. THE ANCHOR MUST BE IN THE DOCUMENT. Firefox ignores `download` on a+// detached element, so `a.click()` navigates (or does nothing) instead of+// saving. Two of the six clicked a detached anchor — the Settings → Backup+// export was one of them, which is the last feature that should silently fail.+// 2. A blob: URL MUST NOT BE REVOKED IN THE SAME TICK. Firefox/Safari have not+// started fetching it yet, and the save lands 0 bytes. One copy revoked after+// 0 ms, another after 2000, a third never.+//+// Both are lore that a helper can hold instead of six call sites remembering it.++/** Long enough for the browser to have started the fetch; short enough that a+ * big blob is not pinned in memory. One copy used 0 ms and reported it was+ * sufficient, another used 2000 — this takes the safe end, because the cost of+ * being wrong is a corrupt download and the cost of waiting is nothing. */+const REVOKE_DELAY_MS = 2_000;++/**+ * @param doc injectable ONLY so this can be tested without a DOM environment+ * (the repo runs vitest in `node`, and adding jsdom to save one file is a+ * worse trade than one defaulted parameter).+ */+export function saveAs(href: string, filename: string, doc: Document = document): void {+ const a = doc.createElement("a");+ a.href = href;+ a.download = filename;+ a.rel = "noopener";+ doc.body.appendChild(a);+ a.click();+ a.remove();+ // Only ours to revoke. A data:/http: URL has no object to release, and calling+ // revokeObjectURL on one is a silent no-op that reads as if it mattered.+ if (href.startsWith("blob:")) setTimeout(() => URL.revokeObjectURL(href), REVOKE_DELAY_MS);+}diff --git a/frontend/slices/code-editor/lib/util.ts b/frontend/slices/code-editor/lib/util.tsindex 72a65fe4..6548af3e 100644--- a/frontend/slices/code-editor/lib/util.ts+++ b/frontend/slices/code-editor/lib/util.ts@@ -1,18 +1,10 @@import type { Lang } from "./highlight";-// Path helpers (POSIX-ish, all paths absolute and "/"-rooted).-export function baseName(path: string): string {- return path.replace(/\/$/, "").split("/").pop() ?? path;-}--export function extOf(path: string): string {- const b = baseName(path);- return b.includes(".") ? (b.split(".").pop() ?? "").toLowerCase() : "";-}--export function joinPath(dir: string, name: string): string {- return dir === "/" ? `/${name}` : `${dir.replace(/\/$/, "")}/${name}`;-}+// Path helpers come from the framework (appshell/lib/paths) — this file had its+// own, subtly different from Files', and both build /api/v1/fs request paths.+import { extOf } from "@/lib/path";+export { baseName, joinPath } from "@/lib/path";+export { extOf };// Map a file extension to a supported highlight language.const EXT_LANG: Record<string, Lang> = {diff --git a/frontend/slices/files-manager/hooks/use-file-commands.ts b/frontend/slices/files-manager/hooks/use-file-commands.tsindex 569f92c0..94e03c3b 100644--- a/frontend/slices/files-manager/hooks/use-file-commands.ts+++ b/frontend/slices/files-manager/hooks/use-file-commands.ts@@ -1,7 +1,7 @@"use client";import { useCallback, useState, type KeyboardEvent, type MouseEvent } from "react";-import { openWindow, toast } from "@/features/os-shell";+import { openWindow, saveAs, toast } from "@/features/os-shell";import { rawUrl, zipUrl, type FsEntry } from "../lib/host";import { appForFile, mediaKind } from "../lib/icons";import { joinPath, parentPath } from "../lib/format";@@ -9,17 +9,6 @@ import { TRASH_PATH, type UseFiles } from "./use-files";import type { UseFileSelection } from "./use-file-selection";import type { ContextState } from "../lib/types";-// Fire a same-origin download through a transient hidden anchor.-function trigger(href: string, name: string) {- const a = document.createElement("a");- a.href = href;- a.download = name;- a.rel = "noopener";- document.body.appendChild(a);- a.click();- a.remove();-}-// All user commands (open, clipboard, trash, keyboard) bound to the current fs// + selection. Keeps app.tsx focused on layout. `del` moves to Trash from a// normal dir but hard-deletes (with confirm) when already inside Trash.@@ -122,7 +111,7 @@ export function useFileCommands(fs: UseFiles, sel: UseFileSelection) {const single =items.length === 1 ? entries.find((e) => e.name === items[0]) ?? null : null;if (single?.kind === "file") {- trigger(rawUrl(joinPath(fs.path, single.name)), single.name);+ saveAs(rawUrl(joinPath(fs.path, single.name)), single.name);toast(`Downloading ${single.name}…`);return;}@@ -130,7 +119,7 @@ export function useFileCommands(fs: UseFiles, sel: UseFileSelection) {const filename = items.length === 1 ? `${items[0]}.zip` : `${dir}.zip`;const hasDir = items.some((n) => entries.find((e) => e.name === n)?.kind === "dir");if (!hasDir) {- trigger(zipUrl(fs.path, items, filename), filename);+ saveAs(zipUrl(fs.path, items, filename), filename);toast(`Zipping ${items.length} item${items.length > 1 ? "s" : ""}…`);return;}@@ -142,7 +131,7 @@ export function useFileCommands(fs: UseFiles, sel: UseFileSelection) {const confirmZip = useCallback((exclude: string[]) => {if (!zipPrompt) return;- trigger(zipUrl(fs.path, zipPrompt.names, zipPrompt.filename, exclude), zipPrompt.filename);+ saveAs(zipUrl(fs.path, zipPrompt.names, zipPrompt.filename, exclude), zipPrompt.filename);toast(`Zipping ${zipPrompt.names.length} item${zipPrompt.names.length > 1 ? "s" : ""}…`);setZipPrompt(null);},diff --git a/frontend/slices/files-manager/lib/format.ts b/frontend/slices/files-manager/lib/format.tsindex 4e2110a7..a4bc38b9 100644--- a/frontend/slices/files-manager/lib/format.ts+++ b/frontend/slices/files-manager/lib/format.ts@@ -13,15 +13,10 @@ export function fmtSize(bytes: number): string {return `${(bytes / GiB).toFixed(1)} GB`;}-// Path helpers — single source of truth so segments never drift.-export const joinPath = (base: string, name: string): string =>- base === "/" ? "/" + name : base + "/" + name;--export const parentPath = (p: string): string => {- const n = p.replace(/\/+$/, "") || "/";- const i = n.lastIndexOf("/");- return i <= 0 ? "/" : n.slice(0, i);-};+// Path helpers live in the framework now — three slices needed them and their+// three copies disagreed about a trailing slash, which becomes a doubled slash in+// an /api/v1/fs `path=`. Re-exported here so this slice's own imports are unchanged.+export { joinPath, parentPath, baseName } from "@/lib/path";// Breadcrumb segments for a path, including the synthetic root.export function crumbsFor(path: string, root = "mso"): { name: string; path: string }[] {diff --git a/frontend/slices/files-manager/lib/icons.ts b/frontend/slices/files-manager/lib/icons.tsindex 86414d87..de432871 100644--- a/frontend/slices/files-manager/lib/icons.ts+++ b/frontend/slices/files-manager/lib/icons.ts@@ -5,9 +5,8 @@ import {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"]);-const VIDEO = new Set(["mp4", "mov", "webm", "avi", "mkv"]);-const AUDIO = new Set(["mp3", "wav", "aiff", "m4a", "flac"]);+// Media families come from the viewer's table (kindForName); these are the two+// groupings it has no opinion about, so they stay local.const CODE = new Set(["ts", "tsx", "js", "jsx", "py", "go", "rs", "css"]);const ARCHIVE = new Set(["zip", "gz", "tar", "rar", "7z"]);@@ -33,12 +32,17 @@ export function iconFor(entry: FsEntry): LucideIcon {// Tailwind text-color class keyed by ext family — color-coded icons. Uses// palette utilities (not hex) so it tracks the active theme.+//+// The media families come from the viewer's table, exactly like iconFor: with a+// local set, a `.heic` drew a picture icon in muted grey and a `.m4v` a film icon+// in no colour at all, because the local list had never heard of them.export function colorFor(entry: FsEntry): string {if (entry.kind === "dir") return "text-primary";const ext = entry.ext?.toLowerCase() ?? "";- if (IMAGE.has(ext)) return "text-amber-500";- if (VIDEO.has(ext)) return "text-pink-500";- if (AUDIO.has(ext)) return "text-emerald-500";+ const kind = kindForName(entry.name);+ if (kind === "image") return "text-amber-500";+ if (kind === "video") return "text-pink-500";+ if (kind === "audio") return "text-emerald-500";if (ext === "json") return "text-slate-400";if (ext === "csv") return "text-green-500";if (ext === "pdf") return "text-red-500";diff --git a/frontend/slices/image-editor/lib/export.ts b/frontend/slices/image-editor/lib/export.tsindex f4ab9590..03420763 100644--- a/frontend/slices/image-editor/lib/export.ts+++ b/frontend/slices/image-editor/lib/export.ts@@ -1,4 +1,5 @@import type Konva from "konva";+import { saveAs } from "@/features/os-shell";export type ExportFormat = "png" | "jpeg" | "webp";@@ -72,14 +73,7 @@ export function stageToDataURL();}-function downloadDataURL(dataURL: string, filename: string) {- const a = document.createElement("a");- a.href = dataURL;- a.download = filename;- document.body.appendChild(a);- a.click();- a.remove();-}+const downloadDataURL = (dataURL: string, filename: string) => saveAs(dataURL, filename);export function exportStage(stage: Konva.Stage,diff --git a/frontend/slices/image-editor/lib/project.ts b/frontend/slices/image-editor/lib/project.tsindex 6b153cea..891566a5 100644--- a/frontend/slices/image-editor/lib/project.ts+++ b/frontend/slices/image-editor/lib/project.ts@@ -1,4 +1,5 @@import { useCallback } from "react";+import { saveAs } from "@/features/os-shell";import type Konva from "konva";import type { Doc } from "./types";@@ -40,14 +41,7 @@ export function restorePaint(export function downloadProject(project: Project, name = "project") {const blob = new Blob([JSON.stringify(project)], { type: "application/json" });- const url = URL.createObjectURL(blob);- const a = document.createElement("a");- a.href = url;- a.download = `${name}.ie.json`;- document.body.appendChild(a);- a.click();- a.remove();- setTimeout(() => URL.revokeObjectURL(url), 2000);+ saveAs(URL.createObjectURL(blob), `${name}.ie.json`);}export function parseProject(text: string): Project | null {diff --git a/frontend/slices/media-viewer/app.tsx b/frontend/slices/media-viewer/app.tsxindex fecf329b..75f9eb7d 100644--- a/frontend/slices/media-viewer/app.tsx+++ b/frontend/slices/media-viewer/app.tsx@@ -3,7 +3,7 @@import { useCallback, useState } from "react";import { TooltipProvider } from "@/components/ui/tooltip";import type { AppProps } from "@/features/os-shell";-import { AppFrame, openWindow, usePublishInspector } from "@/features/os-shell";+import { AppFrame, openWindow, saveAs, usePublishInspector } from "@/features/os-shell";import { SAMPLES } from "./lib/samples";import { editorFor } from "./lib/media";import { ViewerToolbar } from "./components/viewer-toolbar";@@ -33,10 +33,7 @@ function SampleGallery() {// Trigger a browser download from the inline data-URI when one exists.const onDownload = useCallback(() => {if (!file.src) return;- const a = document.createElement("a");- a.href = file.src;- a.download = file.name;- a.click();+ saveAs(file.src, file.name);}, [file]);const editor = editorFor(file.kind);diff --git a/frontend/slices/media-viewer/components/remote-view.tsx b/frontend/slices/media-viewer/components/remote-view.tsxindex 11667392..6279b732 100644--- a/frontend/slices/media-viewer/components/remote-view.tsx+++ b/frontend/slices/media-viewer/components/remote-view.tsx@@ -4,7 +4,7 @@ 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 { AppFrame, openWindow, saveAs, usePublishInspector } from "@/features/os-shell";import { rawUrl } from "../lib/host";import { cn } from "@/lib/utils";import { editorFor } from "../lib/media";@@ -55,15 +55,7 @@ export function RemoteView({ file }: { file: RemoteFile }) {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 download = useCallback(() => saveAs(src, current.name), [src, current.name]);const openInEditor = useCallback(() => {if (!editor) return;diff --git a/frontend/slices/media-viewer/lib/host.ts b/frontend/slices/media-viewer/lib/host.tsindex 388857b9..abdc7c72 100644--- a/frontend/slices/media-viewer/lib/host.ts+++ b/frontend/slices/media-viewer/lib/host.ts@@ -2,3 +2,7 @@// 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, useOsApi } from "@/features/os-shell";+// Pure string math, not host I/O — same category as `cn`, so it comes straight+// from lib rather than through the seam above (and keeps a plain helper module+// out of the shell barrel's module graph).+export { joinPath, parentPath } from "@/lib/path";diff --git a/frontend/slices/media-viewer/lib/mime-parity.test.ts b/frontend/slices/media-viewer/lib/mime-parity.test.tsnew file mode 100644index 00000000..b2af2e66--- /dev/null+++ b/frontend/slices/media-viewer/lib/mime-parity.test.ts@@ -0,0 +1,70 @@+// Two tables, one contract. Preview decides HOW to render a file from its+// extension (frontend/slices/media-viewer/lib/kinds.ts); /api/v1/fs/raw decides+// what Content-Type those bytes are served with (lib/host/fs.ts). They live in+// different halves of the app and nothing connected them.+//+// The failure that gap produces is silent and looks like a broken app: Preview+// renders <video src=…> for a `.m4v`, the server answers+// application/octet-stream, the element errors, and the operator sees "this+// browser could not decode the file" about a file their browser decodes fine.+//+// The second direction matters more. Adding `html: "text/html"` to that map would+// turn any file on the host into an ACTIVE document on the cockpit's own origin,+// with the session cookie attached — the exact hazard the SVG `sandbox` header+// already exists for. Preview reads text and HTML with fetch() precisely so the+// map never needs an executable type, and this test is what keeps a future+// "helpful" addition from undoing that.+import { describe, expect, it, vi } from "vitest";+import { kindForExt } from "./kinds";++// The server module is server-only and imports nothing else heavy; the shim is+// what every other test of lib/host uses.+vi.mock("server-only", () => ({}));+const { mimeFor } = await import("@/lib/host/fs");++/** Every extension the viewer claims it can render from a URL. */+const STREAMED = [+ "png jpg jpeg jfif gif webp avif bmp ico svg tif tiff heic heif",+ "mp4 m4v mov webm ogv mkv avi wmv mpg mpeg 3gp",+ "mp3 wav m4a aac flac ogg oga opus aiff aif wma",+ "pdf",+]+ .join(" ")+ .split(" ");++/** What the viewer fetches and renders itself — never framed from the raw URL. */+const FETCHED = ["html", "htm", "xhtml", "md", "csv", "tsv", "txt", "log", "json", "xml", "yml"];++describe("Preview kinds ↔ the raw-bytes MIME map", () => {+ it("serves a real type for every format Preview points an element at", () => {+ const missing = STREAMED.filter((ext) => mimeFor(`f.${ext}`) === "application/octet-stream");+ expect(missing, "these render as an element but download as a blob").toEqual([]);+ });++ it("agrees with the viewer about which family each one is", () => {+ const family: Record<string, string> = { image: "image/", video: "video/", audio: "audio/", pdf: "application/pdf" };+ const wrong = STREAMED.filter((ext) => {+ const kind = kindForExt(ext);+ const prefix = family[kind];+ return !prefix || !mimeFor(`f.${ext}`).startsWith(prefix);+ });+ expect(wrong, "the viewer's family and the served Content-Type disagree").toEqual([]);+ });++ it("NEVER serves an executable document type", () => {+ // Not "html is absent" — any type a browser would run as a document on our+ // origin. If one appears here, the fix is to keep reading those bytes with+ // fetch() in the viewer, not to relax this test.+ const active = FETCHED.map((ext) => mimeFor(`f.${ext}`)).filter((m) =>+ /^text\/html|xhtml|^application\/xml|javascript/.test(m),+ );+ expect(active).toEqual([]);+ });++ it("keeps SVG in the map, because the route hardens it explicitly", () => {+ // fs.ts pairs image/svg+xml with `content-security-policy: sandbox` — dropping+ // the MIME would silently drop that pairing too.+ expect(mimeFor("logo.svg")).toBe("image/svg+xml");+ expect(kindForExt("svg")).toBe("image");+ });+});diff --git a/frontend/slices/media-viewer/lib/use-siblings.ts b/frontend/slices/media-viewer/lib/use-siblings.tsindex 1aa282bb..0d30957b 100644--- a/frontend/slices/media-viewer/lib/use-siblings.ts+++ b/frontend/slices/media-viewer/lib/use-siblings.ts@@ -1,7 +1,7 @@"use client";import { useCallback, useEffect, useMemo, useState } from "react";-import { useOsApi } from "./host";+import { joinPath, parentPath, useOsApi } from "./host";import { kindForName, isPreviewable, type ViewKind } from "./kinds";// ← → through the folder, the way every OS preview works.@@ -17,11 +17,6 @@ export interface Sibling {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;@@ -31,7 +26,7 @@ export function useSiblings(path: string, name: string): {} {const api = useOsApi();const [items, setItems] = useState<Sibling[]>([]);- const dir = useMemo(() => parentOf(path), [path]);+ const dir = useMemo(() => parentPath(path), [path]);useEffect(() => {let alive = true;@@ -46,7 +41,7 @@ export function useSiblings(path: string, name: string): {res.entries.filter((e) => e.kind === "file" && isPreviewable(kindForName(e.name))).map((e) => ({- path: `${base.replace(/\/+$/, "")}/${e.name}`,+ path: joinPath(base, e.name),name: e.name,kind: kindForName(e.name),})),diff --git a/frontend/slices/os-settings/components/backup-section.tsx b/frontend/slices/os-settings/components/backup-section.tsxindex d53a7b0e..30aaffd2 100644--- a/frontend/slices/os-settings/components/backup-section.tsx+++ b/frontend/slices/os-settings/components/backup-section.tsx@@ -3,14 +3,7 @@import { useRef, useState } from "react";import { AlertTriangle, Download, DatabaseBackup, Upload } from "lucide-react";import { Button } from "@/components/ui/button";-import {- FormDrawer,- collectLocalState,- localStateFilename,- parseLocalState,- restoreLocalState,- type LocalStateBlob,-} from "@/features/os-shell";+import { collectLocalState, FormDrawer, localStateFilename, parseLocalState, restoreLocalState, saveAs, type LocalStateBlob } from "@/features/os-shell";import { SettingsSection, SettingsActionRow, SettingsBlock } from "@/features/shell-settings";import pkg from "../../../../package.json";@@ -30,14 +23,9 @@ export function BackupSection() {setError(null);const blob = collectLocalState(pkg.version ?? "0.0.0");const url = URL.createObjectURL(new Blob([JSON.stringify(blob, null, 2)], { type: "application/json" }));- const a = document.createElement("a");- a.href = url;- a.download = localStateFilename();- a.click();- // Deferred, not immediate: revoking in the same tick as .click() has raced- // the download in Firefox/Safari (the blob fetch has not started yet) and- // yields a 0-byte or failed save. One macrotask is enough.- setTimeout(() => URL.revokeObjectURL(url), 0);+ // saveAs owns the anchor rules AND the deferred revoke — this copy clicked a+ // DETACHED anchor, which Firefox ignores, so the backup silently did nothing there.+ saveAs(url, localStateFilename());setExported(Object.keys(blob.keys).length);};diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.tsnew file mode 100644index 00000000..fb03dfc3--- /dev/null+++ b/lib/config/env-example.test.ts@@ -0,0 +1,79 @@+// Every knob the code reads must be documented where someone would look for it.+//+// CLAUDE.md carries this as a chore ("still grep process.env before adding a new+// one"), and the chore had already slipped: `OS_CODEX_BUILTIN_TOOLS` — which turns+// on provider-run tools that BILL to the owner's account — was readable by the code+// and absent from `.env.example`. A var nobody can find is a var nobody can turn+// off. This is that grep, run by the suite instead of by memory.+//+// The allowlist below is the other half of the contract: vars that are deliberately+// NOT in .env.example because you never set them by hand. Each one carries the+// reason, so adding to this list is a decision rather than a way to silence a test.+import { readFileSync } from "node:fs";+import { execSync } from "node:child_process";+import path from "node:path";+import { describe, expect, it } from "vitest";++const ROOT = path.join(__dirname, "..", "..");++/** Not documented in .env.example, on purpose. */+const NOT_A_KNOB: Record<string, string> = {+ // Injected by the framework or the runtime.+ NEXT_RUNTIME: "set by Next itself",+ NEXT_PUBLIC_BUILD_ID: "injected by next.config.mjs at build time",+ VITEST: "set by the test runner",+ // The OS gives these to every process.+ SHELL: "the OS's",+ HOME: "the OS's",+ XDG_RUNTIME_DIR: "set by logind, or by the unit — see lib/managed-apps/user-bus.ts",+ // systemd's, read by instrumentation for the watchdog handshake.+ NOTIFY_SOCKET: "systemd's",+ WATCHDOG_USEC: "systemd's",+ // Test + tooling only, never part of a deployment.+ E2E_BASE_URL: "test harness",+ E2E_PASSWORD: "test harness",+ E2E_DEVICE: "test harness",+ E2E_HEADED: "test harness",+ E2E_PREVIEW_DIR: "test harness",+ OS_MEDIA_BASE: "scripts/gen-readme-media.mjs only",+ OS_MEDIA_DEVICE: "scripts/gen-readme-media.mjs only",+};++function usedEnvNames(): string[] {+ const files = execSync("git ls-files '*.ts' '*.tsx' '*.mjs'", { cwd: ROOT, encoding: "utf8" })+ .split("\n")+ .filter(Boolean)+ // A test may stub anything, so .test files do not count as "the app reads it".+ // The e2e HARNESSES do count — they are committed code, and the vars they read+ // are exactly the ones that belong in NOT_A_KNOB rather than in .env.example.+ .filter((f) => !f.includes(".test."));+ const names = new Set<string>();+ for (const file of files) {+ const src = readFileSync(path.join(ROOT, file), "utf8");+ for (const m of src.matchAll(/process\.env\.([A-Z][A-Z_0-9]{2,})/g)) names.add(m[1]);+ // `process.env["X"]` and destructuring are not used here; if they appear, this+ // regex stops seeing them — which is why the reconciliation lives in a test that+ // someone will read, not in a silent script.+ }+ return [...names].sort();+}++describe(".env.example documents every knob", () => {+ const example = readFileSync(path.join(ROOT, ".env.example"), "utf8");+ const documented = new Set(+ [...example.matchAll(/^#?\s*([A-Z][A-Z_0-9]+)=/gm)].map((m) => m[1]),+ );++ it("has a line for each env var the app reads", () => {+ const missing = usedEnvNames().filter((n) => !documented.has(n) && !(n in NOT_A_KNOB));+ expect(missing, "add these to .env.example, or to NOT_A_KNOB with a reason").toEqual([]);+ });++ it("keeps the exemption list honest — every entry is still read somewhere", () => {+ const used = new Set(usedEnvNames());+ // An exemption for a var the code no longer reads is stale lore that outlives+ // the reason it was written.+ const stale = Object.keys(NOT_A_KNOB).filter((n) => !used.has(n));+ expect(stale, "these are exempted but no longer read — drop them").toEqual([]);+ });+});diff --git a/lib/path.test.ts b/lib/path.test.tsnew file mode 100644index 00000000..676213e2--- /dev/null+++ b/lib/path.test.ts@@ -0,0 +1,39 @@+// These strings become the `path=` of an /api/v1/fs request, so the edges are not+// cosmetic. The three copies this file replaced disagreed on exactly the cases+// below — Files' join left "/a//b" for a base with a trailing slash, and every+// caller happened to pass a clean base until one did not.+import { describe, expect, it } from "vitest";+import { joinPath, parentPath, baseName, extOf } from "./path";++describe("joinPath", () => {+ it("joins without doubling or dropping a separator", () => {+ expect(joinPath("/home/rahman", "a.txt")).toBe("/home/rahman/a.txt");+ expect(joinPath("/", "a.txt")).toBe("/a.txt");+ expect(joinPath("/home/rahman/", "a.txt")).toBe("/home/rahman/a.txt");+ expect(joinPath("/home/rahman", "/a.txt")).toBe("/home/rahman/a.txt");+ expect(joinPath("/home//", "//a.txt")).toBe("/home/a.txt");+ });+});++describe("parentPath", () => {+ it("walks up, and stops at the root instead of returning empty", () => {+ expect(parentPath("/home/rahman/a.txt")).toBe("/home/rahman");+ expect(parentPath("/home/rahman/")).toBe("/home");+ expect(parentPath("/home")).toBe("/");+ expect(parentPath("/")).toBe("/");+ });+});++describe("baseName / extOf", () => {+ it("takes the last segment and the last dot", () => {+ expect(baseName("/a/b/c.txt")).toBe("c.txt");+ expect(baseName("/a/b/")).toBe("b");+ expect(baseName("/")).toBe("");+ expect(extOf("/a/my.trip.2026.JPG")).toBe("jpg");+ expect(extOf("/a/Makefile")).toBe("");+ // A dotfile's name after the dot IS treated as the extension, deliberately:+ // Preview's table lists `gitignore`/`editorconfig` as text, and that is only+ // reachable if ".gitignore" resolves to "gitignore".+ expect(extOf("/a/.gitignore")).toBe("gitignore");+ });+});diff --git a/lib/path.ts b/lib/path.tsnew file mode 100644index 00000000..bf4f1ff2--- /dev/null+++ b/lib/path.ts@@ -0,0 +1,37 @@+// POSIX path math for the shell's apps — ONE implementation.+//+// There were three, and they disagreed at the edges. Files' `joinPath` did not+// strip a trailing slash from the base ("/a/" + "b" → "/a//b"), the Code editor's+// did, and Preview's sibling lookup carried a third copy of the same regex. These+// strings are not cosmetic: they become the `path=` of an /api/v1/fs request, and a+// doubled slash is a different path to a host that resolves it literally.+//+// Lives in `lib/` rather than in a slice because three slices need it and+// cross-slice imports are barrel-only. Same category as `@/lib/utils` (cn):+// universal, brand-free, no React and no host access — the appshell framework may+// import it without acquiring a dependency it could not lift.++/** `join("/a", "b")` → `/a/b`; tolerant of a trailing slash on either side. */+export function joinPath(base: string, name: string): string {+ const dir = base.replace(/\/+$/, "");+ const leaf = name.replace(/^\/+/, "");+ return dir ? `${dir}/${leaf}` : `/${leaf}`;+}++/** The containing directory, or `/` at the root. Never returns "". */+export function parentPath(p: string): string {+ const n = p.replace(/\/+$/, "") || "/";+ const cut = n.lastIndexOf("/");+ return cut <= 0 ? "/" : n.slice(0, cut);+}++/** The last segment: `/a/b.txt` → `b.txt`. `/` → "". */+export function baseName(p: string): string {+ return p.replace(/\/+$/, "").split("/").pop() ?? "";+}++/** Lowercased extension without the dot, or "" when there is none. */+export function extOf(p: string): string {+ const base = baseName(p);+ return base.includes(".") ? (base.split(".").pop() ?? "").toLowerCase() : "";+}diff --git a/vitest.config.mts b/vitest.config.mtsindex ea2da45c..13952cdb 100644--- a/vitest.config.mts+++ b/vitest.config.mts@@ -7,8 +7,13 @@ const root = path.dirname(fileURLToPath(import.meta.url));export default defineConfig({resolve: {alias: {- "@": root,+ // ORDER MATTERS: Vite tries these in insertion order, so the more specific+ // prefix has to come first. With "@" first, `@/features/os-shell` resolved to+ // <root>/features/os-shell — a path that does not exist — and any test whose+ // module graph touched a slice barrel failed with "Cannot find package".+ // tsconfig had it right; only the test runner disagreed."@/features": path.join(root, "frontend", "slices"),+ "@": root,},},test: {