Wire operator Integrations page + capability-gating framework

Completes the arcadia-admin operator surface for the integration registry and
the capability/route-guard framework it depends on.

- Integration registry: route + Data-group nav entry + `platform.integrations`
  capability; the in-app client now delegates to the shared
  `@crema/integration-registry-client` lib (vite alias + tsconfig); the
  operator Integrations page (committed earlier) is now reachable.
- Capability gating: capabilities map + route-guard + jwt helpers + the
  apps/plan/entitlements routes and supporting tenants/session changes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
jules
2026-06-09 23:09:24 +10:00
parent 06490865d3
commit 4b817b85ff
15 changed files with 1176 additions and 341 deletions

View File

@@ -39,6 +39,8 @@ import {
Plug,
MessageSquare,
Eye,
LayoutGrid,
CreditCard,
// CREMA:NAV-ICONS
} from "lucide-react"
@@ -67,6 +69,7 @@ import {
} from "~/components/ui/popover"
import { profileInitials, useProfile } from "~/lib/profile"
import { signOut, useSession } from "~/lib/session"
import { capabilityForPath, useCapabilities } from "~/lib/capabilities"
import {
addNotification,
dismiss,
@@ -96,6 +99,7 @@ import {
SheetTrigger,
} from "~/components/ui/sheet"
import { ScriptsDialog, useScriptsHotkey } from "~/components/scripts-dialog"
import { RouteGuard } from "~/components/route-guard"
type NavItem = {
to: string
@@ -134,6 +138,16 @@ const navGroups: NavGroup[] = [
{ to: "/sso", icon: ShieldCheck, label: "SSO" },
],
},
{
key: "billing",
label: "Billing",
icon: CreditCard,
items: [
{ to: "/apps", icon: LayoutGrid, label: "Apps" },
{ to: "/plan", icon: CreditCard, label: "Plan" },
{ to: "/entitlements", icon: Gauge, label: "Entitlements" },
],
},
{
key: "data",
label: "Data",
@@ -142,6 +156,7 @@ const navGroups: NavGroup[] = [
{ to: "/storage", icon: HardDrive, label: "Storage" },
{ to: "/buckets", icon: Boxes, label: "Buckets" },
{ to: "/secrets", icon: KeyRound, label: "Secrets" },
{ to: "/integrations", icon: Plug, label: "Integrations" },
],
},
{
@@ -189,15 +204,6 @@ const extraNavItems: NavItem[] = [
// CREMA:NAV-ITEMS
]
// Flat list — used by the icon-only collapsed rail, where group headers
// don't render and items appear as a single column of icons.
const allNavItems: NavItem[] = [
...pinnedTop,
...navGroups.flatMap((g) => g.items),
...extraNavItems,
...pinnedBottom,
]
function readNavGroupState(): Record<string, boolean> {
if (typeof window === "undefined") return {}
try {
@@ -230,6 +236,7 @@ export function AppShell({
const defaultUser = useUser()
const profile = useProfile()
const session = useSession()
const caps = useCapabilities()
const navigate = useNavigate()
const brand = brandOverride ?? defaultBrand
// Prefer the live session for identity, fall back to the stub user.
@@ -264,11 +271,51 @@ export function AppShell({
useScriptsHotkey(() => setScriptsOpen(true))
const location = useLocation()
// Filter the nav by what the active session can actually reach. A
// capability map exists for every protected route — items without one
// (or whose capability isn't held) are dropped here, so the sidebar
// doesn't advertise routes the user will only hit a 403 from.
const allowed = (item: NavItem): boolean => {
const cap = capabilityForPath(item.to)
if (!cap) return true // unknown routes default to visible
return caps.has(cap)
}
const visiblePinnedTop = useMemo(
() => pinnedTop.filter(allowed),
[caps],
)
const visiblePinnedBottom = useMemo(
() => pinnedBottom.filter(allowed),
[caps],
)
const visibleNavGroups: NavGroup[] = useMemo(
() =>
navGroups
.map((g) => ({ ...g, items: g.items.filter(allowed) }))
.filter((g) => g.items.length > 0),
[caps],
)
const visibleExtraItems = useMemo(
() => extraNavItems.filter(allowed),
[caps],
)
const visibleAllNavItems: NavItem[] = useMemo(
() => [
...visiblePinnedTop,
...visibleNavGroups.flatMap((g) => g.items),
...visibleExtraItems,
...visiblePinnedBottom,
],
[visiblePinnedTop, visibleNavGroups, visibleExtraItems, visiblePinnedBottom],
)
const activeGroupKey = useMemo(
() =>
navGroups.find((g) => g.items.some((it) => location.pathname.startsWith(it.to)))
?.key ?? null,
[location.pathname],
visibleNavGroups.find((g) =>
g.items.some((it) => location.pathname.startsWith(it.to)),
)?.key ?? null,
[location.pathname, visibleNavGroups],
)
const [openGroups, setOpenGroups] = useState<Record<string, boolean>>(() =>
@@ -339,11 +386,11 @@ export function AppShell({
<nav className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto p-2">
{expanded ? (
<>
{pinnedTop.map((item) => (
{visiblePinnedTop.map((item) => (
<NavRow key={item.label} item={item} expanded />
))}
{navGroups.map((group) => {
{visibleNavGroups.map((group) => {
const isOpen = !!openGroups[group.key]
const GroupIcon = group.icon
return (
@@ -375,16 +422,16 @@ export function AppShell({
)
})}
{extraNavItems.length > 0 ? (
{visibleExtraItems.length > 0 ? (
<div className="mt-1.5 flex flex-col gap-0.5">
{extraNavItems.map((item) => (
{visibleExtraItems.map((item) => (
<NavRow key={item.label} item={item} expanded />
))}
</div>
) : null}
<div className="mt-auto flex flex-col gap-0.5 pt-2">
{pinnedBottom.map((item) => (
{visiblePinnedBottom.map((item) => (
<NavRow key={item.label} item={item} expanded />
))}
</div>
@@ -392,7 +439,7 @@ export function AppShell({
) : (
// Icon-only rail: flat list, no group headers.
<>
{allNavItems.map((item) => (
{visibleAllNavItems.map((item) => (
<NavRow key={item.label} item={item} expanded={false} />
))}
</>
@@ -443,7 +490,7 @@ export function AppShell({
</SheetTitle>
</SheetHeader>
<nav className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto p-2">
{pinnedTop.map((item) => (
{visiblePinnedTop.map((item) => (
<NavRow
key={item.label}
item={item}
@@ -453,7 +500,7 @@ export function AppShell({
/>
))}
{navGroups.map((group) => {
{visibleNavGroups.map((group) => {
const isOpen = !!openGroups[group.key]
const GroupIcon = group.icon
return (
@@ -492,9 +539,9 @@ export function AppShell({
)
})}
{extraNavItems.length > 0 ? (
{visibleExtraItems.length > 0 ? (
<div className="mt-1.5 flex flex-col gap-0.5">
{extraNavItems.map((item) => (
{visibleExtraItems.map((item) => (
<NavRow
key={item.label}
item={item}
@@ -507,7 +554,7 @@ export function AppShell({
) : null}
<div className="mt-auto flex flex-col gap-0.5 pt-2">
{pinnedBottom.map((item) => (
{visiblePinnedBottom.map((item) => (
<NavRow
key={item.label}
item={item}
@@ -601,12 +648,16 @@ export function AppShell({
<div
id="main-content"
tabIndex={-1}
// First-child padding clears the fixed top-right floating actions
// pill so page headers can put refresh/new buttons in their normal
// top-right slot without sliding under the appbar avatar/controls.
className="flex flex-1 flex-col gap-6 p-6 focus:outline-none [&>*:first-child]:lg:pr-72"
className="flex flex-1 flex-col focus:outline-none"
>
{children}
{/* Centered content column. Caps line lengths and frames pages
on wide displays so the canvas reads as composed instead of
one floating card in a sea of black. The floating actions
pill is fixed to the viewport edge and lives outside this
column, so it stays clear regardless of cap width. */}
<div className="mx-auto flex w-full max-w-[1180px] flex-1 flex-col gap-6 p-6 [&>*:first-child]:lg:pr-72">
<RouteGuard>{children}</RouteGuard>
</div>
</div>
</main>
@@ -645,7 +696,11 @@ function NavRow({
data-action={`${prefix}${item.label.toLowerCase()}`}
className={({ isActive }) =>
[
"flex items-center gap-3 rounded-lg py-2 text-sm font-medium transition-colors duration-fast ease-standard",
"relative flex items-center gap-3 rounded-lg py-2 text-sm font-medium transition-colors duration-fast ease-standard",
// 2px left accent rail on active. Absolute-positioned so the rail
// anchors to the rail's edge regardless of per-item left padding,
// and a fixed 14px height keeps it from filling tall rows.
"before:absolute before:left-0 before:top-1/2 before:h-3.5 before:w-[2px] before:-translate-y-1/2 before:rounded-r-full before:bg-primary before:opacity-0 before:transition-opacity before:duration-fast",
expanded
? inGroup
? // Indent the label by chevron(12) + gap(8) = 20px so it
@@ -654,7 +709,7 @@ function NavRow({
: "justify-start px-3"
: "justify-center px-3",
isActive
? "bg-primary/10 text-primary"
? "bg-primary/[0.08] text-primary before:opacity-100"
: "text-muted-foreground hover:bg-accent hover:text-accent-foreground",
].join(" ")
}

View File

@@ -0,0 +1,50 @@
// Per-route capability guard. Wrap the page body — if the active
// session doesn't hold the route's capability, render a 403 instead of
// the page. Server-side authz is still the real gate; this is UX so a
// deep link doesn't 500 inside a route loader that assumes access.
import { useLocation } from "react-router"
import { ShieldAlert } from "lucide-react"
import {
capabilityForPath,
useCapabilities,
type Capability,
} from "~/lib/capabilities"
import { Card, CardContent } from "~/components/ui/card"
type RouteGuardProps = {
children: React.ReactNode
/** Override the capability derived from the current path. Useful for
* nested routes where you want to check a specific cap. */
capability?: Capability
}
export function RouteGuard({ children, capability }: RouteGuardProps) {
const caps = useCapabilities()
const location = useLocation()
const required = capability ?? capabilityForPath(location.pathname)
// No mapping = route is intentionally unguarded (e.g. login flows
// never reach AppShell anyway).
if (!required) return <>{children}</>
if (caps.has(required)) return <>{children}</>
return <Forbidden capability={required} />
}
function Forbidden({ capability }: { capability: Capability }) {
return (
<div className="flex min-h-[60vh] items-center justify-center">
<Card className="max-w-md">
<CardContent className="flex flex-col items-center gap-3 py-10 text-center">
<ShieldAlert className="size-10 text-muted-foreground" />
<h2 className="text-lg font-semibold">You can't access this page</h2>
<p className="text-sm text-muted-foreground">
This view requires the <code className="font-mono text-xs">{capability}</code>{" "}
capability on your active tenant. If you think you should have it,
switch tenants from the avatar menu or ask an admin.
</p>
</CardContent>
</Card>
</div>
)
}

View File

@@ -1,205 +1,40 @@
// Integration-registry API client (operator surface).
//
// Talks to arcadia-llm-gateway's `/api/v1/integrations*` endpoints — the
// platform operator manages pooled/platform credentials at ANY scope and
// inspects cross-tenant usage *metadata* (never secrets; reads return
// `has_secret`, never a value).
//
// The tenant mirror (`/api/v1/me/integrations*`, scoped to the caller) lives
// in arcadia-console. Pure functions over an injected gateway `ArcadiaClient`
// (see `~/lib/gateway`); no app coupling, so this lifts into a shared lib once
// both apps exist.
// Integration-registry client (operator surface) — thin shim over the shared
// `@crema/integration-registry-client` lib, bound to `operator` mode. The lib
// owns the types, the HTTP contract, and the display helpers (shared with
// arcadia-console's tenant surface); this file just exposes operator-idiomatic
// names so the page reads naturally.
import type { ArcadiaClient } from "@crema/arcadia-client"
import {
createIntegrationsApi,
type CredentialInput,
type IntegrationInput,
type ScopeFilter,
} from "@crema/integration-registry-client"
export type Scope = "platform" | "tenant" | "app" | "user" | "agent"
export type AuthKind = "bearer_static" | "basic" | "api_key_header" | "oauth2"
export type CredentialSource = "byo" | "pooled"
export type CredentialStatus = "active" | "expired" | "revoked"
// Re-export the shared types + helpers so callers import from one place.
export * from "@crema/integration-registry-client"
export interface CostModel {
unit?: "call" | "search" | "1k_tokens"
price_usd?: string | number
currency?: string
}
const op = (c: ArcadiaClient) => createIntegrationsApi(c, "operator")
export interface Constraints {
rate_per_min?: number
monthly_budget_usd?: string | number
monthly_call_cap?: number
}
export interface Credential {
id: string
integration_id: string
secret_name: string
auth_kind: AuthKind
meta: Record<string, unknown>
/** Presence, not value — the secret is write-only. */
has_secret: boolean
expires_at: string | null
last_rotated_at: string | null
source: CredentialSource
status: CredentialStatus
}
export interface Integration {
id: string
scope: Scope
scope_id: string | null
provider: string
capability: string | null
display_name: string | null
description: string | null
docs_url: string | null
base_url: string | null
enabled: boolean
cost_model: CostModel
constraints: Constraints
created_by: string | null
credentials: Credential[]
}
export interface UsageEntry {
integration_id: string
scope: Scope
scope_id: string | null
provider: string
capability: string | null
units: number
cost_usd: string
calls: number
}
export interface IntegrationInput {
scope?: Scope
scope_id?: string | null
provider: string
capability?: string | null
display_name?: string | null
description?: string | null
docs_url?: string | null
base_url?: string | null
enabled?: boolean
cost_model?: CostModel
constraints?: Constraints
}
export interface CredentialInput {
secret_name: string
auth_kind: AuthKind
/** Plaintext, write-only — sent on create/rotate, never returned. */
secret?: string
source?: CredentialSource
expires_at?: string | null
meta?: Record<string, unknown>
}
export interface TestVerdict {
status: string
auth_kind?: AuthKind
policy?: {
within_budget: boolean
within_rate: boolean
remaining_budget_usd: string | null
}
}
export interface ScopeFilter {
scope?: Scope
scope_id?: string
}
const BASE = "/api/v1/integrations"
export async function listIntegrations(
c: ArcadiaClient,
filter: ScopeFilter = {},
): Promise<Integration[]> {
const res = await c.GET<{ integrations: Integration[] }>(BASE, {
params: { scope: filter.scope, scope_id: filter.scope_id },
})
return res.integrations
}
export async function createIntegration(
c: ArcadiaClient,
input: IntegrationInput,
): Promise<Integration> {
const res = await c.POST<{ integration: Integration }>(BASE, { body: input })
return res.integration
}
export async function updateIntegration(
export const listIntegrations = (c: ArcadiaClient, filter: ScopeFilter = {}) =>
op(c).list(filter)
export const createIntegration = (c: ArcadiaClient, input: IntegrationInput) =>
op(c).create(input)
export const updateIntegration = (
c: ArcadiaClient,
id: string,
input: Partial<IntegrationInput>,
): Promise<Integration> {
const res = await c.PATCH<{ integration: Integration }>(`${BASE}/${id}`, { body: input })
return res.integration
}
export async function deleteIntegration(c: ArcadiaClient, id: string): Promise<void> {
await c.DELETE(`${BASE}/${id}`)
}
export async function addCredential(
c: ArcadiaClient,
integrationId: string,
input: CredentialInput,
): Promise<Credential> {
const res = await c.POST<{ credential: Credential }>(`${BASE}/${integrationId}/credentials`, {
body: input,
})
return res.credential
}
export async function updateCredential(
) => op(c).update(id, input)
export const deleteIntegration = (c: ArcadiaClient, id: string) => op(c).remove(id)
export const addCredential = (c: ArcadiaClient, integrationId: string, input: CredentialInput) =>
op(c).addCredential(integrationId, input)
export const updateCredential = (
c: ArcadiaClient,
credentialId: string,
input: Partial<CredentialInput>,
): Promise<Credential> {
const res = await c.PATCH<{ credential: Credential }>(`/api/v1/credentials/${credentialId}`, {
body: input,
})
return res.credential
}
export async function deleteCredential(c: ArcadiaClient, credentialId: string): Promise<void> {
await c.DELETE(`/api/v1/credentials/${credentialId}`)
}
/**
* Run the registry's policy gate against an integration's credential. 200 with
* a verdict; 4xx (409 expired / 429 over-budget / 404 no credential) is thrown
* by `ArcadiaClient` as an `ArcadiaError` — inspect `err.status`.
*/
export async function testIntegration(c: ArcadiaClient, id: string): Promise<TestVerdict> {
return c.POST<TestVerdict>(`${BASE}/${id}/test`)
}
export async function usageSummary(
c: ArcadiaClient,
filter: ScopeFilter = {},
): Promise<UsageEntry[]> {
const res = await c.GET<{ usage: UsageEntry[] }>(`${BASE}/usage`, {
params: { scope: filter.scope, scope_id: filter.scope_id },
})
return res.usage
}
// ── display helpers ────────────────────────────────────────────────────
export function formatUsd(value: string | number | null | undefined): string {
if (value === null || value === undefined) return "—"
const n = typeof value === "string" ? Number(value) : value
if (Number.isNaN(n)) return "—"
return `$${n.toFixed(n < 0.01 && n > 0 ? 4 : 2)}`
}
export function credentialHealth(cred: Credential): "ok" | "expired" | "revoked" | "missing" {
if (cred.status === "revoked") return "revoked"
if (!cred.has_secret) return "missing"
if (cred.expires_at && new Date(cred.expires_at).getTime() < Date.now()) return "expired"
return "ok"
}
) => op(c).updateCredential(credentialId, input)
export const deleteCredential = (c: ArcadiaClient, credentialId: string) =>
op(c).deleteCredential(credentialId)
export const testIntegration = (c: ArcadiaClient, id: string) => op(c).test(id)
export const usageSummary = (c: ArcadiaClient, filter: ScopeFilter = {}) => op(c).usage(filter)

View File

@@ -91,3 +91,23 @@ export async function deactivateTenant(arcadia: ArcadiaClient, id: string): Prom
const res = await arcadia.POST<{ data: Tenant }>(`/api/v1/admin/tenants/${id}/deactivate`)
return res.data
}
export interface ProvisionTenantInput {
tenant: { name: string; slug: string }
admin_user: {
email: string
password: string
first_name: string
last_name: string
}
}
export async function provisionTenant(
arcadia: ArcadiaClient,
input: ProvisionTenantInput,
): Promise<Tenant> {
const res = await arcadia.POST<{ data: Tenant }>("/api/v1/admin/tenants/provision", {
body: input,
})
return res.data
}

168
app/lib/capabilities.ts Normal file
View File

@@ -0,0 +1,168 @@
// Capability gating — the contract between roles, nav, and routes.
//
// A capability is a *thing the user can do in this UI*. The set held by
// the current session is computed from their active membership's roles
// + the slug of the active tenant (platform-admin gets the platform.*
// fleet by default). Sidebar nav filters by it; per-route guards 403
// when the user deep-links to one they don't hold.
//
// The server is the real authority — these checks are UI-shaping, not
// security. Don't ever trust the client capability check on its own.
export type Capability =
// tenant.* — held by tenant_admin on the active membership.
| "tenant.home"
| "tenant.users"
| "tenant.invitations"
| "tenant.roles"
| "tenant.memberships"
| "tenant.apps"
| "tenant.plan"
| "tenant.entitlements"
| "tenant.storage"
| "tenant.buckets"
| "tenant.activity"
| "tenant.settings"
| "tenant.profile"
// platform.* — held by platform_admin on platform-admin.
| "platform.tenants"
| "platform.organizations"
| "platform.networking"
| "platform.monitoring"
| "platform.status_page"
| "platform.scheduled_tasks"
| "platform.secrets"
| "platform.webhooks"
| "platform.announcements"
| "platform.sso"
| "platform.library"
| "platform.search"
| "platform.ai"
| "platform.integrations" // external-API registry (keys/budgets) on the gateway
// Special — always-on; not gated.
| "always.assistant"
| "always.profile"
/** Roles arcadia issues that this UI knows about. */
export type Role =
| "platform_admin"
| "tenant_admin"
| "member"
| (string & {}) // accept unknown roles forward-compat
const TENANT_ADMIN_CAPS: Capability[] = [
"tenant.home",
"tenant.users",
"tenant.invitations",
"tenant.roles",
"tenant.memberships",
"tenant.apps",
"tenant.plan",
"tenant.entitlements",
"tenant.storage",
"tenant.buckets",
"tenant.activity",
"tenant.settings",
"tenant.profile",
]
const PLATFORM_ADMIN_CAPS: Capability[] = [
// platform_admin also gets every tenant.* — they're an admin of the
// platform-admin tenant, so they manage *its* users, storage, etc.
...TENANT_ADMIN_CAPS,
"platform.tenants",
"platform.organizations",
"platform.networking",
"platform.monitoring",
"platform.status_page",
"platform.scheduled_tasks",
"platform.secrets",
"platform.webhooks",
"platform.announcements",
"platform.sso",
"platform.library",
"platform.search",
"platform.ai",
"platform.integrations",
]
const ALWAYS_CAPS: Capability[] = ["always.assistant", "always.profile"]
export function capabilitiesForRoles(roles: readonly string[] | undefined): Set<Capability> {
const caps = new Set<Capability>(ALWAYS_CAPS)
const has = (r: string) => (roles ?? []).includes(r)
if (has("platform_admin")) PLATFORM_ADMIN_CAPS.forEach((c) => caps.add(c))
if (has("tenant_admin") || has("admin")) TENANT_ADMIN_CAPS.forEach((c) => caps.add(c))
// "member" / other roles get only the always-on set.
return caps
}
/** Pure helper — handy in tests + route loaders. */
export function holds(caps: Set<Capability>, cap: Capability): boolean {
return caps.has(cap)
}
// ----------------------------- Route map ----------------------------
//
// Every protected route declares which capability it needs. Sidebar nav
// and the per-route guard both read this map, so the contract lives in
// one place.
export const ROUTE_CAPABILITY: Record<string, Capability> = {
"/": "tenant.home",
"/users": "tenant.users",
"/memberships": "tenant.memberships",
"/storage": "tenant.storage",
"/buckets": "tenant.buckets",
"/activity": "tenant.activity",
"/settings": "tenant.settings",
"/apps": "tenant.apps",
"/plan": "tenant.plan",
"/entitlements": "tenant.entitlements",
"/tenants": "platform.tenants",
"/organizations": "platform.organizations",
"/networking": "platform.networking",
"/monitoring": "platform.monitoring",
"/status-page": "platform.status_page",
"/scheduled-tasks": "platform.scheduled_tasks",
"/secrets": "platform.secrets",
"/webhooks": "platform.webhooks",
"/announcements": "platform.announcements",
"/sso": "platform.sso",
"/library": "platform.library",
"/search": "platform.search",
"/ai": "platform.ai",
"/integrations": "platform.integrations",
"/assistant": "always.assistant",
"/profile": "always.profile",
}
// ----------------------------- Hooks --------------------------------
import { useMemo } from "react"
import { useSession } from "~/lib/session"
/** The active session's capability set. Empty when not signed in. */
export function useCapabilities(): Set<Capability> {
const session = useSession()
return useMemo(() => capabilitiesForRoles(session?.roles), [session?.roles])
}
export function useHasCapability(cap: Capability): boolean {
return useCapabilities().has(cap)
}
export function capabilityForPath(pathname: string): Capability | null {
// Exact match first.
if (ROUTE_CAPABILITY[pathname]) return ROUTE_CAPABILITY[pathname]
// Then prefix match — "/users/123" inherits "/users"'s capability.
// Walk known keys longest-first so "/scheduled-tasks/x" picks the
// right one over "/s".
const keys = Object.keys(ROUTE_CAPABILITY).sort((a, b) => b.length - a.length)
for (const k of keys) {
if (k !== "/" && pathname.startsWith(k + "/")) return ROUTE_CAPABILITY[k]
}
return null
}

49
app/lib/jwt.ts Normal file
View File

@@ -0,0 +1,49 @@
// Tiny JWT helpers — we never *verify* tokens client-side (the server
// is the only authority), we just decode the payload to read claims
// the UI uses for nav gating + tenant context.
export type ArcadiaClaims = {
sub?: string
email?: string
tenant_id?: string
tenant_slug?: string
roles?: string[]
available_tenants?: AvailableTenantClaim[]
exp?: number
iat?: number
[k: string]: unknown
}
export type AvailableTenantClaim = {
id?: string
slug?: string
name?: string
roles?: string[]
}
function b64urlDecode(s: string): string {
const pad = "=".repeat((4 - (s.length % 4)) % 4)
const b64 = (s + pad).replace(/-/g, "+").replace(/_/g, "/")
if (typeof atob === "function") return atob(b64)
// Node fallback (SSR / tests)
return Buffer.from(b64, "base64").toString("binary")
}
export function decodeJwt(token: string): ArcadiaClaims | null {
if (!token) return null
const parts = token.split(".")
if (parts.length !== 3) return null
try {
const raw = b64urlDecode(parts[1])
// Handle UTF-8: atob returns binary string; reconstruct UTF-8.
const utf8 =
typeof TextDecoder !== "undefined"
? new TextDecoder().decode(
Uint8Array.from(raw, (c) => c.charCodeAt(0)),
)
: raw
return JSON.parse(utf8) as ArcadiaClaims
} catch {
return null
}
}

View File

@@ -6,6 +6,14 @@
import { useEffect, useSyncExternalStore } from "react"
import { profileInitials } from "~/lib/profile"
import { decodeJwt, type AvailableTenantClaim } from "~/lib/jwt"
export type AvailableTenant = {
id: string
slug?: string
name?: string
roles: string[]
}
export type Session = {
userId: string
@@ -14,6 +22,11 @@ export type Session = {
token: string
// Issued at, ms since epoch.
issuedAt: number
// Active membership context — derived from the JWT.
tenantId?: string
tenantSlug?: string
roles: string[]
availableTenants: AvailableTenant[]
}
const STORAGE_KEY = "crema.session"
@@ -41,6 +54,18 @@ function readFromStorage(): Session | null {
token: parsed.token,
issuedAt:
typeof parsed.issuedAt === "number" ? parsed.issuedAt : Date.now(),
tenantId: typeof parsed.tenantId === "string" ? parsed.tenantId : undefined,
tenantSlug:
typeof parsed.tenantSlug === "string" ? parsed.tenantSlug : undefined,
roles: Array.isArray(parsed.roles)
? parsed.roles.filter((r): r is string => typeof r === "string")
: [],
availableTenants: Array.isArray(parsed.availableTenants)
? (parsed.availableTenants.filter(
(t): t is AvailableTenant =>
!!t && typeof (t as AvailableTenant).id === "string",
) as AvailableTenant[])
: [],
}
} catch {
return null
@@ -72,12 +97,31 @@ export function persistFromArcadiaLogin(
[user?.first_name, user?.last_name].filter(Boolean).join(" ") ||
user?.email ||
"Signed-in user"
const claims = decodeJwt(tokens.access_token) ?? {}
const availableTenants: AvailableTenant[] = Array.isArray(
claims.available_tenants,
)
? (claims.available_tenants as AvailableTenantClaim[])
.filter((t) => t && typeof t.id === "string")
.map((t) => ({
id: t.id as string,
slug: t.slug,
name: t.name,
roles: Array.isArray(t.roles) ? t.roles : [],
}))
: []
const session: Session = {
userId: user?.id ?? `arcadia-${Date.now().toString(36)}`,
name,
email: user?.email ?? "",
token: tokens.access_token,
issuedAt: Date.now(),
tenantId:
typeof claims.tenant_id === "string" ? claims.tenant_id : undefined,
tenantSlug:
typeof claims.tenant_slug === "string" ? claims.tenant_slug : undefined,
roles: Array.isArray(claims.roles) ? claims.roles : [],
availableTenants,
}
if (typeof window !== "undefined") {
sessionStorage.setItem("arcadia_access_token", tokens.access_token)

View File

@@ -28,5 +28,9 @@ export default [
route("announcements", "routes/announcements.tsx"),
route("status-page", "routes/status-page.tsx"),
route("search", "routes/search.tsx"),
route("apps", "routes/apps.tsx"),
route("plan", "routes/plan.tsx"),
route("entitlements", "routes/entitlements.tsx"),
route("integrations", "routes/integrations.tsx"),
// CREMA:ROUTES
] satisfies RouteConfig

View File

@@ -69,6 +69,39 @@ export const meta = () => pageTitle("Announcements")
const TYPES: AnnouncementType[] = ["info", "warning", "maintenance", "incident", "feature"]
const KIND_OPTIONS: { value: AnnouncementType; hint: string }[] = [
{ value: "info", hint: "Neutral update" },
{ value: "warning", hint: "Degraded service or heads-up" },
{ value: "maintenance", hint: "Scheduled work" },
{ value: "incident", hint: "Active outage" },
{ value: "feature", hint: "Something new shipped" },
]
function typeToAlertVariant(
t: AnnouncementType,
): "info" | "success" | "warning" | "error" | "neutral" {
if (t === "incident") return "error"
if (t === "warning" || t === "maintenance") return "warning"
if (t === "feature") return "success"
return "info"
}
function publishButtonLabel(opts: {
isEdit: boolean
active: boolean
audience: "platform" | "tenant"
tenantId: string
tenants: Tenant[]
}): string {
if (opts.isEdit) return "Save changes"
if (!opts.active) return "Save draft"
if (opts.audience === "tenant") {
const name = opts.tenants.find((t) => t.id === opts.tenantId)?.name
return name ? `Publish to ${name}` : "Publish to tenant"
}
return "Publish to all users"
}
type Editor =
| { kind: "create" }
| { kind: "edit"; announcement: Announcement }
@@ -86,6 +119,8 @@ export default function AnnouncementsRoute() {
const [search, setSearch] = useState("")
const [editor, setEditor] = useState<Editor>(null)
const [pendingDelete, setPendingDelete] = useState<Announcement | null>(null)
const [refreshedAt, setRefreshedAt] = useState<number | null>(null)
const [now, setNow] = useState(() => Date.now())
const refresh = useCallback(async () => {
setError(null)
@@ -97,6 +132,7 @@ export default function AnnouncementsRoute() {
])
setItems(a)
setTenants(t)
setRefreshedAt(Date.now())
} catch (err) {
setError(err instanceof ArcadiaError ? err.message : "Failed to load announcements.")
} finally {
@@ -104,6 +140,21 @@ export default function AnnouncementsRoute() {
}
}, [arcadia])
useEffect(() => {
if (refreshedAt == null) return
const id = window.setInterval(() => setNow(Date.now()), 30_000)
return () => window.clearInterval(id)
}, [refreshedAt])
const lastRefreshedLabel = useMemo(() => {
if (refreshedAt == null) return null
const seconds = Math.max(1, Math.round((now - refreshedAt) / 1000))
if (seconds < 60) return `${seconds}s ago`
const minutes = Math.round(seconds / 60)
if (minutes < 60) return `${minutes}m ago`
return `${Math.round(minutes / 60)}h ago`
}, [refreshedAt, now])
useEffect(() => {
if (session) refresh()
}, [session, refresh])
@@ -133,13 +184,12 @@ export default function AnnouncementsRoute() {
},
{
id: "scope",
header: "Scope",
cell: (a) =>
a.tenant_id ? (
<Badge variant="secondary">tenant</Badge>
) : (
<Badge>platform</Badge>
),
header: "Audience",
cell: (a) => {
if (!a.tenant_id) return <Badge>All apps</Badge>
const t = tenants.find((x) => x.id === a.tenant_id)
return <Badge variant="secondary">{t?.slug ?? "Single tenant"}</Badge>
},
},
{
id: "active",
@@ -207,7 +257,7 @@ export default function AnnouncementsRoute() {
},
},
],
[arcadia, refresh],
[arcadia, refresh, tenants],
)
const summary = useMemo(
@@ -234,32 +284,48 @@ export default function AnnouncementsRoute() {
return (
<AppShell>
<div className="flex flex-col gap-4">
<header className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-semibold tracking-tight">Announcements</h1>
<p className="text-sm text-muted-foreground">
Platform-wide and per-tenant banners. Apps consuming arcadia surface these to users.
<header className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div className="min-w-0">
<h1 className="text-[26px] font-[620] leading-[1.1] tracking-[-0.02em]">
Announcements
</h1>
<p className="mt-1.5 max-w-[56ch] text-[13.5px] leading-[1.5] text-muted-foreground">
Banners that appear at the top of every Sky AI app. Use them for maintenance
windows, incidents, or new features.
</p>
</div>
<div className="flex items-center gap-2">
<div className="flex shrink-0 items-center gap-3">
{lastRefreshedLabel ? (
<span
className="text-xs tabular-nums text-muted-foreground"
aria-live="polite"
title={`Last refreshed ${lastRefreshedLabel}`}
>
<span className="hidden sm:inline">Updated </span>
{lastRefreshedLabel}
</span>
) : null}
<Button
variant="outline"
size="sm"
variant="ghost"
size="icon-sm"
onClick={refresh}
disabled={loading}
aria-label="Refresh announcements"
data-action="announcements-refresh"
className="text-muted-foreground hover:text-foreground"
>
<RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
Refresh
</Button>
<Button
size="sm"
onClick={() => setEditor({ kind: "create" })}
data-action="announcements-create"
>
<Plus className="size-4" />
New announcement
</Button>
{items.length > 0 ? (
<Button
size="sm"
onClick={() => setEditor({ kind: "create" })}
data-action="announcements-create"
>
<Plus className="size-4" />
New announcement
</Button>
) : null}
</div>
</header>
@@ -283,9 +349,13 @@ export default function AnnouncementsRoute() {
data-action="announcements-search"
className="max-w-sm flex-1"
/>
<div className="ml-auto text-xs text-muted-foreground">
{table.total} of {items.length}
</div>
{items.length > 0 ? (
<div className="ml-auto text-xs tabular-nums text-muted-foreground">
{search && table.total !== items.length
? `${table.total} of ${items.length}`
: `${items.length} ${items.length === 1 ? "announcement" : "announcements"}`}
</div>
) : null}
</CardHeader>
<CardContent className="relative p-0">
@@ -295,12 +365,47 @@ export default function AnnouncementsRoute() {
/>
{table.total === 0 && !loading ? (
<EmptyState
icon={<Megaphone className="size-6" />}
icon={
<div
className="grid size-14 place-items-center rounded-full"
style={{
background:
"radial-gradient(circle at center, color-mix(in oklch, var(--primary) 22%, transparent), transparent 70%)",
}}
>
<Megaphone
className="size-6"
style={{ color: "var(--primary)" }}
/>
</div>
}
title={search ? "No announcements match." : "No announcements yet."}
description={
search ? "Try a different search." : "Post the first one — platform-wide or scoped to a tenant."
search
? "Try a different search."
: "Post your first banner. Show it to everyone, or scope it to a single tenant."
}
action={
search ? (
<Button
size="sm"
variant="outline"
onClick={() => setSearch("")}
data-action="announcements-clear-search"
>
Clear search
</Button>
) : (
<Button
size="sm"
onClick={() => setEditor({ kind: "create" })}
data-action="announcements-create-empty"
>
<Plus className="size-4" />
New announcement
</Button>
)
}
className="py-12"
/>
) : (
<>
@@ -407,6 +512,11 @@ function AnnouncementEditorDialog({
const [dismissible, setDismissible] = useState(true)
const [active, setActive] = useState(true)
const [saving, setSaving] = useState(false)
const [localError, setLocalError] = useState<string | null>(null)
useEffect(() => {
if (!open) setLocalError(null)
}, [open])
useEffect(() => {
if (!open) return
@@ -439,6 +549,7 @@ function AnnouncementEditorDialog({
const submit = async () => {
onError(null)
setLocalError(null)
setSaving(true)
try {
const input: AnnouncementInput = {
@@ -462,13 +573,13 @@ function AnnouncementEditorDialog({
await onSaved("Announcement posted.")
}
} catch (err) {
onError(
const msg =
err instanceof ArcadiaError
? err.message
: err instanceof Error
? err.message
: "Save failed.",
)
: "Save failed."
setLocalError(msg)
} finally {
setSaving(false)
}
@@ -476,15 +587,59 @@ function AnnouncementEditorDialog({
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="sm:max-w-xl max-h-[90vh] overflow-y-auto">
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{isEdit ? "Edit announcement" : "New announcement"}</DialogTitle>
<DialogDescription>
Banners surface in apps that consume arcadia. Active + currently within the start/end
window = visible.
A banner shows at the top of every Sky AI app. It's visible when it's switched on
and today falls inside its date range.
</DialogDescription>
</DialogHeader>
{/* Live preview — what users will see. Updates as the form is edited so
the operator never has to imagine the output or publish blind. */}
<div className="flex flex-col gap-1.5">
<Label className="text-xs uppercase tracking-wider text-muted-foreground">
Preview
</Label>
<div className="rounded-md border bg-muted/30 p-3">
<AlertBanner
variant={typeToAlertVariant(type)}
title={title || "Your banner title appears here"}
dismissible={dismissible}
onDismiss={() => {}}
action={
actionLabel && actionUrl ? (
<Button size="xs" variant="outline" type="button" tabIndex={-1}>
{actionLabel}
</Button>
) : undefined
}
>
{body || (
<span className="italic opacity-60">Body text appears here.</span>
)}
</AlertBanner>
<p className="mt-2 text-[11px] text-muted-foreground">
{audience === "tenant"
? `Visible to users of ${
tenants.find((t) => t.id === tenantId)?.name ?? "the selected tenant"
} only.`
: "Visible to everyone across every Sky AI app."}
</p>
</div>
</div>
{localError ? (
<AlertBanner
variant="error"
dismissible
onDismiss={() => setLocalError(null)}
>
{localError}
</AlertBanner>
) : null}
<div className="grid grid-cols-2 gap-3">
<div className="col-span-2 flex flex-col gap-1.5">
<Label htmlFor="ann-title">Title</Label>
@@ -493,6 +648,7 @@ function AnnouncementEditorDialog({
value={title}
onChange={(e) => setTitle(e.target.value)}
data-action="announcement-form-title"
placeholder="Scheduled maintenance Sunday 2am AEST"
/>
</div>
<div className="col-span-2 flex flex-col gap-1.5">
@@ -501,21 +657,25 @@ function AnnouncementEditorDialog({
id="ann-body"
value={body}
onChange={(e) => setBody(e.target.value)}
rows={4}
rows={3}
data-action="announcement-form-body"
placeholder="Expect ~10 minutes of downtime while we ship the new tenant switcher."
/>
</div>
<div className="flex flex-col gap-1.5">
<Label>Type</Label>
<Label>Kind</Label>
<Select value={type} onValueChange={setType}>
<SelectTrigger data-action="announcement-form-type">
<SelectValue />
</SelectTrigger>
<SelectContent>
{TYPES.map((t) => (
<SelectItem key={t} value={t}>
{t}
{KIND_OPTIONS.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
<div className="flex flex-col">
<span className="font-medium capitalize">{opt.value}</span>
<span className="text-xs text-muted-foreground">{opt.hint}</span>
</div>
</SelectItem>
))}
</SelectContent>
@@ -523,21 +683,21 @@ function AnnouncementEditorDialog({
</div>
<div className="flex flex-col gap-1.5">
<Label>Audience</Label>
<Label>Who sees this</Label>
<Select value={audience} onValueChange={(v) => setAudience(v as "platform" | "tenant")}>
<SelectTrigger data-action="announcement-form-audience">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="platform">Platform-wide</SelectItem>
<SelectItem value="tenant">Single tenant</SelectItem>
<SelectItem value="platform">Everyone</SelectItem>
<SelectItem value="tenant">Just one tenant</SelectItem>
</SelectContent>
</Select>
</div>
{audience === "tenant" ? (
<div className="col-span-2 flex flex-col gap-1.5">
<Label>Tenant</Label>
<Label>Which tenant</Label>
<Select value={tenantId} onValueChange={setTenantId}>
<SelectTrigger data-action="announcement-form-tenant">
<SelectValue placeholder="Pick a tenant" />
@@ -554,7 +714,7 @@ function AnnouncementEditorDialog({
) : null}
<div className="flex flex-col gap-1.5">
<Label htmlFor="ann-starts">Starts at</Label>
<Label htmlFor="ann-starts">Starts</Label>
<Input
id="ann-starts"
type="datetime-local"
@@ -564,7 +724,7 @@ function AnnouncementEditorDialog({
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="ann-ends">Ends at</Label>
<Label htmlFor="ann-ends">Ends</Label>
<Input
id="ann-ends"
type="datetime-local"
@@ -574,57 +734,88 @@ function AnnouncementEditorDialog({
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="ann-action-label">Action label (optional)</Label>
<Input
id="ann-action-label"
value={actionLabel}
onChange={(e) => setActionLabel(e.target.value)}
placeholder="Read more"
data-action="announcement-form-action-label"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="ann-action-url">Action URL (optional)</Label>
<Input
id="ann-action-url"
value={actionUrl}
onChange={(e) => setActionUrl(e.target.value)}
placeholder="/changelog/v2"
data-action="announcement-form-action-url"
/>
{/* Optional link group — heading clarifies these two are paired. */}
<div className="col-span-2 flex flex-col gap-2 rounded-md border border-dashed p-3">
<div className="flex items-baseline justify-between gap-2">
<Label className="text-sm">Add a link</Label>
<span className="text-xs text-muted-foreground">Optional</span>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="ann-action-label" className="text-xs text-muted-foreground">
Button text
</Label>
<Input
id="ann-action-label"
value={actionLabel}
onChange={(e) => setActionLabel(e.target.value)}
placeholder="Read more"
data-action="announcement-form-action-label"
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="ann-action-url" className="text-xs text-muted-foreground">
Where it goes
</Label>
<Input
id="ann-action-url"
value={actionUrl}
onChange={(e) => setActionUrl(e.target.value)}
placeholder="/changelog/v2"
data-action="announcement-form-action-url"
/>
</div>
</div>
</div>
<div className="flex items-center justify-between rounded-md border px-3 py-2">
<Label className="text-sm">Dismissible</Label>
{/* End-user behavior toggle, not publish state — kept with content fields. */}
<div className="col-span-2 flex items-center justify-between rounded-md border px-3 py-2">
<div className="flex flex-col">
<Label className="text-sm">Let users dismiss</Label>
<span className="text-xs text-muted-foreground">
Adds an × users can click to hide the banner.
</span>
</div>
<Switch
checked={dismissible}
onCheckedChange={setDismissible}
data-action="announcement-form-dismissible"
/>
</div>
<div className="flex items-center justify-between rounded-md border px-3 py-2">
<Label className="text-sm">Active</Label>
</div>
<DialogFooter className="flex-col items-stretch gap-3 sm:flex-row sm:items-center sm:justify-between">
{/* Active = publish state, paired with the publish button. */}
<label
htmlFor="ann-active"
className="flex items-center gap-2 text-xs text-muted-foreground sm:mr-auto"
>
<Switch
id="ann-active"
checked={active}
onCheckedChange={setActive}
data-action="announcement-form-active"
/>
</div>
</div>
<span>{active ? "Switched on" : "Switched off (draft)"}</span>
</label>
<DialogFooter>
<Button variant="outline" onClick={onClose} disabled={saving}>
Cancel
</Button>
<Button
onClick={submit}
disabled={saving || !title.trim() || (audience === "tenant" && !tenantId)}
data-action="announcement-form-save"
>
{saving ? <RefreshCw className="size-4 animate-spin" /> : <CheckCircle2 className="size-4" />}
{isEdit ? "Save" : "Post"}
</Button>
<div className="flex items-center justify-end gap-2">
<Button variant="outline" onClick={onClose} disabled={saving}>
Cancel
</Button>
<Button
onClick={submit}
disabled={saving || !title.trim() || (audience === "tenant" && !tenantId)}
data-action="announcement-form-save"
>
{saving ? (
<RefreshCw className="size-4 animate-spin" />
) : (
<CheckCircle2 className="size-4" />
)}
{publishButtonLabel({ isEdit, active, audience, tenantId, tenants })}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>

44
app/routes/apps.tsx Normal file
View File

@@ -0,0 +1,44 @@
// Tenant-scoped "Apps" — placeholder. Real surface is the apps this
// tenant publishes (and their per-app users/grants on the personal
// cloud side). Wired into the nav so tenant admins see the route they
// expect; data layer follows.
import { LayoutGrid } from "lucide-react"
import { AppShell } from "~/components/layout/app-shell"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card"
export default function AppsRoute() {
return (
<AppShell>
<div className="flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-lg bg-primary/10 text-primary">
<LayoutGrid className="size-5" />
</div>
<div>
<h1 className="text-2xl font-semibold">Apps</h1>
<p className="text-sm text-muted-foreground">
Apps this tenant publishes and the users that have granted them
access to their personal clouds.
</p>
</div>
</div>
<Card>
<CardHeader>
<CardTitle>Coming soon</CardTitle>
<CardDescription>
App authoring lives in arcadia-agents-manager today. This view will
surface published apps + per-app grants once the catalog endpoint
is wired.
</CardDescription>
</CardHeader>
<CardContent />
</Card>
</AppShell>
)
}

View File

@@ -0,0 +1,42 @@
// Tenant entitlements — placeholder. Lists the metered allowances
// (AI tokens, storage GB, etc.) granted to the active tenant and how
// much of each has been consumed. Data source not wired yet.
import { Gauge } from "lucide-react"
import { AppShell } from "~/components/layout/app-shell"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card"
export default function EntitlementsRoute() {
return (
<AppShell>
<div className="flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-lg bg-primary/10 text-primary">
<Gauge className="size-5" />
</div>
<div>
<h1 className="text-2xl font-semibold">Entitlements</h1>
<p className="text-sm text-muted-foreground">
Metered allowances for this tenant included units and usage to
date per meter.
</p>
</div>
</div>
<Card>
<CardHeader>
<CardTitle>Coming soon</CardTitle>
<CardDescription>
Personal-cloud entitlements are tracked per account today. A
tenant-rollup endpoint is pending.
</CardDescription>
</CardHeader>
<CardContent />
</Card>
</AppShell>
)
}

40
app/routes/plan.tsx Normal file
View File

@@ -0,0 +1,40 @@
// Tenant subscription + billing — placeholder. Real surface lists the
// active plan, renewal date, invoices, and payment method for the
// active tenant. Data source not wired yet.
import { CreditCard } from "lucide-react"
import { AppShell } from "~/components/layout/app-shell"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card"
export default function PlanRoute() {
return (
<AppShell>
<div className="flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-lg bg-primary/10 text-primary">
<CreditCard className="size-5" />
</div>
<div>
<h1 className="text-2xl font-semibold">Plan</h1>
<p className="text-sm text-muted-foreground">
Your tenant's subscription, billing details, and invoice history.
</p>
</div>
</div>
<Card>
<CardHeader>
<CardTitle>Coming soon</CardTitle>
<CardDescription>
Billing is not yet wired to a payment provider on this deployment.
</CardDescription>
</CardHeader>
<CardContent />
</Card>
</AppShell>
)
}

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from "react"
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react"
import { Pause, Play, Plus, RefreshCw } from "lucide-react"
import { ArcadiaError, useArcadiaClient } from "@crema/arcadia-client"
@@ -26,10 +26,21 @@ import {
CardHeader,
CardTitle,
} from "~/components/ui/card"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "~/components/ui/dialog"
import { Input } from "~/components/ui/input"
import { Label } from "~/components/ui/label"
import {
activateTenant,
deactivateTenant,
listTenants,
provisionTenant,
suspendTenant,
type Tenant,
type TenantStatus,
@@ -54,6 +65,7 @@ export default function TenantsRoute() {
const [error, setError] = useState<string | null>(null)
const [pending, setPending] = useState<PendingAction>(null)
const [search, setSearch] = useState("")
const [createOpen, setCreateOpen] = useState(false)
const refresh = useCallback(async () => {
setError(null)
@@ -191,7 +203,11 @@ export default function TenantsRoute() {
<RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
Refresh
</Button>
<Button size="sm" disabled data-action="tenants-create">
<Button
size="sm"
onClick={() => setCreateOpen(true)}
data-action="tenants-create"
>
<Plus className="size-4" />
New tenant
</Button>
@@ -252,6 +268,15 @@ export default function TenantsRoute() {
</CardContent>
</Card>
<TenantCreateDialog
open={createOpen}
onClose={() => setCreateOpen(false)}
onCreated={async () => {
setCreateOpen(false)
await refresh()
}}
onError={setError}
/>
<ConfirmDialog
open={pending?.kind === "suspend"}
onOpenChange={(o) => !o && setPending(null)}
@@ -330,3 +355,218 @@ function rowActions(
})
return items
}
function formatArcadiaError(err: unknown, fallback: string): string {
if (!(err instanceof ArcadiaError)) return fallback
// 422 validation errors carry per-field reasons in `details`. Shape from
// Ecto's FallbackController is typically `{ field: ["msg1", "msg2"] }` or
// nested `{ tenant: { slug: ["has already been taken"] } }`. Flatten so
// the user sees what to fix instead of a generic "validation failed".
if (err.isValidation && err.details) {
const lines: string[] = []
const walk = (obj: unknown, prefix: string) => {
if (Array.isArray(obj)) {
lines.push(`${prefix}: ${obj.join(", ")}`)
} else if (obj && typeof obj === "object") {
for (const [k, v] of Object.entries(obj)) {
walk(v, prefix ? `${prefix}.${k}` : k)
}
}
}
walk(err.details, "")
if (lines.length) return `${err.message}${lines.join("; ")}`
}
return err.message
}
function slugify(name: string): string {
return name
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
}
function TenantCreateDialog({
open,
onClose,
onCreated,
onError,
}: {
open: boolean
onClose: () => void
onCreated: () => Promise<void> | void
onError: (msg: string) => void
}) {
const arcadia = useArcadiaClient()
const [name, setName] = useState("")
const [slug, setSlug] = useState("")
const [slugDirty, setSlugDirty] = useState(false)
const [firstName, setFirstName] = useState("")
const [lastName, setLastName] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (!open) {
setName("")
setSlug("")
setSlugDirty(false)
setFirstName("")
setLastName("")
setEmail("")
setPassword("")
setSubmitting(false)
}
}, [open])
const slugInvalid = slug.length > 0 && !/^[a-z0-9-]+$/.test(slug)
const canSubmit =
!submitting &&
name.trim().length > 0 &&
slug.length > 0 &&
!slugInvalid &&
firstName.trim().length > 0 &&
lastName.trim().length > 0 &&
email.trim().length > 0 &&
password.length >= 8
async function handleSubmit(e: FormEvent) {
e.preventDefault()
if (!canSubmit) return
setSubmitting(true)
try {
await provisionTenant(arcadia, {
tenant: { name: name.trim(), slug },
admin_user: {
email: email.trim(),
password,
first_name: firstName.trim(),
last_name: lastName.trim(),
},
})
await onCreated()
} catch (err) {
onError(formatArcadiaError(err, "Failed to create tenant."))
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="sm:max-w-lg">
<form onSubmit={handleSubmit}>
<DialogHeader>
<DialogTitle>New tenant</DialogTitle>
<DialogDescription>
Provisions the tenant with default roles, quotas, and an initial admin user.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="tenant-name">Tenant name</Label>
<Input
id="tenant-name"
value={name}
onChange={(e) => {
setName(e.target.value)
if (!slugDirty) setSlug(slugify(e.target.value))
}}
placeholder="Acme Corp"
autoFocus
data-action="tenants-create-name"
/>
</div>
<div className="space-y-2">
<Label htmlFor="tenant-slug">Slug</Label>
<Input
id="tenant-slug"
value={slug}
onChange={(e) => {
setSlugDirty(true)
setSlug(e.target.value)
}}
placeholder="acme"
data-action="tenants-create-slug"
/>
<p className="text-xs text-muted-foreground">
{slugInvalid
? "Lowercase letters, digits, and hyphens only."
: "Lowercase letters, digits, and hyphens. Used in URLs and the X-Tenant-ID header."}
</p>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-2">
<Label htmlFor="tenant-admin-first-name">Admin first name</Label>
<Input
id="tenant-admin-first-name"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
placeholder="Jane"
data-action="tenants-create-admin-first-name"
/>
</div>
<div className="space-y-2">
<Label htmlFor="tenant-admin-last-name">Admin last name</Label>
<Input
id="tenant-admin-last-name"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
placeholder="Doe"
data-action="tenants-create-admin-last-name"
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="tenant-admin-email">Admin email</Label>
<Input
id="tenant-admin-email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="admin@acme.com"
data-action="tenants-create-admin-email"
/>
</div>
<div className="space-y-2">
<Label htmlFor="tenant-admin-password">Admin password</Label>
<Input
id="tenant-admin-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="At least 8 characters"
data-action="tenants-create-admin-password"
/>
</div>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={onClose}
disabled={submitting}
data-action="tenants-create-cancel"
>
Cancel
</Button>
<Button
type="submit"
disabled={!canSubmit}
data-action="tenants-create-submit"
>
{submitting ? "Creating…" : "Create tenant"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}