Publish curated ITWorx-ModelForge source from 990401737f96c8d46a9f7b0d84994516cadcb6a0

This commit is contained in:
Public Source Publisher committed 2026-09-30 09:23:17 +00:00
1 parent 7082ab955a
commit 848f0d8f8a
434 files changed
+67298 -4315

No files matched your search

+125 -103
View File
@@ -1,63 +1,113 @@
import { FormEvent, useCallback, useEffect, useState } from "react";
import { FormEvent, useCallback, useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { Activity, CircleGauge, Clock3, KeyRound, Play, RefreshCw, ShieldCheck } from "lucide-react";
import { CapabilityDetails } from "./CapabilityDetails";
import { PromotionGate } from "./PromotionGate";
import type { OperatorIdentity } from "../lib/api";
import { CircleGauge, Clock3, KeyRound, Play, RefreshCw, ShieldCheck } from "lucide-react";
import { api, ApiError, operatorCredentialReference } from "../lib/api";
import { api, ApiError, operatorCredentialReference, operatorSessionVersion } 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,
CapabilityDeployment, CapabilityContractRecord, CapabilityEstate, DeploymentCandidate, GatewayInvokeResponse,
GatewayRequest, OCRInvokeResponse, PlacementPlan, ProductionApproval, RuntimeProfile, SchedulerBudget, SchedulerPolicy, ServiceClient,
ServiceClientCreated, SpeechTranscriptionResponse, VisionEmbeddingResponse,
} from "../types";
type View = "overview" | "scheduler" | "requests" | "clients" | "promotion" | "playground";
type CapabilityReadFailure = {
kind: "offline" | "error" | "unknown";
message: string;
code: string;
correlationId: string | null;
retryable: boolean;
nextAction: string;
};
type CapabilityReadState =
| { kind: "loading" }
| { kind: "fresh"; lastUpdatedAt: number }
| { kind: "unavailable"; failure: CapabilityReadFailure }
| { kind: "stale"; failure: CapabilityReadFailure; lastUpdatedAt: number };
const capabilityViews: TabDescriptor<View>[] = [
{ 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 }) {
export function CapabilityWorkspace({ onError, role = "viewer", targetDeploymentId }: { onError: (message: string | null) => void; role?: OperatorIdentity["role"]; targetDeploymentId?: string | null }) {
const sessionReference = operatorCredentialReference();
const sessionActive = Boolean(sessionReference);
const sessionActive = Boolean(sessionReference) && role === "admin";
const generation = operatorSessionVersion();
const [view, setView] = useState<View>("overview");
const [deployments, setDeployments] = useState<CapabilityDeployment[]>([]);
const [contracts, setContracts] = useState<CapabilityContractRecord[]>([]);
const [estate, setEstate] = useState<CapabilityEstate[]>([]);
const [budgets, setBudgets] = useState<SchedulerBudget[]>([]);
const [profiles, setProfiles] = useState<RuntimeProfile[]>([]);
const [candidates, setCandidates] = useState<DeploymentCandidate[]>([]);
const [requests, setRequests] = useState<GatewayRequest[]>([]);
const [clients, setClients] = useState<ServiceClient[]>([]);
const [approvals, setApprovals] = useState<ProductionApproval[]>([]);
const [plans, setPlans] = useState<PlacementPlan[]>([]);
const [policy, setPolicy] = useState<SchedulerPolicy | null>(null);
const [adminToken, setAdminToken] = useState(sessionReference);
const [adminUnlocked, setAdminUnlocked] = useState(sessionActive);
const adminToken = sessionReference;
const adminUnlocked = sessionActive;
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [publicRead, setPublicRead] = useState<CapabilityReadState>({ kind: "loading" });
const publicRequest = useRef(0);
const publicSnapshotAt = useRef<number | null>(null);
const mounted = useRef(false);
useEffect(() => {
mounted.current = true;
return () => { mounted.current = false; publicRequest.current += 1; };
}, []);
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 request = ++publicRequest.current;
const session = operatorSessionVersion();
const current = () => mounted.current && request === publicRequest.current && session === operatorSessionVersion();
try {
const [nextDeployments, nextBudgets, nextCandidates, nextEstate, nextProfiles, nextContracts] = await Promise.all([
api.capabilityDeployments(), api.scheduler(), api.deploymentCandidates(), api.capabilityEstate(),
api.runtimeProfiles(), api.capabilityContracts(),
]);
if (!current()) return;
setContracts(nextContracts);
setDeployments(nextDeployments);
setBudgets(nextBudgets);
setCandidates(nextCandidates);
setEstate(nextEstate);
setProfiles(nextProfiles);
const lastUpdatedAt = Date.now();
publicSnapshotAt.current = lastUpdatedAt;
setPublicRead({ kind: "fresh", lastUpdatedAt });
} catch (cause: unknown) {
if (!current()) return;
const failure = capabilityReadFailure(cause);
const lastUpdatedAt = publicSnapshotAt.current;
setPublicRead(lastUpdatedAt === null
? { kind: "unavailable", failure }
: { kind: "stale", failure, lastUpdatedAt });
}
}, []);
const loadAdmin = useCallback(async (token: string) => {
if (!token && !sessionActive) return;
if (!sessionActive || generation !== operatorSessionVersion()) 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),
]);
if (generation !== operatorSessionVersion()) return;
setRequests(nextRequests);
setClients(nextClients);
setApprovals(nextApprovals);
setPlans(nextPlans);
setPolicy(nextPolicy);
}, [sessionActive]);
}, [sessionActive, generation]);
useEffect(() => {
Promise.all([loadPublic(), sessionActive ? loadAdmin(sessionReference) : Promise.resolve()])
@@ -67,66 +117,65 @@ export function CapabilityWorkspace({ onError }: { onError: (message: string | n
useEffect(() => {
const interval = window.setInterval(() => {
loadPublic().catch((cause: unknown) => onError(errorMessage(cause)));
void loadPublic();
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)]); }
setRefreshing(true);
try { await Promise.all([loadPublic(), sessionActive ? loadAdmin(adminToken) : Promise.resolve()]); }
catch (cause: unknown) { onError(errorMessage(cause)); }
finally { setRefreshing(false); }
};
const authenticateAdmin = async (event: FormEvent) => {
event.preventDefault(); onError(null);
try { await loadAdmin(adminToken); setAdminUnlocked(true); }
catch (cause: unknown) { onError(errorMessage(cause)); }
};
if (loading) return <div className="state-card"><span className="state-spinner" />Loading capability serving state…</div>;
if (loading || publicRead.kind === "loading") return <div className="state-card"><span className="state-spinner" />Loading capability serving state…</div>;
if (publicRead.kind === "unavailable") return <CapabilityReadNotice failure={publicRead.failure} onRetry={refresh} refreshing={refreshing} />;
return <div className="capability-stack">
{publicRead.kind === "stale" ? <CapabilityReadNotice failure={publicRead.failure} lastUpdatedAt={publicRead.lastUpdatedAt} onRetry={refresh} refreshing={refreshing} /> : null}
<section className="capability-hero panel">
<div><span className="eyebrow">MULTI-CAPABILITY ESTATE</span><h2>{estate.length} governed contracts</h2><p>Capability-first routing across RAG, document, vision and audio · no client-visible model names</p></div>
<div className="capability-health"><span className={`status-chip ${deployment && ["healthy", "ready_on_demand"].includes(deployment.health_status) ? "active" : "degraded"}`}>{deployment?.health_status ?? "unavailable"}</span><strong>{deployment?.status ?? "not promoted"}</strong></div>
<div><span className="eyebrow">MULTI-CAPABILITY ESTATE</span><h2>{contracts.length} declared contracts</h2><p>Capability-first routing across RAG, document, vision and audio · no client-visible model names</p></div>
<div className="capability-health"><strong>{deployments.length} deployment records</strong><span>Inspect health per exact binding below.</span></div>
</section>
<div className="capability-toolbar">
<TabList idPrefix="capability" label="Capability operations" className="capability-tabs" tabs={capabilityViews} active={view} onSelect={setView} />
<button className="icon-action" aria-label="Refresh capability state" onClick={refresh}><RefreshCw size={15} /></button>
</div>
<TabPanel idPrefix="capability" active={view} className="capability-tabpanel">
{view === "overview" ? <CapabilityOverview deployment={deployment} requests={requests} estate={estate} /> : null}
{view === "scheduler" ? <><SchedulerView budgets={budgets} deployments={deployments} plans={plans} policy={policy} token={adminToken} unlocked={adminUnlocked} onChanged={refresh} onError={onError} /><AdminBoundary unlocked={adminUnlocked} token={adminToken} onToken={setAdminToken} onSubmit={authenticateAdmin}><></></AdminBoundary></> : null}
{view === "requests" ? <AdminBoundary unlocked={adminUnlocked} token={adminToken} onToken={setAdminToken} onSubmit={authenticateAdmin}><RequestHistory requests={requests} /></AdminBoundary> : null}
{view === "clients" ? <AdminBoundary unlocked={adminUnlocked} token={adminToken} onToken={setAdminToken} onSubmit={authenticateAdmin}><Clients clients={clients} token={adminToken} onChanged={() => loadAdmin(adminToken)} onError={onError} /></AdminBoundary> : null}
{view === "promotion" ? <AdminBoundary unlocked={adminUnlocked} token={adminToken} onToken={setAdminToken} onSubmit={authenticateAdmin}><Promotion deployment={deployment} candidates={candidates} approvals={approvals} token={adminToken} onChanged={refresh} onError={onError} /></AdminBoundary> : null}
{view === "overview" ? <CapabilityDetails contracts={contracts} deployments={deployments} estate={estate} targetDeploymentId={targetDeploymentId} /> : null}
{view === "scheduler" ? <><SchedulerView budgets={budgets} deployments={deployments} plans={plans} policy={policy} token={adminToken} unlocked={adminUnlocked} onChanged={refresh} onError={onError} /><AdminBoundary unlocked={adminUnlocked}><></></AdminBoundary></> : null}
{view === "requests" ? <AdminBoundary unlocked={adminUnlocked}><RequestHistory requests={requests} /></AdminBoundary> : null}
{view === "clients" ? <AdminBoundary unlocked={adminUnlocked}><Clients clients={clients} token={adminToken} onChanged={() => loadAdmin(adminToken)} onError={onError} /></AdminBoundary> : null}
{view === "promotion" ? <AdminBoundary unlocked={adminUnlocked}><PromotionGate key={generation} deployments={deployments} candidates={candidates} profiles={profiles} approvals={approvals} token={adminToken} onChanged={refresh} /></AdminBoundary> : null}
{view === "playground" ? <Playground /> : null}
</TabPanel>
</div>;
}
function CapabilityOverview({ deployment, requests, estate }: { deployment?: CapabilityDeployment; requests: GatewayRequest[]; estate: CapabilityEstate[] }) {
if (!estate.length) return <div className="state-card">No capability contracts are registered.</div>;
const successful = requests.filter((item) => item.status === "completed");
const warmHits = successful.filter((item) => item.cold === false).length;
return <>
<section className="project-grid">{estate.map((item) => <article className="panel project-card" key={`${item.capability}@${item.version}`}><span className="eyebrow">{item.category} · {item.resource_class}</span><h2>{item.capability}@{item.version}</h2><p>{item.purpose}</p><div className="binding-list"><div><span>State</span><strong>{item.operational_state}</strong></div><div><span>Evaluation</span><strong>{item.evaluation_state}</strong></div><div><span>Privacy</span><strong>{item.privacy_class}</strong></div><div><span>Consumers</span><strong>{item.consumers.join(", ") || "none declared"}</strong></div></div></article>)}</section>
{!deployment ? <div className="state-card">No stable deployment exists. New modality capabilities remain LAB-only.</div> : <>
<section className="metrics-grid capability-metrics">
<CapabilityMetric label="Channel" value={deployment.channel} hint={deployment.production ? "Production approved" : "Not production"} />
<CapabilityMetric label="Residency" value={deployment.residency.state} hint={`${deployment.residency.load_count} measured loads`} />
<CapabilityMetric label="GPU envelope" value={formatBytes(deployment.resource_envelope.required_vram_bytes)} hint="Measured, not estimated" />
<CapabilityMetric label="Queue" value={String(Math.max(0, requests.filter((item) => item.status === "queued").length))} hint={`Bounded at ${deployment.max_queue_depth}`} />
<CapabilityMetric label="Requests" value={String(requests.length)} hint="Bounded visible history" />
<CapabilityMetric label="Warm hit rate" value={successful.length ? `${Math.round((warmHits / successful.length) * 100)}%` : "No data"} hint="Only completed visible requests" />
</section>
<section className="grid-two">
<article className="panel evidence-list"><div className="panel-header"><div><span className="eyebrow">CONTRACT</span><h2>Backend-authoritative boundary</h2></div><ShieldCheck size={19} /></div><Evidence label="Input modality" value="text"/><Evidence label="Output modality" value="vector"/><Evidence label="Dimension / normalized" value={`${deployment.embedding_space.dimension} / ${deployment.embedding_space.normalized}`}/><Evidence label="Migration" value={deployment.embedding_space.migration_class}/><Evidence label="Retention" value="No request content persisted"/></article>
<article className="panel evidence-list"><div className="panel-header"><div><span className="eyebrow">RESIDENCY</span><h2>Load-on-demand state</h2></div><Activity size={19} /></div><Evidence label="Policy" value={`${deployment.residency_policy} · ${deployment.keep_warm_seconds}s`}/><Evidence label="State" value={deployment.residency.state}/><Evidence label="Active requests" value={String(deployment.residency.active_requests)}/><Evidence label="Resident since" value={formatTime(deployment.residency.resident_since)}/><Evidence label="Embedding space" value={deployment.embedding_space.id}/></article>
</section>
</>}</>;
function CapabilityReadNotice({ failure, lastUpdatedAt, onRetry, refreshing }: {
failure: CapabilityReadFailure;
lastUpdatedAt?: number;
onRetry: () => Promise<void>;
refreshing: boolean;
}) {
const hasSnapshot = lastUpdatedAt !== undefined;
const stateLabel = failure.kind === "offline" ? "OFFLINE" : hasSnapshot ? "STALE" : failure.kind.toUpperCase();
const stateClass = failure.kind === "offline" ? "offline" : hasSnapshot ? "stale" : failure.kind === "unknown" ? "unknown" : "error";
return <section className={hasSnapshot ? "panel capability-read-notice" : "error-banner capability-read-notice"} role={hasSnapshot ? "status" : "alert"} aria-labelledby="capability-read-notice-title">
<div><span className={`status-chip ${stateClass}`}>{stateLabel}</span><h2 id="capability-read-notice-title">{hasSnapshot ? "Capability data may be out of date" : "Capability serving state is unavailable"}</h2></div>
{hasSnapshot
? <p>The last successful snapshot was read {formatTime(new Date(lastUpdatedAt).toISOString())}. Counts below show that snapshot; the latest read failed.</p>
: <p>No authoritative snapshot was loaded, so contract and deployment totals are unknown. A failed read does not mean the estate is empty.</p>}
<div className="evidence-list">
<Evidence label="Read failure" value={failure.message} />
<Evidence label="Failure code" value={failure.code} />
<Evidence label="Correlation ID" value={failure.correlationId ?? "Not provided"} />
<Evidence label="Retryable" value={failure.retryable ? "Yes" : "No"} />
</div>
<p><strong>Next action:</strong> {failure.nextAction}</p>
<button type="button" onClick={() => void onRetry()} disabled={refreshing}>{refreshing ? "Retrying capability state…" : "Retry capability state"}</button>
</section>;
}
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<void>; onError: (message: string | null) => void }) {
@@ -221,49 +270,6 @@ function Clients({ clients, token, onChanged, onError }: { clients: ServiceClien
return <section className="grid-two"><form className="panel client-form" onSubmit={submit}><span className="eyebrow">SCOPED IDENTITY</span><h2>Create service client</h2><label>Name<input required pattern="[a-z][a-z0-9-]*" value={name} onChange={(event) => setName(event.target.value)} /></label><label>Requests per minute<input type="number" min="1" max="10000" value={rpm} onChange={(event) => setRpm(Number(event.target.value))} /></label><p>Scope is fixed to <code>rag.embedding@1</code>; concurrency starts conservatively at one.</p><button type="submit"><KeyRound size={15}/>Create one-time credential</button>{created ? <div className="one-time-secret"><strong>Copy this credential now</strong><code>{created.credential}</code><small>Only its hash is stored. It cannot be retrieved again.</small></div> : null}</form><article className="panel evidence-list"><div className="panel-header"><div><span className="eyebrow">CLIENTS</span><h2>Authorized consumers</h2></div><KeyRound size={19}/></div>{clients.length ? clients.map((client) => <div className="client-row" key={client.id}><div><strong>{client.name}</strong><span>{client.allowed_capabilities.join(", ")} · {client.requests_per_minute}/min · last used {formatTime(client.last_used_at)}</span></div><button className="danger" disabled={client.status !== "active"} onClick={() => revoke(client.id)}>{client.status === "active" ? "Revoke" : "Revoked"}</button></div>) : <p>No service clients created.</p>}</article></section>;
}
function Promotion({ deployment, candidates, approvals, token, onChanged, onError }: { deployment?: CapabilityDeployment; candidates: DeploymentCandidate[]; approvals: ProductionApproval[]; token: string; onChanged: () => Promise<void>; 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<Record<string, boolean>>({});
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 <article className="panel evidence-list"><div className="panel-header"><div><span className="eyebrow">AUDITED PRODUCTION GATE</span><h2>Promotion evidence</h2></div><ShieldCheck size={20}/></div>{deployment ? evidence.map(([label, value]) => <Evidence key={label} label={label} value={value}/>) : <><p>No stable deployment exists. Promotion remains two explicit, audited actions.</p><Evidence label="LAB_READY candidate" value={candidate?.id ?? "none"}/><Evidence label="Production approval" value={approval?.status ?? "required"}/>{candidate && !approval ? <details className="promotion-review" open><summary>Review the evidence being attested</summary><p>ModelForge records only claims the operator explicitly confirms below. Verify each claim in Registry, Runtime and Evaluation before approval.</p><div className="promotion-checklist">{reviewItems.map(([key, label]) => <label key={key}><input type="checkbox" checked={Boolean(reviewed[key])} onChange={(event) => setReviewed((current) => ({ ...current, [key]: event.target.checked }))}/><span>{label}</span></label>)}</div><label className="license-review">Reviewed license identifier<input value={licenseIdentifier} onChange={(event) => setLicenseIdentifier(event.target.value)} placeholder="For example: Apache-2.0" /></label></details> : null}<div className="promotion-actions"><button onClick={approve} disabled={!candidate || Boolean(approval) || !reviewComplete}>1. Record reviewed approval</button><button onClick={promote} disabled={!candidate || !approval}>2. Promote exact binding</button></div></>}</article>;
}
type ModalityResult = GatewayInvokeResponse | OCRInvokeResponse | VisionEmbeddingResponse | SpeechTranscriptionResponse;
async function fileBase64(file: File): Promise<string> {
@@ -307,14 +313,30 @@ function Playground() {
return <form className="panel playground" onSubmit={invoke}><div className="panel-header"><div><span className="eyebrow">REAL GATEWAY PATH</span><h2>Capability playground</h2></div><Play size={20}/></div><p>The client selects a capability contract. No model name, path, or runtime engine is accepted here.</p><label>Capability<select value={capability} onChange={(event) => { setCapability(event.target.value as typeof capability); setResult(null); }}><option value="rag.embedding">rag.embedding@1</option><option value="document.ocr">document.ocr@1</option><option value="vision.embedding">vision.embedding@1</option><option value="speech.transcription">speech.transcription@1</option></select></label><label>Service credential<input required type="password" autoComplete="off" value={credential} onChange={(event) => setCredential(event.target.value)} /></label>{capability === "rag.embedding" ? <label>Input text<textarea required maxLength={8192} value={input} onChange={(event) => setInput(event.target.value)} /></label> : <label>{capability === "speech.transcription" ? "WAV audio" : "PNG or JPEG image"}<input required type="file" accept={capability === "speech.transcription" ? ".wav,audio/wav" : "image/png,image/jpeg"} onChange={(event) => setFile(event.target.files?.[0] ?? null)} /></label>}<button disabled={running}>{running ? "Invoking…" : "Invoke capability"}</button>{failure ? <div className="error-banner"><strong>Typed gateway failure</strong><span>{failure}</span></div> : null}{result ? <div className="playground-result"><span className={`registry-status ${result.execution.cold ? "candidate" : "ready"}`}>{result.execution.cold ? "cold" : "warm"}</span><Evidence label="Request ID" value={result.request_id}/><Evidence label="Output" value={output}/>{"embedding_space_id" in result ? <Evidence label="Embedding space" value={result.embedding_space_id}/> : null}<Evidence label="Total / inference" value={`${formatMs(result.execution.timings.total_ms)} / ${formatMs(result.execution.timings.inference_ms)}`}/></div> : null}</form>;
}
function AdminBoundary({ unlocked, token, onToken, onSubmit, children }: { unlocked: boolean; token: string; onToken: (value: string) => void; onSubmit: (event: FormEvent) => Promise<void>; children: ReactNode }) {
if (unlocked) return <>{children}</>;
return <form className="panel admin-boundary" onSubmit={onSubmit}><ShieldCheck size={22}/><div><h2>Operator authentication required</h2><p>Administrative data and actions require the operator credential. It remains in browser memory only.</p></div><label htmlFor="capability-operator-key">Operator API key</label><input id="capability-operator-key" name="operator-api-key" required type="password" autoComplete="off" value={token} onChange={(event) => onToken(event.target.value)} /><button type="submit">Unlock operational view</button></form>;
function AdminBoundary({ unlocked, children }: { unlocked: boolean; children: ReactNode }) {
return unlocked ? <>{children}</> : <div className="state-card">Read-only access. Administrative operations require an active admin Console session.</div>;
}
function CapabilityMetric({ label, value, hint }: { label: string; value: string; hint: string }) { return <article className="metric-card"><span>{label}</span><strong>{value}</strong><small>{hint}</small></article>; }
function Evidence({ label, value }: { label: string; value: string }) { return <div className="evidence-row"><span>{label}</span><strong title={value}>{value}</strong></div>; }
function formatBytes(value: number): string { return `${(value / 1024 ** 3).toFixed(2)} GiB`; }
function formatMs(value?: number | null): string { return value == null ? "—" : `${value.toFixed(1)} ms`; }
function formatTime(value?: string | null): string { return value ? new Date(value).toLocaleString() : "never"; }
function capabilityReadFailure(cause: unknown): CapabilityReadFailure {
const apiFailure = cause instanceof ApiError ? cause : null;
const offline = apiFailure === null && ((cause instanceof TypeError) || (typeof navigator !== "undefined" && navigator.onLine === false));
const kind: CapabilityReadFailure["kind"] = offline ? "offline" : apiFailure ? "error" : "unknown";
const failureCode = apiFailure?.details.failure_code;
const code = typeof failureCode === "string" ? failureCode : apiFailure?.code ?? (apiFailure ? `HTTP_${apiFailure.status}` : offline ? "NETWORK_UNAVAILABLE" : "UNKNOWN_ERROR");
const retryable = apiFailure ? apiFailure.status === 408 || apiFailure.status === 429 || apiFailure.status >= 500 : offline;
const rawMessage = cause instanceof Error ? cause.message : "Capability state could not be read";
const message = rawMessage.replace(/\s+\(correlation [^)]+\)$/, "");
const nextAction = offline
? "Restore the connection to the ModelForge API, then retry this read."
: apiFailure?.status === 401 || apiFailure?.status === 403
? "Check the active Console identity and its read access, then retry."
: retryable
? "Retry this read. If it continues to fail, share the failure code and correlation ID with the operator team."
: "Review the API response and Console access, then retry after addressing the reported failure.";
return { kind, message, code, correlationId: apiFailure?.correlationId ?? null, retryable, nextAction };
}
function errorMessage(cause: unknown): string { return cause instanceof ApiError ? `${cause.message}${typeof cause.details.failure_code === "string" ? ` (${cause.details.failure_code})` : ""}` : cause instanceof Error ? cause.message : "Capability operation failed"; }