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(shell): persist and embed external app connections

Rahman8345e2e67e21
diff --git a/app/api/v1/shell-apps/route.test.ts b/app/api/v1/shell-apps/route.test.ts
new file mode 100644
index 00000000..bca56a7a
--- /dev/null
+++ b/app/api/v1/shell-apps/route.test.ts
@@ -0,0 +1,37 @@
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({ session: vi.fn(), list: vi.fn(), save: vi.fn(), audit: vi.fn(), rate: vi.fn() }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: mocks.session }));
+vi.mock("@/lib/host/shell-apps-api", () => ({ shellAppSettings: mocks.list, manageShellApp: mocks.save, SurfaceConfigError: class extends Error { status = 409; } }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.rate }));
+vi.mock("@/lib/demo", () => ({ IS_DEMO: false }));
+import { GET, POST } from "./route";
+const request = (body?: unknown) => new NextRequest("https://cockpit.example.test/api/v1/shell-apps", body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : undefined);
+beforeEach(() => { vi.clearAllMocks(); mocks.rate.mockReturnValue(false); mocks.list.mockResolvedValue({ schemaVersion: 1, apps: [] }); });
+describe("shell application authority", () => {
+ it.each([null, "viewer", "operator"])("denies read/write for %s", async role => {
+ mocks.session.mockResolvedValue(role ? { session: { device_id: "fixture" }, role } : null);
+ expect((await GET(request())).status).toBe(role ? 403 : 401);
+ expect((await POST(request({}))).status).toBe(403);
+ expect(mocks.list).not.toHaveBeenCalled(); expect(mocks.save).not.toHaveBeenCalled();
+ });
+ it("lists only through the bounded host API without caching", async () => {
+ mocks.session.mockResolvedValue({ session: { device_id: "fixture" }, role: "owner" });
+ const response = await GET(request());
+ expect(response.status).toBe(200); expect(response.headers.get("cache-control")).toContain("no-store");
+ expect(mocks.list).toHaveBeenCalledWith("https://cockpit.example.test");
+ });
+ it("passes a mutation to the host and audits only identity/action metadata", async () => {
+ mocks.session.mockResolvedValue({ session: { device_id: "fixture" }, role: "owner" });
+ mocks.save.mockResolvedValue({ id: "tool", revision: "new" });
+ const body = { schemaVersion: 1, action: "remove", id: "tool", expectedRevision: "old", confirm: true };
+ expect((await POST(request(body))).status).toBe(200);
+ expect(mocks.save).toHaveBeenCalledWith(body, "https://cockpit.example.test");
+ expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({ target: "tool", detail: "shell-app.remove" }));
+ });
+ it("rate limits before applying a write", async () => {
+ mocks.session.mockResolvedValue({ session: { device_id: "fixture" }, role: "owner" }); mocks.rate.mockReturnValue(true);
+ expect((await POST(request({}))).status).toBe(429); expect(mocks.save).not.toHaveBeenCalled();
+ });
+});
diff --git a/app/api/v1/shell-apps/route.ts b/app/api/v1/shell-apps/route.ts
new file mode 100644
index 00000000..b222a043
--- /dev/null
+++ b/app/api/v1/shell-apps/route.ts
@@ -0,0 +1,32 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { roleAtLeast } from "@/lib/auth/roles";
+import { readSetupJson } from "@/lib/infra/setup-http";
+import { audit } from "@/lib/host/audit-api";
+import { rateLimited } from "@/lib/host/limits-api";
+import { IS_DEMO } from "@/lib/demo";
+import { shellAppSettings, manageShellApp, SurfaceConfigError } from "@/lib/host/shell-apps-api";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+const headers = { "Cache-Control": "no-store, private" };
+export async function GET(request: NextRequest) {
+ const context = await getSessionContext();
+ if (!context?.session.device_id) return NextResponse.json({ error: "unauthorized" }, { status: 401, headers });
+ if (!roleAtLeast(context.role, "owner")) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
+ try { return NextResponse.json(await shellAppSettings(request.nextUrl.origin), { headers }); }
+ catch { return NextResponse.json({ error: "surface_registry_unavailable" }, { status: 503, headers }); }
+}
+export async function POST(request: NextRequest) {
+ const context = await getSessionContext();
+ if (IS_DEMO || !context?.session.device_id || !roleAtLeast(context.role, "owner")) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
+ if (rateLimited(`shell-app:${context.session.device_id}`, 20, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429, headers });
+ try {
+ const input = await readSetupJson(request);
+ const result = await manageShellApp(input, request.nextUrl.origin);
+ void audit({ action: "infra.write", actor: context.session.device_id, target: result.id, ok: true, detail: `shell-app.${input.action}` });
+ return NextResponse.json(result, { headers });
+ } catch (error) {
+ return NextResponse.json({ error: error instanceof SurfaceConfigError ? error.message : "shell_app_update_failed" }, { status: error instanceof SurfaceConfigError ? error.status : 400, headers });
+ }
+}
diff --git a/app/os-root.tsx b/app/os-root.tsx
index 6d951690..384f6d6d 100644
--- a/app/os-root.tsx
+++ b/app/os-root.tsx
@@ -17,15 +17,17 @@ import "@/features/os-shell/integrations";
import { AuthGate, SessionProvider, useSession, type DeviceRole, type SessionStatus } from "@/features/auth";
import { appAllowedForRole } from "@/lib/auth/app-access";
-import { useInstalledApps, useDisabledIds } from "@/features/app-store";
+import { useInstalledApps, useDisabledIds, useExternalApps, ShellAppsProvider } from "@/features/app-store";
function Shell() {
const dynamic = useInstalledApps();
+ const external = useExternalApps();
const disabled = useDisabledIds();
const { status, role } = useSession();
const manifest: ShellManifest = useMemo(() => {
const off = new Set(disabled);
- const all = [...BUILTIN_APPS, ...dynamic].filter((app) => !off.has(app.id));
+ const reserved = new Set([...BUILTIN_APPS, ...external].map(app => app.id));
+ const all = [...BUILTIN_APPS, ...external, ...dynamic.filter(app => !reserved.has(app.id))].filter((app) => !off.has(app.id));
// Signed-out is the unrestricted mock showcase. A live delegated session sees
// only apps its role can actually use; unknown runtime apps fail closed for
// non-owners because their host contract cannot be inferred safely.
@@ -43,10 +45,15 @@ function Shell() {
persistKey: TOPSIDE_PERSIST_KEY,
capabilities: topsideCapabilities,
};
- }, [dynamic, disabled, status, role]);
+ }, [dynamic, external, disabled, status, role]);
return <AppShell manifest={manifest} />;
}
+function ConnectedShell() {
+ const { status, role } = useSession();
+ return <ShellAppsProvider active={status === "in" && role === "owner"}><Shell /></ShellAppsProvider>;
+}
+
export function OsRoot({
initialStatus,
initialRole,
@@ -67,7 +74,7 @@ export function OsRoot({
<SessionProvider initialStatus={initialStatus} initialRole={initialRole}>
<AuthGate>
<OsApiProvider>
- <Shell />
+ <ConnectedShell />
</OsApiProvider>
</AuthGate>
</SessionProvider>
diff --git a/bin/mso b/bin/mso
index 60d428e6..fa5f4968 100755
--- a/bin/mso
+++ b/bin/mso
@@ -63,7 +63,7 @@
#
# Apps
# apps App-store runtime apps
-# mapp * Managed apps on the box (hermes, openclaw): logs, update…
+# mapp * Managed apps; shell-list / shell-save <JSON|@file> for connected apps
# term * Interactive PTY sessions (open | input | resize | stream | close)
#
# AI + state
diff --git a/components/external-app-frame.tsx b/components/external-app-frame.tsx
new file mode 100644
index 00000000..66e82acb
--- /dev/null
+++ b/components/external-app-frame.tsx
@@ -0,0 +1,34 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { ExternalLink, LogIn, RefreshCw } from "lucide-react";
+import type { WorkflowEmbed } from "@/lib/contracts/surface-app";
+import { Button } from "@/components/ui/button";
+
+export function ExternalAppFrame({ app, frameTitle }: { app: WorkflowEmbed; frameTitle?: string }) {
+ const [revision, setRevision] = useState(0);
+ const [loading, setLoading] = useState(true);
+ const [slow, setSlow] = useState(false);
+ useEffect(() => {
+ const timer = setTimeout(() => setSlow(true), 15000);
+ return () => clearTimeout(timer);
+ }, [revision]);
+ if (app.blocked || !app.url) return <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 p-6 text-center text-sm" data-slot="external-app-frame" role="alert">
+ <p>{app.reason || "This editor destination is unavailable."}</p>
+ <p className="text-xs text-muted-foreground">No editor or login link is opened. Configure a separate cookie-isolated origin before connecting.</p>
+ </div>;
+ const reload = () => { setLoading(true); setSlow(false); setRevision((value) => value + 1); };
+ return <div className="flex h-full min-h-0 min-w-0 flex-col" data-slot="external-app-frame">
+ <div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b px-3 py-1.5">
+ <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground" title={app.origin}>{app.origin}</span>
+ {app.loginUrl ? <Button asChild variant="ghost" size="sm"><a href={app.loginUrl} target="_blank" rel="noopener noreferrer"><LogIn className="size-4"/><span>Sign in</span></a></Button> : null}
+ <Button asChild variant="outline" size="sm"><a href={app.url} target="_blank" rel="noopener noreferrer"><ExternalLink className="size-4"/><span>Open {app.title}</span></a></Button>
+ {app.renderer === "iframe" ? <Button variant="ghost" size="icon" onClick={reload} aria-label={`Reload ${app.title}`} title={`Reload ${app.title}`}><RefreshCw className="size-4"/></Button> : null}
+ </div>
+ {app.renderer === "iframe" ? <div className="relative min-h-0 min-w-0 flex-1">
+ {loading ? <div className="absolute inset-x-0 top-0 z-10 border-b bg-background px-3 py-2 text-xs text-muted-foreground" role="status">{slow ? `Taking longer than expected. Open ${app.title} in a new tab if its login or frame policy blocks embedding.` : `Loading ${app.title}…`}</div> : null}
+ <iframe key={`${revision}:${app.sandbox}`} src={app.url} title={frameTitle ?? `${app.title} application`} sandbox={app.sandbox} referrerPolicy="no-referrer" className="h-full w-full border-0 bg-background" onLoad={() => setLoading(false)} onError={() => { setLoading(true); setSlow(true); }}/>
+ </div> : <div className="flex min-h-0 flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">{app.reason || `${app.title} opens in a separate tab. Embedded access is not enabled for this provider.`}</div>}
+ <p className="shrink-0 border-t px-3 py-1.5 text-xs text-muted-foreground [@media(max-height:520px)]:sr-only">{app.title} keeps its own login. Sign in in a new tab, then reload here. If embedding is blocked, use Open {app.title}.</p>
+ </div>;
+}
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 95cbf8aa..1cd93acd 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `shell` persist and embed external app connections
- `managed-apps` preflight install backend on host
- `jev` persist reusable session capsules
- `settings` nest version and updates under About
diff --git a/docs/CLI.md b/docs/CLI.md
index 66382cbd..994d832a 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -103,7 +103,7 @@ Commands:
Apps
apps App-store runtime apps
- mapp * Managed apps on the box (hermes, openclaw): logs, update…
+ mapp * Managed apps; shell-list / shell-save <JSON|@file> for connected apps
term * Interactive PTY sessions (open | input | resize | stream | close)
AI + state
diff --git a/docs/CONNECTED-APPS.md b/docs/CONNECTED-APPS.md
new file mode 100644
index 00000000..1c275b67
--- /dev/null
+++ b/docs/CONNECTED-APPS.md
@@ -0,0 +1,19 @@
+# Connected applications
+
+MSO is the shell and control surface. Connected applications run in their own services; adding or disconnecting a shell entry does not install, stop, or delete a service or its data. This implementation has no dependency on manef-ui or manef-db.
+
+## Owner journey
+
+Open App Store → Apps. Managed applications use the existing reviewed Hermes, OpenClaw and 9Router setup panels and their host preflight checks. For an already running external or custom tool, select Connect app, enter its name, stable ID and address, and choose an embedded window or separate tab. Entries persist on the server and appear in the shell without a rebuild. Edit updates the connection; Disconnect removes only the shell entry.
+
+A subdomain is optional. HTTPS addresses can be embedded when the application permits framing. HTTP addresses open in a separate tab. Applications retain their own login. Addresses sharing the MSO session-cookie scope are rejected, including the same hostname on another port. Query strings, URL credentials and fragments are rejected; enter secrets only through the application's trusted setup flow.
+
+## Current API and lifecycle
+
+Owner-only `GET /api/v1/shell-apps` returns schemaVersion 1, a revision, configurability and app views. `POST` accepts schemaVersion 1, action add/update/remove, expectedRevision, confirm true, and app metadata or the removed ID. App metadata contains id, title, description, url and mode (embed/tab). Concurrent updates return conflict and require a fresh review. The CLI exposes `mso mapp shell-list` and `mso mapp shell-save @request.json`.
+
+Entries share the surface registry, its atomic locking, 16-entry/16-KiB limits and environment-managed read-only mode. Shell placement never grants MCP Page access. New shell entries cannot overwrite Workflow or Page entries. Legacy local HTML manifests must resolve to a reviewed shell connection before rendering. The shared iframe renderer is also used by n8n.
+
+## Remaining migration
+
+This is the first implemented registry path, not the complete [external feature target contract](./EXTERNAL-FEATURE-CONTRACT.md). Native shell features still ship with MSO. The remote manef.dev catalog, generic install recipes, generic domain provisioning, feature extraction and independent package releases remain future work. Connecting an arbitrary URL does not imply an installer, health check, SSO or AI tool grant. Existing Managed Apps retain their separate reviewed runtime and proxy boundaries.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 0dc17378..80cf9802 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,5 +1,10 @@
## 2026-09-27 — External feature contract and registry audit
+## 2026-09-27 — Server-persisted connected applications
+
+The Owner App Store now exposes real Managed Apps setup and a versioned external connection registry. Connected tools run separately and become dynamic shell windows without rebuilding MSO. Registry mutations share the surface-store lock and revision, reject cross-placement ownership and cookie-scope overlap, and never execute install scripts or delete service data. HTTP/no-domain connections open separately; n8n and registered tools share the reviewed iframe renderer. Legacy HTML manifests require registry admission. manef-ui and manef-db are unrelated and excluded. Remote catalog delivery and extraction of native features remain pending; see CONNECTED-APPS.md for the implemented boundary.
+
+
Defined the v1 design contract for portable feature definitions, separate installation
bindings and grants, embedded views, reviewed adapters, shell slots and lifecycle
verification. Audited the existing AppShell, runtime App Store, SurfaceApp and Managed
diff --git a/docs/README.md b/docs/README.md
index 84555ba0..91f2a273 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -62,6 +62,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`MCP-FEATURE-IMPLEMENTATION.md`](./MCP-FEATURE-IMPLEMENTATION.md) | Stepwise reverse-engineering workflow for MCP tools, trusted skills and project capabilities |
| [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) | ChatGPT custom MCP app setup, diagrams, scopes and file bridge |
| [`PLUGIN-REFERENCE-MATRIX.md`](./PLUGIN-REFERENCE-MATRIX.md) | Living cross-plugin architecture matrix, audit decisions and candidate generic primitives |
+| [`CONNECTED-APPS.md`](./CONNECTED-APPS.md) | Server-persisted external app connections, dynamic shell windows and lifecycle boundaries |
| [`MANAGED-APPS.md`](./MANAGED-APPS.md) | Hermes/OpenClaw/9Router lifecycle, jobs, backup/restore and dashboard access boundary |
| [`HERMES-INTEGRATION.md`](./HERMES-INTEGRATION.md) | Hermes-specific integration behaviour |
| [`OPENCLAW-INTEGRATION.md`](./OPENCLAW-INTEGRATION.md) | OpenClaw-specific integration behaviour |
diff --git a/frontend/slices/app-store/app.tsx b/frontend/slices/app-store/app.tsx
index 1babf927..c09d311a 100644
--- a/frontend/slices/app-store/app.tsx
+++ b/frontend/slices/app-store/app.tsx
@@ -2,13 +2,16 @@
import { useId, useState } from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { CategoryTabs, McpStorePanel, SkillStorePanel } from "@/features/extensions";
+import ConnectedAppsPanel from "./components/connected-apps-panel";
+import { useShellApps } from "./lib/shell-apps";
import AppsPanel from "./components/apps-panel";
export default function AppStore() {
+ const { active } = useShellApps();
const [tab, setTab] = useState("apps"), id = useId();
return <div className="flex h-full min-h-0 min-w-0 flex-col">
- <div className="shrink-0 border-b px-3 py-2"><CategoryTabs id={id} label="Store categories" items={[{ id: "apps", label: "Apps" }, { id: "mcp", label: "MCP" }, { id: "skills", label: "Skills" }]} value={tab} onChange={setTab} /></div>
+ <div className="shrink-0 border-b px-3 py-2"><CategoryTabs id={id} label="Store categories" items={[{ id: "apps", label: "Apps" }, { id: "builtins", label: "Shell features" }, { id: "mcp", label: "MCP" }, { id: "skills", label: "Skills" }]} value={tab} onChange={setTab} /></div>
<section id={`${id}-panel`} role="tabpanel" aria-labelledby={`${id}-${tab}`} className="min-h-0 flex-1">
- {tab === "apps" ? <AppsPanel /> : <ScrollArea className="h-full"><div className="@container p-4">{tab === "mcp" ? <McpStorePanel /> : <SkillStorePanel />}</div></ScrollArea>}
+ {tab === "apps" ? (active ? <ConnectedAppsPanel /> : <AppsPanel />) : tab === "builtins" ? <AppsPanel systemOnly /> : <ScrollArea className="h-full"><div className="@container p-4">{tab === "mcp" ? <McpStorePanel /> : <SkillStorePanel />}</div></ScrollArea>}
</section>
</div>;
}
diff --git a/frontend/slices/app-store/components/apps-panel.tsx b/frontend/slices/app-store/components/apps-panel.tsx
index f5eaa1b8..61d97e0d 100644
--- a/frontend/slices/app-store/components/apps-panel.tsx
+++ b/frontend/slices/app-store/components/apps-panel.tsx
@@ -26,9 +26,9 @@ import { useStoreInstall } from "../lib/use-store-install";
// flips its localStorage row (useInstalledApps surfaces it in the dock/launchpad).
// The "Apps"/"Features" sections instead toggle the built-in apps + shell features
// on/off (enabled-store) — os-root filters the manifest by the disabled set.
-export default function AppStore() {
+export default function AppStore({ systemOnly = false }: { systemOnly?: boolean }) {
const [query, setQuery] = useState("");
- const [filter, setFilter] = useState<StoreFilter>("Featured");
+ const [filter, setFilter] = useState<StoreFilter>(systemOnly ? "Apps" : "Featured");
// Store-level zone: a right-click anywhere in the grid gets this, and a
// right-click ON a card merges the card's items ABOVE it (nested).
const storeZone = useContextZone((): MenuItem[] => [
@@ -99,7 +99,7 @@ export default function AppStore() {
return (
<div ref={paneRef} className="flex h-full">
- {!compact && <StoreSidebar value={filter} onChange={setFilter} />}
+ {!compact && <StoreSidebar systemOnly={systemOnly} value={filter} onChange={setFilter} />}
<AppFrame
className="min-w-0 flex-1"
@@ -122,7 +122,7 @@ export default function AppStore() {
className={ios ? "h-9 border-0 bg-[var(--fill)] pl-8" : "h-9 pl-8"}
/>
</div>
- {compact && <StoreFilterChips value={filter} onChange={setFilter} />}
+ {compact && <StoreFilterChips systemOnly={systemOnly} value={filter} onChange={setFilter} />}
</header>
}
>
diff --git a/frontend/slices/app-store/components/connect-app-form.tsx b/frontend/slices/app-store/components/connect-app-form.tsx
new file mode 100644
index 00000000..7a703d67
--- /dev/null
+++ b/frontend/slices/app-store/components/connect-app-form.tsx
@@ -0,0 +1,39 @@
+"use client";
+import { useId, useState, type FormEvent } from "react";
+import { FormDrawer } from "@/features/appshell";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
+import type { ShellAppDefinition } from "@/lib/contracts/shell-app";
+import { useShellApps } from "../lib/shell-apps";
+
+export function ConnectAppForm({ existing, onClose }: { existing?: ShellAppDefinition; onClose: () => void }) {
+ const prefix = useId(), { mutate } = useShellApps();
+ const [app, setApp] = useState<ShellAppDefinition>(existing ?? { id: "", title: "", description: "", url: "", mode: "embed" });
+ const [busy, setBusy] = useState(false), [error, setError] = useState("");
+ const change = (key: keyof ShellAppDefinition, value: string) => setApp(current => ({ ...current, [key]: value }));
+ const submit = async (event: FormEvent) => {
+ event.preventDefault(); if (busy) return;
+ setBusy(true); setError("");
+ try { await mutate({ action: existing ? "update" : "add", app }); onClose(); }
+ catch (reason) { setError(reason instanceof Error ? reason.message : "Could not connect app."); }
+ finally { setBusy(false); }
+ };
+ return <FormDrawer open onOpenChange={open => { if (!open && !busy) onClose(); }} size="md">
+ <FormDrawer.Header><FormDrawer.Title>{existing ? "Edit connected app" : "Connect a running app"}</FormDrawer.Title><FormDrawer.Description>Add your own tool or an existing service to this shell. The application keeps running on its host.</FormDrawer.Description></FormDrawer.Header>
+ <form onSubmit={submit} className="min-h-0 space-y-4 overflow-y-auto px-4 pb-4">
+ <div className="space-y-1.5"><Label htmlFor={`${prefix}-name`}>App name</Label><Input id={`${prefix}-name`} value={app.title} maxLength={120} required onChange={event => {
+ const title = event.target.value;
+ setApp(current => ({ ...current, title, ...(!existing && (!current.id || current.id === current.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")) ? { id: title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 64) } : {}) }));
+ }}/></div>
+ <div className="space-y-1.5"><Label htmlFor={`${prefix}-id`}>App ID</Label><Input id={`${prefix}-id`} value={app.id} readOnly={Boolean(existing)} pattern="[a-z0-9][a-z0-9-]{0,63}" maxLength={64} required onChange={event => change("id", event.target.value)} /><p className="text-xs text-muted-foreground">A unique name using lowercase letters, numbers and hyphens.</p></div>
+ <div className="space-y-1.5"><Label htmlFor={`${prefix}-url`}>App URL</Label><Input id={`${prefix}-url`} type="url" value={app.url} placeholder="https://your-app.example or http://192.168.1.10:5678" maxLength={2048} required onChange={event => change("url", event.target.value)} /><p className="text-xs text-muted-foreground">Use an address reachable from this browser. A domain is optional. HTTP addresses open in a separate tab. Do not include tokens or passwords.</p></div>
+ <div className="space-y-1.5"><Label htmlFor={`${prefix}-description`}>Description</Label><Input id={`${prefix}-description`} value={app.description} maxLength={240} onChange={event => change("description", event.target.value)} /></div>
+ <div className="flex items-center gap-2"><Switch aria-label="Embed HTTPS app inside MSO" checked={app.mode === "embed"} onCheckedChange={checked => change("mode", checked === true ? "embed" : "tab")} /><span className="text-sm">Embed HTTPS app inside MSO</span></div>
+ <p className="text-xs text-muted-foreground">The app keeps its own sign-in. Some apps block embedding; Open in new tab remains available. Connecting does not install or stop a service.</p>
+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
+ <div className="flex justify-end gap-2"><Button type="button" variant="ghost" disabled={busy} onClick={onClose}>Cancel</Button><Button type="submit" disabled={busy}>{busy ? "Saving…" : existing ? "Save changes" : "Connect app"}</Button></div>
+ </form>
+ </FormDrawer>;
+}
diff --git a/frontend/slices/app-store/components/connected-apps-panel.tsx b/frontend/slices/app-store/components/connected-apps-panel.tsx
new file mode 100644
index 00000000..a81a5426
--- /dev/null
+++ b/frontend/slices/app-store/components/connected-apps-panel.tsx
@@ -0,0 +1,53 @@
+"use client";
+import { useState } from "react";
+import { Globe, Plus, RefreshCw } from "lucide-react";
+import { FormDrawer, openWindow } from "@/features/appshell";
+import { shellAppId, type ShellAppDefinition } from "@/lib/contracts/shell-app";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { useShellApps } from "../lib/shell-apps";
+import { ConnectAppForm } from "./connect-app-form";
+import { ManagedAppsCatalog } from "./managed-apps-catalog";
+
+export default function ConnectedAppsPanel() {
+ const { active, snapshot, loading, error, refresh, mutate } = useShellApps();
+ const [query, setQuery] = useState("");
+ const [editing, setEditing] = useState<ShellAppDefinition | "new" | null>(null);
+ const [removing, setRemoving] = useState<ShellAppDefinition | null>(null);
+ const [busy, setBusy] = useState(false), [message, setMessage] = useState("");
+ const remove = async () => {
+ if (!removing || busy) return;
+ setBusy(true); setMessage("");
+ try { await mutate({ action: "remove", id: removing.id }); setRemoving(null); }
+ catch (reason) { setMessage(reason instanceof Error ? reason.message : "Could not disconnect app."); }
+ finally { setBusy(false); }
+ };
+ if (!active) return <div className="grid h-full place-items-center p-6 text-center text-sm text-muted-foreground">Sign in as the owner to install or connect apps on this host. Shell features and the MCP/Skills catalogs are available in their tabs.</div>;
+ const apps = snapshot.apps.filter(app => `${app.title} ${app.description}`.toLowerCase().includes(query.toLowerCase()));
+ return <ScrollArea className="h-full"><div className="@container space-y-6 p-4">
+ <div className="flex flex-wrap items-center gap-2"><div className="min-w-0 flex-1"><h2 className="font-semibold">Apps on your host</h2><p className="text-sm text-muted-foreground">Install a supported app or connect a tool that is already running.</p></div><Button variant="ghost" size="icon" disabled={loading} aria-label="Refresh connected apps" onClick={() => void refresh()}><RefreshCw className="size-4"/></Button></div>
+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
+ <ManagedAppsCatalog query={query}/>
+ <section className="space-y-3" aria-label="Connected apps">
+ <div className="flex flex-wrap items-center gap-2"><h3 className="mr-auto font-medium">Connected apps</h3><Button onClick={() => setEditing("new")} disabled={!snapshot.configurable || loading}><Plus className="size-4"/>Connect app</Button></div>
+ <Input aria-label="Search connected apps" placeholder="Search connected apps" value={query} onChange={event => setQuery(event.target.value)}/>
+ {!snapshot.configurable && !loading && !error && <p className="text-xs text-muted-foreground">This registry is managed by deployment configuration.</p>}
+ {loading && !snapshot.revision ? <p role="status" className="text-sm text-muted-foreground">Loading apps…</p> : apps.length === 0 ? <p className="rounded-xl border border-dashed p-6 text-sm text-muted-foreground">{query ? "No matching apps." : "No connected apps yet. Add the address of n8n or your own tool to open it from the shell."}</p> : <div className="grid gap-3 @min-[640px]:grid-cols-2">
+ {apps.map(app => <article key={app.id} className="min-w-0 space-y-3 rounded-xl border p-4">
+ <div className="flex items-center gap-2"><Globe className="size-5 shrink-0"/><h4 className="truncate font-medium">{app.title}</h4></div>
+ {app.description && <p className="text-sm text-muted-foreground">{app.description}</p>}
+ <p className="break-all text-xs text-muted-foreground">{app.origin}</p>
+ <p className="text-xs text-muted-foreground">{app.blocked ? app.reason : app.renderer === "iframe" ? "Embedded app · service managed separately" : app.reason || "Opens in a separate tab"}</p>
+ <div className="flex flex-wrap gap-2"><Button size="sm" onClick={() => openWindow(shellAppId(app.id), app.title)} disabled={Boolean(app.blocked)}>Open</Button><Button size="sm" variant="outline" disabled={!snapshot.configurable} onClick={() => setEditing(app.definition)}>Edit</Button><Button size="sm" variant="ghost" disabled={!snapshot.configurable} onClick={() => { setMessage(""); setRemoving(app.definition); }}>Disconnect</Button></div>
+ </article>)}
+ </div>}
+ </section>
+ {editing && <ConnectAppForm existing={editing === "new" ? undefined : editing} onClose={() => setEditing(null)}/>}
+ <FormDrawer open={Boolean(removing)} onOpenChange={open => { if (!open && !busy) setRemoving(null); }} size="sm">
+ <FormDrawer.Header><FormDrawer.Title>Disconnect {removing?.title}?</FormDrawer.Title><FormDrawer.Description>This removes its shell entry. The application keeps running and its data is untouched.</FormDrawer.Description></FormDrawer.Header>
+ {message && <p role="alert" className="px-4 text-sm text-destructive">{message}</p>}
+ <FormDrawer.Footer><Button variant="ghost" disabled={busy} onClick={() => setRemoving(null)}>Cancel</Button><Button variant="destructive" disabled={busy} onClick={() => void remove()}>{busy ? "Disconnecting…" : "Disconnect"}</Button></FormDrawer.Footer>
+ </FormDrawer>
+ </div></ScrollArea>;
+}
diff --git a/frontend/slices/app-store/components/external-app.tsx b/frontend/slices/app-store/components/external-app.tsx
new file mode 100644
index 00000000..fe916096
--- /dev/null
+++ b/frontend/slices/app-store/components/external-app.tsx
@@ -0,0 +1,10 @@
+"use client";
+import { ExternalAppFrame } from "@/components/external-app-frame";
+import { useShellApps } from "../lib/shell-apps";
+
+export default function ExternalApp({ id }: { id: string }) {
+ const { snapshot, error, loading } = useShellApps();
+ const app = snapshot.apps.find(entry => entry.id === id);
+ if (!app) return <div className="grid h-full place-items-center p-6 text-center text-sm text-muted-foreground" role="status">{loading ? "Loading app…" : error || "This app was disconnected or is no longer available. Open App Store to reconnect it."}</div>;
+ return <ExternalAppFrame key={`${app.id}:${app.url}:${app.sandbox}`} app={app} />;
+}
diff --git a/frontend/slices/app-store/components/legacy-html-app.tsx b/frontend/slices/app-store/components/legacy-html-app.tsx
new file mode 100644
index 00000000..423aae31
--- /dev/null
+++ b/frontend/slices/app-store/components/legacy-html-app.tsx
@@ -0,0 +1,19 @@
+"use client";
+import { openWindow } from "@/features/appshell";
+import { Button } from "@/components/ui/button";
+import { useShellApps } from "../lib/shell-apps";
+import ExternalApp from "./external-app";
+import type { AppManifest } from "./runtime-app-types";
+
+export function LegacyHtmlApp({ manifest }: { manifest: AppManifest }) {
+ const { snapshot } = useShellApps();
+ let url = "";
+ try { url = new URL(manifest.entry).href; } catch { /* Invalid legacy data never grants framing. */ }
+ const app = snapshot.apps.find(entry => entry.definition.url === url);
+ if (app) return <ExternalApp id={app.id}/>;
+ return <div className="grid h-full place-items-center p-6"><div className="max-w-md space-y-3 text-center">
+ <h2 className="font-semibold">Connect {manifest.title}</h2>
+ <p className="text-sm text-muted-foreground">This browser-only entry needs a reviewed connection before it can be embedded. Open App Store and connect the running application.</p>
+ <Button onClick={() => openWindow("app-store", "App Store")}>Open App Store</Button>
+ </div></div>;
+}
diff --git a/frontend/slices/app-store/components/managed-apps-catalog.tsx b/frontend/slices/app-store/components/managed-apps-catalog.tsx
new file mode 100644
index 00000000..50e816bc
--- /dev/null
+++ b/frontend/slices/app-store/components/managed-apps-catalog.tsx
@@ -0,0 +1,29 @@
+"use client";
+import { useEffect, useState } from "react";
+import { openWindow } from "@/features/appshell";
+import type { ManagedAppView } from "@/lib/managed-apps/types";
+import { Button } from "@/components/ui/button";
+
+export function ManagedAppsCatalog({ query }: { query: string }) {
+ const [apps, setApps] = useState<ManagedAppView[]>([]), [error, setError] = useState("");
+ useEffect(() => {
+ const controller = new AbortController();
+ void fetch("/api/v1/managed-apps", { cache: "no-store", signal: controller.signal }).then(async response => {
+ if (!response.ok) throw new Error("Could not load installable apps.");
+ const data = await response.json() as { apps: ManagedAppView[] };
+ setApps(data.apps); setError("");
+ }).catch(reason => { if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : "Could not load apps."); });
+ return () => controller.abort();
+ }, []);
+ return <section aria-label="Managed applications" className="space-y-3">
+ <h3 className="font-medium">Install and manage</h3>
+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
+ <div className="grid gap-3 @min-[640px]:grid-cols-3">{apps.filter(app => app.name.toLowerCase().includes(query.toLowerCase())).map(app => <article key={app.id} className="min-w-0 space-y-3 rounded-xl border p-4">
+ <h4 className="font-medium">{app.name}</h4><p className="text-xs text-muted-foreground">{app.installed ? app.state : "Not installed"}</p>
+ <p className="text-sm text-muted-foreground">{app.description}</p>
+ {app.diagnostic && <p className="text-xs text-muted-foreground">{app.diagnostic}</p>}
+ <Button size="sm" variant="outline" onClick={() => openWindow(app.id, app.name)}>{app.installed ? "Open and manage" : "Set up"}</Button>
+ </article>)}</div>
+ <p className="text-xs text-muted-foreground">Setup uses the reviewed installer and checks the host before installation. Other running tools can be connected below.</p>
+ </section>;
+}
diff --git a/frontend/slices/app-store/components/runtime-app.tsx b/frontend/slices/app-store/components/runtime-app.tsx
index 98f322b1..970bb26a 100644
--- a/frontend/slices/app-store/components/runtime-app.tsx
+++ b/frontend/slices/app-store/components/runtime-app.tsx
@@ -2,6 +2,7 @@
import { Boxes, ExternalLink } from "lucide-react";
import type { AppProps } from "../lib/host";
+import { LegacyHtmlApp } from "./legacy-html-app";
import { AppConsole } from "./app-console";
import type { AppManifest } from "./runtime-app-types";
@@ -10,7 +11,7 @@ export type { AppManifest } from "./runtime-app-types";
const isUrl = (s: string) => /^https?:\/\//i.test(s);
// Generic host for runtime apps. HTML apps whose entry is a URL render in a
-// sandboxed iframe; non-html apps whose entry is a command/script run live on
+// reviewed shell connection; non-html apps whose entry is a command/script run live on
// the VPS via the OsApi exec contract (terminal-style console). Anything else
// falls back to the manifest card.
export function RuntimeApp({ manifest, payload }: { manifest?: AppManifest } & AppProps) {
@@ -24,16 +25,7 @@ export function RuntimeApp({ manifest, payload }: { manifest?: AppManifest } & A
);
}
- if (m.runtime === "html" && isUrl(m.entry)) {
- return (
- <iframe
- title={m.title}
- src={m.entry}
- className="size-full border-0 bg-white"
- sandbox="allow-scripts allow-same-origin allow-forms"
- />
- );
- }
+ if (m.runtime === "html" && isUrl(m.entry)) return <LegacyHtmlApp manifest={m} />;
// Non-html runtime with a command/script entry → run it on the host.
if (m.runtime !== "html" && m.entry && !isUrl(m.entry)) {
diff --git a/frontend/slices/app-store/components/store-sidebar.tsx b/frontend/slices/app-store/components/store-sidebar.tsx
index 23556d80..7afda2a9 100644
--- a/frontend/slices/app-store/components/store-sidebar.tsx
+++ b/frontend/slices/app-store/components/store-sidebar.tsx
@@ -34,9 +34,11 @@ const SYSTEM_ICON: Record<"Apps" | "Features", LucideIcon> = {
export function StoreSidebar({
value,
onChange,
+ systemOnly = false,
}: {
value: StoreFilter;
onChange: (f: StoreFilter) => void;
+ systemOnly?: boolean;
}) {
const item = (f: StoreFilter, Icon: LucideIcon) => (
<Button
@@ -58,14 +60,14 @@ export function StoreSidebar({
return (
<aside className="flex w-40 shrink-0 flex-col gap-0.5 border-r border-border bg-secondary/30 p-2">
- <div className="flex items-center gap-1.5 px-2 py-1.5 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
+ {!systemOnly && <><div className="flex items-center gap-1.5 px-2 py-1.5 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
<Compass className="size-3.5" /> Discover
</div>
<TouchList className="gap-0.5">
{FILTERS.map((f) =>
item(f, f === "Featured" ? Compass : glyphIcon(FILTER_GLYPH[f as StoreCategory])),
)}
- </TouchList>
+ </TouchList></>}
<div className="mt-2 flex items-center gap-1.5 px-2 py-1.5 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
<LayoutGrid className="size-3.5" /> System
@@ -82,13 +84,15 @@ export function StoreSidebar({
export function StoreFilterChips({
value,
onChange,
+ systemOnly = false,
}: {
value: StoreFilter;
onChange: (f: StoreFilter) => void;
+ systemOnly?: boolean;
}) {
return (
<div className="flex gap-1.5 overflow-x-auto [scrollbar-width:none]">
- {[...FILTERS, ...SYSTEM_FILTERS].map((f) => (
+ {[...(systemOnly ? [] : FILTERS), ...SYSTEM_FILTERS].map((f) => (
<Button
key={f}
type="button"
diff --git a/frontend/slices/app-store/index.ts b/frontend/slices/app-store/index.ts
index 18b5fb73..0f6a569b 100644
--- a/frontend/slices/app-store/index.ts
+++ b/frontend/slices/app-store/index.ts
@@ -20,3 +20,5 @@ export { useApps, setInstalled, createApp, type AppRow } from "./lib/apps-store"
export { useDisabledIds } from "./lib/enabled-store";
// Shared glyph helpers (create-app icon picker/preview reuse the App Store set).
export { GLYPH_KEYS, glyphIcon } from "./lib/glyph";
+
+export { ShellAppsProvider, useShellApps, useExternalApps } from "./lib/shell-apps";
diff --git a/frontend/slices/app-store/lib/shell-apps.tsx b/frontend/slices/app-store/lib/shell-apps.tsx
new file mode 100644
index 00000000..0bbfc113
--- /dev/null
+++ b/frontend/slices/app-store/lib/shell-apps.tsx
@@ -0,0 +1,73 @@
+"use client";
+
+import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { Globe } from "lucide-react";
+import type { AppDescriptor } from "@/features/appshell";
+import { shellAppId, type ShellAppMutation, type ShellAppSnapshot } from "@/lib/contracts/shell-app";
+
+const EMPTY: ShellAppSnapshot = { schemaVersion: 1, revision: "", configurable: false, apps: [] };
+type ShellAppsContext = {
+ active: boolean; loading: boolean; error: string; snapshot: ShellAppSnapshot;
+ refresh: () => Promise<void>;
+ mutate: (value: Pick<ShellAppMutation, "action" | "app" | "id">) => Promise<void>;
+};
+const Context = createContext<ShellAppsContext>({ active: false, loading: false, error: "", snapshot: EMPTY, refresh: async () => {}, mutate: async () => { throw new Error("Owner access required."); } });
+const errors: Record<string, string> = {
+ app_id_exists: "That app ID is already registered. Choose another ID.",
+ app_cookie_scope_conflict: "This address shares MSO's login cookies. Use a different host address, not just a different port.",
+ plain_app_url_required: "Use an HTTP or HTTPS address without credentials, query parameters or fragments.",
+ surface_registry_changed_reload: "The app list changed. Refresh and review your changes before saving again.",
+ surface_registry_managed_by_environment: "This app list is managed by deployment configuration.",
+ app_owned_by_another_surface: "This entry belongs to another surface. Use a different app ID.",
+};
+export function ShellAppsProvider({ active, children }: { active: boolean; children: ReactNode }) {
+ const [snapshot, setSnapshot] = useState(EMPTY);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState("");
+ const generation = useRef(0);
+ const refresh = useCallback(async () => {
+ if (!active) return;
+ const token = ++generation.current;
+ setLoading(true);
+ try {
+ const response = await fetch("/api/v1/shell-apps", { cache: "no-store" });
+ if (!response.ok) throw new Error(response.status === 403 ? "Owner access is required." : "Could not load connected apps.");
+ const next = await response.json() as ShellAppSnapshot;
+ if (next.schemaVersion !== 1 || !Array.isArray(next.apps)) throw new Error("Unsupported app registry version.");
+ if (token === generation.current) { setSnapshot(next); setError(""); }
+ } catch (reason) {
+ if (token === generation.current) { setSnapshot(EMPTY); setError(reason instanceof Error ? reason.message : "Could not load apps."); }
+ } finally { if (token === generation.current) setLoading(false); }
+ }, [active]);
+ const invalidate = useCallback(() => { generation.current++; }, []);
+ useEffect(() => {
+ if (!active) return;
+ const frame = requestAnimationFrame(() => { void refresh(); });
+ const poll = setInterval(() => { if (document.visibilityState === "visible") void refresh(); }, 30_000);
+ const focus = () => { void refresh(); };
+ window.addEventListener("focus", focus);
+ return () => { invalidate(); cancelAnimationFrame(frame); clearInterval(poll); window.removeEventListener("focus", focus); };
+ }, [active, refresh, invalidate]);
+ const mutate = useCallback(async (value: Pick<ShellAppMutation, "action" | "app" | "id">) => {
+ if (!active || !snapshot.configurable) throw new Error("Owner access to a configurable app registry is required.");
+ const response = await fetch("/api/v1/shell-apps", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...value, schemaVersion: 1, expectedRevision: snapshot.revision, confirm: true }) });
+ const data = await response.json() as { error?: string };
+ if (!response.ok) { if (response.status === 409) await refresh(); throw new Error(errors[data.error ?? ""] ?? "Could not save this app. Check its ID and address."); }
+ await refresh();
+ }, [active, snapshot, refresh]);
+ const value = useMemo(() => ({ active, loading: active && loading, error: active ? error : "", snapshot: active ? snapshot : EMPTY, refresh, mutate }), [active, loading, error, snapshot, refresh, mutate]);
+ return <Context.Provider value={value}>{children}</Context.Provider>;
+}
+export const useShellApps = () => useContext(Context);
+export function useExternalApps(): AppDescriptor[] {
+ const { snapshot } = useShellApps();
+ const signature = JSON.stringify(snapshot.apps.map(({ id, title }) => ({ id, title })));
+ return useMemo(() => (JSON.parse(signature) as Array<{ id: string; title: string }>).map(app => ({
+ id: shellAppId(app.id), slug: shellAppId(app.id), title: app.title, icon: Globe,
+ gradient: "var(--primary)", prefetch: "never" as const, defaultSize: { w: 1100, h: 720 },
+ load: async () => {
+ const { default: ExternalApp } = await import("../components/external-app");
+ return { default: () => createElement(ExternalApp, { id: app.id }) };
+ },
+ })), [signature]);
+}
diff --git a/frontend/slices/n8n/components/n8n-embed-panel.test.tsx b/frontend/slices/n8n/components/n8n-embed-panel.test.tsx
index 23b652c6..5ced7372 100644
--- a/frontend/slices/n8n/components/n8n-embed-panel.test.tsx
+++ b/frontend/slices/n8n/components/n8n-embed-panel.test.tsx
@@ -12,7 +12,7 @@ describe("blocked external editor rendering", () => {
});
it("remounts the iframe whenever the reviewed sandbox policy changes", () => {
- const source = readFileSync(new URL("./n8n-embed-panel.tsx", import.meta.url), "utf8");
+ const source = readFileSync(new URL("../../../../components/external-app-frame.tsx", import.meta.url), "utf8");
expect(source).toContain('key={`${revision}:${app.sandbox}`}');
});
it("fails closed if a destination is missing even without the blocked flag", () => {
diff --git a/frontend/slices/n8n/components/n8n-embed-panel.tsx b/frontend/slices/n8n/components/n8n-embed-panel.tsx
index f0e6842e..1402f1d1 100644
--- a/frontend/slices/n8n/components/n8n-embed-panel.tsx
+++ b/frontend/slices/n8n/components/n8n-embed-panel.tsx
@@ -1,34 +1,6 @@
"use client";
-
-import { useEffect, useState } from "react";
-import { ExternalLink, LogIn, RefreshCw } from "lucide-react";
import type { WorkflowEmbed } from "@/lib/contracts/surface-app";
-import { Button } from "@/components/ui/button";
-
+import { ExternalAppFrame } from "@/components/external-app-frame";
export function N8nEmbedPanel({ app }: { app: WorkflowEmbed }) {
- const [revision, setRevision] = useState(0);
- const [loading, setLoading] = useState(true);
- const [slow, setSlow] = useState(false);
- useEffect(() => {
- const timer = setTimeout(() => setSlow(true), 15000);
- return () => clearTimeout(timer);
- }, [revision]);
- if (app.blocked || !app.url) return <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 p-6 text-center text-sm" data-slot="n8n-embed-panel" role="alert">
- <p>{app.reason || "This editor destination is unavailable."}</p>
- <p className="text-xs text-muted-foreground">No editor or login link is opened. Configure a separate cookie-isolated origin before connecting.</p>
- </div>;
- const reload = () => { setLoading(true); setSlow(false); setRevision((value) => value + 1); };
- return <div className="flex h-full min-h-0 min-w-0 flex-col" data-slot="n8n-embed-panel">
- <div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b px-3 py-1.5">
- <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground" title={app.origin}>{app.origin}</span>
- {app.loginUrl ? <Button asChild variant="ghost" size="sm"><a href={app.loginUrl} target="_blank" rel="noopener noreferrer"><LogIn className="size-4"/><span>Sign in</span></a></Button> : null}
- <Button asChild variant="outline" size="sm"><a href={app.url} target="_blank" rel="noopener noreferrer"><ExternalLink className="size-4"/><span>Open {app.title}</span></a></Button>
- {app.renderer === "iframe" ? <Button variant="ghost" size="icon" onClick={reload} aria-label={`Reload ${app.title}`} title={`Reload ${app.title}`}><RefreshCw className="size-4"/></Button> : null}
- </div>
- {app.renderer === "iframe" ? <div className="relative min-h-0 min-w-0 flex-1">
- {loading ? <div className="absolute inset-x-0 top-0 z-10 border-b bg-background px-3 py-2 text-xs text-muted-foreground" role="status">{slow ? `Taking longer than expected. Open ${app.title} in a new tab if its login or frame policy blocks embedding.` : `Loading ${app.title}…`}</div> : null}
- <iframe key={`${revision}:${app.sandbox}`} src={app.url} title="n8n automation editor" sandbox={app.sandbox} referrerPolicy="no-referrer" className="h-full w-full border-0 bg-background" onLoad={() => setLoading(false)} onError={() => { setLoading(true); setSlow(true); }}/>
- </div> : <div className="flex min-h-0 flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">{app.reason || `${app.title} opens in a separate tab. Embedded access is not enabled for this provider.`}</div>}
- <p className="shrink-0 border-t px-3 py-1.5 text-xs text-muted-foreground [@media(max-height:520px)]:sr-only">{app.title} keeps its own login. Sign in in a new tab, then reload here. If embedding is blocked, use Open {app.title}.</p>
- </div>;
+ return <ExternalAppFrame app={app} frameTitle="n8n automation editor" />;
}
diff --git a/lib/contracts/shell-app.ts b/lib/contracts/shell-app.ts
new file mode 100644
index 00000000..afa81cb3
--- /dev/null
+++ b/lib/contracts/shell-app.ts
@@ -0,0 +1,25 @@
+import type { WorkflowEmbed } from "./surface-app";
+
+export type ShellAppDefinition = {
+ id: string;
+ title: string;
+ description: string;
+ url: string;
+ mode: "embed" | "tab";
+};
+export type ShellAppView = WorkflowEmbed & { definition: ShellAppDefinition };
+export type ShellAppSnapshot = {
+ schemaVersion: 1;
+ revision: string;
+ configurable: boolean;
+ apps: ShellAppView[];
+};
+export type ShellAppMutation = {
+ schemaVersion: 1;
+ action: "add" | "update" | "remove";
+ expectedRevision: string;
+ confirm: true;
+ app?: ShellAppDefinition;
+ id?: string;
+};
+export const shellAppId = (id: string) => `external-${id}`;
diff --git a/lib/contracts/surface-app.ts b/lib/contracts/surface-app.ts
index 13ec45a9..50e72ae5 100644
--- a/lib/contracts/surface-app.ts
+++ b/lib/contracts/surface-app.ts
@@ -1,7 +1,7 @@
export type SurfaceRenderer = "iframe" | "remote";
export type SurfacePresentation = "inline" | "fullscreen" | "pip";
export type SurfaceEnvironment = "development" | "preview" | "production" | "other";
-export type SurfacePlacement = "workflows" | "n8n" | "mcp-page";
+export type SurfacePlacement = "workflows" | "n8n" | "mcp-page" | "shell";
export type SurfaceApp = {
id: string;
diff --git a/lib/host/shell-apps-api.ts b/lib/host/shell-apps-api.ts
new file mode 100644
index 00000000..d48ee34d
--- /dev/null
+++ b/lib/host/shell-apps-api.ts
@@ -0,0 +1,2 @@
+export { shellAppSettings, manageShellApp } from "@/lib/surfaces/shell-apps";
+export { SurfaceConfigError } from "@/lib/surfaces/registry-store";
diff --git a/lib/surfaces/config.ts b/lib/surfaces/config.ts
index fe8025e1..03b0351d 100644
--- a/lib/surfaces/config.ts
+++ b/lib/surfaces/config.ts
@@ -23,11 +23,11 @@ const SAFE_SANDBOX = new Set([
const PRESENTATIONS = new Set<SurfacePresentation>(["inline", "fullscreen", "pip"]);
const ENVIRONMENTS = new Set<SurfaceEnvironment>(["development", "preview", "production", "other"]);
-function safeOrigin(value: unknown): string | null {
+function safeOrigin(value: unknown, allowHttp = false): string | null {
if (typeof value !== "string") return null;
try {
const url = new URL(value);
- if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) return null;
+ if ((url.protocol !== "https:" && !(allowHttp && url.protocol === "http:")) || url.username || url.password || url.pathname !== "/" || url.search || url.hash) return null;
return url.origin;
} catch { return null; }
}
@@ -60,7 +60,8 @@ function parseApp(entry: unknown, seen: Set<string>): SurfaceApp | null {
if (!entry || typeof entry !== "object") return null;
const row = entry as Record<string, unknown>;
const id = boundedText(row.id, true), title = boundedText(row.title, true);
- const origin = safeOrigin(row.origin), startPath = safePath(row.startPath);
+ const shellOnly = Array.isArray(row.placements) && row.placements.length === 1 && row.placements[0] === "shell";
+ const origin = safeOrigin(row.origin, shellOnly && row.renderer === "remote"), startPath = safePath(row.startPath);
const renderer = row.renderer, presentation = row.presentation, environment = row.environment;
if (!id || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(id) || seen.has(id) || !title || !origin || !startPath) return null;
if (renderer !== "iframe" && renderer !== "remote") return null;
@@ -71,7 +72,7 @@ function parseApp(entry: unknown, seen: Set<string>): SurfaceApp | null {
if (row.externalAuthPath !== undefined && !externalAuthPath) return null;
const project = boundedText(row.project, true);
if (row.project !== undefined && !project) return null;
- if (row.placements !== undefined && (!Array.isArray(row.placements) || row.placements.some((value) => value !== "workflows" && value !== "n8n" && value !== "mcp-page"))) return null;
+ if (row.placements !== undefined && (!Array.isArray(row.placements) || row.placements.some((value) => value !== "workflows" && value !== "n8n" && value !== "mcp-page" && value !== "shell"))) return null;
const placements = row.placements === undefined ? undefined : [...new Set(row.placements)] as SurfacePlacement[];
seen.add(id);
const reason = boundedText(row.reason);
diff --git a/lib/surfaces/manage.ts b/lib/surfaces/manage.ts
index 5caf7949..aacbdace 100644
--- a/lib/surfaces/manage.ts
+++ b/lib/surfaces/manage.ts
@@ -1,31 +1,11 @@
-import { constants, promises as fs } from "node:fs";
-import { createHash, randomUUID } from "node:crypto";
-import { configuredSurfaceApps, surfaceRegistryPath } from "./config";
-import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { configuredSurfaceApps } from "./config";
+import { readSurfaceRegistry, registryRevision, mutateSurfaceRegistry, SurfaceConfigError } from "./registry-store";
+export { SurfaceConfigError } from "./registry-store";
-const MAX_BYTES = 16_384;
const APP_FIELDS = new Set(["id", "title", "description", "origin", "startPath", "renderer", "presentation", "environment", "sandbox", "externalAuthPath", "reason", "project", "placements"]);
-export class SurfaceConfigError extends Error {
- constructor(message: string, readonly status = 400) { super(message); }
-}
-async function readRegistry() {
- const env = process.env.MSO_SURFACE_APPS_JSON;
- if (env !== undefined) return { raw: env, managedByEnvironment: true };
- let handle;
- try {
- handle = await fs.open(/* turbopackIgnore: true */ surfaceRegistryPath(), constants.O_RDONLY | constants.O_NOFOLLOW);
- const stat = await handle.stat();
- if (!stat.isFile() || stat.size > MAX_BYTES || stat.uid !== process.getuid?.()) throw new SurfaceConfigError("unsafe_surface_registry", 409);
- return { raw: await handle.readFile("utf8"), managedByEnvironment: false };
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return { raw: "[]", managedByEnvironment: false };
- throw error;
- } finally { await handle?.close(); }
-}
-const revision = (raw: string) => createHash("sha256").update(raw).digest("hex");
export async function surfaceRegistrySnapshot() {
- const state = await readRegistry();
- return { revision: revision(state.raw), configurable: !state.managedByEnvironment, apps: await configuredSurfaceApps(state.raw) };
+ const state = await readSurfaceRegistry();
+ return { revision: registryRevision(state.raw), configurable: !state.managedByEnvironment, apps: await configuredSurfaceApps(state.raw) };
}
/** Explicit owner operation. Never accepts a filesystem path or credential values. */
export async function saveWorkflowSurface(input: Record<string, unknown>) {
@@ -39,19 +19,14 @@ export async function saveWorkflowSurface(input: Record<string, unknown>) {
const normalized = await configuredSurfaceApps(JSON.stringify([{ ...row, placements: [selectedPlacement] }]));
if (normalized.length !== 1) throw new SurfaceConfigError("invalid_surface_metadata");
const selected = normalized[0];
- return withSecurityStoreLock(surfaceRegistryPath(), async () => {
- const current = await readRegistry();
- if (current.managedByEnvironment) throw new SurfaceConfigError("surface_registry_managed_by_environment", 409);
- if (input.expectedRevision !== revision(current.raw)) throw new SurfaceConfigError("surface_registry_changed_reload", 409);
- let entries: Array<Record<string, unknown>>;
- try { entries = JSON.parse(current.raw); } catch { throw new SurfaceConfigError("invalid_existing_surface_registry", 409); }
- if (!Array.isArray(entries) || entries.some((entry) => !entry || typeof entry !== "object" || Array.isArray(entry))) throw new SurfaceConfigError("invalid_existing_surface_registry", 409);
+ const result = await mutateSurfaceRegistry(input.expectedRevision, async entries => {
const matches = entries.filter((entry) => entry.id === selected.id);
if (matches.length > 1) throw new SurfaceConfigError("duplicate_surface_identity", 409);
const replacement = { ...selected };
// Missing placements is legacy Page approval only when the existing row is
// itself a valid reviewed app. Invalid historical bytes cannot grant Page.
const existing = matches[0];
+ if (Array.isArray(existing?.placements) && existing.placements.includes("shell")) throw new SurfaceConfigError("surface_owned_by_shell", 409);
const existingNormalized = existing ? (await configuredSurfaceApps(JSON.stringify([existing])))[0] : undefined;
const sharesPage = Boolean(existingNormalized && (existingNormalized.placements === undefined ||
existingNormalized.placements?.includes("mcp-page")));
@@ -65,11 +40,7 @@ export async function saveWorkflowSurface(input: Record<string, unknown>) {
else delete replacement.externalAuthPath;
}
const next = matches.length ? entries.map((entry) => entry.id === selected.id ? replacement : entry) : [...entries, replacement];
- const raw = JSON.stringify(next, null, 2) + "\n";
- if (next.length > 16 || Buffer.byteLength(raw) > MAX_BYTES) throw new SurfaceConfigError("surface_registry_capacity", 409);
- const file = surfaceRegistryPath(), temporary = `${file}.${randomUUID()}.tmp`;
- try { await fs.writeFile(temporary, raw, { mode: 0o600, flag: "wx" }); await fs.rename(temporary, file); }
- finally { await fs.unlink(temporary).catch(() => undefined); }
- return { revision: revision(raw), configurable: true, id: selected.id };
+ return next;
});
+ return { ...result, id: selected.id };
}
diff --git a/lib/surfaces/registry-store.ts b/lib/surfaces/registry-store.ts
new file mode 100644
index 00000000..a2137ead
--- /dev/null
+++ b/lib/surfaces/registry-store.ts
@@ -0,0 +1,44 @@
+import { constants, promises as fs } from "node:fs";
+import { createHash, randomUUID } from "node:crypto";
+import { surfaceRegistryPath } from "./config";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+
+const MAX_BYTES = 16_384;
+export class SurfaceConfigError extends Error {
+ constructor(message: string, readonly status = 400) { super(message); }
+}
+export const registryRevision = (raw: string) => createHash("sha256").update(raw).digest("hex");
+export async function readSurfaceRegistry() {
+ const env = process.env.MSO_SURFACE_APPS_JSON;
+ if (env !== undefined) return { raw: env, managedByEnvironment: true };
+ let handle;
+ try {
+ handle = await fs.open(/* turbopackIgnore: true */ surfaceRegistryPath(), constants.O_RDONLY | constants.O_NOFOLLOW);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size > MAX_BYTES || stat.uid !== process.getuid?.()) throw new SurfaceConfigError("unsafe_surface_registry", 409);
+ return { raw: await handle.readFile("utf8"), managedByEnvironment: false };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { raw: "[]", managedByEnvironment: false };
+ throw error;
+ } finally { await handle?.close(); }
+}
+export async function mutateSurfaceRegistry(
+ expectedRevision: unknown,
+ update: (entries: Array<Record<string, unknown>>) => Promise<Array<Record<string, unknown>>>,
+) {
+ return withSecurityStoreLock(surfaceRegistryPath(), async () => {
+ const current = await readSurfaceRegistry();
+ if (current.managedByEnvironment) throw new SurfaceConfigError("surface_registry_managed_by_environment", 409);
+ if (expectedRevision !== registryRevision(current.raw)) throw new SurfaceConfigError("surface_registry_changed_reload", 409);
+ let entries: Array<Record<string, unknown>>;
+ try { entries = JSON.parse(current.raw); } catch { throw new SurfaceConfigError("invalid_existing_surface_registry", 409); }
+ if (!Array.isArray(entries) || entries.some(entry => !entry || typeof entry !== "object" || Array.isArray(entry))) throw new SurfaceConfigError("invalid_existing_surface_registry", 409);
+ const next = await update(entries);
+ const raw = JSON.stringify(next, null, 2) + "\n";
+ if (next.length > 16 || Buffer.byteLength(raw) > MAX_BYTES) throw new SurfaceConfigError("surface_registry_capacity", 409);
+ const file = surfaceRegistryPath(), temporary = `${file}.${randomUUID()}.tmp`;
+ try { await fs.writeFile(temporary, raw, { mode: 0o600, flag: "wx" }); await fs.rename(temporary, file); }
+ finally { await fs.unlink(temporary).catch(() => undefined); }
+ return { revision: registryRevision(raw), configurable: true };
+ });
+}
diff --git a/lib/surfaces/shell-apps.test.ts b/lib/surfaces/shell-apps.test.ts
new file mode 100644
index 00000000..67889ef8
--- /dev/null
+++ b/lib/surfaces/shell-apps.test.ts
@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { manageShellApp, shellAppSettings } from "./shell-apps";
+import { configuredSurfaceApps } from "./config";
+import { saveWorkflowSurface } from "./manage";
+
+let dir: string, file: string;
+const origin = "https://cockpit.example.test";
+const app = { id: "custom-editor", title: "Custom editor", description: "My tool", url: "https://editor.example.test/editor", mode: "embed" };
+const save = async (change: Record<string, unknown> = {}, action = "add") => manageShellApp({ schemaVersion: 1, action, app: { ...app, ...change }, expectedRevision: (await shellAppSettings(origin)).revision, confirm: true }, origin);
+beforeEach(async () => {
+ dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-shell-app-")); file = path.join(dir, "registry.json");
+ vi.stubEnv("MSO_SURFACE_APPS_FILE", file); vi.stubEnv("MSO_SURFACE_APPS_JSON", undefined);
+ vi.stubEnv("OS_PUBLIC_ORIGIN", origin); vi.stubEnv("OS_MCP_UI_ORIGIN", "https://widgets.example.test");
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "");
+});
+afterEach(async () => { vi.unstubAllEnvs(); await fs.rm(dir, { recursive: true, force: true }); });
+
+describe("server-owned connected applications", () => {
+ it("persists a reviewed embed, edits it by revision and disconnects only its metadata", async () => {
+ const before = await shellAppSettings(origin);
+ await save();
+ let snapshot = await shellAppSettings(origin);
+ expect(snapshot.schemaVersion).toBe(1); expect(snapshot.revision).not.toBe(before.revision);
+ expect(snapshot.apps[0]).toMatchObject({ title: app.title, url: app.url, renderer: "iframe" });
+ expect((await fs.stat(file)).mode & 0o777).toBe(0o600);
+ await save({ title: "Renamed" }, "update");
+ snapshot = await shellAppSettings(origin);
+ expect(snapshot.apps[0].title).toBe("Renamed");
+ await manageShellApp({ schemaVersion: 1, action: "remove", id: app.id, expectedRevision: snapshot.revision, confirm: true }, origin);
+ expect((await shellAppSettings(origin)).apps).toEqual([]);
+ });
+ it("supports an IP without a domain as a separate-tab destination", async () => {
+ await save({ url: "http://192.0.2.10:5678/" });
+ expect((await shellAppSettings(origin)).apps[0]).toMatchObject({ renderer: "remote", url: "http://192.0.2.10:5678/" });
+ const row = JSON.parse(await fs.readFile(file, "utf8"))[0];
+ expect(await configuredSurfaceApps(JSON.stringify([{ ...row, placements: ["mcp-page"] }]))).toEqual([]);
+ expect(await configuredSurfaceApps(JSON.stringify([{ ...row, placements: ["shell", "mcp-page"] }]))).toEqual([]);
+ expect(await configuredSurfaceApps(JSON.stringify([{ ...row, renderer: "iframe" }]))).toEqual([]);
+ });
+ it.each([origin, "https://cockpit.example.test:9443", "http://cockpit.example.test:5678", "https://widgets.example.test"])("rejects cockpit cookie/origin conflicts: %s", async url => {
+ await expect(save({ url })).rejects.toThrow("app_cookie_scope_conflict");
+ await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+ it.each([
+ { url: "javascript:alert(1)" }, { url: "https://user:[email protected]" },
+ { url: "https://editor.example.test/?token=private" }, { url: "https://editor.example.test/#token" },
+ { token: "not-allowed" }, { command: "run-tool" }, { id: "../escape" }, { mode: "native" },
+ ])("rejects executable and secret-bearing metadata %j", async change => { await expect(save(change)).rejects.toThrow(); });
+ it("never overwrites another placement or grants MCP Page visibility", async () => {
+ const other = { id: app.id, title: "Page", origin: "https://page.example.test", startPath: "/", description: "", renderer: "iframe", presentation: "inline", environment: "production" };
+ await fs.writeFile(file, JSON.stringify([other]));
+ await expect(save()).rejects.toThrow("app_id_exists");
+ await expect(save({}, "update")).rejects.toThrow("app_owned_by_another_surface");
+ await save({ id: "second" });
+ expect(JSON.parse(await fs.readFile(file, "utf8"))[0]).toEqual(other);
+ expect((await shellAppSettings(origin)).apps).toHaveLength(1);
+ expect((await configuredSurfaceApps()).find(row => row.id === "second")?.placements).toEqual(["shell"]);
+ });
+ it("rejects a stale mutation and concurrent lost writes", async () => {
+ const revision = (await shellAppSettings(origin)).revision;
+ const request = { schemaVersion: 1, action: "add", app, expectedRevision: revision, confirm: true };
+ const results = await Promise.allSettled([manageShellApp(request, origin), manageShellApp({ ...request, app: { ...app, id: "other" } }, origin)]);
+ expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1);
+ expect((await shellAppSettings(origin)).apps).toHaveLength(1);
+ });
+ it("shares revision authority with workflow surfaces and preserves their entries", async () => {
+ await save();
+ await saveWorkflowSurface({ app: { id: "n8n", title: "n8n", description: "", origin: "https://automation.example.test", startPath: "/", renderer: "iframe", presentation: "inline", environment: "production", placements: ["n8n"] }, expectedRevision: (await shellAppSettings(origin)).revision, confirm: true });
+ await save({ title: "New title" }, "update");
+ expect((await configuredSurfaceApps()).map(row => row.id)).toEqual([app.id, "n8n"]);
+ });
+ it("prevents workflow updates from taking ownership of shell entries", async () => {
+ await save();
+ const before = await fs.readFile(file, "utf8");
+ await expect(saveWorkflowSurface({ app: { id: app.id, title: "Replacement", description: "", origin: "https://automation.example.test", startPath: "/", renderer: "iframe", presentation: "inline", environment: "production", placements: ["n8n"] }, expectedRevision: (await shellAppSettings(origin)).revision, confirm: true })).rejects.toThrow("surface_owned_by_shell");
+ expect(await fs.readFile(file, "utf8")).toBe(before);
+ });
+ it("blocks previously configured entries when cockpit origin changes", async () => {
+ await save();
+ const snapshot = await shellAppSettings("https://editor.example.test");
+ expect(snapshot.apps[0]).toMatchObject({ blocked: true, renderer: "remote" });
+ expect(snapshot.apps[0].url).toBeUndefined();
+ });
+ it("rejects malformed and environment-owned stores without modifying them", async () => {
+ await fs.writeFile(file, "{broken");
+ await expect(save()).rejects.toThrow("invalid_existing_surface_registry");
+ expect(await fs.readFile(file, "utf8")).toBe("{broken");
+ vi.stubEnv("MSO_SURFACE_APPS_JSON", "[]");
+ await expect(save()).rejects.toThrow("surface_registry_managed_by_environment");
+ });
+ it("requires the supported wire version and explicit review", async () => {
+ const base = { schemaVersion: 1, action: "add", app, expectedRevision: (await shellAppSettings(origin)).revision, confirm: true };
+ await expect(manageShellApp({ ...base, schemaVersion: 2 }, origin)).rejects.toThrow("invalid_shell_request");
+ await expect(manageShellApp({ ...base, confirm: false }, origin)).rejects.toThrow("invalid_shell_request");
+ });
+});
diff --git a/lib/surfaces/shell-apps.ts b/lib/surfaces/shell-apps.ts
new file mode 100644
index 00000000..9d655ec5
--- /dev/null
+++ b/lib/surfaces/shell-apps.ts
@@ -0,0 +1,74 @@
+import type { ShellAppDefinition, ShellAppSnapshot, ShellAppView } from "@/lib/contracts/shell-app";
+import type { SurfaceApp } from "@/lib/contracts/surface-app";
+import { configuredSurfaceApps } from "./config";
+import { externalSurfaceSharesSession } from "./cookie-policy";
+import { readSurfaceRegistry, registryRevision, mutateSurfaceRegistry, SurfaceConfigError } from "./registry-store";
+
+const ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
+const SANDBOX = "allow-scripts allow-same-origin allow-forms";
+const text = (value: unknown, max: number) => typeof value === "string" && value.trim().length > 0 && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value);
+const object = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === "object" && !Array.isArray(value);
+
+function origins(requestOrigin: string) {
+ return [requestOrigin, process.env.OS_PUBLIC_ORIGIN, process.env.OS_MCP_UI_ORIGIN].flatMap(value => {
+ try { return value ? [new URL(value).origin] : []; } catch { return []; }
+ });
+}
+function blocked(origin: string, requestOrigin: string) {
+ const cockpit = origins(requestOrigin);
+ return cockpit.includes(origin) || externalSurfaceSharesSession(origin, cockpit);
+}
+function definition(value: unknown): ShellAppDefinition {
+ if (!object(value) || Object.keys(value).some(key => !["id", "title", "description", "url", "mode"].includes(key))) throw new SurfaceConfigError("invalid_shell_app");
+ if (typeof value.id !== "string" || !ID.test(value.id) || !text(value.title, 120) ||
+ typeof value.description !== "string" || value.description.length > 240 ||
+ /[\u0000-\u001f\u007f]/.test(value.description) ||
+ !text(value.url, 2048) || !["embed", "tab"].includes(String(value.mode))) throw new SurfaceConfigError("invalid_shell_app");
+ let url: URL;
+ try { url = new URL(value.url as string); } catch { throw new SurfaceConfigError("invalid_app_url"); }
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash ||
+ /[\\\u0000-\u001f\u007f]/.test(value.url as string)) throw new SurfaceConfigError("plain_app_url_required");
+ return { id: value.id, title: (value.title as string).trim(), description: value.description.trim(), url: url.href, mode: value.mode as "embed" | "tab" };
+}
+function view(app: SurfaceApp, requestOrigin: string): ShellAppView {
+ const url = new URL(app.startPath, app.origin).href;
+ const def: ShellAppDefinition = { id: app.id, title: app.title, description: app.description, url, mode: app.renderer === "iframe" ? "embed" : "tab" };
+ const base = { id: app.id, title: app.title, description: app.description, origin: app.origin, sandbox: SANDBOX, definition: def };
+ if (blocked(app.origin, requestOrigin)) return { ...base, renderer: "remote", blocked: true, reason: "This address shares MSO's session cookie scope. Use a separate host address." };
+ const insecure = new URL(app.origin).protocol !== "https:";
+ return { ...base, url, renderer: insecure ? "remote" : app.renderer,
+ ...(insecure ? { reason: "HTTP apps open separately. Use an HTTPS address to embed this app." } : {}) };
+}
+export async function shellAppSettings(requestOrigin: string): Promise<ShellAppSnapshot> {
+ const state = await readSurfaceRegistry();
+ const apps = await configuredSurfaceApps(state.raw);
+ return { schemaVersion: 1, revision: registryRevision(state.raw), configurable: !state.managedByEnvironment,
+ apps: apps.filter(app => app.placements?.includes("shell")).map(app => view(app, requestOrigin)) };
+}
+export async function manageShellApp(input: Record<string, unknown>, requestOrigin: string) {
+ if (input.schemaVersion !== 1 || input.confirm !== true ||
+ Object.keys(input).some(key => !["schemaVersion", "action", "expectedRevision", "confirm", "app", "id"].includes(key)) ||
+ !["add", "update", "remove"].includes(String(input.action))) throw new SurfaceConfigError("invalid_shell_request");
+ const removing = input.action === "remove";
+ if ((removing && input.app !== undefined) || (!removing && input.id !== undefined)) throw new SurfaceConfigError("invalid_shell_request");
+ const app = removing ? undefined : definition(input.app);
+ const id = app?.id ?? input.id;
+ if (typeof id !== "string" || !ID.test(id)) throw new SurfaceConfigError("invalid_shell_app");
+ const url = app ? new URL(app.url) : undefined;
+ if (url && blocked(url.origin, requestOrigin)) throw new SurfaceConfigError("app_cookie_scope_conflict");
+ const row = app && url ? {
+ id, title: app.title, description: app.description, origin: url.origin, startPath: url.pathname,
+ renderer: app.mode === "embed" && url.protocol === "https:" ? "iframe" : "remote",
+ presentation: "inline", environment: "production", sandbox: SANDBOX, placements: ["shell"],
+ } : undefined;
+ if (row && (await configuredSurfaceApps(JSON.stringify([row]))).length !== 1) throw new SurfaceConfigError("invalid_shell_app");
+ const result = await mutateSurfaceRegistry(input.expectedRevision, async entries => {
+ const matches = entries.filter(entry => entry.id === id);
+ if (input.action === "add" && matches.length) throw new SurfaceConfigError("app_id_exists", 409);
+ if (input.action !== "add" && matches.length !== 1) throw new SurfaceConfigError("app_not_found_or_ambiguous", 409);
+ if (matches.some(entry => !Array.isArray(entry.placements) || entry.placements.length !== 1 || entry.placements[0] !== "shell")) throw new SurfaceConfigError("app_owned_by_another_surface", 409);
+ if (removing) return entries.filter(entry => entry.id !== id);
+ return input.action === "add" ? [...entries, row!] : entries.map(entry => entry.id === id ? row! : entry);
+ });
+ return { ...result, id, schemaVersion: 1 };
+}
diff --git a/scripts/cli/commands-runtime.sh b/scripts/cli/commands-runtime.sh
index 67870f88..be1edd49 100755
--- a/scripts/cli/commands-runtime.sh
+++ b/scripts/cli/commands-runtime.sh
@@ -34,6 +34,8 @@ case "$cmd" in
mapp)
sub="${1:-list}"; shift || true
case "$sub" in
+ shell-list) jget "/api/v1/shell-apps" ;;
+ shell-save) shell_input="${1:?JSON or @file required}"; if [ "${shell_input:0:1}" = "@" ]; then shell_input=$(cat -- "${shell_input:1}"); fi; jpost "/api/v1/shell-apps" "$shell_input" ;;
list) jget "/api/v1/managed-apps" ;;
show) jget "/api/v1/managed-apps/$(enc "${1:?id}")" ;;
logs) jget "/api/v1/managed-apps/$(enc "${1:?id}")/logs" ;;
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 543eb215..1691143a 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -31,7 +31,7 @@ U_channels="channels list|create --input <JSON|@file>|save <id> --revision <n> -
U_provider="provider list|show <id>|setup <provider> <user> <connection>|set <id>|rm <id>|doctor [id]|projects|zones"
U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo] | agent --oneshot <prompt> [--json] [--approve-scope read|write|exec]"
-U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
+U_mapp="mapp shell-list|shell-save <JSON|@file>|list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows>|stream <id>|close <id>"
U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"
U_service="service status|start|stop|restart|logs [n]"
diff --git a/scripts/e2e/mcp-settings.mjs b/scripts/e2e/mcp-settings.mjs
index 7b108497..04d66844 100644
--- a/scripts/e2e/mcp-settings.mjs
+++ b/scripts/e2e/mcp-settings.mjs
@@ -50,7 +50,14 @@ async function chooseProjectTarget(page, fixture) {
await input.fill(fixture.dir);
await expect(input).toHaveValue(fixture.dir);
await expect(useProject).toBeEnabled();
+ const inspected = page.waitForResponse(response => {
+ if (!response.url().endsWith("/api/v1/project-mcp") || response.request().method() !== "POST") return false;
+ const body = response.request().postDataJSON();
+ return body?.action === "inspect" && body.project === fixture.dir;
+ }, { timeout: 15000 });
await useProject.click();
+ expect((await inspected).status()).toBe(200);
+ await expect(useProject).toBeEnabled();
} finally { release(); await page.unroute("**/api/v1/project-mcp", hold); }
}
export async function mcpOwnerJourneys(page, fixture) {
diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjs
index 4c154ac2..e248ba69 100644
--- a/scripts/e2e/release.mjs
+++ b/scripts/e2e/release.mjs
@@ -13,6 +13,7 @@ import { camoufoxConnectionJourney } from "./camoufox-connection.mjs";
import { memoryBackupHistoryJourney } from "./memory-backup-history.mjs";
import { aiProviderSwitchJourney } from "./ai-provider-switch.mjs";
+execFileSync(process.execPath, ["scripts/e2e/shell-apps.mjs"], { stdio: "inherit" });
execFileSync(process.execPath, ["scripts/e2e/mcp-page.mjs"], { stdio: "inherit" });
execFileSync(process.execPath, ["scripts/e2e/workflow-embeds.mjs"], { stdio: "inherit" });
execFileSync(process.execPath, ["scripts/e2e/organization-flow.mjs"], { stdio: "inherit" });
diff --git a/scripts/e2e/shell-apps.mjs b/scripts/e2e/shell-apps.mjs
new file mode 100644
index 00000000..7c1d3103
--- /dev/null
+++ b/scripts/e2e/shell-apps.mjs
@@ -0,0 +1,77 @@
+#!/usr/bin/env node
+import { chromium, expect } from "@playwright/test";
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { releaseFixture } from "./release-fixture.mjs";
+
+const fixture = await releaseFixture();
+let browser;
+try {
+ browser = await chromium.launch({ headless: true });
+ for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }, { width: 844, height: 390 }]) {
+ const context = await browser.newContext({ viewport });
+ await context.addInitScript(device => {
+ if (window !== window.top) return;
+ localStorage.setItem("mso.device.id", device);
+ localStorage.setItem("mso:onboarding:v1", "done");
+ }, fixture.device);
+ await context.route("**/api/v1/managed-apps", route => route.fulfill({ json: { apps: [] } }));
+ await context.route("https://tool.example.test/**", route => route.fulfill({ contentType: "text/html", body: '<!doctype html><html><body><h1>Custom tool</h1><label>Draft <input aria-label="Draft"></label></body></html>' }));
+ const page = await context.newPage();
+ page.setDefaultTimeout(15_000);
+ const errors = [];
+ page.on("pageerror", error => errors.push(error.message));
+ await page.goto(fixture.base + "/login?returnTo=%2Fstore");
+ await page.locator('input[type="password"]').fill(fixture.password);
+ await page.getByRole("button", { name: "Unlock", exact: true }).click();
+ await expect(page.getByRole("heading", { name: "Apps on your host" })).toBeVisible();
+ await page.getByRole("button", { name: "Connect app", exact: true }).click();
+ const form = page.getByRole("dialog");
+ await form.getByLabel("App name", { exact: true }).fill("Fixture tool");
+ await form.getByLabel("App URL", { exact: true }).fill("https://tool.example.test/editor");
+ await form.locator("form").hover();
+ await page.mouse.wheel(0, 1000);
+ await expect(form.getByRole("button", { name: "Connect app", exact: true })).toBeInViewport({ ratio: 1 });
+ await form.getByRole("button", { name: "Connect app", exact: true }).click();
+ await expect(form).toHaveCount(0);
+ const card = page.getByRole("article").filter({ has: page.getByRole("heading", { name: "Fixture tool", exact: true }) });
+ await expect(card).toBeVisible();
+ await card.getByRole("button", { name: "Open", exact: true }).click();
+ const iframe = page.locator('iframe[title="Fixture tool application"]');
+ const frame = page.frameLocator('iframe[title="Fixture tool application"]');
+ await expect(frame.getByRole("heading", { name: "Custom tool" })).toBeVisible();
+ await frame.getByLabel("Draft", { exact: true }).fill("Keep my draft");
+ const refreshed = page.waitForResponse(response => response.url().endsWith("/api/v1/shell-apps") && response.request().method() === "GET");
+ await page.evaluate(() => window.dispatchEvent(new Event("focus")));
+ await refreshed;
+ await expect(frame.getByLabel("Draft", { exact: true })).toHaveValue("Keep my draft");
+ await page.reload();
+ await expect(frame.getByRole("heading", { name: "Custom tool" })).toBeVisible();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);
+ expect((await iframe.boundingBox()).height).toBeGreaterThan(120);
+ expect(JSON.parse(await readFile(path.join(fixture.dir, "surface-apps.json"), "utf8"))[0].id).toBe("fixture-tool");
+ await page.goto(fixture.base + "/store");
+ await card.getByRole("button", { name: "Edit", exact: true }).click();
+ await page.getByRole("dialog").getByLabel("App URL", { exact: true }).fill("http://192.0.2.10:5678/");
+ await page.getByRole("button", { name: "Save changes", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await card.getByRole("button", { name: "Open", exact: true }).click();
+ await expect(page.getByRole("link", { name: "Open Fixture tool", exact: true })).toHaveAttribute("href", "http://192.0.2.10:5678/");
+ await expect(iframe).toHaveCount(0);
+ await page.goto(fixture.base + "/store");
+ await card.getByRole("button", { name: "Disconnect", exact: true }).click();
+ await expect(page.getByText("This removes its shell entry. The application keeps running and its data is untouched.")).toBeVisible();
+ const disconnected = page.waitForResponse(response => response.url().endsWith("/api/v1/shell-apps") && response.request().method() === "POST");
+ await page.getByRole("dialog").getByRole("button", { name: "Disconnect", exact: true }).click();
+ expect((await disconnected).status()).toBe(200);
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(card).toHaveCount(0);
+ expect(JSON.parse(await readFile(path.join(fixture.dir, "surface-apps.json"), "utf8"))).toEqual([]);
+ await fixture.setRole("viewer");
+ expect(await page.evaluate(async () => (await fetch("/api/v1/shell-apps")).status)).toBe(403);
+ await fixture.setRole("owner");
+ expect(errors).toEqual([]);
+ await context.close();
+ console.log(`PASS connected app CRUD, embed draft retention, persistence, IP fallback and authorization ${viewport.width}x${viewport.height}`);
+ }
+} finally { await browser?.close(); await fixture.close(); }