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.

fix(perf,ux): halve the boot API calls, unstick the dead chunk spinner, cut 9 orphans

Rahman69b8ef9bb004
diff --git a/.env.example b/.env.example
index be9baf6f..e7e8168f 100644
--- a/.env.example
+++ b/.env.example
@@ -58,17 +58,9 @@ OS_SESSION_SECRET=
# Upstream dashboards the feature proxy targets.
# HERMES_DASHBOARD_URL=http://127.0.0.1:9119
# OPENCLAW_DASHBOARD_URL=http://127.0.0.1:18789
-# The three paths below take an absolute path, or "~/…" for the home of the user
-# running mso. Leave unset to use the defaults noted per var.
-# Hermes install home. Default ~/.hermes. The built dashboard is read from
-# <home>/hermes-agent/hermes_cli/web_dist (override with HERMES_WEB_DIST for a
-# wheel/Docker install that puts it elsewhere). This is also the tree the
-# managed-app backup action copies.
+# Hermes install home. Default ~/.hermes. Absolute, or "~/…" for the home of the
+# user running mso. This is the tree the managed-app backup action copies.
# HERMES_HOME=/home/you/.hermes
-# HERMES_WEB_DIST=/opt/hermes/hermes_cli/web_dist
-# OpenClaw control-UI build, used only when the gateway is unreachable.
-# Default ~/.local/lib/node_modules/openclaw/dist/control-ui.
-# OPENCLAW_CONTROL_UI_DIST=/opt/openclaw/dist/control-ui
# Public origin the BROWSER uses, e.g. https://mso.rahmanef.com. Only the scheme
# + host + port are read. The managed-app proxy scopes its Content-Security-Policy
diff --git a/CLAUDE.md b/CLAUDE.md
index 9ae6189e..94746bad 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -166,7 +166,7 @@ to `resources/` (rr) and drive any project from one manifest:
- **`git add` aborts on a bad pathspec** and stages NOTHING new — after a
`git rm`, don't re-list the removed file in `git add`; prefer `git add -A` and
check `git status --short` before committing (a broken commit shipped once this way).
-- **Deploy demo (only if you re-create it — see above, it is not running):** from
+- **Deploy demo** (it IS running — `active`+`enabled`, 200 on 127.0.0.1:4006): from
`/home/rahman/projects/mso-demo`: `git fetch origin -q && git reset --hard
origin/main -q && bun run build && sudo systemctl restart mso-demo.service`.
Mind the cwd — running the sync from the prod dir is a classic slip.
@@ -207,11 +207,10 @@ to `resources/` (rr) and drive any project from one manifest:
`cp -p ~/.local/state/camoufox/session-backup/1/* <profile>/`, start. Roll back to `2`
or `3` if generation `1` already captured the logged-out state.
- Verify shell behaviour with **Playwright directly** — `os-browser/node_modules/playwright`
- (CommonJS) is the repo's only install — at 1280 for desktop and 390 for mobile. (This
- used to say "on the demo, via os-browser"; both are gone. There is no demo instance on
- this host, and the `os-browser` SERVICE is stopped + disabled — only its Playwright
- install is still used. Point Playwright at :4005 and log in, or build a throwaway with
- `NEXT_PUBLIC_OS_DEMO=1` on another port.) Drive Spotlight with Meta+k; click the dock by
+ (CommonJS) is the repo's only install — at 1280 for desktop and 390 for mobile. The
+ `os-browser` SERVICE is gone (its source was deleted 2026-08-10; only the vendored
+ Playwright install remains). Point Playwright at the **demo on 127.0.0.1:4006** — it
+ runs, and demo mode skips login entirely — or at :4005 and log in. Drive Spotlight with Meta+k; click the dock by
the BOTTOM-most `a[href="/<slug>"]` (the centre ones are the hidden Launchpad).
`X-Content-Type-Options: nosniff` is set on all routes, so wrong MIME is fatal — keep
static Content-Types correct.
diff --git a/frontend/slices/appshell/components/window-content.tsx b/frontend/slices/appshell/components/window-content.tsx
index 6f8abe9e..0dea20b3 100644
--- a/frontend/slices/appshell/components/window-content.tsx
+++ b/frontend/slices/appshell/components/window-content.tsx
@@ -2,6 +2,7 @@
import { useEffect, useState, type ComponentType } from "react";
import { Loader2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
import { useApp } from "../lib/registry";
import { WindowErrorBoundary } from "./window-error-boundary";
import type { AppProps } from "../lib/types";
@@ -20,6 +21,7 @@ export function WindowContent({ app, payload, winId }: { app: string; payload?:
// matches, so `Comp` derives back to null (spinner) without a synchronous
// setState reset in the effect (react-hooks/set-state-in-effect).
const [loaded, setLoaded] = useState<{ key: string; Comp: ComponentType<AppProps> } | null>(null);
+ const [failed, setFailed] = useState<string | null>(null);
const Comp = loaded?.key === app ? loaded.Comp : null;
useEffect(() => {
@@ -28,8 +30,14 @@ export function WindowContent({ app, payload, winId }: { app: string; payload?:
descriptor
.load()
.then((m) => alive && setLoaded({ key: app, Comp: m.default }))
- .catch(() => {
- /* leave the spinner; a failed chunk import is caught by the SW recovery */
+ .catch((e: unknown) => {
+ // Show the failure INSTEAD of spinning forever, then rethrow. The rethrow
+ // is the point: register-sw.tsx recovers a stale chunk from the global
+ // `unhandledrejection` event, and a rejection this catch swallowed never
+ // fires it — so the old `.catch(() => {})` left the user on a dead spinner
+ // and disabled the one thing that could have fixed it.
+ if (alive) setFailed(app);
+ throw e;
});
return () => {
alive = false;
@@ -44,6 +52,17 @@ export function WindowContent({ app, payload, winId }: { app: string; payload?:
);
}
+ if (!Comp && failed === app) {
+ return (
+ <div className="grid h-full place-items-center gap-3 p-6 text-center text-sm text-muted-foreground">
+ <p>Gagal memuat {descriptor.title}.</p>
+ <Button size="sm" variant="secondary" onClick={() => location.reload()}>
+ Muat ulang
+ </Button>
+ </div>
+ );
+ }
+
if (!Comp) {
return (
<div className="grid h-full place-items-center text-muted-foreground">
diff --git a/frontend/slices/appshell/index.ts b/frontend/slices/appshell/index.ts
index 0908bd63..3dd5583a 100644
--- a/frontend/slices/appshell/index.ts
+++ b/frontend/slices/appshell/index.ts
@@ -101,10 +101,10 @@ export { registerContextMenu, getContextMenuItems } from "./lib/context-menu";
export type { MenuItem, ContextMenuCtx, ContextMenuProvider } from "./lib/context-menu";
export { ContextMenu, ShellContextMenu, useContextMenu, useShellContextMenu } from "./components/shells/context-menu";
export { ContextMenuHost } from "./components/shells/context-menu-host";
-export { useContextZone, ContextZone, attachZone, collectZones } from "./lib/context-zone";
+export { useContextZone, attachZone, collectZones } from "./lib/context-zone";
export type { ZoneCtx, ZoneProvider, ZoneResult } from "./lib/context-zone";
export { resetDesktopIcons, setAddDialog } from "./features/desktop-icons";
-export { registerWallpaper, getWallpaper, listWallpapers, useWallpapers } from "./lib/wallpaper-registry";
+export { registerWallpaper, getWallpaper, useWallpapers } from "./lib/wallpaper-registry";
export type { WallpaperDescriptor, WallpaperProps } from "./lib/wallpaper-registry";
export {
usePublishInspector,
@@ -135,7 +135,6 @@ export { ApprovalCard } from "./components/approval-card";
// active one is resolved by form factor.
export {
registerShell,
- getShell,
shellList,
shellsForSurface,
resolveShell,
@@ -165,7 +164,7 @@ export { AppFrame } from "./primitives/app-frame";
export { MasterDetail } from "./primitives/master-detail";
export { ResponsiveToolbar } from "./primitives/responsive-toolbar";
export type { ToolbarItem } from "./primitives/responsive-toolbar";
-export { TouchList, TouchRow } from "./primitives/touch-list";
+export { TouchList } from "./primitives/touch-list";
// ── Manifest-driven shell: the wrapper provider + feature/slot/brand registry ─
export { AppShell } from "./provider/app-shell";
diff --git a/frontend/slices/appshell/lib/context-zone.tsx b/frontend/slices/appshell/lib/context-zone.tsx
index 7b511c39..68646ec4 100644
--- a/frontend/slices/appshell/lib/context-zone.tsx
+++ b/frontend/slices/appshell/lib/context-zone.tsx
@@ -50,24 +50,6 @@ export function useContextZone(provide: ZoneProvider) {
}, []);
}
-/** JSX form for when a ref is awkward. `display:contents` = zero layout box. */
-export function ContextZone({
- provide,
- children,
- className,
-}: {
- provide: ZoneProvider;
- children: ReactNode;
- className?: string;
-}) {
- const ref = useContextZone(provide);
- return (
- <div ref={ref} className={className ?? "contents"}>
- {children}
- </div>
- );
-}
-
/** Walk target → parentElement, calling every zone en route; each zone's items
* become ONE group (innermost first). `sealed` = a zone said stop. */
export function collectZones(
diff --git a/frontend/slices/appshell/lib/wallpaper-registry.ts b/frontend/slices/appshell/lib/wallpaper-registry.ts
index 2e5a5d1e..2486a118 100644
--- a/frontend/slices/appshell/lib/wallpaper-registry.ts
+++ b/frontend/slices/appshell/lib/wallpaper-registry.ts
@@ -44,10 +44,6 @@ export function getWallpaper(id: string): WallpaperDescriptor | undefined {
return registry.get(id);
}
-export function listWallpapers(): WallpaperDescriptor[] {
- return snapshot;
-}
-
/** Reactive list for the picker (re-renders when registrations change). */
export function useWallpapers(): WallpaperDescriptor[] {
return useSyncExternalStore(
diff --git a/frontend/slices/appshell/primitives/touch-list.tsx b/frontend/slices/appshell/primitives/touch-list.tsx
index ba3b2e52..ead56761 100644
--- a/frontend/slices/appshell/primitives/touch-list.tsx
+++ b/frontend/slices/appshell/primitives/touch-list.tsx
@@ -5,9 +5,8 @@ import { cn } from "@/lib/utils";
import { useResponsive } from "../responsive/use-responsive";
// A list whose rows grow to ≥44px hit targets on coarse pointers (touch), and
-// stay compact with a fine pointer (mouse). Wrap rows in <TouchRow> or pass
-// plain children — the min-height is enforced via a child selector so existing
-// row markup doesn't need to change.
+// stay compact with a fine pointer (mouse). Pass plain children — the min-height
+// is enforced via a child selector so existing row markup doesn't need to change.
export function TouchList({
children,
className,
@@ -30,29 +29,3 @@ export function TouchList({
);
}
-export function TouchRow({
- children,
- onClick,
- selected,
- className,
-}: {
- children: ReactNode;
- onClick?: () => void;
- selected?: boolean;
- className?: string;
-}) {
- return (
- <div
- role="listitem"
- onClick={onClick}
- className={cn(
- "flex items-center gap-2 rounded-md px-2 py-1.5 text-sm",
- onClick && "cursor-pointer hover:bg-accent",
- selected && "bg-accent",
- className,
- )}
- >
- {children}
- </div>
- );
-}
diff --git a/frontend/slices/appshell/registry/shells.tsx b/frontend/slices/appshell/registry/shells.tsx
index b73919c1..66686bd1 100644
--- a/frontend/slices/appshell/registry/shells.tsx
+++ b/frontend/slices/appshell/registry/shells.tsx
@@ -59,9 +59,6 @@ function syncShellCommands(): void {
})),
);
}
-export function getShell(id: ShellId | null | undefined): ShellDescriptor | undefined {
- return id ? REGISTRY.get(id) : undefined;
-}
/** Registered shells in display order (for the switcher). */
export function shellList(): ShellDescriptor[] {
return order.map((id) => REGISTRY.get(id)).filter(Boolean) as ShellDescriptor[];
diff --git a/frontend/slices/image-picker/agent.md b/frontend/slices/image-picker/agent.md
deleted file mode 100644
index c4fb208a..00000000
--- a/frontend/slices/image-picker/agent.md
+++ /dev/null
@@ -1,34 +0,0 @@
-<!-- AUTO-GENERATED by scripts/features/gen-slice-agent-md.mjs -->
-<!-- DO NOT EDIT — re-run `node scripts/features/gen-slice-agent-md.mjs` -->
-
-# Install `image-picker` — Image Picker — one-button image/wallpaper chooser (gallery · upload · link · Unsplash · reposition)
-
-> Generic image/wallpaper picker — not coupled to Notion.
-
-📚 Knowledge base : https://resource.rahmanef.com/llms.txt
-📦 Slice detail : https://resource.rahmanef.com/slices/image-picker
-🧠 JSON catalog : https://resource.rahmanef.com/api/knowledge?slice=image-picker
-🤖 Prompt page : https://resource.rahmanef.com/agents/image-picker
-
-## 1. Install
-
-```bash
-npx rahman-resources add image-picker
-# alias: npx rr add image-picker
-```
-
-## 2. What it ships
-
-- tags: `ui`, `image`, `picker`, `wallpaper`, `cover`, `upload`, `unsplash`, `gallery`, `reposition`, `files`, `primitive`, `portable`, `dialog`
-
-## 3. Wire it up
-
-Run `npx rr add image-picker`. The headline component is `<ImagePickerButton label="Change wallpaper" onChange={(img)=>save(img)} onUpload={…} searchUnsplash={…} />` — ONE button that opens the 4-tab dialog (gallery / upload / link / Unsplash). For a reposition-able cover/hero band use `<ImageBanner image={value} onChange={save} resolvedUrl={…} onUpload={…} searchUnsplash={…} />` (also passable to notion-shell's `<NotionPage coverSlot={…} />`). Inject the backend: `onUpload` = the `files` slice's useFileUpload().upload (returns a FileRef); resolve upload images for display with `resolvedUrl` = files useFileUrl(parseFileRef(imageRef(parseImage(value))).storageId). `searchUnsplash` = `unsplashSearchVia('/api/unsplash')` — add a server route that proxies api.unsplash.com with UNSPLASH_ACCESS_KEY (never expose the key client-side). Ships a curated Unsplash + gallery fallback so it works with zero wiring. ImageValue = { type, value, positionY?, metadata? }; parseImage handles legacy string values.
-
-## Rules of engagement
-
-- shadcn-only UI primitives. No raw `<button>` / `<dialog>` / native date or file inputs.
-- 200-line hard cap per source file (extract neighbours when over).
-- All Convex queries hit an index (`.withIndex(...)`); never bare `.collect()`.
-- Public mutations/queries declare `args:` validators + authz.
-- Full ruleset: https://resource.rahmanef.com/best-practice
diff --git a/frontend/slices/image-picker/components/image-banner.tsx b/frontend/slices/image-picker/components/image-banner.tsx
deleted file mode 100644
index 01e80683..00000000
--- a/frontend/slices/image-picker/components/image-banner.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-"use client";
-
-/** ImageBanner — render an ImageValue as a full-width band (colour / gradient /
- * texture / uploaded / linked / unsplash image) with hover controls: Change
- * (opens the picker dialog) · Reposition (drag the vertical focal point) ·
- * Remove. Optional — use it for a page cover, profile header, or card hero;
- * for a plain set-an-image control use ImagePickerButton instead. `resolvedUrl`
- * is the host-resolved URL for upload (FileRef) values — for every other type
- * the value IS the URL. Pure / props-driven. */
-
-import * as React from "react";
-import { Image as ImageIcon, Move, X } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { cn } from "@/lib/utils";
-import type { ImageValue, ImageField, ImageSourceProps } from "../types";
-import { parseImage } from "../lib/parseImage";
-import { imageStyle } from "../lib/imageStyle";
-import { ImagePickerDialog } from "./image-picker-dialog";
-
-interface Props extends ImageSourceProps {
- image: ImageField;
- onChange: (next: ImageValue | null) => void;
- resolvedUrl?: string | null;
- className?: string;
-}
-
-export function ImageBanner({ image, onChange, resolvedUrl, onUpload, className }: Props) {
- const data = parseImage(image);
- const [pickerOpen, setPickerOpen] = React.useState(false);
- const [reposition, setReposition] = React.useState(false);
- const ref = React.useRef<HTMLDivElement>(null);
- const dragging = React.useRef(false);
-
- const setY = (clientY: number, el: HTMLElement) => {
- if (!data) return;
- const r = el.getBoundingClientRect();
- const pct = ((clientY - r.top) / r.height) * 100;
- onChange({ ...data, positionY: Math.max(0, Math.min(100, pct)) });
- };
-
- React.useEffect(() => {
- if (!reposition) return;
- const move = (e: MouseEvent) => { if (dragging.current && ref.current) setY(e.clientY, ref.current); };
- const up = () => { dragging.current = false; };
- window.addEventListener("mousemove", move);
- window.addEventListener("mouseup", up);
- return () => { window.removeEventListener("mousemove", move); window.removeEventListener("mouseup", up); };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [reposition, data]);
-
- if (!data) return null;
-
- return (
- <div className="group/banner relative w-full shrink-0">
- <div
- ref={ref}
- onMouseDown={(e) => { if (!reposition) return; dragging.current = true; setY(e.clientY, e.currentTarget); }}
- className={cn("h-44 w-full md:h-56", reposition && "cursor-ns-resize ring-2 ring-inset ring-primary", className)}
- style={imageStyle(data, resolvedUrl)}
- />
- <div className={cn("absolute bottom-3 right-3 flex gap-1.5 opacity-0 transition group-hover/banner:opacity-100", reposition && "opacity-100")}>
- {reposition ? (
- <Button size="sm" variant="secondary" onClick={() => setReposition(false)}>Save position</Button>
- ) : (
- <>
- <Button size="sm" variant="secondary" onClick={() => setPickerOpen(true)}><ImageIcon className="mr-1 h-3 w-3" />Change</Button>
- <Button size="sm" variant="secondary" onClick={() => setReposition(true)}><Move className="mr-1 h-3 w-3" />Reposition</Button>
- <Button size="icon" variant="secondary" aria-label="Remove image" onClick={() => onChange(null)}><X className="h-3.5 w-3.5" /></Button>
- </>
- )}
- </div>
- <ImagePickerDialog open={pickerOpen} onOpenChange={setPickerOpen} onSelect={onChange} onUpload={onUpload} />
- </div>
- );
-}
diff --git a/frontend/slices/image-picker/index.ts b/frontend/slices/image-picker/index.ts
index f98a9e84..bb7b3661 100644
--- a/frontend/slices/image-picker/index.ts
+++ b/frontend/slices/image-picker/index.ts
@@ -2,12 +2,10 @@
* button (ImagePickerButton) that opens a dialog: Gallery (colours / gradients
* / textures) · Upload (inject your storage via `onUpload`) · Link (paste a
* URL) · Stock (curated set + keyless live search via /api/v1/stock/search —
- * Openverse by default, Unsplash when the server holds a key). ImageBanner is
- * the optional reposition-able band (page cover / profile header / hero). */
+ * Openverse by default, Unsplash when the server holds a key). */
export { ImagePickerButton } from "./components/image-picker-button";
export { ImagePickerDialog } from "./components/image-picker-dialog";
-export { ImageBanner } from "./components/image-banner";
export { parseImage, isCssImage, isUrlImage, imageRef } from "./lib/parseImage";
export { imageStyle } from "./lib/imageStyle";
diff --git a/frontend/slices/image-picker/slice.manifest.json b/frontend/slices/image-picker/slice.manifest.json
deleted file mode 100644
index b79e08c6..00000000
--- a/frontend/slices/image-picker/slice.manifest.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "name": "image-picker",
- "description": "One-button image/wallpaper chooser — ImagePickerButton opens a dialog: Gallery (colours/gradients/textures), Upload (inject storage), Link (URL), Unsplash (curated + live search). ImageBanner is the optional reposition-able band (page cover / profile header / hero). Props-driven, imports no other slice + no backend.",
- "deps": {
- "shared": ["lib/utils"],
- "slices": [],
- "convex": []
- },
- "notes": "Pure client-side slice, not coupled to Notion. The upload backend + Unsplash search are INJECTED: wire onUpload to the `files` slice (useFileUpload) and searchUnsplash to a server route via unsplashSearchVia('/api/unsplash') that holds UNSPLASH_ACCESS_KEY server-side (never NEXT_PUBLIC). Ships a curated Unsplash fallback + texture gallery so it works with zero config. resolvedUrl for upload (FileRef) values is resolved by the host (files useFileUrl). Headline API = ImagePickerButton; ImageBanner adds drag-to-reposition for cover/hero use."
-}
diff --git a/frontend/slices/quicklinks/slice.manifest.json b/frontend/slices/quicklinks/slice.manifest.json
deleted file mode 100644
index 6cd10da7..00000000
--- a/frontend/slices/quicklinks/slice.manifest.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "name": "quicklinks",
- "description": "User-curated website shortcuts (URL + favicon). Managed in Settings → Quicklink; surfaced in the dock, Launchpad, mobile grid, Today widget and a dedicated window. Opening one pops a new native browser tab. The shell reads the list via the injected useQuickLinks capability.",
- "deps": {
- "shared": ["lib/utils", "lib/quicklinks"],
- "slices": ["os-shell"],
- "convex": []
- },
- "notes": "Pure client-side. The quicklinks store (lib/quicklinks) persists to localStorage; os-shell adapts it to the appshell useQuickLinks capability so appshell + its feature slices carry no host dependency."
-}
diff --git a/lib/host/multipart.ts b/lib/host/multipart.ts
index 238834b6..5dc0926f 100644
--- a/lib/host/multipart.ts
+++ b/lib/host/multipart.ts
@@ -37,23 +37,6 @@ export function boundaryFromContentType(ct: string | null): string {
return b;
}
-function indexOf(hay: Bytes, needle: Bytes, from: number): number {
- outer: for (let i = from; i <= hay.length - needle.length; i++) {
- for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;
- return i;
- }
- return -1;
-}
-
-type Bytes = Uint8Array<ArrayBufferLike>;
-
-function concat(a: Bytes, b: Bytes): Bytes {
- const out = new Uint8Array(a.length + b.length);
- out.set(a, 0);
- out.set(b, a.length);
- return out;
-}
-
function parseHeaders(block: string): { name: string; filename?: string } {
let name = "";
let filename: string | undefined;
@@ -75,7 +58,12 @@ export async function* parseMultipart(
const reader = stream.getReader();
const delim = new TextEncoder().encode(`\r\n--${boundary}`);
const headerEnd = new Uint8Array([CR, LF, CR, LF]);
- let buf: Bytes = new Uint8Array(0);
+ const CRLF = new Uint8Array([CR, LF]);
+ // A Buffer, not a bare Uint8Array: Uint8Array#indexOf searches for a single
+ // BYTE VALUE, while Buffer#indexOf takes a subsequence — and subarray keeps the
+ // Buffer type, so every slice below stays searchable. This replaced a hand-rolled
+ // O(n*m) scan and an allocate-and-copy concat.
+ let buf: Buffer = Buffer.alloc(0);
let done = false;
let total = 0; // running bytes across all part bodies (the cap subject)
let pulled = 0; // RAW bytes read from the stream — the security backstop
@@ -92,14 +80,14 @@ export async function* parseMultipart(
// and OOM the host before any part-body counter runs.
pulled += value.length;
if (pulled > limit) throw new UploadTooLargeError(limit);
- buf = concat(buf, value);
+ buf = Buffer.concat([buf, value]);
return true;
}
// Skip the preamble up to the first boundary line.
const first = new TextEncoder().encode(`--${boundary}`);
for (;;) {
- const i = indexOf(buf, first, 0);
+ const i = buf.indexOf(first);
if (i >= 0) {
buf = buf.subarray(i + first.length);
break;
@@ -112,18 +100,18 @@ export async function* parseMultipart(
while (buf.length < 2) if (!(await pull())) return;
if (buf[0] === DASH && buf[1] === DASH) return; // closing boundary
// consume the CRLF after the boundary token
- let nl = indexOf(buf, new Uint8Array([CR, LF]), 0);
+ let nl = buf.indexOf(CRLF);
while (nl !== 0) {
if (!(await pull())) return;
- nl = indexOf(buf, new Uint8Array([CR, LF]), 0);
+ nl = buf.indexOf(CRLF);
}
buf = buf.subarray(2);
// Read this part's header block (terminated by CRLFCRLF).
- let he = indexOf(buf, headerEnd, 0);
+ let he = buf.indexOf(headerEnd);
while (he < 0) {
if (!(await pull())) throw new HostError("malformed multipart header");
- he = indexOf(buf, headerEnd, 0);
+ he = buf.indexOf(headerEnd);
}
const head = new TextDecoder().decode(buf.subarray(0, he));
buf = buf.subarray(he + headerEnd.length);
@@ -133,7 +121,7 @@ export async function* parseMultipart(
let ended = false;
async function* partBody(): AsyncGenerator<Uint8Array> {
for (;;) {
- const d = indexOf(buf, delim, 0);
+ const d = buf.indexOf(delim);
if (d >= 0) {
if (d > 0) {
total += d;
diff --git a/lib/managed-apps/catalog.ts b/lib/managed-apps/catalog.ts
index bb945bbc..f8bf8202 100644
--- a/lib/managed-apps/catalog.ts
+++ b/lib/managed-apps/catalog.ts
@@ -28,7 +28,6 @@ const definitions = {
containerNames: ["hermes", "hermes-dashboard"],
dashboardUrl: process.env.HERMES_DASHBOARD_URL ?? "http://127.0.0.1:9119",
stateDirName: ".hermes",
- assetDir: expandHome(process.env.HERMES_WEB_DIST),
homeDir: expandHome(process.env.HERMES_HOME),
gradient: "linear-gradient(160deg,#8b5cf6,#4f46e5)",
},
@@ -43,7 +42,6 @@ const definitions = {
containerNames: ["openclaw", "openclaw-gateway"],
dashboardUrl: process.env.OPENCLAW_DASHBOARD_URL ?? "http://127.0.0.1:18789",
stateDirName: ".openclaw",
- assetDir: expandHome(process.env.OPENCLAW_CONTROL_UI_DIST),
gradient: "linear-gradient(160deg,#f97316,#dc2626)",
},
} as const satisfies Record<ManagedAppId, ManagedAppDefinition>;
diff --git a/lib/managed-apps/proxy-csp.ts b/lib/managed-apps/proxy-csp.ts
index 4600a4e0..e6f9e538 100644
--- a/lib/managed-apps/proxy-csp.ts
+++ b/lib/managed-apps/proxy-csp.ts
@@ -11,8 +11,7 @@
// policy, so for Hermes the result is ours, unchanged.
//
// Server-only (it pins the injected shim by hash, via node:crypto).
-// proxy-headers.ts must not import it: the frontend imports that module for
-// PROXY_BLOCKED_EXTERNALS.
+// proxy-headers.ts must not import it.
type Policy = Map<string, string[]>;
@@ -60,7 +59,7 @@ export interface PolicyMount {
// cookie and cannot be an oracle — and fonts.gstatic.com breaks visibly.
// • img-src/font-src carry `https:`: chat avatars and remote webfont files are
// inert bytes, and blocking them broke visibly. connect-src names no foreign
-// HOST beyond what the upstream itself declares — see PROXY_BLOCKED_EXTERNALS.
+// HOST beyond what the upstream itself declares.
// Its one addition is the ws:// twin of the prefix (root-mounted only), which
// is the same origin under a scheme CSP will not match implicitly.
// Who may frame us. The cockpit is a different origin now, so it has to be named —
diff --git a/lib/managed-apps/proxy-headers.test.ts b/lib/managed-apps/proxy-headers.test.ts
index e69f6c34..623003ee 100644
--- a/lib/managed-apps/proxy-headers.test.ts
+++ b/lib/managed-apps/proxy-headers.test.ts
@@ -1,62 +1,17 @@
// Policy scoping + redirect plumbing for the managed-app proxy, unit-tested
// straight off the pure helpers (the policy itself is proxy-csp.test.ts; the route
// wiring is covered in app/api/v1/managed-apps/proxy.test.ts).
-import { afterEach, describe, expect, it } from "vitest";
+import { describe, expect, it } from "vitest";
import {
- PROXY_BLOCKED_EXTERNALS,
buildUpstreamHeaders,
isServiceWorkerPath,
proxyPrefix,
- publicProxyUrl,
rewriteLocation,
} from "./proxy-headers";
const PREFIX = proxyPrefix("hermes");
const PREFIX_URL = `https://mso.rahmanef.com${PREFIX}/`;
-describe("publicProxyUrl", () => {
- afterEach(() => {
- delete process.env.OS_PUBLIC_ORIGIN;
- });
-
- it("prefers OS_PUBLIC_ORIGIN over anything a request can carry", () => {
- process.env.OS_PUBLIC_ORIGIN = "https://mso.rahmanef.com";
- const spoofed = new Request(`http://localhost:4005${PREFIX}/chat`, {
- headers: { "x-forwarded-host": "evil.example", "x-forwarded-proto": "https", host: "evil.example" },
- });
- expect(publicProxyUrl(spoofed, "hermes")).toBe(PREFIX_URL);
- });
-
- it("ignores a malformed OS_PUBLIC_ORIGIN instead of emitting junk", () => {
- process.env.OS_PUBLIC_ORIGIN = "mso.rahmanef.com";
- const req = new Request(`http://localhost:4005${PREFIX}/chat`, { headers: { host: "mso.rahmanef.com" } });
- expect(publicProxyUrl(req, "hermes")).toBe(`http://mso.rahmanef.com${PREFIX}/`);
- });
-
- it("trusts the real Host header over a client-settable X-Forwarded-Host", () => {
- const spoofed = new Request(`http://localhost:4005${PREFIX}/chat`, {
- headers: { host: "mso.rahmanef.com", "x-forwarded-host": "evil.example", "x-forwarded-proto": "https" },
- });
- // The host decides which origin the whole policy is scoped to.
- expect(publicProxyUrl(spoofed, "hermes")).toBe(PREFIX_URL);
- });
-
- it("uses the hop the browser made, not the plain-http hop from Traefik", () => {
- const req = new Request(`http://localhost:4005${PREFIX}/chat`, {
- headers: { "x-forwarded-proto": "https,http", "x-forwarded-host": "mso.rahmanef.com" },
- });
- expect(publicProxyUrl(req, "hermes")).toBe(PREFIX_URL);
- });
-
- it("falls back to the Host header, then to the request URL", () => {
- const withHost = new Request(`http://localhost:4005${PREFIX}/chat`, { headers: { host: "mso.rahmanef.com" } });
- expect(publicProxyUrl(withHost, "hermes")).toBe(`http://mso.rahmanef.com${PREFIX}/`);
- expect(publicProxyUrl(new Request(`http://localhost:4005${PREFIX}/chat`), "hermes")).toBe(
- `http://localhost:4005${PREFIX}/`,
- );
- });
-});
-
describe("buildUpstreamHeaders", () => {
const base = new URL("http://127.0.0.1:9119");
const withHeaders = (init: Record<string, string>) =>
@@ -91,22 +46,6 @@ describe("buildUpstreamHeaders", () => {
});
});
-describe("PROXY_BLOCKED_EXTERNALS", () => {
- it("names what nothing grants, and nothing the upstream policy already declares", () => {
- const hosts = PROXY_BLOCKED_EXTERNALS.map((entry) => entry.host);
- // Hermes ships no policy of its own, so its Google Fonts sheet has no source
- // to be honoured from; OpenClaw calls generativelanguage without declaring it.
- expect(hosts).toEqual(["fonts.googleapis.com", "generativelanguage.googleapis.com"]);
- // Honoured by the intersection now (OpenClaw's own connect-src lists them).
- expect(hosts).not.toContain("api.openai.com");
- expect(hosts).not.toContain("tweakcn.com");
- for (const entry of PROXY_BLOCKED_EXTERNALS) {
- expect(["style-src", "connect-src"]).toContain(entry.directive);
- expect(entry.effect.length).toBeGreaterThan(0);
- }
- });
-});
-
describe("isServiceWorkerPath", () => {
it("catches the script OpenClaw actually registers, at any depth", () => {
expect(isServiceWorkerPath(["sw.js"])).toBe(true);
diff --git a/lib/managed-apps/proxy-headers.ts b/lib/managed-apps/proxy-headers.ts
index 0822450a..bcbd5422 100644
--- a/lib/managed-apps/proxy-headers.ts
+++ b/lib/managed-apps/proxy-headers.ts
@@ -246,67 +246,6 @@ export function isServiceWorkerPath(segments: string[]): boolean {
return last !== undefined && SERVICE_WORKER_SCRIPTS.has(last.toLowerCase());
}
-// The CSP source below must be the URL the BROWSER sees — Traefik terminates TLS
-// and forwards plain http, so req.url alone would emit a scheme that matches
-// nothing and white-screen the app. Precedence matters: X-Forwarded-Host is
-// client-settable, and the host in it decides which origin the whole policy is
-// scoped to, so it is consulted LAST. OS_PUBLIC_ORIGIN (deployment-owned) wins,
-// then the real Host header, then the forwarded pair, then the request URL.
-export function publicProxyUrl(req: Request, id: string): string {
- const explicit = process.env.OS_PUBLIC_ORIGIN?.trim();
- if (explicit) {
- try {
- return `${new URL(explicit).origin}${proxyPrefix(id)}/`;
- } catch {
- // Misconfigured value: fall through to the headers rather than emit junk.
- }
- }
- const url = new URL(req.url);
- const forwarded = req.headers.get("x-forwarded-proto")?.split(",")[0].trim();
- const proto = forwarded || url.protocol.replace(":", "");
- const host = req.headers.get("host") ?? req.headers.get("x-forwarded-host") ?? url.host;
- return `${proto}://${host}${proxyPrefix(id)}/`;
-}
-
-/** An upstream subresource the containment policy refuses.
- *
- * NO LONGER RENDERED. This fed a banner above the managed-app frame; that was
- * removed by request (it showed on every feature view and could not be
- * dismissed for good). The table is kept deliberately, not by accident: it is
- * the only structured record of which hosts the app-policy ∩ containment-policy
- * intersection kills and what each one costs the user, and its test asserts
- * that. Nothing consumes it at runtime, so it no longer reaches the client
- * bundle — expect a dead-code sweep to flag it, and read this before deleting. */
-export type BlockedExternal = {
- host: string;
- app: "hermes" | "openclaw";
- /** The directive that refuses it — the one NOT widened to `https:`. */
- directive: "style-src" | "connect-src";
- /** What the user loses, in their words. */
- effect: string;
-};
-
-// img-src/font-src were widened to `https:` (passive bytes), and proxy-csp.ts now
-// honours the external https hosts the UPSTREAM's own policy declares — so
-// OpenClaw keeps fonts.googleapis.com, api.openai.com and tweakcn.com. What is
-// left below is what nothing grants: a host Hermes needs but never declares (it
-// ships no policy at all), and one OpenClaw calls without declaring — blocked in
-// its own deployment too. Surfaced so the window can say so out loud instead of
-// the app silently half-working. Verified against the installed bundles.
-export const PROXY_BLOCKED_EXTERNALS: readonly BlockedExternal[] = [
- {
- host: "fonts.googleapis.com",
- app: "hermes",
- directive: "style-src",
- effect: "Theme webfonts (Inter, IBM Plex, …) fall back to system faces.",
- },
- {
- host: "generativelanguage.googleapis.com",
- app: "openclaw",
- directive: "connect-src",
- effect: "The Gemini live-audio socket in chat cannot connect.",
- },
-];
-
// The policy itself lives in proxy-csp.ts: building it needs node:crypto (it pins
-// the injected shim by hash) and the frontend imports this module.
+// the injected shim by hash). Both modules are server-only — nothing under
+// frontend/ imports either one.
diff --git a/lib/managed-apps/types.ts b/lib/managed-apps/types.ts
index c6796af3..ecf9bc75 100644
--- a/lib/managed-apps/types.ts
+++ b/lib/managed-apps/types.ts
@@ -22,9 +22,6 @@ export interface ManagedAppDefinition {
dashboardUrl: string;
stateDirName: string;
gradient: string;
- /** Override for the upstream SPA build dir that feature discovery reads. Empty = use
- * the default. Absolute once resolved: the catalog expands a leading `~`. */
- assetDir?: string;
/** Override for the upstream state/install home. Empty = `~/<stateDirName>`. */
homeDir?: string;
}
diff --git a/lib/models/index.js b/lib/models/index.js
index 6722a165..17a0a90c 100644
--- a/lib/models/index.js
+++ b/lib/models/index.js
@@ -1,4 +1,4 @@
export { getCatalog, listModels } from './catalog.js'
-export { PROVIDERS, hostOf } from './registry.js'
+export { PROVIDERS } from './registry.js'
export { envCredentialStore } from './store.js'
export { parseRef, resolveModel } from './resolve.js'
diff --git a/lib/models/registry.js b/lib/models/registry.js
index 5f63bddb..1f955ed2 100644
--- a/lib/models/registry.js
+++ b/lib/models/registry.js
@@ -40,4 +40,3 @@ export const PROVIDERS = {
zenmux: { baseUrl: 'https://zenmux.ai/api/v1', protocol: 'openai', envVars: ['ZENMUX_API_KEY'], catalogId: 'zenmux' },
}
-export const hostOf = (u) => new URL(u).host
diff --git a/lib/models/resolve.js b/lib/models/resolve.js
index 5d161b77..8fd3d9d4 100644
--- a/lib/models/resolve.js
+++ b/lib/models/resolve.js
@@ -1,10 +1,10 @@
// resolveModel — turn a `provider/model` ref + a tenant into a ready-to-call descriptor.
-// Pure & offline by default (no network); pass {info:true} to attach models.dev metadata.
+// Pure & offline: no network. (An {info:true} option once attached models.dev metadata;
+// no call site ever passed it, so `info` was permanently null. Deleted 2026-08-10.)
//
// SECURITY (host-gate, hermes' key-selection fix): the key is fetched by PROVIDER slug and
// paired only with THAT provider's baseUrl. Provider A's key can never be sent to provider B.
-import { getCatalog } from './catalog.js'
import { PROVIDERS } from './registry.js'
/**
@@ -15,7 +15,6 @@ import { PROVIDERS } from './registry.js'
* @property {string} baseUrl
* @property {string} apiKey
* @property {'openai'|'anthropic'} protocol
- * @property {object|null} info models.dev metadata (only when opts.info)
*/
/** Split on the FIRST '/', so model ids may contain '/' (OpenRouter style). */
@@ -27,10 +26,10 @@ export function parseRef(ref) {
/**
* @param {string} ref "provider/model"
- * @param {{tenantId?:string, store:import('./store.js').CredentialStore, baseUrl?:string, protocol?:'openai'|'anthropic', info?:boolean}} opts
+ * @param {{tenantId?:string, store:import('./store.js').CredentialStore, baseUrl?:string, protocol?:'openai'|'anthropic'}} opts
* @returns {Promise<ResolvedModel>}
*/
-export async function resolveModel(ref, { tenantId, store, baseUrl, protocol, info = false } = {}) {
+export async function resolveModel(ref, { tenantId, store, baseUrl, protocol } = {}) {
const { provider, model } = parseRef(ref)
const conn = PROVIDERS[provider]
if (!conn && !baseUrl) throw new Error(`unknown provider "${provider}" — add it to registry.js or pass opts.baseUrl`)
@@ -39,7 +38,7 @@ export async function resolveModel(ref, { tenantId, store, baseUrl, protocol, in
const apiKey = await store.getKey(tenantId, provider)
if (!apiKey) throw new Error(`no API key for provider="${provider}" tenant="${tenantId ?? 'default'}" — user must BYOK`)
- const resolved = {
+ return {
ref, provider, model,
// host-gate: known providers are PINNED to their registry endpoint so a caller-supplied
// baseUrl can never redirect a provider's key to another host. Override only honored for
@@ -49,11 +48,5 @@ export async function resolveModel(ref, { tenantId, store, baseUrl, protocol, in
// known providers keep their registry protocol; a custom (conn-less) provider
// uses the caller's declared protocol, defaulting to openai-compatible.
protocol: conn?.protocol || protocol || 'openai',
- info: null,
}
- if (info) {
- const cat = await getCatalog().catch(() => ({}))
- resolved.info = cat?.[conn?.catalogId || provider]?.models?.[model] ?? null
- }
- return resolved
}
diff --git a/lib/prefs/use-prefs-sync.test.ts b/lib/prefs/use-prefs-sync.test.ts
new file mode 100644
index 00000000..deb35f4b
--- /dev/null
+++ b/lib/prefs/use-prefs-sync.test.ts
@@ -0,0 +1,51 @@
+import { describe, it, expect, vi, afterEach } from "vitest";
+import { pullPrefs } from "./use-prefs-sync";
+
+const realFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+
+function stubFetch(impl: () => Promise<Response>) {
+ const spy = vi.fn(impl);
+ globalThis.fetch = spy as unknown as typeof fetch;
+ return spy;
+}
+
+const ok = (body: unknown) =>
+ new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
+
+describe("pullPrefs", () => {
+ it("collapses concurrent callers into ONE request", async () => {
+ const spy = stubFetch(async () => ok({ tweaks: { a: 1 }, quicklinks: [] }));
+ // The two providers (appearance + quicklinks) mount in the same tick.
+ const [a, b] = await Promise.all([pullPrefs(), pullPrefs()]);
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(a).toEqual({ tweaks: { a: 1 }, quicklinks: [] });
+ expect(b).toBe(a);
+ });
+
+ it("refetches after settle, so the focus/auth retry still works", async () => {
+ const spy = stubFetch(async () => ok({ tweaks: {} }));
+ await pullPrefs();
+ await pullPrefs();
+ expect(spy).toHaveBeenCalledTimes(2);
+ });
+
+ it("resolves null on a non-ok response instead of throwing", async () => {
+ stubFetch(async () => new Response("nope", { status: 401 }));
+ expect(await pullPrefs()).toBeNull();
+ });
+
+ it("resolves null when the network throws", async () => {
+ stubFetch(async () => {
+ throw new Error("offline");
+ });
+ expect(await pullPrefs()).toBeNull();
+ });
+
+ it("resolves null on malformed JSON rather than rejecting", async () => {
+ stubFetch(async () => new Response("{not json", { status: 200 }));
+ expect(await pullPrefs()).toBeNull();
+ });
+});
diff --git a/lib/prefs/use-prefs-sync.ts b/lib/prefs/use-prefs-sync.ts
index 520a9ce3..7509c2ea 100644
--- a/lib/prefs/use-prefs-sync.ts
+++ b/lib/prefs/use-prefs-sync.ts
@@ -8,6 +8,22 @@ const DEBOUNCE_MS = 1500;
/** Fired by the auth slice when a login lands (providers mount outside AuthGate). */
export const AUTHED_EVENT = "mso:authed";
+// Both callers (appearance `tweaks` + quicklinks) mount together in os-root and each
+// used to GET the whole blob, so every boot paid two authenticated round-trips — and
+// every window focus while signed out fired two more 401s. One in-flight promise now
+// serves both. It clears on settle, so the focus/auth retry still refetches.
+let inflight: Promise<Record<string, unknown> | null> | null = null;
+
+export function pullPrefs() {
+ inflight ??= fetch("/api/prefs", { cache: "no-store" })
+ .then((r) => (r.ok ? (r.json() as Promise<Record<string, unknown>>) : null))
+ .catch(() => null) // offline / bad JSON — keep local state, stay silent
+ .finally(() => {
+ inflight = null;
+ });
+ return inflight;
+}
+
// Shared server-sync seam for the appearance + quicklinks providers. Offline-first:
// mount → GET /api/prefs → apply the stored section (server wins on initial load) →
// from then on, debounce local changes into a POST. A failed GET (401 on the login
@@ -28,24 +44,19 @@ export function usePrefsSync<T>(opts: {
if (IS_DEMO) return;
let alive = true;
const pull = async () => {
- try {
- const r = await fetch("/api/prefs", { cache: "no-store" });
- if (!r.ok) {
- failed.current = true;
- return;
- }
- const data = (await r.json()) as Record<string, unknown>;
- if (!alive) return;
- const server = data[section];
- if (server != null) {
- echo.current = true; // don't POST back what we just applied
- apply(server as T);
- }
- ready.current = true;
- failed.current = false;
- } catch {
- failed.current = true; // offline — keep local state, stay silent
+ const data = await pullPrefs();
+ if (data == null) {
+ failed.current = true;
+ return;
+ }
+ if (!alive) return;
+ const server = data[section];
+ if (server != null) {
+ echo.current = true; // don't POST back what we just applied
+ apply(server as T);
}
+ ready.current = true;
+ failed.current = false;
};
void pull();
const retry = () => {