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.

6.7 KB
Raw Blame
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { openWindow } from "@/features/appshell";
import type { AppCatalogEntry } from "@/lib/contracts/app-catalog";
import type { ManagedAppView } from "@/lib/managed-apps/types";
import { Button } from "@/components/ui/button";
import { ConnectAppForm } from "./connect-app-form";
import { AppDomainStep } from "./app-domain-step";
import { hostnameFromUrl } from "../lib/app-domain";

type CatalogState = { status: "remote" | "stale" | "unavailable"; entries: AppCatalogEntry[] };

export function ManagedAppsCatalog({ query }: { query: string }) {
  const [apps, setApps] = useState<ManagedAppView[]>([]);
  const [catalog, setCatalog] = useState<CatalogState | null>(null);
  const [selected, setSelected] = useState<Extract<AppCatalogEntry, { kind: "connected" }> | null>(null);
  const [domainFor, setDomainFor] = useState<{ id: string; title: string; address: string | null } | null>(null);
  const [error, setError] = useState("");
  // Set the moment the operator asks to set an app up. Install runs in its own
  // MSO window; when this catalog next reads the host and finds that app
  // installed, the domain step is offered — the same step the connect path uses.
  const awaiting = useRef<{ id: string; title: string } | null>(null);
  useEffect(() => {
    const controller = new AbortController();
    const loadApps = async () => {
      try {
        const response = await fetch("/api/v1/managed-apps", { cache: "no-store", signal: controller.signal });
        if (!response.ok) throw new Error("Could not load installable apps.");
        const data = await response.json() as { apps: ManagedAppView[] };
        setApps(data.apps);
        setError("");
        const pending = awaiting.current;
        const installed = pending ? data.apps.find(app => app.id === pending.id) : undefined;
        if (pending && installed?.installed) {
          awaiting.current = null;
          setDomainFor({ id: installed.id, title: pending.title, address: installed.publicDashboardUrl });
        }
      } catch (reason) {
        if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : "Could not load apps.");
      }
    };

    void loadApps();
    void fetch("/api/v1/app-catalog", { cache: "no-store", signal: controller.signal }).then(async response => {
      if (!response.ok) throw new Error("Catalog unavailable.");
      setCatalog(await response.json() as CatalogState);
    }).catch(() => { if (!controller.signal.aborted) setCatalog({ status: "unavailable", entries: [] }); });

    // Installing a managed app happens in a separate MSO window. The App Store can
    // remain mounted behind it, so a mount-only read leaves the card saying "Not
    // installed" even after the server is running. Refresh only on user-return
    // signals; no background polling is needed for this catalog surface.
    const refreshVisible = () => {
      if (!document.hidden) void loadApps();
    };
    document.addEventListener("visibilitychange", refreshVisible);
    window.addEventListener("focus", refreshVisible);

    return () => {
      controller.abort();
      document.removeEventListener("visibilitychange", refreshVisible);
      window.removeEventListener("focus", refreshVisible);
    };
  }, []);

  const managedIds = useMemo(() => catalog?.entries.filter(entry => entry.kind === "managed").map(entry => entry.id) ?? [], [catalog]);
  const managed = apps.filter(app => (managedIds.length === 0 || managedIds.includes(app.id) || app.installed) &&
    app.name.toLowerCase().includes(query.toLowerCase())).sort((a, b) => {
      const left = managedIds.indexOf(a.id), right = managedIds.indexOf(b.id);
      return (left < 0 ? managedIds.length : left) - (right < 0 ? managedIds.length : right);
    });
  const connected = catalog?.entries.filter((entry): entry is Extract<AppCatalogEntry, { kind: "connected" }> =>
    entry.kind === "connected" && `${entry.manifest.title} ${entry.manifest.description}`.toLowerCase().includes(query.toLowerCase())) ?? [];

  return <section aria-label="Applications from MANEF" className="space-y-3">
    <h3 className="font-medium">Install and manage</h3>
    {catalog?.status === "stale" && <p role="status" className="text-xs text-muted-foreground">Showing the last valid MANEF catalog while it is unavailable.</p>}
    {catalog?.status === "unavailable" && <p role="status" className="text-xs text-muted-foreground">MANEF catalog is unavailable. Local reviewed installers remain available.</p>}
    {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
    <div className="grid gap-3 @min-[640px]:grid-cols-3">{managed.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>}
      <div className="flex flex-wrap gap-2">
        <Button size="sm" variant="outline" onClick={() => {
          if (!app.installed) awaiting.current = { id: app.id, title: app.name };
          openWindow(app.id, app.name);
        }}>{app.installed ? "Open and manage" : "Set up"}</Button>
        {app.installed && <Button size="sm" variant="ghost" onClick={() => setDomainFor({ id: app.id, title: app.name, address: app.publicDashboardUrl })}>Add domain</Button>}
      </div>
    </article>)}</div>
    {connected.length > 0 && <div className="space-y-3">
      <h3 className="font-medium">Connect a running tool</h3>
      <div className="grid gap-3 @min-[640px]:grid-cols-2">{connected.map(entry => <article key={entry.manifest.id} className="min-w-0 space-y-3 rounded-xl border p-4">
        <h4 className="font-medium">{entry.manifest.title}</h4>
        <p className="text-sm text-muted-foreground">{entry.manifest.description}</p>
        <p className="text-xs text-muted-foreground">MANEF catalog template · no service installed</p>
        <Button size="sm" variant="outline" onClick={() => setSelected(entry)}>Review and connect</Button>
      </article>)}</div>
    </div>}
    <p className="text-xs text-muted-foreground">Managed setup uses the reviewed installer and checks this host. Connected tools keep their own service and sign-in; a domain is optional.</p>
    {selected && <ConnectAppForm manifest={selected.manifest} onClose={() => setSelected(null)}/>}
    {domainFor && <AppDomainStep appId={domainFor.id} appTitle={domainFor.title} defaultHostname={hostnameFromUrl(domainFor.address)} appAddress={domainFor.address} onDone={() => setDomainFor(null)}/>}
  </section>;
}