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(shells): Windows/iOS/Android to their 2026 specs, plus a backup for local state

Rahman24063bc6c7f3
diff --git a/app/globals.css b/app/globals.css
index da8a7b1c..2b80e89b 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -420,10 +420,35 @@ body {
--shell-font: Roboto, "Google Sans Text", system-ui, var(--font-ui);
/* M3 Expressive spring-ish enter: a mild overshoot (y>1) gives app-open a
lively settle. Android-only + enter-only (no exit/geometry glide on mobile),
- so it can't cause dismiss bounce; reduce-motion still collapses --shell-dur. */
+ so it can't cause dismiss bounce; reduce-motion still collapses --shell-dur.
+ Kept because features/notifications/components/dynamic-island.tsx still reads
+ --shell-ease; the M3 tokens below supersede it inside the Android shell. */
--shell-ease: cubic-bezier(0.2, 0.9, 0.3, 1.06);
--shell-dur: 300ms;
--shell-dur-slow: 400ms;
+
+ /* Material 3 Expressive replaced duration+easing with PHYSICS: spatial springs
+ for anything that moves (may overshoot) and effects springs for colour and
+ opacity (must not). CSS has no spring primitive, so each token below is a real
+ spring sampled into linear().
+ Six M3 tokens collapse into three curves because a spring's normalised SHAPE
+ depends only on its damping ratio — stiffness only scales time, which is what
+ the durations carry.
+ The durations are multiples of --shell-dur ON PURPOSE: the reduce-motion block
+ further down collapses --shell-dur to 1ms, and hard-coded milliseconds here
+ would silently opt every Android animation out of that.
+ CEILING: a linear() cannot be interrupted and re-targeted mid-flight the way a
+ real spring can — it always restarts from zero velocity. Swap for a JS spring
+ only if an interruptible gesture ever needs it. */
+ --m3-spatial-fast: linear(0, 0.0857, 0.2789, 0.504, 0.7122, 0.8779, 0.9931, 1.0608, 1.0905, 1.0935, 1.0805, 1.0604, 1.0392, 1.0208, 1.0069, 0.9978, 0.9928, 0.9911, 0.9915, 0.993, 1); /* k=800 ζ=0.6 */
+ --m3-spatial: linear(0, 0.0538, 0.1769, 0.3268, 0.477, 0.6125, 0.7266, 0.8174, 0.8862, 0.936, 0.9702, 0.9923, 1.0055, 1.0123, 1.0149, 1.0149, 1.0135, 1.0113, 1.009, 1.0068, 1); /* k=380 ζ=0.8 */
+ --m3-effects: linear(0, 0.1712, 0.4382, 0.6532, 0.7972, 0.8856, 0.9371, 0.966, 0.9819, 0.9905, 1); /* ζ=1.0, never overshoots */
+ --m3-dur-spatial-fast: calc(var(--shell-dur) * 1.073); /* 322ms @300 — small elements */
+ --m3-dur-spatial: calc(var(--shell-dur) * 1.237); /* 371ms */
+ --m3-dur-spatial-slow: calc(var(--shell-dur) * 1.703); /* 511ms — large surfaces */
+ --m3-dur-effects-fast: calc(var(--shell-dur) * 0.403); /* 121ms */
+ --m3-dur-effects: calc(var(--shell-dur) * 0.620); /* 186ms */
+ --m3-dur-effects-slow: calc(var(--shell-dur) * 0.877); /* 263ms */
--shell-icon-radius: 50%;
}
/* Top safe-area floor per touch shell — the back/nav buttons + top bars must
diff --git a/docs/MCP.md b/docs/MCP.md
index 1047a2dc..3c2413b7 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -72,8 +72,8 @@ managed-app and browser tools before Alfa had them.
The tiering is about blast radius, not about which layer the call lands in.
`apps_logs` reads a daemon's journal, so "why is hermes down?" is answerable from
a `read` token — the same question through `exec_run` would need a full shell.
-`apps_power` is three verbs against known units, so restarting a daemon does not
-require handing one over either.
+`apps_power` is four verbs (start, stop, restart, backup) against known units, so
+restarting a daemon does not require handing one over either.
`tools/list` is filtered by the token's scope, and `tools/call` re-checks it — a
client that calls a tool it was never shown still gets refused.
diff --git a/frontend/slices/appshell/components/mobile-app-library.tsx b/frontend/slices/appshell/components/mobile-app-library.tsx
index 43e89d6e..c6613909 100644
--- a/frontend/slices/appshell/components/mobile-app-library.tsx
+++ b/frontend/slices/appshell/components/mobile-app-library.tsx
@@ -95,10 +95,14 @@ export function MobileAppLibrary({
<div className="grid grid-cols-4 gap-x-3 gap-y-4">
{folderApps.map((a) => (
<Button key={a.id} type="button" variant="ghost" onClick={() => onOpen(a)} className="h-auto p-0 hover:bg-transparent flex flex-col items-center gap-1.5">
- <span className="aspect-square w-full max-w-[56px]">
+ {/* 60px, the iPhone icon size — an opened App Library folder shows
+ full-size icons, not the shrunken ones the closed card packs
+ into its 2×2 preview. Was 56px. The 4-column card is ~69px per
+ cell here, so 60 fits without reflowing the overlay. */}
+ <span className="aspect-square w-full max-w-[60px]">
<AppIcon app={a} />
</span>
- <span className="max-w-full truncate text-[11px] font-medium">{a.title}</span>
+ <span className="max-w-full truncate text-[11px] font-medium leading-[13px]">{a.title}</span>
</Button>
))}
</div>
diff --git a/frontend/slices/appshell/components/mobile-home-parts.tsx b/frontend/slices/appshell/components/mobile-home-parts.tsx
index dba09ff5..dec7fdf7 100644
--- a/frontend/slices/appshell/components/mobile-home-parts.tsx
+++ b/frontend/slices/appshell/components/mobile-home-parts.tsx
@@ -1,22 +1,27 @@
"use client";
-/* iPhone-home sub-surfaces — the app grid page (upward-swipe search + long-press
- quick actions) and the haptic-touch action sheet. Split from mobile-home.tsx
- (≤200-LOC modularity gate). */
-import { useRef } from "react";
+/* iPhone-home sub-surfaces — ONE page of the app grid (upward-swipe search +
+ long-press quick actions) and the haptic-touch action sheet. Split from
+ mobile-home.tsx (≤200-LOC modularity gate). */
+import { useMemo, useRef } from "react";
import { Button } from "@/components/ui/button";
import type { AppDescriptor } from "../lib/types";
-import { useQuickLinks } from "../registry/capabilities";
+import { useQuickLinks, type QuickLink } from "../registry/capabilities";
import { AppIcon } from "./app-icon";
import { QuicklinkIcon } from "./quicklink-icon";
+// iPhone's home page is a FIXED 6 rows × 4 columns and never scrolls vertically —
+// past 24 icons you swipe sideways. Ours was one 4-column `overflow-y-auto` grid
+// that (measured on the demo) began scrolling at 21 icons on a 390×844 phone and
+// at 17 on a 375×667 one — 375 already scrolled with the 18 apps shipping today,
+// and quicklinks spend the same budget, so three bookmarks tipped 390 over too.
+const ICONS_PER_PAGE = 24;
+
// Long-press quick-actions sheet (iPhone's haptic-touch menu): Open + whatever
// menu items the app declares for the macOS menu bar — one declaration, both OSes.
export function AppActionSheet({
app, onOpen, onClose,
}: {
- app: AppDescriptor;
- onOpen: () => void;
- onClose: () => void;
+ app: AppDescriptor; onOpen: () => void; onClose: () => void;
}) {
const items = (app.menus ?? []).flatMap((m) => m.items).filter(
(it): it is Extract<typeof it, { label: string }> => !("sep" in it),
@@ -52,20 +57,68 @@ export function AppActionSheet({
);
}
-// App grid page. A clear upward swipe (not a horizontal page flick) opens search;
+export type HomeTile =
+ | { key: string; kind: "app"; app: AppDescriptor }
+ | { key: string; kind: "link"; link: QuickLink };
+
+// Apps, then quicklinks, chunked into pages of 24. It lives here rather than in
+// MobileHome because quicklinks arrive through a capability hook, so this is the
+// only place that sees BOTH lists. Always ≥1 page, or the pager collapses.
+export function useHomePages(apps: AppDescriptor[]): HomeTile[][] {
+ const { items } = useQuickLinks();
+ return useMemo(() => {
+ const tiles: HomeTile[] = [
+ ...apps.map((app): HomeTile => ({ key: `app:${app.id}`, kind: "app", app })),
+ ...items.map((link): HomeTile => ({ key: `link:${link.id}`, kind: "link", link })),
+ ];
+ const pages: HomeTile[][] = [];
+ for (let i = 0; i < tiles.length; i += ICONS_PER_PAGE) pages.push(tiles.slice(i, i + ICONS_PER_PAGE));
+ return pages.length > 0 ? pages : [[]];
+ }, [apps, items]);
+}
+
+// One tile. The icon is `flex-1 max-h-[60px]` — sized by the ROW, not the column:
+// sizing by width (`w-full max-w-[58px]`, what this was) overflows a 667px-tall
+// phone, so six rows could never fit. 60px is iPhone's size and 390×844 measures
+// exactly that, but a row only affords what our chrome leaves it — 375×667 measures
+// 45.5px, 320×568 29px. See the top spacer in mobile-home.tsx for where it goes.
+function Tile({
+ label, icon, onClick, onPointerDown, onContextMenu,
+}: {
+ label: string; icon: React.ReactNode; onClick: () => void;
+ onPointerDown?: (e: React.PointerEvent) => void; onContextMenu?: (e: React.MouseEvent) => void;
+}) {
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ onPointerDown={onPointerDown}
+ onContextMenu={onContextMenu}
+ onClick={onClick}
+ className="h-auto min-h-0 p-0 hover:bg-transparent flex flex-col items-center gap-1"
+ >
+ {/* No max-w — width follows height via aspect-square. Clamping the width too
+ made the tile 58.5×60, visibly non-square, on a 360px-wide phone. */}
+ <span className="aspect-square min-h-0 max-h-[60px] flex-1">{icon}</span>
+ {/* 11px/13px — iOS home labels are 11pt SF, one line, tight leading. Was 12px
+ inheriting the Button's 1.43 (17.1px measured), wasting 4px per row — 24px
+ over six rows, which is the margin six rows fit by. */}
+ <span className="max-w-full shrink-0 truncate text-[11px] font-medium leading-[13px] text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]">
+ {label}
+ </span>
+ </Button>
+ );
+}
+
+// One home page. A clear upward swipe (not a horizontal page flick) opens search;
// holding an icon ~450ms (or right-click) opens its quick-actions sheet.
export function AppsGrid({
- apps,
- onLaunch,
- onSearch,
- onContext,
+ tiles, onLaunch, onSearch, onContext,
}: {
- apps: AppDescriptor[];
- onLaunch: (app: AppDescriptor) => void;
- onSearch: () => void;
- onContext: (app: AppDescriptor) => void;
+ tiles: HomeTile[]; onSearch: () => void;
+ onLaunch: (app: AppDescriptor) => void; onContext: (app: AppDescriptor) => void;
}) {
- const { items: links, open: openLink } = useQuickLinks();
+ const { open: openLink } = useQuickLinks();
// Long-press bookkeeping: a fired hold must swallow the click that follows.
const holdTimer = useRef<number | null>(null);
const held = useRef(false);
@@ -91,13 +144,12 @@ export function AppsGrid({
window.addEventListener("pointerup", up);
};
+ // A page no longer scrolls, so an upward drag is unambiguous — the old
+ // `scrollTop <= 0` guard existed only to stop this from stealing the grid's
+ // own vertical scroll, and there is no longer one to steal.
const onPointerDown = (e: React.PointerEvent) => {
const sy = e.clientY;
const sx = e.clientX;
- // Only let an upward swipe mean "search" when the grid is already scrolled
- // to the top — otherwise it fights the vertical scroll that reveals
- // overflow apps + quicklinks.
- const atTop = (e.currentTarget as HTMLElement).scrollTop <= 0;
let fired = false;
const cleanup = () => {
window.removeEventListener("pointermove", move);
@@ -106,7 +158,7 @@ export function AppsGrid({
const move = (ev: PointerEvent) => {
const dy = ev.clientY - sy;
const dx = ev.clientX - sx;
- if (!fired && atTop && dy < -70 && Math.abs(dx) < 50) {
+ if (!fired && dy < -70 && Math.abs(dx) < 50) {
fired = true;
cleanup();
onSearch();
@@ -117,49 +169,32 @@ export function AppsGrid({
};
return (
- // Scrolls vertically so every app + quicklink is reachable. touch-action is
- // left AUTO (was pan-y, which BLOCKED the home pager's horizontal swipe when a
- // touch started on the grid): the browser direction-locks — a vertical drag
- // scrolls this grid, a horizontal drag pages the pager.
+ // 6 rows × 4 cols must equal ICONS_PER_PAGE: change one without the others and
+ // the surplus does not wrap to page 2, it vanishes behind this `overflow-hidden`
+ // — which is equally what stops the page scrolling. touch-action stays AUTO so
+ // the pager's horizontal swipe still reaches the scroller above. 26px gap + px-6
+ // = a 66px column at 390, centring the 60px icon 27px from the edge, 32px apart.
<div
onPointerDown={onPointerDown}
- className="grid h-full grid-cols-4 content-start gap-x-3.5 gap-y-[22px] overflow-y-auto px-6 pt-[18px] pb-6 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
+ className="grid h-full grid-cols-4 grid-rows-6 gap-x-[26px] overflow-hidden px-6 pb-6 pt-[18px]"
>
- {apps.map((app) => (
- <Button
- key={app.id}
- type="button"
- variant="ghost"
- onPointerDown={startHold(app)}
- onContextMenu={(e) => { e.preventDefault(); onContext(app); }}
- onClick={() => { if (held.current) { held.current = false; return; } onLaunch(app); }}
- className="h-auto p-0 hover:bg-transparent flex flex-col items-center gap-1.5"
- >
- <span className="aspect-square w-full max-w-[58px]">
- <AppIcon app={app} />
- </span>
- <span className="max-w-full truncate text-[12px] font-medium text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]">
- {app.title}
- </span>
- </Button>
- ))}
- {links.map((link) => (
- <Button
- key={link.id}
- type="button"
- variant="ghost"
- onClick={() => openLink(link)}
- className="h-auto p-0 hover:bg-transparent flex flex-col items-center gap-1.5"
- >
- <span className="aspect-square w-full max-w-[58px]">
- <QuicklinkIcon link={link} />
- </span>
- <span className="max-w-full truncate text-[12px] font-medium text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.5)]">
- {link.title}
- </span>
- </Button>
- ))}
+ {tiles.map((tile) => {
+ if (tile.kind === "link") {
+ const { link } = tile; // const so the narrowing survives into the closure
+ return <Tile key={tile.key} label={link.title} icon={<QuicklinkIcon link={link} />} onClick={() => openLink(link)} />;
+ }
+ const { app } = tile;
+ return (
+ <Tile
+ key={tile.key}
+ label={app.title}
+ icon={<AppIcon app={app} />}
+ onPointerDown={startHold(app)}
+ onContextMenu={(e) => { e.preventDefault(); onContext(app); }}
+ onClick={() => { if (held.current) { held.current = false; return; } onLaunch(app); }}
+ />
+ );
+ })}
</div>
);
}
-
diff --git a/frontend/slices/appshell/components/mobile-home.tsx b/frontend/slices/appshell/components/mobile-home.tsx
index b207f7c8..b5099721 100644
--- a/frontend/slices/appshell/components/mobile-home.tsx
+++ b/frontend/slices/appshell/components/mobile-home.tsx
@@ -7,11 +7,12 @@ import type { AppDescriptor } from "../lib/types";
import { AppIcon } from "./app-icon";
import { Slot } from "../registry/feature-registry";
import { MobileAppLibrary } from "./mobile-app-library";
-import { AppActionSheet, AppsGrid } from "./mobile-home-parts";
+import { AppActionSheet, AppsGrid, useHomePages } from "./mobile-home-parts";
import { ShellContextMenu, useShellContextMenu } from "./shells/context-menu";
-// Paged iPhone home: [Today widgets] · [App grid] · [App Library]. The status
-// clock, dock, page dots and home-indicator persist across pages.
+// Paged iPhone home: [Today widgets] · [App grid ×N] · [App Library]. The dock,
+// page dots and home-indicator persist across pages. The app grid is N pages of
+// 24 (iPhone's 6×4), not one vertical scroller — see mobile-home-parts.
export function MobileHome({
apps,
dockApps,
@@ -32,9 +33,11 @@ export function MobileHome({
indicator: React.ReactNode;
}) {
const pagerRef = useRef<HTMLDivElement>(null);
- const [page, setPage] = useState(1); // 0 widgets · 1 apps · 2 library
+ const [page, setPage] = useState(1); // 0 widgets · 1…N apps · N+1 library
const [ctxApp, setCtxApp] = useState<AppDescriptor | null>(null); // long-press sheet
const menu = useShellContextMenu("ios", "mobile"); // home background long-press menu
+ const gridPages = useHomePages(apps);
+ const pageCount = gridPages.length + 2; // + Today + App Library
// Open on the app grid (the middle page), like iPhone's default home.
useLayoutEffect(() => {
@@ -83,7 +86,12 @@ export function MobileHome({
{/* Top safe-area spacer: reserves the notch / Dynamic-Island zone (a real
phone's hardware lives here) and owns the swipe-down gesture →
Notification Center (left half) / Control Center (right half).
- Deliberately empty — no status clock (not useful in a VPS cockpit). */}
+ Deliberately empty — no status clock (not useful in a VPS cockpit).
+ This 2.25rem is ON TOP of --sai-top, which globals.css floors at 2.75rem
+ for data-shell="ios" — they ADD, so iOS starts the pager 80px down even in
+ a browser reporting no inset. Read that before "reclaiming" space here:
+ 80px + 34px of dots + a 100px dock block + a 36px indicator = 250px, and
+ what is left is what caps the home icon (60px at 844 tall, 45.5 at 667). */}
<div
className="shrink-0 [touch-action:none]"
style={{ height: "calc(2.25rem + var(--sai-top))" }}
@@ -96,21 +104,24 @@ export function MobileHome({
className="flex min-h-0 flex-1 snap-x snap-mandatory overflow-x-auto overflow-y-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
>
<Page active={page === 0}>
- {/* Own scroller so tall Today widgets scroll (pages 1/2 already do) */}
+ {/* Today keeps its OWN scroller — a widget stack is genuinely taller than
+ the page. The app pages deliberately do not scroll (see AppsGrid). */}
<div className="h-full overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<Slot region="today" />
</div>
</Page>
- <Page active={page === 1}>
- <AppsGrid apps={apps} onLaunch={onLaunch} onSearch={onSearch} onContext={setCtxApp} />
- </Page>
- <Page active={page === 2}>
+ {gridPages.map((tiles, i) => (
+ <Page key={tiles[0]?.key ?? `home-${i}`} active={page === i + 1}>
+ <AppsGrid tiles={tiles} onLaunch={onLaunch} onSearch={onSearch} onContext={setCtxApp} />
+ </Page>
+ ))}
+ <Page active={page === pageCount - 1}>
<MobileAppLibrary apps={apps} onOpen={onLaunch} />
</Page>
</div>
<div className="flex justify-center gap-0.5 pb-1.5 pt-1">
- {[0, 1, 2].map((i) => (
+ {Array.from({ length: pageCount }, (_, i) => (
<button
key={i}
type="button"
diff --git a/frontend/slices/appshell/components/shells/android/android-motion.tsx b/frontend/slices/appshell/components/shells/android/android-motion.tsx
new file mode 100644
index 00000000..c42637b0
--- /dev/null
+++ b/frontend/slices/appshell/components/shells/android/android-motion.tsx
@@ -0,0 +1,60 @@
+/* Material 3 Expressive motion — the Android shell's spring tokens, in one place.
+
+ WHAT CHANGED AND WHY. This shell animated with `cubic-bezier(0.2,0.9,0.3,1.06)`
+ at a flat 300ms, which is the pre-2025 Material model (duration + easing).
+ M3 Expressive (m3.material.io, 2026) replaced that: motion is now described by
+ a spring — a stiffness/damping pair — in two families. "Spatial" springs drive
+ anything that moves or resizes and are allowed to overshoot; "effects" springs
+ drive colour and opacity and must NOT, because an alpha that overshoots past 1
+ clips flat and reads as a flicker rather than as momentum.
+
+ CSS has no spring primitive. Each easing below is a `linear()` SAMPLED off the
+ real spring's unit-step response (mass 1, as M3 specifies), truncated where the
+ curve settles inside ±0.5% of rest.
+
+ THE CEILING OF THIS APPROXIMATION, stated plainly: a sampled linear() is still
+ a fixed-duration easing. A real spring can be interrupted mid-flight and
+ re-targeted, carrying its current velocity into the new animation. A CSS easing
+ always restarts from zero velocity and always runs its full duration, so
+ flicking the shade open-closed-open looks like three separate animations rather
+ than one continuous mass. Anything that genuinely needs interruptible physics
+ has to leave CSS for WAAPI or a JS spring; do not try to fix it by adding more
+ keyframes here.
+
+ ONLY THREE CURVES, not six. Normalised to 0..1 a spring's SHAPE depends only on
+ the damping ratio; stiffness merely scales time. So M3's six spring tokens
+ collapse to three easings plus six durations:
+ ζ=0.6 spatial fast → 9.3% overshoot
+ ζ=0.8 spatial default/slow → 1.5% overshoot
+ ζ=1.0 every effects token → critically damped, no overshoot
+
+ DURATIONS ARE calc(var(--shell-dur) * K), NOT RAW MS, ON PURPOSE. globals.css
+ collapses --shell-dur to 1ms under prefers-reduced-motion. Before this change
+ the only Android motion that honoured that was the one animation already
+ written in terms of --shell-dur; every press/enter animation added here would
+ have silently opted OUT of the reduce-motion contract if the ms were hard-coded.
+ K = settle time ÷ the 300ms Android --shell-dur:
+ spatial fast 322ms (k=800, ζ=0.6) ×1.073
+ spatial default 371ms (k=380, ζ=0.8) ×1.237
+ spatial slow 511ms (k=200, ζ=0.8) ×1.703
+ effects fast 121ms (k=3800, ζ=1.0) ×0.403
+ effects default 186ms (k=1600, ζ=1.0) ×0.620
+ effects slow 263ms (k=800, ζ=1.0) ×0.877
+ The tokens themselves now live under [data-shell="android"] in app/globals.css,
+ so every Android surface inherits them from the shell root with no provider and
+ no per-render style object. This module keeps only the class that consumes them.
+
+ BROWSER FLOOR: linear() is Chrome 113 / Safari 17.2 / Firefox 112. Older engines
+ drop the whole timing-function declaration and fall back to `ease`, which is a
+ correct-looking degrade, not a break — so no @supports guard. */
+/* Touch press-down. Real Android answers a tap with a ripple, which CSS cannot
+ draw without a pseudo-element sized from the touch point; a spring scale-down
+ is the honest substitute and carries the same "the surface is physical" signal.
+ `transition-transform` also covers `scale` (Tailwind 4 puts scale in the
+ transform group), and it deliberately REPLACES the shadcn Button base's
+ `transition-colors` via tailwind-merge — every call site here is
+ `hover:bg-transparent`, so there is no colour transition to lose, and keeping
+ `transition` (all properties) would have put a 9.3%-overshoot SPATIAL curve on
+ colour, which is exactly the family mix M3 forbids. */
+export const M3_PRESS =
+ "transition-transform duration-[var(--m3-dur-spatial-fast)] ease-[var(--m3-spatial-fast)]";
diff --git a/frontend/slices/appshell/components/shells/android/android-notifications.tsx b/frontend/slices/appshell/components/shells/android/android-notifications.tsx
index 90d3cad9..24390566 100644
--- a/frontend/slices/appshell/components/shells/android/android-notifications.tsx
+++ b/frontend/slices/appshell/components/shells/android/android-notifications.tsx
@@ -40,9 +40,21 @@ export function AndroidNotifications({ open, onClose }: { open: boolean; onClose
if (!open) return null;
return (
- <div className="absolute inset-0 z-[45] flex flex-col bg-black/40" onClick={onClose}>
+ // Scrim = opacity only → M3 EFFECTS default (k=1600, ζ=1, ~186ms), critically
+ // damped so the dim can never overshoot past its target alpha and flicker.
+ // It had no animation at all before; the black wash appeared in one frame.
+ <div className="absolute inset-0 z-[45] flex flex-col bg-black/40 animate-in fade-in duration-[var(--m3-dur-effects)] ease-[var(--m3-effects)]" onClick={onClose}>
+ {/* The shade is pulled DOWN from the top edge, but it was animating with
+ `appOpen`, which travels 14px UPWARD from below — the panel arrived moving
+ against the gesture that summoned it. It now slides down from -100% (its
+ own height, above the viewport) on the M3 SPATIAL SLOW spring (k=200,
+ ζ=0.8, ~511ms): a full-width surface, so the slow tier.
+ The 1.5% overshoot briefly parks the panel ~7px low, exposing a sliver of
+ scrim above it. That IS the spring, and it is what makes the shade read as
+ having mass. If it ever looks like a bug, the fix is to make the panel
+ taller than its clip — not to flatten the curve. */}
<div
- className="flex max-h-[85%] flex-col overflow-hidden rounded-b-[1.75rem] border-b border-border bg-card text-foreground shadow-2xl [animation:appOpen_var(--shell-dur)_var(--shell-ease)]"
+ className="flex max-h-[85%] flex-col overflow-hidden rounded-b-[1.75rem] border-b border-border bg-card text-foreground shadow-2xl animate-in slide-in-from-top duration-[var(--m3-dur-spatial-slow)] ease-[var(--m3-spatial)]"
onClick={(e) => e.stopPropagation()}
style={{ paddingTop: "var(--sai-top, 0px)" }}
>
@@ -68,8 +80,24 @@ export function AndroidNotifications({ open, onClose }: { open: boolean; onClose
</div>
) : (
<div className="flex flex-col gap-1.5">
- {items.map((n) => (
- <div key={n.id} className="flex items-start gap-3 rounded-2xl bg-muted/60 p-3.5">
+ {/* Staggered row entry is the M3 Expressive signature the shade was
+ missing — the panel arrived and its contents were simply already
+ there. Transform-only (no fade) to keep this file's one rule: a
+ single animation never carries both a spatial and an effects
+ property. The step is capped at 5 slots, otherwise a 40-item log
+ would still be dealing rows out two seconds after the pull. The
+ delay is expressed in terms of --m3-dur-effects so that it, like
+ every duration here, collapses under prefers-reduced-motion. */}
+ {items.map((n, i) => (
+ <div
+ key={n.id}
+ // fill-mode-backwards is not optional with a delay: without it the
+ // row paints at its FINAL position for the length of the delay,
+ // then snaps back to the start to animate. That flash is the whole
+ // reason delayed CSS animations get called broken.
+ className="flex items-start gap-3 rounded-2xl bg-muted/60 p-3.5 animate-in slide-in-from-top-2 fill-mode-backwards duration-[var(--m3-dur-spatial)] ease-[var(--m3-spatial)]"
+ style={{ animationDelay: `calc(var(--m3-dur-effects) * ${Math.min(i, 5) * 0.25})` }}
+ >
<span className={cn("mt-1 size-2 shrink-0 rounded-full", TONE_DOT[n.tone] ?? "bg-muted-foreground")} />
<div className="min-w-0 flex-1">
<div className="line-clamp-3 text-sm">{n.message}</div>
diff --git a/frontend/slices/appshell/components/shells/android/android-parts.tsx b/frontend/slices/appshell/components/shells/android/android-parts.tsx
index a041ba95..9688d61a 100644
--- a/frontend/slices/appshell/components/shells/android/android-parts.tsx
+++ b/frontend/slices/appshell/components/shells/android/android-parts.tsx
@@ -10,6 +10,7 @@ import { ChevronLeft, Search, X } from "lucide-react";
import { shellStore, closeWindow, closeAll } from "../../../lib/store";
import { useSwipeUpClose } from "../../../hooks/use-swipe-close";
import { AppIcon } from "../../app-icon";
+import { M3_PRESS } from "./android-motion";
import type { AppDescriptor, WindowState } from "../../../lib/types";
// 3-button gesture/nav row. 48px button row (--android-nav) + the device
@@ -29,7 +30,11 @@ export function NavBar({ inactive = false, onBack, onHome, onRecents }: { inacti
inert={inactive}
aria-hidden={inactive}
>
- <Button type="button" variant="ghost" onClick={onBack} aria-label="Back" className="h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center">
+ {/* The nav row had NO press feedback at all — on a touch device a tap that
+ moves nothing reads as a dropped input, which is why Back/Home/Recents
+ felt dead even after they were made visible. M3 spatial-FAST (k=800,
+ ζ=0.6): small element, and the 9.3% overshoot is the release. */}
+ <Button type="button" variant="ghost" onClick={onBack} aria-label="Back" className={`h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center active:scale-90 ${M3_PRESS}`}>
<ChevronLeft className="size-6" />
</Button>
{/* border-current, not border-foreground/70: these two are drawn as outlines,
@@ -37,10 +42,10 @@ export function NavBar({ inactive = false, onBack, onHome, onRecents }: { inacti
drift from it. (border-foreground/70 was also silently dead until the
@layer base fix in globals.css — every border-<color> utility was being
overridden by an unlayered `*` rule.) */}
- <Button type="button" variant="ghost" onClick={onHome} aria-label="Home" className="h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center">
+ <Button type="button" variant="ghost" onClick={onHome} aria-label="Home" className={`h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center active:scale-90 ${M3_PRESS}`}>
<span className="size-4 rounded-full border-2 border-current opacity-80" />
</Button>
- <Button type="button" variant="ghost" onClick={onRecents} aria-label="Recents" className="h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center">
+ <Button type="button" variant="ghost" onClick={onRecents} aria-label="Recents" className={`h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center active:scale-90 ${M3_PRESS}`}>
<span className="size-3.5 rounded-[3px] border-2 border-current opacity-80" />
</Button>
</div>
@@ -50,11 +55,18 @@ export function NavBar({ inactive = false, onBack, onHome, onRecents }: { inacti
export function Recents({ order, apps, onResume, onHome }: { order: string[]; apps: AppDescriptor[]; onResume: (id: string) => void; onHome: () => void }) {
const wins = order.map((id) => shellStore.getWindow(id)).filter(Boolean) as WindowState[];
return (
- <div className="absolute inset-0 z-[30] flex flex-col bg-background/90 backdrop-blur-xl" onClick={onHome}>
+ // Recents used to appear with NO animation whatsoever — a full-screen blurred
+ // scrim popping in one frame, which reads as a glitch rather than as a switcher
+ // arriving. Split by family, deliberately: the scrim is pure opacity, so it gets
+ // the critically-damped EFFECTS spring (k=1600, ζ=1, ~186ms) and cannot
+ // overshoot; the card deck moves, so it gets SPATIAL default (k=380, ζ=0.8,
+ // ~371ms) and is allowed to. One animation covering both would have had to pick
+ // one curve and be wrong for the other half.
+ <div className="absolute inset-0 z-[30] flex flex-col bg-background/90 backdrop-blur-xl animate-in fade-in duration-[var(--m3-dur-effects)] ease-[var(--m3-effects)]" onClick={onHome}>
{/* Empty deck must stay tappable-through: the inner container fills the
overlay (no Clear-all bar), so swallowing clicks would trap the user
with no exit (NavBar sits under the z-30 overlay). */}
- <div className="flex min-h-0 flex-1 items-center gap-3 overflow-x-auto p-5" onClick={(e) => { if (wins.length > 0) e.stopPropagation(); }}>
+ <div className="flex min-h-0 flex-1 items-center gap-3 overflow-x-auto p-5 animate-in slide-in-from-bottom-4 duration-[var(--m3-dur-spatial)] ease-[var(--m3-spatial)]" onClick={(e) => { if (wins.length > 0) e.stopPropagation(); }}>
{wins.length === 0 && <div className="m-auto text-sm text-muted-foreground">No recent apps · tap to go home</div>}
{wins.map((w) => (
<RecentCard key={w.id} win={w} app={apps.find((a) => a.id === w.app)} onResume={() => onResume(w.id)} />
@@ -130,8 +142,12 @@ function RecentCard({ win, app, onResume }: { win: WindowState; app?: AppDescrip
export function AppCell({ app, onClick }: { app: AppDescriptor; onClick: () => void }) {
return (
- <Button type="button" variant="ghost" onClick={onClick} className="h-auto p-0 font-normal hover:bg-transparent flex flex-col items-center gap-1.5">
- <span className="size-14"><AppIcon app={app} /></span>
+ // Press scales the ICON, not the whole cell: scaling the cell drags the label
+ // with it and the text goes blurry mid-transform on a low-DPI panel. `group`
+ // + `group-active:` is required because the :active is on the Button while the
+ // thing that moves is its child. Spatial-FAST — an icon is a small element.
+ <Button type="button" variant="ghost" onClick={onClick} className="group h-auto p-0 font-normal hover:bg-transparent flex flex-col items-center gap-1.5">
+ <span className={`size-14 group-active:scale-90 ${M3_PRESS}`}><AppIcon app={app} /></span>
{/* Colour is INHERITED, deliberately: this cell renders both on the home grid
(over the wallpaper, where the parent sets white + a shadow) and inside the
App Drawer (a light bg-background/95 sheet, where white would be invisible).
@@ -145,7 +161,15 @@ export function AppDrawer({ apps, onLaunch, onClose }: { apps: AppDescriptor[];
const [q, setQ] = useState("");
const list = useMemo(() => apps.filter((a) => a.title.toLowerCase().includes(q.toLowerCase())), [apps, q]);
return (
- <div className="absolute inset-0 z-[30] flex flex-col bg-background/95 backdrop-blur-xl [animation:appOpen_var(--shell-dur)_var(--shell-ease)]">
+ // Spatial SLOW (k=200, ζ=0.8, ~511ms): M3 picks the speed tier from the SIZE of
+ // the moving element, and this is a full-screen surface. Only the model changed
+ // here — a 300ms cubic-bezier for the sampled spring — because appOpen's 14px
+ // UPWARD travel was already the right direction: the drawer is opened from the
+ // "All apps" target at the BOTTOM of the home surface, so it should arrive
+ // rising from where the finger was. (That target is drawn as a grabber but is a
+ // plain tap — there is no swipe-up gesture in this shell, only usePullDown for
+ // the shade and useSwipeUpClose for Recents cards.)
+ <div className="absolute inset-0 z-[30] flex flex-col bg-background/95 backdrop-blur-xl [animation:appOpen_var(--m3-dur-spatial-slow)_var(--m3-spatial)]">
{/* Visually a thin pull handle, but a ≥36px hit area (same treatment as
the iOS home indicator) so it's actually closable by thumb. */}
<Button
diff --git a/frontend/slices/appshell/components/shells/android/android-shell.tsx b/frontend/slices/appshell/components/shells/android/android-shell.tsx
index eb93d0e3..4ecc328f 100644
--- a/frontend/slices/appshell/components/shells/android/android-shell.tsx
+++ b/frontend/slices/appshell/components/shells/android/android-shell.tsx
@@ -2,8 +2,11 @@
/* Android (Material-You) mobile shell — same store + apps as every other shell,
one fullscreen app at a time (mirrors MobileShell). Chrome: pull-DOWN on the home
surface → the REAL Control Center feature (controlCenter slot; the old fake Shade
- is gone), big clock + date on the wallpaper, search pill → Spotlight, swipe-up App
- Drawer, gesture nav (back / home / recents), and a Recents card deck. Transparent
+ is gone), big clock + date on the wallpaper, search pill → Spotlight, an App Drawer
+ opened by TAPPING the bottom "All apps" target — it is drawn as a grabber, but no
+ swipe-up gesture is wired here, and this line claiming one is what sent a later
+ motion comment on to justify an animation direction by a gesture that does not
+ exist — gesture nav (back / home / recents), and a Recents card deck. Transparent
root: the shared <Wallpaper> shows through, like every other shell. Bottom inset
system: the root sets `--android-nav` (NavBar row height); every surface that must
clear the bottom chrome pads with `calc(var(--android-nav) + var(--sai-bottom))`. */
@@ -21,6 +24,7 @@ import { useShellConfig } from "../../../registry/shell-config";
import { ShellUIProvider, type ShellUI } from "../../../registry/shell-ui";
import { Clock } from "../../clock";
import { AppCell, AppDrawer, NavBar, Recents } from "./android-parts";
+import { M3_PRESS } from "./android-motion";
import { ShellContextMenu, useShellContextMenu } from "../context-menu";
import type { AppDescriptor } from "../../../lib/types";
import { useInspectorInfo } from "../../../lib/inspector";
@@ -134,7 +138,7 @@ function AndroidShell() {
<button
type="button"
onClick={toggleSpotlight}
- className="mt-4 flex h-11 shrink-0 items-center gap-3 rounded-full border border-border bg-card/80 px-4 text-left shadow-sm backdrop-blur"
+ className={`mt-4 flex h-11 shrink-0 items-center gap-3 rounded-full border border-border bg-card/80 px-4 text-left shadow-sm backdrop-blur active:scale-[0.97] ${M3_PRESS}`}
>
<Search className="size-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">Search</span>
@@ -156,9 +160,13 @@ function AndroidShell() {
<AppCell key={a.id} app={a} onClick={() => launch(a)} />
))}
</div>
+ {/* 0.97, not the 0.90 the icon-only buttons get: this target carries an
+ 11px text label, and scaling type resamples it — blurry for the length
+ of the press on a low-DPI panel. Same reason AppCell scales its icon
+ and leaves its label alone, and the same 0.97 the search pill uses. */}
<Button type="button" variant="ghost"
onClick={() => setDrawer(true)}
- className="h-auto p-0 font-normal hover:bg-transparent mx-auto mb-1 mt-auto flex flex-col items-center gap-0.5 text-[11px] text-muted-foreground"
+ className={`h-auto p-0 font-normal hover:bg-transparent mx-auto mb-1 mt-auto flex flex-col items-center gap-0.5 text-[11px] text-muted-foreground active:scale-[0.97] ${M3_PRESS}`}
>
<span className="h-1 w-9 rounded-full bg-foreground/30" />
All apps
@@ -167,9 +175,16 @@ function AndroidShell() {
<NavBar inactive={showApp} onBack={goHome} onHome={goHome} onRecents={() => setRecents(true)} />
- {/* fullscreen app */}
+ {/* Fullscreen app. Open = M3 SPATIAL SLOW (k=200, ζ=0.8, ~511ms). The speed
+ tier is chosen by the SIZE of the thing that moves, not by how far it
+ moves: this is the largest surface in the shell, so "slow" is right even
+ though appOpen only travels 14px. Most of the perceived movement is over
+ by ~40% of that; the tail is the settle, which is exactly the part a
+ cubic-bezier cannot express. Transform-only on purpose — no opacity,
+ because pairing an effects fade with a spatial slide inside ONE animation
+ would force a single easing on both families. */}
{showApp && activeApp && top && (
- <div className="absolute inset-0 z-[20] flex flex-col bg-background [animation:appOpen_var(--shell-dur)_var(--shell-ease)] [transform-origin:center_bottom]">
+ <div className="absolute inset-0 z-[20] flex flex-col bg-background [animation:appOpen_var(--m3-dur-spatial-slow)_var(--m3-spatial)] [transform-origin:center_bottom]">
{/* M3 top app bar: flat surface (bg-card, hairline divider), leading
ArrowLeft up-affordance, Title Large regular weight — not a colored
brand header. The per-app color still reads on the icon + recents. */}
@@ -177,12 +192,16 @@ function AndroidShell() {
className="flex shrink-0 items-center gap-3 border-b border-border bg-card px-3 text-foreground"
style={{ height: "calc(3rem + var(--sai-top, 0px))", paddingTop: "var(--sai-top, 0px)" }}
>
- <Button type="button" variant="ghost" onClick={goHome} aria-label="Back" className="-ml-2 h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center"><ArrowLeft className="size-5" /></Button>
+ {/* Top-bar icon buttons get the same spatial-FAST press as the nav row:
+ small elements, so "fast" (k=800, ζ=0.6, ~322ms, 9.3% overshoot).
+ The overshoot is what makes a press feel like a physical button
+ releasing rather than a scale tween returning. */}
+ <Button type="button" variant="ghost" onClick={goHome} aria-label="Back" className={`-ml-2 h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center active:scale-90 ${M3_PRESS}`}><ArrowLeft className="size-5" /></Button>
<span className="flex-1 truncate text-[19px] font-normal">{activeApp.title}</span>
{appActions.length > 0 && (
<>
- <Button type="button" variant="ghost" aria-label="Ask Alfa" onClick={toggleInspector} className="h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center"><Sparkles className="size-5" /></Button>
- <Button type="button" variant="ghost" aria-label="Actions" onClick={() => setActionsOpen(true)} className="-mr-2 h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center"><MoreHorizontal className="size-5" /></Button>
+ <Button type="button" variant="ghost" aria-label="Ask Alfa" onClick={toggleInspector} className={`h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center active:scale-90 ${M3_PRESS}`}><Sparkles className="size-5" /></Button>
+ <Button type="button" variant="ghost" aria-label="Actions" onClick={() => setActionsOpen(true)} className={`-mr-2 h-auto p-0 font-normal hover:bg-transparent grid size-12 place-items-center active:scale-90 ${M3_PRESS}`}><MoreHorizontal className="size-5" /></Button>
</>
)}
</header>
diff --git a/frontend/slices/appshell/components/shells/windows/run-dialog.tsx b/frontend/slices/appshell/components/shells/windows/run-dialog.tsx
index 2bb9f572..562db65f 100644
--- a/frontend/slices/appshell/components/shells/windows/run-dialog.tsx
+++ b/frontend/slices/appshell/components/shells/windows/run-dialog.tsx
@@ -82,7 +82,13 @@ export function RunDialog({ onClose }: { onClose: () => void }) {
className="absolute bottom-[60px] left-3 z-[6001] w-[400px] max-w-[92vw] rounded-lg border border-border bg-card p-4 shadow-2xl"
>
<div className="mb-3 flex items-center gap-3">
- <span className="grid size-9 shrink-0 place-items-center rounded-md bg-primary/15 text-primary">
+ {/* 32px plate, was 36px. Win+R's header icon is the classic 32px dialog
+ icon at 100% scale, and 36px is not a size Windows draws at all — it
+ was just "a bit bigger than the 32px Start pins" by accident. The 20px
+ glyph stays: 20-in-32 is the ~62% inset Windows uses when it has to
+ plate a glyph, and shrinking it too would have made the plate read as
+ an empty chip. */}
+ <span className="grid size-8 shrink-0 place-items-center rounded-md bg-primary/15 text-primary">
<Terminal className="size-5" aria-hidden />
</span>
<div>
diff --git a/frontend/slices/appshell/components/shells/windows/snap-assist.tsx b/frontend/slices/appshell/components/shells/windows/snap-assist.tsx
index 31d4efd1..ea1577a7 100644
--- a/frontend/slices/appshell/components/shells/windows/snap-assist.tsx
+++ b/frontend/slices/appshell/components/shells/windows/snap-assist.tsx
@@ -89,9 +89,15 @@ function Candidate({ id, app, onPick }: { id: string; app: ReturnType<typeof use
className="h-auto p-0 font-normal hover:bg-transparent group flex flex-col overflow-hidden rounded-xl border border-border bg-background text-left shadow transition hover:-translate-y-0.5 hover:ring-2 hover:ring-primary"
>
<div className="h-6 w-full" style={{ background: a?.gradient ?? "var(--muted)" }} />
+ {/* 40px, and deliberately NOT snapped to the Fluent icon table: real Snap
+ Assist shows a live window thumbnail here, and this icon is standing in
+ for that thumbnail, not acting as an icon. Forcing it to 32px (the largest
+ table row) would shrink the card's subject below its own caption strip. */}
<div className="grid flex-1 place-items-center py-4">
{a && <span className="size-10 opacity-90"><AppIcon app={a} /></span>}
</div>
+ {/* The strip below IS a title bar, so 16px is the right row and already was.
+ Left alone on purpose — do not "align" it with the 40px above. */}
<div className="flex items-center gap-1.5 border-t border-border px-2 py-1.5">
{a && <span className="size-4 shrink-0"><AppIcon app={a} /></span>}
<span className="min-w-0 flex-1 truncate text-xs font-medium">{win.title}</span>
diff --git a/frontend/slices/appshell/components/shells/windows/start-menu.tsx b/frontend/slices/appshell/components/shells/windows/start-menu.tsx
index 410851a3..41730fe1 100644
--- a/frontend/slices/appshell/components/shells/windows/start-menu.tsx
+++ b/frontend/slices/appshell/components/shells/windows/start-menu.tsx
@@ -94,7 +94,11 @@ export function StartMenu({ onClose }: { onClose: () => void }) {
onClick={() => launch(app)}
className={`${NEUTRAL} flex w-full items-center justify-start gap-3 rounded-md px-2 py-1.5 hover:bg-muted`}
>
- <span className="size-7">
+ {/* 24px — the "Start all apps / search results" row of
+ learn.microsoft.com/windows/apps/design/iconography/app-icon-construction
+ at 100% scale. Was 28px (size-7), a size that appears nowhere in
+ that table, so the list sat visibly heavier than a real one. */}
+ <span className="size-6">
<AppIcon app={app} />
</span>
<span className="truncate text-sm">{app.title}</span>
@@ -111,7 +115,13 @@ export function StartMenu({ onClose }: { onClose: () => void }) {
onClick={() => launch(app)}
className={`${NEUTRAL} flex flex-col items-center gap-1.5 rounded-lg p-2 hover:bg-muted`}
>
- <span className="size-10">
+ {/* This ONE grid renders two different rows of the Fluent table:
+ Start pins (32px) and, when `searching`, search results — which
+ the table puts at 24px alongside All apps. Was a flat 40px
+ (size-10), the taskbar BUTTON size and no icon size at all, so
+ pins overflowed the tile and every search hit rendered as if it
+ were a pinned tile. */}
+ <span className={searching ? "size-6" : "size-8"}>
<AppIcon app={app} />
</span>
<span className="w-full truncate text-center text-[11px]">{app.title}</span>
@@ -138,7 +148,10 @@ export function StartMenu({ onClose }: { onClose: () => void }) {
onClick={() => launch(app)}
className={`${NEUTRAL} flex items-center justify-start gap-2 rounded-md px-2 py-1.5 hover:bg-muted`}
>
- <span className="size-7">
+ {/* Recommended is a list row, not a pin, so it takes the same
+ 24px as All apps. Was 28px (size-7) — off-table, and it made
+ a recommendation look more important than a pinned app. */}
+ <span className="size-6">
<AppIcon app={app} />
</span>
<span className="truncate text-xs">{app.title}</span>
diff --git a/frontend/slices/appshell/components/shells/windows/taskbar.tsx b/frontend/slices/appshell/components/shells/windows/taskbar.tsx
index bfb45fb8..1b643d92 100644
--- a/frontend/slices/appshell/components/shells/windows/taskbar.tsx
+++ b/frontend/slices/appshell/components/shells/windows/taskbar.tsx
@@ -1,7 +1,14 @@
"use client";
/* Windows 11 taskbar — centered Start + search + per-window buttons, system
tray clock on the right. Buttons drive the shared store (focus/minimize/
- restore), mirroring real taskbar click behavior. */
+ restore), mirroring real taskbar click behavior.
+ METRICS (learn.microsoft.com/windows/apps/design/iconography/app-icon-construction,
+ 100% scale): 48px bar (h-12), 40px buttons (size-10), 24px icons on that row
+ (size-6). Every one was a size small — 36px buttons, 20px app icons, a 14px Start
+ mark, a 16px Task View glyph — so the bar rendered ~90% beside a real Windows 11
+ one. The search box is the exception: its magnifier went 14px → 16px (the system-
+ glyph row), NOT 24px, because it is a LABELLED box and a 24px magnifier beside a
+ 12px label reads as a button whose caption fell off. */
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { useEffect, useMemo, useState } from "react";
@@ -49,18 +56,18 @@ export function Taskbar({ onTaskView }: { onTaskView?: () => void }) {
<StartButton open={startOpen} onClick={() => setStartOpen((o) => !o)} onTaskView={onTaskView} />
<Button type="button" variant="ghost"
onClick={toggleSpotlight}
- className="h-auto p-0 font-normal hover:bg-transparent flex h-9 items-center gap-2 rounded-md border border-border bg-background/60 px-3 text-xs text-muted-foreground hover:bg-muted"
+ className="h-auto p-0 font-normal hover:bg-transparent flex h-10 items-center gap-2 rounded-md border border-border bg-background/60 px-3 text-xs text-muted-foreground hover:bg-muted"
>
- <Search className="size-3.5" /> Search
+ <Search className="size-4" /> Search
</Button>
{onTaskView && (
<Button type="button" variant="ghost"
onClick={onTaskView}
title="Task View"
aria-label="Task View"
- className="h-auto p-0 font-normal hover:bg-transparent grid size-9 place-items-center rounded-md hover:bg-muted"
+ className="h-auto p-0 font-normal hover:bg-transparent grid size-10 place-items-center rounded-md hover:bg-muted"
>
- <LayoutGrid className="size-4" />
+ <LayoutGrid className="size-6" />
</Button>
)}
{pinnedApps.length > 0 && <span className="mx-1 h-6 w-px bg-border" />}
@@ -72,7 +79,7 @@ export function Taskbar({ onTaskView }: { onTaskView?: () => void }) {
))}
</div>
<div className="ml-auto flex items-center gap-0.5">
- <ControlCenterDesktop />
+ <ControlCenterDesktop size={40} />
<Clock />
</div>
</div>
@@ -102,11 +109,13 @@ function StartButton({ open, onClick, onTaskView }: { open: boolean; onClick: ()
onClick={onClick}
onContextMenu={menu.open}
aria-label="Start"
- className={cn(`h-auto p-0 font-normal hover:bg-transparent grid size-9 place-items-center rounded-md hover:bg-muted ${open ? "bg-muted" : ""}`)}
+ className={cn(`h-auto p-0 font-normal hover:bg-transparent grid size-10 place-items-center rounded-md hover:bg-muted ${open ? "bg-muted" : ""}`)}
>
+ {/* 11px tiles + 2px gutter = a 24px mark. Tiles were 6px (size-1.5) → a 14px
+ mark, so Start read as a speck between two 24px neighbours. */}
<span className="grid grid-cols-2 gap-[2px]">
{[0, 1, 2, 3].map((i) => (
- <span key={i} className="size-1.5 rounded-[1px] bg-primary" />
+ <span key={i} className="size-[11px] rounded-[1px] bg-primary" />
))}
</span>
</Button>
@@ -123,9 +132,9 @@ function PinnedApp({ app, running }: { app: AppDescriptor; running: boolean }) {
onClick={() => openWindow(app.id, app.title, app.defaultSize, undefined, { multi: app.multi })}
title={app.title}
aria-label={app.title}
- className={cn(`h-auto p-0 font-normal hover:bg-transparent relative grid size-9 place-items-center rounded-md hover:bg-muted ${running ? "bg-muted" : ""}`)}
+ className={cn(`h-auto p-0 font-normal hover:bg-transparent relative grid size-10 place-items-center rounded-md hover:bg-muted ${running ? "bg-muted" : ""}`)}
>
- <span className="size-5">
+ <span className="size-6">
<AppIcon app={app} />
</span>
<span
@@ -155,10 +164,10 @@ function TaskButton({ id }: { id: string }) {
onClick={onClick}
onContextMenu={menu.open}
title={win.title}
- className={cn(`h-auto p-0 font-normal hover:bg-transparent relative flex h-9 items-center gap-2 rounded-md px-2 hover:bg-muted ${active ? "bg-muted" : ""}`)}
+ className={cn(`h-auto p-0 font-normal hover:bg-transparent relative flex h-10 items-center gap-2 rounded-md px-2 hover:bg-muted ${active ? "bg-muted" : ""}`)}
>
{app && (
- <span className="size-5">
+ <span className="size-6">
<AppIcon app={app} />
</span>
)}
@@ -193,6 +202,10 @@ function TaskButton({ id }: { id: string }) {
}
// Clock doubles as the Notification Center toggle, like the real Win11 tray.
+// h-10 like every other button in this bar: the tray sits on the same 40px row as
+// Start and the task buttons, and at h-9 its hover pill was 4px shorter than its
+// neighbours' — visible on hover as a step in the row. (ControlCenterDesktop, the
+// other tray button, is still a 28px box and lives in another slice.)
function Clock() {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
@@ -203,7 +216,7 @@ function Clock() {
<Button type="button" variant="ghost"
onClick={toggleNotificationCenter}
aria-label="Notifications"
- className="h-auto p-0 font-normal hover:bg-transparent flex h-9 min-w-9 flex-col items-end justify-center gap-0 rounded-md px-2 text-[11px] leading-tight text-muted-foreground hover:bg-muted"
+ className="h-auto p-0 font-normal hover:bg-transparent flex h-10 min-w-10 flex-col items-end justify-center gap-0 rounded-md px-2 text-[11px] leading-tight text-muted-foreground hover:bg-muted"
>
<span>{now.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</span>
<span>{now.toLocaleDateString([], { day: "2-digit", month: "2-digit", year: "numeric" })}</span>
diff --git a/frontend/slices/appshell/components/win-caption.tsx b/frontend/slices/appshell/components/win-caption.tsx
index ed0ad796..2b0fc698 100644
--- a/frontend/slices/appshell/components/win-caption.tsx
+++ b/frontend/slices/appshell/components/win-caption.tsx
@@ -7,6 +7,11 @@ import { SnapLayoutsMenu } from "./snap-layouts";
import type { WinId } from "../lib/types";
// Windows 11 caption buttons (minimize / maximize-restore / close), right-aligned.
+// No app icon here, by design: window.tsx's Windows title bar is title-text + these
+// three buttons, and Win11's own title bars only show a 16px app icon when the app
+// asks for one. Nothing to resize — the 10px SVGs below are Segoe Fluent CAPTION
+// glyphs, which are 10px in a 46x32 button and have no relation to the 16px
+// title-bar APP-icon row in the Fluent icon table. Don't grow them to 16px.
export function WinCaption({
id, maximized, onMinimize, onMaximize, onClose,
}: {
diff --git a/frontend/slices/appshell/components/window.tsx b/frontend/slices/appshell/components/window.tsx
index 19b70a28..31e40583 100644
--- a/frontend/slices/appshell/components/window.tsx
+++ b/frontend/slices/appshell/components/window.tsx
@@ -97,7 +97,12 @@ export const Window = memo(function Window({ id, variant = "macos" }: { id: WinI
>
{isWin ? (
<div
- className="flex h-[34px] shrink-0 cursor-grab items-center border-b border-border bg-[var(--mica-win,var(--card))] font-[family-name:var(--shell-font)] active:cursor-grabbing"
+ // 32px, not 34: Windows 11's title bar is 32px at 100% scale and its caption
+ // buttons are 46x32. win-caption.tsx already sets w-[46px] but inherits the
+ // height from here, so a 34px row rendered them 46x34 — two pixels tall
+ // everywhere, which is exactly the kind of thing that reads as "not quite
+ // Windows" without being nameable.
+ className="flex h-8 shrink-0 cursor-grab items-center border-b border-border bg-[var(--mica-win,var(--card))] font-[family-name:var(--shell-font)] active:cursor-grabbing"
onPointerDown={onBarDown}
onDoubleClick={() => toggleMaximize(id)}
onContextMenu={ctx.open}
diff --git a/frontend/slices/appshell/features/control-center/components/control-center-desktop.tsx b/frontend/slices/appshell/features/control-center/components/control-center-desktop.tsx
index 0e1633fc..f2ca5509 100644
--- a/frontend/slices/appshell/features/control-center/components/control-center-desktop.tsx
+++ b/frontend/slices/appshell/features/control-center/components/control-center-desktop.tsx
@@ -10,12 +10,16 @@ import { ControlCenterTiles } from "./control-center-tiles";
// real toggles as the mobile CC. Mounted via the `menuBarStatus` slot, so it lives
// only in the macOS menu bar (the only surface that renders that region). No
// fabricated-hardware sliders — VPS essence, same as the mobile CC.
-export function ControlCenterDesktop() {
+/** @param size box size in px. 28 suits the macOS menu bar (this component's
+ * original and still default home). The Windows taskbar row is 40px per the
+ * Fluent table, and a 28px box there left one visibly short item next to the
+ * clock — so the taskbar passes 40 rather than every surface being bumped. */
+export function ControlCenterDesktop({ size = 28 }: { size?: number } = {}) {
const [open, setOpen] = useState(false);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
- <Button type="button" variant="ghost" size="icon" aria-label="Control Center" className="size-7 rounded-md">
+ <Button type="button" variant="ghost" size="icon" aria-label="Control Center" className="rounded-md" style={{ width: size, height: size }}>
<SlidersHorizontal className="size-4" />
</Button>
</PopoverTrigger>
diff --git a/frontend/slices/appshell/index.ts b/frontend/slices/appshell/index.ts
index a7d7db27..dd9066bf 100644
--- a/frontend/slices/appshell/index.ts
+++ b/frontend/slices/appshell/index.ts
@@ -86,6 +86,7 @@ export * from "./lib/lock";
export * from "./lib/profiles";
export * from "./lib/shortcuts";
export * from "./lib/focus-mode";
+export * from "./lib/local-state";
export {
useFocusedHotkey,
inEditable,
diff --git a/frontend/slices/appshell/lib/local-state.test.ts b/frontend/slices/appshell/lib/local-state.test.ts
new file mode 100644
index 00000000..18df3dc0
--- /dev/null
+++ b/frontend/slices/appshell/lib/local-state.test.ts
@@ -0,0 +1,195 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ LOCAL_STATE_KIND,
+ LOCAL_STATE_SCHEMA,
+ collectLocalState,
+ localStateFilename,
+ ownsKey,
+ parseLocalState,
+ restoreLocalState,
+ type LocalStateBlob,
+} from "./local-state";
+
+// vitest runs this suite under `environment: "node"`, which has no Web Storage.
+// A Map-backed stand-in is enough: the module only uses length/key/getItem/
+// setItem/removeItem. `key(i)` re-materialises the key list on every call, which
+// is what reproduces Storage's live-collection semantics — delete during an
+// indexed walk and the tail shifts down under you. The multi-key REPLACE test
+// below depends on that fidelity; a snapshot-once fake would pass either way.
+function installStorage(seed: Record<string, string> = {}): Map<string, string> {
+ const map = new Map(Object.entries(seed));
+ const fake: Storage = {
+ get length() {
+ return map.size;
+ },
+ key: (i: number) => [...map.keys()][i] ?? null,
+ getItem: (k: string) => map.get(k) ?? null,
+ setItem: (k: string, v: string) => void map.set(k, v),
+ removeItem: (k: string) => void map.delete(k),
+ clear: () => map.clear(),
+ };
+ Object.defineProperty(globalThis, "localStorage", { value: fake, configurable: true, writable: true });
+ return map;
+}
+
+const SEED = {
+ "alfa.automations": '[{"id":"nightly"}]',
+ "alfa.agents": '[{"id":"ops"}]',
+ "mso:layout": '{"windows":[]}',
+ "mso:apps": '["files"]',
+ "sv:dock": '{"size":"md"}',
+ "reel.draft": '{"clips":[]}',
+ "mso.device.id": "deadbeefdeadbeefdeadbeefdeadbeef", // denied: second auth factor
+ "mso:demo-fs": "{}", // denied: regenerable mock data
+ "ext-analytics-consent": "1", // not ours
+};
+
+describe("ownsKey", () => {
+ it("takes the namespaced prefixes and the legacy allowlist, minus the deny list", () => {
+ expect(ownsKey("mso:layout")).toBe(true);
+ expect(ownsKey("sv:dock")).toBe(true);
+ expect(ownsKey("alfa.skills")).toBe(true);
+ expect(ownsKey("reel.settings")).toBe(true);
+ expect(ownsKey("mso.device.id")).toBe(false);
+ expect(ownsKey("mso:demo-fs")).toBe(false);
+ expect(ownsKey("ext-analytics-consent")).toBe(false);
+ });
+});
+
+describe("round trip", () => {
+ beforeEach(() => installStorage(SEED));
+
+ it("exports every owned key and no other, then restores them verbatim", () => {
+ const blob = collectLocalState("1.2.3");
+ expect(blob.kind).toBe(LOCAL_STATE_KIND);
+ expect(blob.schema).toBe(LOCAL_STATE_SCHEMA);
+ expect(blob.appVersion).toBe("1.2.3");
+ expect(Object.keys(blob.keys).sort()).toEqual([
+ "alfa.agents",
+ "alfa.automations",
+ "mso:apps",
+ "mso:layout",
+ "reel.draft",
+ "sv:dock",
+ ]);
+
+ const map = installStorage({ "mso.device.id": "cafebabecafebabecafebabecafebabe" });
+ const { restored, skipped } = restoreLocalState(blob);
+ expect(skipped).toEqual([]);
+ expect(restored.sort()).toEqual(Object.keys(blob.keys).sort());
+ expect(map.get("alfa.automations")).toBe('[{"id":"nightly"}]');
+ expect(map.get("sv:dock")).toBe('{"size":"md"}');
+ // The blob never carried it, so the browser keeps the id it already had —
+ // an import must not re-approve the device it is imported into.
+ expect(map.get("mso.device.id")).toBe("cafebabecafebabecafebabecafebabe");
+ });
+
+ it("REPLACES: an owned key added after the export is gone after the restore", () => {
+ const blob = collectLocalState("1.2.3");
+ const map = installStorage({ ...SEED, "alfa.skills": '[{"id":"added-later"}]' });
+ restoreLocalState(blob);
+ expect(map.has("alfa.skills")).toBe(false);
+ // Foreign and denied keys are outside the replace, so they survive.
+ expect(map.get("ext-analytics-consent")).toBe("1");
+ expect(map.get("mso:demo-fs")).toBe("{}");
+ });
+
+ // Three consecutive stale keys, not one: an indexed walk that deletes as it
+ // goes removes 1st and 3rd and SKIPS the 2nd, so a single-key case passes even
+ // when the iteration is wrong. This is the case that pins the array snapshot in
+ // ownedKeys — drop it and a restore silently leaves a third of the stale
+ // Playbooks behind, which reads as "the backup was incomplete".
+ it("REPLACES every stale key, not every other one", () => {
+ const blob = collectLocalState("1.2.3");
+ const map = installStorage({
+ ...SEED,
+ "alfa.skills": "[]",
+ "mso:desktop-icons": "{}",
+ "sv:wallpaper": '"a.png"',
+ });
+ restoreLocalState(blob);
+ expect(map.has("alfa.skills")).toBe(false);
+ expect(map.has("mso:desktop-icons")).toBe(false);
+ expect(map.has("sv:wallpaper")).toBe(false);
+ });
+
+ it("survives a parse of its own serialized output", () => {
+ const text = JSON.stringify(collectLocalState("1.2.3"));
+ const res = parseLocalState(text);
+ expect(res.ok).toBe(true);
+ if (res.ok) expect(res.unknown).toEqual([]);
+ });
+});
+
+describe("parseLocalState rejection", () => {
+ it("refuses a schema it does not understand instead of half-restoring it", () => {
+ const future = JSON.stringify({ kind: LOCAL_STATE_KIND, schema: LOCAL_STATE_SCHEMA + 1, keys: { "mso:layout": "{}" } });
+ const res = parseLocalState(future);
+ expect(res.ok).toBe(false);
+ if (!res.ok) expect(res.error).toMatch(/schema 2/);
+ });
+
+ it("refuses non-JSON, a non-object, a foreign file and a non-string value", () => {
+ for (const bad of ["not json", "[]", "null", JSON.stringify({ kind: "something.else", schema: 1, keys: {} })]) {
+ expect(parseLocalState(bad).ok).toBe(false);
+ }
+ // Carries valid metadata on purpose: the appVersion/exportedAt guard runs
+ // first, so without these the case would pass on the WRONG branch and stop
+ // testing the non-string value it is named for.
+ const numeric = JSON.stringify({
+ kind: LOCAL_STATE_KIND,
+ schema: LOCAL_STATE_SCHEMA,
+ appVersion: "1.2.3",
+ exportedAt: new Date().toISOString(),
+ keys: { "mso:layout": 42 },
+ });
+ const res = parseLocalState(numeric);
+ expect(res.ok).toBe(false);
+ if (!res.ok) expect(res.error).toMatch(/non-string/);
+ });
+
+ it("refuses a file whose version or timestamp is not a string", () => {
+ // The confirm dialog interpolates both into the sentence the user approves.
+ const bad = JSON.stringify({
+ kind: LOCAL_STATE_KIND,
+ schema: LOCAL_STATE_SCHEMA,
+ appVersion: { major: 1 },
+ exportedAt: new Date().toISOString(),
+ keys: { "mso:layout": "{}" },
+ });
+ expect(parseLocalState(bad).ok).toBe(false);
+ });
+});
+
+describe("unrecognised keys", () => {
+ const blob: LocalStateBlob = {
+ kind: LOCAL_STATE_KIND,
+ schema: LOCAL_STATE_SCHEMA,
+ appVersion: "9.9.9",
+ exportedAt: new Date().toISOString(),
+ keys: { "mso:layout": '{"windows":[]}', "future.feature": "x", "mso.device.id": "beef" },
+ };
+
+ it("reports them at parse time rather than dropping them behind the user's back", () => {
+ const res = parseLocalState(JSON.stringify(blob));
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect(res.known).toEqual(["mso:layout"]);
+ expect(res.unknown.sort()).toEqual(["future.feature", "mso.device.id"]);
+ });
+
+ it("does not write them, and names them in `skipped`", () => {
+ const map = installStorage();
+ const { restored, skipped } = restoreLocalState(blob);
+ expect(restored).toEqual(["mso:layout"]);
+ expect(skipped.sort()).toEqual(["future.feature", "mso.device.id"]);
+ expect(map.has("future.feature")).toBe(false);
+ expect(map.has("mso.device.id")).toBe(false);
+ });
+});
+
+describe("localStateFilename", () => {
+ it("date-stamps so two exports don't collapse onto one download", () => {
+ expect(localStateFilename(new Date("2026-08-11T10:00:00Z"))).toBe("mso-backup-2026-08-11.json");
+ });
+});
diff --git a/frontend/slices/appshell/lib/local-state.ts b/frontend/slices/appshell/lib/local-state.ts
new file mode 100644
index 00000000..1fee5ec2
--- /dev/null
+++ b/frontend/slices/appshell/lib/local-state.ts
@@ -0,0 +1,200 @@
+"use client";
+
+// Export / import of everything the shell keeps in localStorage — Playbooks,
+// Agents, Automations, the window layout, the app registry, the desktop-icon
+// arrangement, widget contents, per-shell wallpapers.
+//
+// CONTRACT.md documents the storage CHOICE; nobody documented the CONSEQUENCE.
+// There is no server copy of any of it, so "Clear browsing data", a new laptop
+// or a profile reset destroys it permanently with no undo. This file is the undo.
+
+/**
+ * WHICH KEYS ARE OURS — a prefix rule plus a short explicit allowlist.
+ *
+ * A flat hardcoded list of all ~30 keys is the obvious implementation and a trap:
+ * the next feature that calls `localStorage.setItem` silently falls out of every
+ * backup taken afterwards and NOTHING fails — the export succeeds, the user gets
+ * a .json, and the loss surfaces only during the restore that was meant to save
+ * them. A prefix rule catches new keys by default, so the failure mode flips to
+ * "a stray key gets backed up": costs bytes, nothing else.
+ *
+ * The key names are the ONE brand-specific thing in this brand-free slice — the
+ * file cannot be correct without knowing them — so they are a default-valued
+ * `rule` parameter, not a hardcoded constant, and a non-mso consumer passes its own.
+ *
+ * `mso:` / `mso.` are the current namespaces; `sv:` is the pre-rename one and is
+ * STILL WRITTEN today (sv:dock, sv:shell, sv:profiles…) — renaming those keys
+ * would have reset every existing user's dock and shell choice, so they stayed.
+ * `alfa.` is the assistant store (skills / agents / automations).
+ *
+ * `extra` is for keys that predate any namespace and cannot be reached by a
+ * prefix without also matching unrelated site data. Keep it short; a new key
+ * should take a prefix instead of landing here.
+ */
+export type KeyRule = {
+ prefixes: readonly string[];
+ extra: readonly string[];
+ deny: readonly string[];
+};
+
+export const MSO_LOCAL_STATE: KeyRule = {
+ prefixes: ["mso:", "mso.", "sv:", "alfa."],
+ extra: [
+ "appshell:layout", // the framework's fallback layout key (used when a manifest omits persistKey)
+ "image-editor:autosave:v1",
+ "studio.save.v1",
+ "reel.draft",
+ "reel.settings",
+ "reel.layout",
+ ],
+ deny: [
+ // The SECOND AUTH FACTOR (auth/lib/device.ts): password + an approved device
+ // id IS the login. Backup files get emailed, synced to Drive, pasted into a
+ // chat — carrying an approved id turns "the file leaked" into "the attacker
+ // skipped device approval". The id is mirrored into a cookie anyway, so a
+ // cache-only wipe already restores it; there is nothing here worth the risk.
+ "mso.device.id",
+ // Demo-mode's mock filesystem: regenerated from mock-data on demand, worth
+ // nothing, and megabytes of it. Backing it up only risks the quota.
+ "mso:demo-fs",
+ ],
+};
+
+/** Bump when the BLOB SHAPE changes. Not the app version — a rebuild must not
+ * invalidate a backup taken by the previous build. */
+export const LOCAL_STATE_SCHEMA = 1;
+
+/** Discriminator so importing an unrelated .json fails with "not an MSO backup"
+ * rather than an unhelpful shape error halfway through the restore. */
+export const LOCAL_STATE_KIND = "mso.local-state";
+
+export type LocalStateBlob = {
+ kind: typeof LOCAL_STATE_KIND;
+ schema: number;
+ /** App version at export time — informational; restore never gates on it. */
+ appVersion: string;
+ exportedAt: string;
+ keys: Record<string, string>;
+};
+
+export type ParseResult =
+ | { ok: true; blob: LocalStateBlob; known: string[]; unknown: string[] }
+ | { ok: false; error: string };
+
+/** localStorage, or null when it is absent OR ACCESS ITSELF THROWS. Same guard as
+ * assistant/lib/store-persist.ts, for the same reason: with site data blocked
+ * ("Block all cookies", a sandboxed iframe, dom.storage.enabled=false) the
+ * property GETTER throws SecurityError, so a bare `typeof localStorage` throws
+ * before it can return anything. */
+function storage(): Storage | null {
+ try {
+ return typeof localStorage === "undefined" ? null : localStorage;
+ } catch {
+ return null;
+ }
+}
+
+export function ownsKey(key: string, rule: KeyRule = MSO_LOCAL_STATE): boolean {
+ if (rule.deny.includes(key)) return false;
+ return rule.prefixes.some((p) => key.startsWith(p)) || rule.extra.includes(key);
+}
+
+/** Every owned key currently in storage. Snapshotted into an array BEFORE any
+ * write — `Storage.key(i)` indexes a live collection, so removing while
+ * iterating skips entries. */
+function ownedKeys(ls: Storage, rule: KeyRule): string[] {
+ const out: string[] = [];
+ for (let i = 0; i < ls.length; i++) {
+ const k = ls.key(i);
+ if (k && ownsKey(k, rule)) out.push(k);
+ }
+ return out;
+}
+
+export function collectLocalState(appVersion: string, rule: KeyRule = MSO_LOCAL_STATE): LocalStateBlob {
+ const ls = storage();
+ const keys: Record<string, string> = {};
+ if (ls) {
+ for (const k of ownedKeys(ls, rule)) {
+ const v = ls.getItem(k);
+ if (v !== null) keys[k] = v;
+ }
+ }
+ return {
+ kind: LOCAL_STATE_KIND,
+ schema: LOCAL_STATE_SCHEMA,
+ appVersion,
+ exportedAt: new Date().toISOString(),
+ keys,
+ };
+}
+
+/** Validate an uploaded file. Rejects anything this build cannot faithfully
+ * restore — a newer schema is a REJECT, not a best-effort merge, because a
+ * half-understood restore silently corrupts state that has no other copy. */
+export function parseLocalState(text: string, rule: KeyRule = MSO_LOCAL_STATE): ParseResult {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch {
+ return { ok: false, error: "Not valid JSON." };
+ }
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, error: "Not an MSO backup file." };
+ const b = raw as Partial<LocalStateBlob>;
+ if (b.kind !== LOCAL_STATE_KIND) return { ok: false, error: "Not an MSO backup file." };
+ if (b.schema !== LOCAL_STATE_SCHEMA) {
+ return {
+ ok: false,
+ error: `Backup schema ${String(b.schema)} — this build only understands ${LOCAL_STATE_SCHEMA}. Update MSO, then import again.`,
+ };
+ }
+ // Both are rendered verbatim in the confirm dialog; unchecked, a hand-edited file makes it read "MSO [object Object] … Invalid Date".
+ if (typeof b.appVersion !== "string" || typeof b.exportedAt !== "string") return { ok: false, error: "Backup is missing its version or timestamp." };
+ if (!b.keys || typeof b.keys !== "object" || Array.isArray(b.keys)) return { ok: false, error: "Backup has no keys." };
+ const entries = Object.entries(b.keys as Record<string, unknown>);
+ if (entries.some(([, v]) => typeof v !== "string")) return { ok: false, error: "Backup holds a non-string value." };
+ const known = entries.map(([k]) => k).filter((k) => ownsKey(k, rule));
+ const unknown = entries.map(([k]) => k).filter((k) => !ownsKey(k, rule));
+ return { ok: true, blob: b as LocalStateBlob, known, unknown };
+}
+
+/**
+ * REPLACE, not merge: owned keys absent from the blob are deleted first. A merge
+ * would leave the Playbook you deleted last week alive next to the restored set,
+ * which is not what "restore my backup" means.
+ *
+ * Keys the rule does not recognise are NOT written — a backup file is arbitrary
+ * user-supplied JSON, and writing unbounded keys into storage is a quota bomb —
+ * but they ARE returned in `skipped` so the caller can name them. Dropping them
+ * in silence is the bug this return type exists to prevent.
+ */
+export function restoreLocalState(
+ blob: LocalStateBlob,
+ rule: KeyRule = MSO_LOCAL_STATE,
+): { restored: string[]; skipped: string[] } {
+ const ls = storage();
+ const restored: string[] = [];
+ const skipped = Object.keys(blob.keys).filter((k) => !ownsKey(k, rule));
+ if (!ls) return { restored, skipped };
+ for (const k of ownedKeys(ls, rule)) {
+ if (!(k in blob.keys)) ls.removeItem(k);
+ }
+ for (const [k, v] of Object.entries(blob.keys)) {
+ if (!ownsKey(k, rule)) continue;
+ try {
+ ls.setItem(k, v);
+ restored.push(k);
+ } catch {
+ // Quota: a partial restore beats an aborted one — the caller reports the
+ // count, and the keys that did land are still better than nothing.
+ }
+ }
+ return { restored, skipped };
+}
+
+/** `mso-backup-2026-08-11.json`. Date-stamped (UTC) because a Downloads folder of
+ * `mso-backup.json`, `mso-backup(1).json`, `mso-backup(2).json` is unrestorable —
+ * you cannot tell which one predates the mistake you are undoing. */
+export function localStateFilename(now = new Date()): string {
+ return `mso-backup-${now.toISOString().slice(0, 10)}.json`;
+}
diff --git a/frontend/slices/assistant/CONTRACT.md b/frontend/slices/assistant/CONTRACT.md
index 27f7c5d6..e0c86b95 100644
--- a/frontend/slices/assistant/CONTRACT.md
+++ b/frontend/slices/assistant/CONTRACT.md
@@ -9,6 +9,14 @@ unrelated things both called "skill".
---
+> **Where this lives, and how to not lose it.** Agents, Skills and Automations are
+> per-browser localStorage (`alfa.*`), so clearing site data destroys them and there
+> is no server copy. **Settings → Backup** exports every mso-owned key as one JSON
+> file and imports it back. The `alfa.` prefix is matched by rule, so a new
+> `alfa.something` key is covered automatically; a key outside every prefix has to be
+> added to `MSO_LOCAL_STATE.extra` in `appshell/lib/local-state.ts` or it silently
+> will not be in the backup.
+
## Tool
**An operation the model can actually invoke.** If it is not here, *Alfa* cannot do
diff --git a/frontend/slices/assistant/components/chat-panel.tsx b/frontend/slices/assistant/components/chat-panel.tsx
index ebf32ffb..a45fddce 100644
--- a/frontend/slices/assistant/components/chat-panel.tsx
+++ b/frontend/slices/assistant/components/chat-panel.tsx
@@ -11,6 +11,7 @@ import {
} from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
+import { errText } from "./error-text";
import {
registerAlfaRunner,
updateAlfa,
@@ -39,16 +40,6 @@ import { useAlfaRunner } from "./use-alfa-runner";
const SUGGESTED = ["Show system stats", "List ~/projects", "Create notes.txt in ~/projects with a TODO"];
-function errText(err: unknown): string {
- const code = err instanceof Error ? err.message : "";
- if (code.startsWith("no_api_key")) {
- const provider = code.split(":")[1] || "selected provider";
- return `No API key set for ${provider}. Add it in Settings → AI, then save and test that provider.`;
- }
- if (code === "unauthorized") return "Session expired — sign in again.";
- return "Couldn't reach the assistant. Try again.";
-}
-
let seq = 0;
const nextId = () => `m${Date.now()}-${seq++}`;
diff --git a/frontend/slices/assistant/components/error-text.ts b/frontend/slices/assistant/components/error-text.ts
new file mode 100644
index 00000000..651cbf1c
--- /dev/null
+++ b/frontend/slices/assistant/components/error-text.ts
@@ -0,0 +1,29 @@
+// Turns an assistant failure into something the user can ACT on.
+//
+// Lifted out of chat-panel.tsx, which was at 218 effective lines against a 220
+// warn ceiling — no room for the next branch, and this is the part that grows.
+// Every branch here exists because the generic fallback sent someone to do the
+// one thing that could not work.
+export function errText(err: unknown): string {
+ const code = err instanceof Error ? err.message : "";
+ if (code.startsWith("no_api_key")) {
+ const provider = code.split(":")[1] || "selected provider";
+ return `No API key set for ${provider}. Add it in Settings → AI, then save and test that provider.`;
+ }
+ if (code === "unauthorized") return "Session expired — sign in again.";
+ // OUR OWN tripwire, not the provider's: /api/assistant allows 30 POSTs per minute
+ // per device and one send spends up to 8 of them (runToolAgent's turn cap), so a
+ // tool-heavy answer burns a quarter of the budget. Calling that "couldn't reach
+ // the assistant" sent people straight back to Send — the one action that is
+ // guaranteed not to work while the window is still open.
+ if (code === "rate_limited" || code === "http_429")
+ return "Too many requests in the last minute — an answer that uses tools costs several. Wait about a minute, then send again.";
+ // The provider's own 429/5xx arrives as free text on the SSE `error` event, AFTER
+ // the response already returned 200, so there is no status left to switch on.
+ if (/rate.?limit|\b429\b|quota/i.test(code))
+ return "Your AI provider is rate-limiting this key. Wait a moment, or switch provider in Settings → AI.";
+ if (code.startsWith("http_5") || /overloaded|\b529\b/i.test(code))
+ return "The AI provider is overloaded or down — nothing on this box is broken. Retry shortly, or pick another model in Settings → AI.";
+ if (code === "oauth_refresh_failed") return "Couldn't refresh the OpenAI Codex sign-in. Reconnect it in Settings → AI.";
+ return "Couldn't reach the assistant. Try again.";
+}
diff --git a/frontend/slices/assistant/host-tools/catalog.ts b/frontend/slices/assistant/host-tools/catalog.ts
index ab747425..c86fe670 100644
--- a/frontend/slices/assistant/host-tools/catalog.ts
+++ b/frontend/slices/assistant/host-tools/catalog.ts
@@ -9,7 +9,12 @@ import type { HostTool } from "./types";
// pty.ts states that keystrokes are unaudited and the destructive-command regex
// cannot reach them. registry.test.ts already keeps `pty.open` away from the
// model; this keeps the window that wraps it away too.
-const SHELL_APPS = new Set(["claude-code", "os-terminal"]);
+//
+// EXPORTED only so registry.test.ts can pin these strings against the two
+// AppDescriptors that own them. They are matched by VALUE: rename either
+// descriptor's `id` and this set quietly matches nothing, app.open starts
+// accepting the renamed app, and every test still passes.
+export const SHELL_APPS = new Set(["claude-code", "os-terminal"]);
// The READ half. Mutating tools live in catalog-mutate.ts.
const READ_TOOLS: HostTool[] = [
diff --git a/frontend/slices/assistant/host-tools/registry.test.ts b/frontend/slices/assistant/host-tools/registry.test.ts
index 2558e17b..9e3afd84 100644
--- a/frontend/slices/assistant/host-tools/registry.test.ts
+++ b/frontend/slices/assistant/host-tools/registry.test.ts
@@ -1,9 +1,17 @@
import { describe, expect, it } from "vitest";
-import { HOST_TOOLS } from "./catalog";
+// Still the os-terminal BARREL, spelled the long way: vitest.config.mts lists the
+// `@` alias before `@/features`, so `@/features/os-terminal` resolves to
+// <root>/features and fails to load under vitest only. Same workaround as
+// lib/mcp/parity.test.ts.
+import { claudeCodeApp, osTerminalApp } from "@/frontend/slices/os-terminal";
+import { HOST_TOOLS, SHELL_APPS } from "./catalog";
import { findHostTool, HOST_AI_TOOLS } from "./registry";
-// Pure-data test: no React / no shell (the catalog + registry only pull the
-// schema helpers + type-only imports, so this runs in the node env).
+// Runs in the node env: the catalog + registry pull only the schema helpers and
+// type-only imports. The one exception is that barrel, imported for the two
+// AppDescriptors below — it is `lazy()` + icons and touches no DOM, which is the
+// only reason it is safe here. Do not reach for the shell barrel to get
+// BUILTIN_APPS instead; that drags the whole window runtime into a data test.
describe("host-tools registry", () => {
it("classifies reads as read; fs mutations + exec as mutate", () => {
const eff = (n: string) => findHostTool(n)?.effect;
@@ -41,6 +49,20 @@ describe("host-tools registry", () => {
expect(open?.description).toMatch(/Terminals are not on this list/);
});
+ it("SHELL_APPS still names the two apps that actually mount a PTY", () => {
+ // The guard in catalog.ts compares app.open's argument to STRING ids. Nothing
+ // else connects those strings to the descriptors they refer to, so renaming
+ // `claude-code` or `os-terminal` in the os-terminal barrel would leave the set
+ // matching nothing — app.open would open a window that auto-runs
+ // `claude --dangerously-skip-permissions`, from a READ-tier tool that parks no
+ // approval card, and this whole file would still be green. The set equality is
+ // the guard; the two literals are the pin, so even a correctly-synced rename
+ // has to come through here on purpose.
+ expect(osTerminalApp.id).toBe("os-terminal");
+ expect(claudeCodeApp.id).toBe("claude-code");
+ expect([...SHELL_APPS].sort()).toEqual([claudeCodeApp.id, osTerminalApp.id].sort());
+ });
+
it("derives one AiTool per catalog tool with an object input_schema", () => {
expect(HOST_AI_TOOLS).toHaveLength(HOST_TOOLS.length);
for (const t of HOST_AI_TOOLS) {
diff --git a/frontend/slices/os-settings/components/backup-section.tsx b/frontend/slices/os-settings/components/backup-section.tsx
new file mode 100644
index 00000000..d53a7b0e
--- /dev/null
+++ b/frontend/slices/os-settings/components/backup-section.tsx
@@ -0,0 +1,141 @@
+"use client";
+
+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 { SettingsSection, SettingsActionRow, SettingsBlock } from "@/features/shell-settings";
+import pkg from "../../../../package.json";
+
+type Pending = { file: string; blob: LocalStateBlob; known: string[]; unknown: string[] };
+
+// Backup for the state that exists in exactly ONE place — this browser's
+// localStorage. Playbooks, Agents, Automations, the window layout, the app
+// registry and the desktop-icon arrangement have no server copy, so a profile
+// wipe is permanent. Export writes them to a .json; Import replaces them.
+export function BackupSection() {
+ const fileInput = useRef<HTMLInputElement>(null);
+ const [exported, setExported] = useState<number | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [pending, setPending] = useState<Pending | null>(null);
+
+ const doExport = () => {
+ 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);
+ setExported(Object.keys(blob.keys).length);
+ };
+
+ const onFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ // Clear the input NOW: picking the same file twice fires no change event
+ // otherwise, so a user who fixes nothing and retries gets a dead button.
+ e.target.value = "";
+ if (!file) return;
+ setError(null);
+ setExported(null);
+ const res = parseLocalState(await file.text());
+ if (!res.ok) {
+ setError(res.error);
+ return;
+ }
+ setPending({ file: file.name, blob: res.blob, known: res.known, unknown: res.unknown });
+ };
+
+ const confirmImport = () => {
+ if (!pending) return;
+ restoreLocalState(pending.blob);
+ setPending(null);
+ // Full reload, not a state refresh: the layout store, app registry and
+ // assistant store all read localStorage once at module init, so anything
+ // short of a reload leaves half the cockpit on the pre-import data.
+ window.location.reload();
+ };
+
+ return (
+ <div className="space-y-4 sm:space-y-5">
+ <SettingsSection
+ icon={<DatabaseBackup />}
+ title="Backup"
+ footnote="Covers Playbooks, Agents, Automations, the window layout, installed apps, desktop icons, widgets and wallpapers — everything stored in this browser only. The approved-device identity is deliberately left out, so a leaked backup can't skip device approval. Appearance and Quicklinks also sync to the server, and the server copy wins on the next sign-in."
+ >
+ <SettingsActionRow label="Export backup…" icon={<Download />} onClick={doExport} />
+ <SettingsActionRow label="Import backup…" icon={<Upload />} onClick={() => fileInput.current?.click()} />
+ {exported !== null && (
+ <SettingsBlock>
+ <p className="text-xs text-muted-foreground">
+ Saved {exported} {exported === 1 ? "entry" : "entries"} to your Downloads folder.
+ </p>
+ </SettingsBlock>
+ )}
+ {error && (
+ <SettingsBlock>
+ <p className="flex items-start gap-2 text-xs text-destructive-text">
+ <AlertTriangle className="mt-px size-3.5 shrink-0" />
+ <span>{error}</span>
+ </p>
+ </SettingsBlock>
+ )}
+ </SettingsSection>
+
+ <input
+ ref={fileInput}
+ type="file"
+ accept="application/json,.json"
+ onChange={onFile}
+ className="hidden"
+ aria-hidden="true"
+ tabIndex={-1}
+ />
+
+ <FormDrawer open={pending !== null} onOpenChange={(o) => !o && setPending(null)} size="sm">
+ <FormDrawer.Header>
+ <FormDrawer.Title>Replace this browser&apos;s data?</FormDrawer.Title>
+ <FormDrawer.Description>
+ {pending
+ ? `${pending.file} holds ${pending.known.length} ${pending.known.length === 1 ? "entry" : "entries"} from MSO ${pending.blob.appVersion}, saved ${new Date(pending.blob.exportedAt).toLocaleString()}. Your current Playbooks, Agents, Automations, layout and app list are REPLACED, not merged, and MSO reloads. Files on disk are untouched.`
+ : ""}
+ </FormDrawer.Description>
+ </FormDrawer.Header>
+ {pending && pending.unknown.length > 0 && (
+ <FormDrawer.Body>
+ {/* Named, never dropped in silence: an entry this build doesn't own
+ is usually a newer MSO's key or the device id, and a user who
+ isn't told will assume it restored. */}
+ <p className="flex items-start gap-2 text-xs text-muted-foreground">
+ <AlertTriangle className="mt-px size-3.5 shrink-0" />
+ <span>
+ Not restored ({pending.unknown.length}, unrecognised by this build):{" "}
+ <span className="break-all font-mono">{pending.unknown.join(", ")}</span>
+ </span>
+ </p>
+ </FormDrawer.Body>
+ )}
+ <FormDrawer.Footer>
+ <Button type="button" variant="ghost" onClick={() => setPending(null)}>
+ Cancel
+ </Button>
+ <Button type="button" variant="destructive" onClick={confirmImport} disabled={pending?.known.length === 0}>
+ <Upload className="size-4" />
+ Replace and reload
+ </Button>
+ </FormDrawer.Footer>
+ </FormDrawer>
+ </div>
+ );
+}
diff --git a/frontend/slices/os-settings/components/nav.tsx b/frontend/slices/os-settings/components/nav.tsx
index 9e9caf97..062cbf2f 100644
--- a/frontend/slices/os-settings/components/nav.tsx
+++ b/frontend/slices/os-settings/components/nav.tsx
@@ -2,6 +2,7 @@
import type { ComponentType } from "react";
import {
+ DatabaseBackup,
Info,
Link2,
Paintbrush,
@@ -15,7 +16,7 @@ import {
import { cn } from "@/lib/utils";
export type SectionId =
- | "appearance" | "theme" | "ai" | "quicklinks" | "mcp" | "devices" | "server" | "cleanup" | "about";
+ | "appearance" | "theme" | "ai" | "quicklinks" | "mcp" | "devices" | "server" | "cleanup" | "backup" | "about";
// Semantic buckets for the iOS grouped index (mobile). Reorder-safe: the mobile
// cards derive from this field, not an index slice, so adding/reordering a
@@ -41,6 +42,10 @@ export const SECTIONS: ReadonlyArray<{
{ id: "devices", label: "Devices", blurb: "Approved browsers and sessions", icon: ShieldCheck, color: "#30d158", group: "system" },
{ id: "server", label: "Server", blurb: "Mock or live host data", icon: Server, color: "#ff9f0a", group: "system" },
{ id: "cleanup", label: "Cleanup", blurb: "Free disk space safely", icon: Trash2, color: "#64d2ff", group: "system" },
+ // Sits immediately before About because About owns "Reset MSO", the one
+ // button that destroys exactly what Backup exists to save — a user reaching
+ // for the reset should have passed the backup row on the way there.
+ { id: "backup", label: "Backup", blurb: "Export or restore browser data", icon: DatabaseBackup, color: "#a2845e", group: "system" },
{ id: "about", label: "About", blurb: "System info and reset", icon: Info, color: "#8e8e93", group: "system" },
];
diff --git a/frontend/slices/os-settings/components/sections.tsx b/frontend/slices/os-settings/components/sections.tsx
index b8b80127..ccc74f3b 100644
--- a/frontend/slices/os-settings/components/sections.tsx
+++ b/frontend/slices/os-settings/components/sections.tsx
@@ -16,6 +16,7 @@ import { QuicklinksSection } from "./quicklinks-section";
import { McpSection } from "./mcp-section";
import { ServerSection } from "./server-section";
import { CleanupSection } from "./cleanup-section";
+import { BackupSection } from "./backup-section";
import { AboutSection } from "./about-section";
// The section content — one functional panel per SectionId, shared verbatim by
@@ -59,6 +60,8 @@ function SectionBody({ id }: { id: SectionId }) {
return <ServerSection />;
case "cleanup":
return <CleanupSection />;
+ case "backup":
+ return <BackupSection />;
case "about":
return <AboutSection />;
}
@@ -96,7 +99,7 @@ export function SectionDetail({ id }: { id: SectionId }) {
// inset to the label. Tapping a row drills the MasterDetail into the section
// content; the back arrow returns here. No large title in-pane — the mobile
// app-chrome header already paints "Settings" (avoids a double title); no search
-// pill either (8 sections don't warrant one, and a dead field is a fake affordance).
+// pill either (ten sections don't warrant one, and a dead field is a fake affordance).
export function SectionList({
active,
onSelect,
diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.ts
index b1e2e56f..49b9835e 100644
--- a/lib/mcp/tools-read.ts
+++ b/lib/mcp/tools-read.ts
@@ -78,7 +78,11 @@ export const READ_TOOLS: McpTool[] = [
scope: "read",
annotations: READ_ONLY,
inputSchema: S({}),
- run: () => listManagedApps(),
+ // `{ apps: [...] }`, not a bare array — GET /api/v1/managed-apps is the authority
+ // on this shape and `mso mapp list` already prints its envelope. Returning the
+ // array raw meant one capability answered in two shapes depending on which
+ // surface asked, which is exactly the drift the parity gate exists to stop.
+ run: async () => ({ apps: await listManagedApps() }),
},
{
name: "apps_logs",
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 82c1f659..f4a5f60b 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -2,6 +2,7 @@ import { writeFile, makeDir, remove, move, copy, runCommand } from "@/lib/host";
import { setCamoufoxEnabled } from "@/lib/camoufox/service";
import { performManagedAppAction } from "@/lib/managed-apps/manager";
import { isManagedAppId } from "@/lib/managed-apps/catalog";
+import { MANAGED_APP_ACTIONS, type ManagedAppAction } from "@/lib/managed-apps/types";
import { type McpTool, str, opt, S, PATH_P } from "./tool-kit";
import { READ_TOOLS } from "./tools-read";
@@ -70,21 +71,29 @@ const MUTATE_TOOLS: McpTool[] = [
limit: { key: "managed-app", max: 12, windowMs: 60_000, keyArg: "id" },
audit: { action: "managed-app.action" as const, targetArg: "id" },
description:
- "Start, stop or restart a managed application on the VPS. Bounded to the known apps and the " +
- "three verbs — restarting a daemon should not require handing over a shell, so this sits at " +
+ "Start, stop, restart or back up a managed application on the VPS. Bounded to the known apps and " +
+ "those four verbs — restarting a daemon should not require handing over a shell, so this sits at " +
"write scope rather than exec. Check apps_list or apps_logs first.",
scope: "write",
annotations: { destructiveHint: true },
+ // The verb list is READ from MANAGED_APP_ACTIONS, never retyped. It was retyped,
+ // and `backup` — a real action with a real route, taken automatically before
+ // every update — was missing from the enum AND from the guard below, so an MCP
+ // client could not take one and was told the tool only did three things.
inputSchema: S({
id: { type: "string", description: "Managed app id from apps_list." },
- action: { type: "string", enum: ["start", "stop", "restart"], description: "start | stop | restart" },
+ action: { type: "string", enum: [...MANAGED_APP_ACTIONS], description: MANAGED_APP_ACTIONS.join(" | ") },
}, ["id", "action"]),
run: (a) => {
const id = str(a, "id");
const action = str(a, "action");
if (!isManagedAppId(id)) throw new Error(`unknown managed application "${id}" — call apps_list for valid ids`);
- if (!["start", "stop", "restart"].includes(action)) throw new Error("action must be start, stop or restart");
- return performManagedAppAction(id, action as "start" | "stop" | "restart");
+ if (!(MANAGED_APP_ACTIONS as readonly string[]).includes(action))
+ throw new Error(`action must be one of ${MANAGED_APP_ACTIONS.join(", ")}`);
+ // `{ app }`, matching POST /api/v1/managed-apps/[id]. Same capability, same
+ // envelope — a client that learned the shape from the CLI or the route must
+ // not have to learn a second one here.
+ return performManagedAppAction(id, action as ManagedAppAction).then((app) => ({ app }));
},
},
{
diff --git a/lib/os-api/http-adapter.test.ts b/lib/os-api/http-adapter.test.ts
new file mode 100644
index 00000000..58bf677b
--- /dev/null
+++ b/lib/os-api/http-adapter.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { HttpAdapter } from "./http-adapter";
+
+// The managed-app calls are the one place in this adapter where the wire shape and
+// the port shape genuinely disagree, and the disagreement is INVISIBLE to tsc: `req`
+// is generic, so whatever type the call site claims is what TypeScript believes the
+// route sent. That is how two separate shipped bugs hid here — an envelope that was
+// never unwrapped (`.length` of an object → Alfa reporting "no managed applications
+// on this host") and a `running` boolean the routes have never sent at all
+// (`ManagedAppView` carries a `state` enum) → "stopped" right after a start that
+// worked. Both were reported to the operator as fact by an AI tool. Only a test that
+// feeds the ROUTE's literal JSON can catch the next one.
+function mockFetch(payload: unknown) {
+ // The `url` parameter is declared even though the body ignores it: without it
+ // `mock.calls` types as an empty tuple and the URL assertions below fail to
+ // compile (TS2493), which is how the url-drift half of this test gets its teeth.
+ const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) =>
+ new Response(JSON.stringify(payload), { status: 200, headers: { "content-type": "application/json" } }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+const view = (id: string, state: string) => ({
+ id,
+ name: id === "hermes" ? "Hermes" : "OpenClaw",
+ description: "",
+ installed: true,
+ installationType: "systemd",
+ state,
+ healthy: state === "running",
+ version: null,
+ dashboardAvailable: state === "running",
+ supportedActions: ["start", "stop", "restart", "backup"],
+});
+
+describe("HttpAdapter — managed apps", () => {
+ const api = HttpAdapter({ url: "" });
+
+ it("unwraps the {apps:[…]} envelope GET /api/v1/managed-apps actually sends", async () => {
+ const f = mockFetch({ apps: [view("hermes", "running"), view("openclaw", "stopped")] });
+ const apps = await api.apps.list();
+ expect(f.mock.calls[0]?.[0]).toBe("/api/v1/managed-apps");
+ expect(apps).toHaveLength(2);
+ expect(apps.map((a) => a.running)).toEqual([true, false]);
+ });
+
+ it("counts unhealthy and starting as running", async () => {
+ // Not a naming quibble. `unhealthy` is a live unit failing its /health probe and
+ // `starting` is one mid-start; calling either "stopped" tells the operator to go
+ // restart a daemon that is already up.
+ mockFetch({ apps: [view("hermes", "unhealthy"), view("openclaw", "starting")] });
+ expect((await api.apps.list()).map((a) => a.running)).toEqual([true, true]);
+ });
+
+ it("unwraps {app:{…}} from a power action and reports post-action liveness", async () => {
+ const f = mockFetch({ app: view("hermes", "running") });
+ const app = await api.apps.power("hermes", "start");
+ expect(f.mock.calls[0]?.[0]).toBe("/api/v1/managed-apps/hermes");
+ // `name` undefined here was the model saying "undefined: stopped (after start)".
+ expect(app.name).toBe("Hermes");
+ expect(app.running).toBe(true);
+ });
+
+ it("surfaces the route's own error message, not the bare status", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () =>
+ new Response(JSON.stringify({ error: "managed application operation failed" }), { status: 409 }),
+ ));
+ await expect(api.apps.power("hermes", "restart")).rejects.toThrow("managed application operation failed");
+ });
+});
diff --git a/lib/os-api/http-adapter.ts b/lib/os-api/http-adapter.ts
index 0f835196..32f85664 100644
--- a/lib/os-api/http-adapter.ts
+++ b/lib/os-api/http-adapter.ts
@@ -1,4 +1,5 @@
import { API_VERSION, type OsApi, type SysStats } from "./types";
+import type { ManagedAppView } from "@/lib/managed-apps/types";
import { uploadChunked } from "./upload";
// /api/v1 routes return `{ error: "..." }` (lib/host/api-error). Surface that
@@ -15,6 +16,30 @@ async function errorFromResponse(res: Response): Promise<Error> {
return new Error(message || `${res.status} ${res.statusText}`.trim());
}
+// Two DIFFERENT shapes, which is the whole problem. The port promises a
+// `running` boolean (appshell owns it and does not export the name, so it is
+// derived, never re-typed); the routes send a `ManagedAppView`, whose liveness is
+// a six-value `state` enum and which carries no `running` key at all. Typing the
+// response as the port's type would compile and still hand callers `undefined`.
+type ManagedApp = Awaited<ReturnType<OsApi["apps"]["list"]>>[number];
+
+// `import type` only — types.ts is server-adjacent and must not ride into the
+// browser bundle behind this client adapter.
+type ManagedAppWire = Pick<ManagedAppView, "id" | "name" | "installed" | "state">;
+
+// `unhealthy` and `starting` are UP, and getting that wrong is not cosmetic:
+// `unhealthy` is a live unit whose /health probe failed, `starting` is one with a
+// start still in flight (manager.ts:98 sets it for the whole operation). Both
+// answer "yes" to "is the daemon up?", and Alfa renders this boolean as the words
+// "running" / "installed, stopped" — so mapping them to false tells the operator
+// their daemon is down while it is serving traffic, right after a start that worked.
+const toSummary = (a: ManagedAppWire): ManagedApp => ({
+ id: a.id,
+ name: a.name,
+ installed: a.installed,
+ running: a.state === "running" || a.state === "unhealthy" || a.state === "starting",
+});
+
// Live adapter → REST + SSE against the VPS daemon / Control Room agent at
// {baseUrl}/api/v1. Auth = the signed session cookie, sent automatically on
// same-origin requests (no Bearer token). Host actions stay allowlisted
@@ -90,9 +115,18 @@ export function HttpAdapter(cfg: { url?: string }): OsApi {
processes: () => req("GET", "/sys/processes"),
},
apps: {
- list: () => req("GET", "/managed-apps"),
+ // UNWRAP, then TRANSLATE. Both managed-app routes answer in an envelope —
+ // `{apps:[…]}` and `{app:{…}}` — while the port promises the payload, and
+ // `req` is generic, so TypeScript inferred the envelope AS the payload and
+ // no shape error was visible anywhere. `apps.list()` handed callers an
+ // object whose `.length` is undefined, which is why Alfa still answered "no
+ // managed applications on this host" even after the URL was repointed to fix
+ // exactly that, and `apps.power()` returned `{app}`, so the tool reported
+ // "undefined: stopped" after a start that had in fact worked.
+ list: async () => (await req<{ apps: ManagedAppWire[] }>("GET", "/managed-apps")).apps.map(toSummary),
logs: (id) => req("GET", `/managed-apps/${encodeURIComponent(id)}/logs`),
- power: (id, action) => req("POST", `/managed-apps/${encodeURIComponent(id)}`, { body: { action } }),
+ power: async (id, action) =>
+ toSummary((await req<{ app: ManagedAppWire }>("POST", `/managed-apps/${encodeURIComponent(id)}`, { body: { action } })).app),
},
browser: {
status: () => req("GET", "/camoufox/service"),