import { FormEvent, useCallback, useEffect, useState } from "react"; import type { ReactNode } from "react"; import { Activity, CircleGauge, Clock3, KeyRound, Play, RefreshCw, ShieldCheck } from "lucide-react"; import { api, ApiError, operatorCredentialReference } from "../lib/api"; import { SafetyDialog } from "./SafetyDialog"; import { TabList, TabPanel } from "./TabList"; import type { TabDescriptor } from "./TabList"; import type { CapabilityDeployment, CapabilityEstate, DeploymentCandidate, GatewayInvokeResponse, GatewayRequest, OCRInvokeResponse, PlacementPlan, ProductionApproval, SchedulerBudget, SchedulerPolicy, ServiceClient, ServiceClientCreated, SpeechTranscriptionResponse, VisionEmbeddingResponse, } from "../types"; type View = "overview" | "scheduler" | "requests" | "clients" | "promotion" | "playground"; const capabilityViews: TabDescriptor[] = [ { key: "overview", label: "overview" }, { key: "scheduler", label: "scheduler" }, { key: "requests", label: "requests" }, { key: "clients", label: "clients" }, { key: "promotion", label: "promotion" }, { key: "playground", label: "playground" }, ]; export function CapabilityWorkspace({ onError }: { onError: (message: string | null) => void }) { const sessionReference = operatorCredentialReference(); const sessionActive = Boolean(sessionReference); const [view, setView] = useState("overview"); const [deployments, setDeployments] = useState([]); const [estate, setEstate] = useState([]); const [budgets, setBudgets] = useState([]); const [candidates, setCandidates] = useState([]); const [requests, setRequests] = useState([]); const [clients, setClients] = useState([]); const [approvals, setApprovals] = useState([]); const [plans, setPlans] = useState([]); const [policy, setPolicy] = useState(null); const [adminToken, setAdminToken] = useState(sessionReference); const [adminUnlocked, setAdminUnlocked] = useState(sessionActive); const [loading, setLoading] = useState(true); const loadPublic = useCallback(async () => { const [nextDeployments, nextBudgets, nextCandidates, nextEstate] = await Promise.all([ api.capabilityDeployments(), api.scheduler(), api.deploymentCandidates(), api.capabilityEstate(), ]); setDeployments(nextDeployments); setBudgets(nextBudgets); setCandidates(nextCandidates); setEstate(nextEstate); }, []); const loadAdmin = useCallback(async (token: string) => { if (!token && !sessionActive) return; const [nextRequests, nextClients, nextApprovals, nextPlans, nextPolicy] = await Promise.all([ api.gatewayRequests(token), api.serviceClients(token), api.productionApprovals(token), api.placementHistory(token), api.schedulerPolicy(token), ]); setRequests(nextRequests); setClients(nextClients); setApprovals(nextApprovals); setPlans(nextPlans); setPolicy(nextPolicy); }, [sessionActive]); useEffect(() => { Promise.all([loadPublic(), sessionActive ? loadAdmin(sessionReference) : Promise.resolve()]) .catch((cause: unknown) => onError(errorMessage(cause))) .finally(() => setLoading(false)); }, [loadAdmin, loadPublic, onError, sessionActive, sessionReference]); useEffect(() => { const interval = window.setInterval(() => { loadPublic().catch((cause: unknown) => onError(errorMessage(cause))); if (adminUnlocked) loadAdmin(adminToken).catch((cause: unknown) => onError(errorMessage(cause))); }, 5000); return () => window.clearInterval(interval); }, [adminToken, adminUnlocked, loadAdmin, loadPublic, onError]); const deployment = deployments.find((item) => item.capability === "rag.embedding" && item.contract_version === 1 && item.production && item.status === "stable", ) ?? deployments.find((item) => item.capability === "rag.embedding" && item.contract_version === 1); const refresh = async () => { onError(null); try { await Promise.all([loadPublic(), loadAdmin(adminToken)]); } catch (cause: unknown) { onError(errorMessage(cause)); } }; const authenticateAdmin = async (event: FormEvent) => { event.preventDefault(); onError(null); try { await loadAdmin(adminToken); setAdminUnlocked(true); } catch (cause: unknown) { onError(errorMessage(cause)); } }; if (loading) return
Loading capability serving state…
; return
MULTI-CAPABILITY ESTATE

{estate.length} governed contracts

Capability-first routing across RAG, document, vision and audio · no client-visible model names

{deployment?.health_status ?? "unavailable"}{deployment?.status ?? "not promoted"}
{view === "overview" ? : null} {view === "scheduler" ? <><> : null} {view === "requests" ? : null} {view === "clients" ? loadAdmin(adminToken)} onError={onError} /> : null} {view === "promotion" ? : null} {view === "playground" ? : null}
; } function CapabilityOverview({ deployment, requests, estate }: { deployment?: CapabilityDeployment; requests: GatewayRequest[]; estate: CapabilityEstate[] }) { if (!estate.length) return
No capability contracts are registered.
; const successful = requests.filter((item) => item.status === "completed"); const warmHits = successful.filter((item) => item.cold === false).length; return <>
{estate.map((item) =>
{item.category} · {item.resource_class}

{item.capability}@{item.version}

{item.purpose}

State{item.operational_state}
Evaluation{item.evaluation_state}
Privacy{item.privacy_class}
Consumers{item.consumers.join(", ") || "none declared"}
)}
{!deployment ?
No stable deployment exists. New modality capabilities remain LAB-only.
: <>
item.status === "queued").length))} hint={`Bounded at ${deployment.max_queue_depth}`} />
CONTRACT

Backend-authoritative boundary

RESIDENCY

Load-on-demand state

}; } function SchedulerView({ budgets, deployments, plans, policy, token, unlocked, onChanged, onError }: { budgets: SchedulerBudget[]; deployments: CapabilityDeployment[]; plans: PlacementPlan[]; policy: SchedulerPolicy | null; token: string; unlocked: boolean; onChanged: () => Promise; onError: (message: string | null) => void }) { const [latest, setLatest] = useState>({}); const [pendingUnload, setPendingUnload] = useState(null); const [unloadAcknowledged, setUnloadAcknowledged] = useState(false); const [unloadPending, setUnloadPending] = useState(false); const [unloadError, setUnloadError] = useState(null); const [unloadOutcome, setUnloadOutcome] = useState(null); if (!budgets.length) return
No accelerator telemetry is available for scheduling.
; const simulate = async (deploymentId: string) => { try { const plan = await api.dryRunPlacement(deploymentId, "interactive", token); setLatest((current) => ({ ...current, [deploymentId]: plan })); } catch (cause: unknown) { onError(errorMessage(cause)); } }; const previewUnload = (deployment: CapabilityDeployment) => { setUnloadAcknowledged(false); setUnloadError(null); setUnloadOutcome(null); setPendingUnload(deployment); }; const confirmUnload = async (deployment: CapabilityDeployment) => { // Guarded against a replayed handler so one acknowledgement can never evict residency twice. if (unloadPending) return; setUnloadPending(true); setUnloadError(null); try { await api.unloadDeployment(deployment.id, token); setPendingUnload(null); setUnloadAcknowledged(false); setUnloadOutcome(`Residency for ${deployment.capability}@${deployment.contract_version} was unloaded.`); await onChanged(); } catch (cause: unknown) { setUnloadError(errorMessage(cause)); } finally { setUnloadPending(false); } }; const changePolicy = async (deployment: CapabilityDeployment, value: string) => { try { await api.updateResidencyPolicy(deployment.id, value, token); await onChanged(); } catch (cause: unknown) { onError(errorMessage(cause)); } }; const pauseLab = async () => { try { await api.updateSchedulerPolicy(!Boolean(policy?.configuration.lab_paused), token); await onChanged(); } catch (cause: unknown) { onError(errorMessage(cause)); } }; return
{budgets.map((budget) => { const segments = [ ["External / unmanaged", budget.external_vram_bytes], ["Safety reserve", budget.safety_reserve_bytes], ["ModelForge resident", budget.resident_vram_bytes], ["Active leases", budget.leased_vram_bytes], ["Schedulable free", budget.schedulable_free_vram_bytes], ] as const; return
GPU SCHEDULING COCKPIT · {budget.node_name}

{budget.accelerator_name}

{budget.pressure_state}
{formatBytes(budget.total_vram_bytes)}Total VRAM · attribution {budget.attribution_confidence}
{segments.map(([label, bytes], index) => )}
{segments.map(([label, bytes]) => )}
Observed {formatBytes(budget.observed_used_vram_bytes)} · invariant delta {formatBytes(budget.invariant_delta_bytes)} · policy {budget.policy_revision} · telemetry {formatTime(budget.observed_at)}. External usage is observation-only and has no controls.
; })}
{unlocked ? <>
RESIDENCY MAP · WHAT CAN RUN NOW?

Managed capability placements

{deployments.map((item) => { const plan = latest[item.id]; return
{item.capability}@{item.contract_version} · {item.residency.state.toUpperCase()}{item.production ? "production" : "lab"} · {formatBytes(item.residency.measured_resident_vram_bytes)} · {item.residency.active_requests} active · cold load {formatMs(item.resource_envelope.cold_load_time_ms)}{plan ? {plan.verdict} · {plan.reason_codes.join(", ")} · after {formatBytes(plan.headroom_after_bytes)}{plan.evictions.length ? ` · evict ${plan.evictions.map((entry) => entry.capability).join(", ")}` : ""} : null}
; })}
PLACEMENT HISTORY

Recent bounded decisions

{plans.slice(0, 20).map((plan) => )}
: null} {unloadOutcome ?

{unloadOutcome}

: null} {pendingUnload ? setPendingUnload(null)} onConfirm={() => void confirmUnload(pendingUnload)} /> : null}
; } function RequestHistory({ requests }: { requests: GatewayRequest[] }) { if (!requests.length) return
No gateway request metadata exists yet. Input text is never displayed or persisted.
; return
PRIVACY-PRESERVING HISTORY

Gateway requests

RequestClientStatePathQueueTotalTime
{requests.map((request) =>
{request.request_id.slice(0, 8)}…{request.client ?? "rejected identity"}{request.failure_code ?? request.status}{request.cold == null ? "—" : request.cold ? "cold" : "warm"}{formatMs(request.queue_time_ms)}{formatMs(request.total_latency_ms)}{formatTime(request.created_at)}
)}
; } function Clients({ clients, token, onChanged, onError }: { clients: ServiceClient[]; token: string; onChanged: () => Promise; onError: (message: string | null) => void }) { const [name, setName] = useState("modelforge-m5-acceptance"); const [rpm, setRpm] = useState(60); const [created, setCreated] = useState(null); const submit = async (event: FormEvent) => { event.preventDefault(); onError(null); try { setCreated(await api.createServiceClient({ name, allowed_capabilities: ["rag.embedding@1"], requests_per_minute: rpm, max_concurrent_requests: 1 }, token)); await onChanged(); } catch (cause: unknown) { onError(errorMessage(cause)); } }; const revoke = async (clientId: string) => { onError(null); try { await api.revokeServiceCredential(clientId, token); await onChanged(); } catch (cause: unknown) { onError(errorMessage(cause)); } }; return
SCOPED IDENTITY

Create service client

Scope is fixed to rag.embedding@1; concurrency starts conservatively at one.

{created ?
Copy this credential now{created.credential}Only its hash is stored. It cannot be retrieved again.
: null}
CLIENTS

Authorized consumers

{clients.length ? clients.map((client) =>
{client.name}{client.allowed_capabilities.join(", ")} · {client.requests_per_minute}/min · last used {formatTime(client.last_used_at)}
) :

No service clients created.

}
; } function Promotion({ deployment, candidates, approvals, token, onChanged, onError }: { deployment?: CapabilityDeployment; candidates: DeploymentCandidate[]; approvals: ProductionApproval[]; token: string; onChanged: () => Promise; onError: (message: string | null) => void }) { const candidate = candidates[0]; const approval = approvals.find((item) => item.deployment_candidate_id === candidate?.id); const reviewItems = [ ["exact_revision_reviewed", "Exact upstream revision and resolved commit reviewed"], ["artifact_hashes_reviewed", "Local artifact SHA-256 digests reviewed"], ["safetensors_only", "Artifact set contains safetensors only"], ["remote_code_required", "No remote repository code is required"], ["pickle_present", "No pickle payload is present"], ["scanner_evidence_reviewed", "Supply-chain scanner evidence reviewed"], ["provenance_complete", "Artifact and derivation provenance is complete"], ["runtime_offline_reviewed", "Offline runtime behavior reviewed"], ["dependency_provenance_reviewed", "Runtime dependency provenance reviewed"], ["license_reviewed", "License evidence and production use reviewed"], ] as const; const [reviewed, setReviewed] = useState>({}); const [licenseIdentifier, setLicenseIdentifier] = useState(""); const reviewComplete = reviewItems.every(([key]) => reviewed[key]) && licenseIdentifier.trim().length > 0; const evidence = deployment ? [ ["Artifact integrity", "verified"], ["Supply chain", "production approved"], ["Runtime probe", String(deployment.provenance.runtime_probe_id ?? "bound")], ["Compatibility", String(deployment.provenance.compatibility_assessment_id ?? "bound")], ["Resource envelope", `${formatBytes(deployment.resource_envelope.required_vram_bytes)} · ${deployment.resource_envelope.stale ? "stale" : "current"}`], ["Node eligibility", "production eligible"], ["Capability contract", "rag.embedding@1"], ["Migration class", deployment.embedding_space.migration_class], ["Production approval", deployment.production_approval_id], ] : []; const approve = async () => { if (!candidate) return; onError(null); try { await api.approveProduction(candidate.id, { approved_by: "operator-ui", reason: "Exact production evidence explicitly reviewed and accepted by operator.", supply_chain_review: { exact_revision_reviewed: true, artifact_hashes_reviewed: true, safetensors_only: true, remote_code_required: false, pickle_present: false, scanner_evidence_reviewed: true, provenance_complete: true, runtime_offline_reviewed: true, dependency_provenance_reviewed: true, license_reviewed: true, license_identifier: licenseIdentifier.trim() }, deployment_config: { capability: "rag.embedding@1", max_concurrency: 1 } }, token); await onChanged(); } catch (cause: unknown) { onError(errorMessage(cause)); } }; const promote = async () => { if (!candidate || !approval) return; onError(null); try { await api.promoteCandidate(candidate.id, { production_approval_id: approval.id, residency_policy: "keep_warm", keep_warm_seconds: 900, max_concurrency: 1, max_queue_depth: 16, routing_weight: 100 }, token); await onChanged(); } catch (cause: unknown) { onError(errorMessage(cause)); } }; return
AUDITED PRODUCTION GATE

Promotion evidence

{deployment ? evidence.map(([label, value]) => ) : <>

No stable deployment exists. Promotion remains two explicit, audited actions.

{candidate && !approval ?
Review the evidence being attested

ModelForge records only claims the operator explicitly confirms below. Verify each claim in Registry, Runtime and Evaluation before approval.

{reviewItems.map(([key, label]) => )}
: null}
}
; } type ModalityResult = GatewayInvokeResponse | OCRInvokeResponse | VisionEmbeddingResponse | SpeechTranscriptionResponse; async function fileBase64(file: File): Promise { const bytes = new Uint8Array(await file.arrayBuffer()); let binary = ""; for (const byte of bytes) binary += String.fromCharCode(byte); return btoa(binary); } function Playground() { const [capability, setCapability] = useState<"rag.embedding" | "document.ocr" | "vision.embedding" | "speech.transcription">("rag.embedding"); const [credential, setCredential] = useState(""); const [input, setInput] = useState("ModelForge capability gateway test"); const [file, setFile] = useState(null); const [result, setResult] = useState(null); const [failure, setFailure] = useState(null); const [running, setRunning] = useState(false); const invoke = async (event: FormEvent) => { event.preventDefault(); setFailure(null); setRunning(true); try { if (capability === "rag.embedding") setResult(await api.invokeEmbedding(input, credential)); else { if (!file) throw new Error("Choose a local fixture first"); const encoded = await fileBase64(file); if (capability === "document.ocr") { if (file.type !== "image/png" && file.type !== "image/jpeg") throw new Error("OCR accepts PNG or JPEG"); setResult(await api.invokeOcr(encoded, file.type, credential)); } else if (capability === "vision.embedding") { if (file.type !== "image/png" && file.type !== "image/jpeg") throw new Error("Vision accepts PNG or JPEG"); setResult(await api.invokeVisionEmbedding(encoded, file.type, credential)); } else { if (file.type !== "audio/wav" && !file.name.toLowerCase().endsWith(".wav")) throw new Error("Transcription accepts WAV"); setResult(await api.invokeTranscription(encoded, credential)); } } } catch (cause: unknown) { setFailure(errorMessage(cause)); } finally { setRunning(false); } }; const output = result ? ("data" in result ? `${result.data.length} × ${result.dimension} finite values` : "text" in result ? result.text || "valid empty text" : "typed output") : ""; return
REAL GATEWAY PATH

Capability playground

The client selects a capability contract. No model name, path, or runtime engine is accepted here.

{capability === "rag.embedding" ?