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

@@ -0,0 +1,179 @@
import { useCallback, useEffect, useRef, useState } from "react";
import type { ChangeEvent, FormEvent } from "react";
import { api, operatorCredentialReference, operatorSessionVersion } from "../lib/api";
import type { OperatorIdentity } from "../lib/api";
import type { DeploymentCandidate, ExecutionApproval, HardwareState, LabCapability, LabInput, LabPreflightResponse, LabTarget, RuntimeProbe, RuntimeProfile } from "../types";
const families: { key: LabCapability; name: string; modality: string }[] = [
{ key: "rag.embedding", name: "Text embedding", modality: "embedding" },
{ key: "rag.reranking", name: "Reranking", modality: "reranking" },
{ key: "document.ocr", name: "Document OCR", modality: "document" },
{ key: "vision.embedding", name: "Visual embedding", modality: "vision" },
{ key: "speech.transcription", name: "Speech transcription", modality: "audio" },
];
const limits = { timeout_seconds: 60, queue_timeout_seconds: 10, retention_seconds: 300, max_output_bytes: 65536, concurrency: 1 as const };
const MAX_FILE_BYTES = 360 * 1024;
const MAX_REQUEST_BYTES = 512 * 1024;
type Evidence = { candidates: DeploymentCandidate[]; profiles: RuntimeProfile[]; approvals: ExecutionApproval[]; probes: RuntimeProbe[]; hardware: HardwareState };
const empty: Evidence = { candidates: [], profiles: [], approvals: [], probes: [], hardware: { overview: { status: "unknown", inventory_state: "unknown", node_count: 0, accelerator_count: 0 }, nodes: [] } };
const approvalUsable = (item: ExecutionApproval) => item.scope === "lab_execution" && item.status === "approved" && !item.stale && !item.revoked_at && (!item.expires_at || Date.parse(item.expires_at) > Date.now());
const explanations: Record<string, string> = {
INPUT_LIMIT_EXCEEDED: "The input exceeds the server's item or text limit. Reduce the input.",
PAYLOAD_LIMIT_EXCEEDED: "The encoded input exceeds the configured gateway limit (64 KiB by default). Use a smaller sample.",
CAPABILITY_CONTRACT_UNAVAILABLE: "This capability version is unavailable in the server configuration.",
CANDIDATE_NOT_FOUND: "The selected candidate no longer exists. Refresh the evidence.",
CANDIDATE_NOT_LAB_READY: "The candidate must remain a non-production LAB-ready candidate.",
TARGET_IDENTITY_MISMATCH: "The selected artifact, profile or node no longer matches the candidate.",
EVIDENCE_MISSING: "Required approval, profile, node, assessment or probe evidence is missing.",
EVIDENCE_IDENTITY_MISMATCH: "The reviewed evidence belongs to a different exact target.",
CAPABILITY_PROFILE_MISMATCH: "The selected runtime profile does not support this capability family.",
RUNTIME_POLICY_UNSUPPORTED: "This Lab check requires offline execution with remote code disabled.",
NODE_NOT_READY: "The node is not online, enabled and eligible for this Lab operation.",
ASSESSMENT_STALE_OR_BLOCKED: "Compatibility evidence changed or has unresolved blockers. Review it in Runtime.",
LAB_APPROVAL_STALE: "The LAB approval expired, was revoked or no longer matches current artifact evidence.",
ARTIFACT_EVIDENCE_MISSING: "Current artifact evidence is unavailable.",
PROBE_NOT_COMPLETED: "A successfully completed, matching runtime probe is required.",
PROBE_OUTPUT_INVALID: "The completed probe does not establish the expected output contract.",
PROBED_ACCELERATOR_MISSING: "The accelerator used by the probe is no longer available on this node.",
};
export function LabPreflightWorkspace({ role = "viewer" }: { role?: OperatorIdentity["role"] }) {
const [evidence, setEvidence] = useState<Evidence>(empty);
const [capability, setCapability] = useState<LabCapability | "">("");
const [candidateId, setCandidateId] = useState("");
const [approvalId, setApprovalId] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const mounted = useRef(false);
const loadSequence = useRef(0);
const generation = operatorSessionVersion();
const current = useCallback(() => mounted.current && operatorSessionVersion() === generation && Boolean(operatorCredentialReference()), [generation]);
const load = useCallback(async () => {
if (!current()) return;
const sequence = ++loadSequence.current;
const valid = () => current() && sequence === loadSequence.current;
setLoading(true);
try {
const [candidates, profiles, approvals, probes, hardware] = await Promise.all([api.deploymentCandidates(), api.runtimeProfiles(), api.executionApprovals(), api.runtimeProbes(), api.hardware()]);
if (!valid()) return;
setEvidence({ candidates, profiles, approvals, probes, hardware });
setCandidateId(id => candidates.some(item => item.id === id) ? id : "");
setApprovalId(id => approvals.some(item => item.id === id && approvalUsable(item)) ? id : "");
setError(null);
} catch {
if (!valid()) return;
setEvidence(empty); setCandidateId(""); setApprovalId("");
setError("Lab evidence could not be loaded. Refresh after checking the connection.");
} finally { if (valid()) setLoading(false); }
}, [current]);
useEffect(() => {
mounted.current = true;
setEvidence(empty); setCapability(""); setCandidateId(""); setApprovalId(""); setError(null);
void load();
return () => { mounted.current = false; loadSequence.current += 1; };
}, [load]);
const candidates = evidence.candidates.filter(item => !item.production && item.channel === "lab" && item.status === "lab_ready" && evidence.profiles.some(profile => profile.id === item.runtime_profile_id && profile.modality === families.find(family => family.key === capability)?.modality));
const candidate = candidates.find(item => item.id === candidateId);
const profile = evidence.profiles.find(item => item.id === candidate?.runtime_profile_id);
const node = evidence.hardware.nodes.find(item => item.id === candidate?.compute_node_id);
const probe = evidence.probes.find(item => item.id === candidate?.runtime_probe_id);
const approvals = evidence.approvals.filter(item => item.artifact_set_id === candidate?.artifact_set_id);
const approval = approvals.find(item => item.id === approvalId && approvalUsable(item) && item.id === probe?.execution_approval_id);
const target: LabTarget | null = candidate && profile && node && approval ? { deployment_candidate_id: candidate.id, artifact_set_id: candidate.artifact_set_id, runtime_profile_id: candidate.runtime_profile_id, compute_node_id: candidate.compute_node_id, execution_approval_id: approval.id } : null;
const bindingKey = JSON.stringify([generation, role, capability, candidate, profile, node, probe, approval]);
return <div className="lab-preflight">
<article className="panel"><h2>Check a Lab request</h2><p>This preview checks an exact candidate and a small input sample. It does not run inference, reserve resources, create a job or grant execution permission.</p><p>Input remains in this view's memory and is sent only when you check it. The server returns redacted metadata. Changing the target, session or capability clears the input and result.</p></article>
{error ? <p role="alert" className="error-banner">{error}</p> : null}
{!current() || role === "viewer" ? <p role="status">Read-only inspection. A verified operator or administrator session is required to check a request.</p> : null}
<button type="button" disabled={loading || !current()} onClick={() => void load()}>{loading ? "Refreshing Lab evidence…" : "Refresh Lab evidence"}</button>
<article className="panel"><div className="grid-two">
<label>Lab capability<select value={capability} onChange={event => { setCapability(event.target.value as LabCapability | ""); setCandidateId(""); setApprovalId(""); }}><option value="">Select a capability</option>{families.map(item => <option key={item.key} value={item.key}>{item.name} · {item.key}@1</option>)}</select></label>
<label>Lab candidate<select value={candidate?.id ?? ""} disabled={!capability} onChange={event => { setCandidateId(event.target.value); setApprovalId(""); }}><option value="">Select an exact candidate</option>{candidates.map(item => <option key={item.id} value={item.id}>{item.id} · {evidence.profiles.find(value => value.id === item.runtime_profile_id)?.name}</option>)}</select></label>
<label>LAB execution approval<select value={approval?.id ?? ""} disabled={!candidate} onChange={event => setApprovalId(event.target.value)}><option value="">Select the reviewed approval</option>{approvals.map(item => <option key={item.id} value={item.id} disabled={!approvalUsable(item) || item.id !== probe?.execution_approval_id}>{item.id}{!approvalUsable(item) ? " · unavailable" : item.id !== probe?.execution_approval_id ? " · different probe" : ""}</option>)}</select></label>
</div>{capability && !loading && !candidates.length ? <p>No LAB-ready candidate with a matching profile is available for this family.</p> : null}
{candidate ? <dl className="runtime-facts"><Fact name="Candidate" value={candidate.id} /><Fact name="Artifact set" value={candidate.artifact_set_id} /><Fact name="Runtime profile" value={profile ? `${profile.name} · ${profile.id}` : "Unavailable"} /><Fact name="Target node" value={node ? `${node.display_name} · ${node.id} · ${node.liveness}` : "Unavailable"} /><Fact name="Runtime probe" value={candidate.runtime_probe_id} /><Fact name="Selected approval" value={approval?.id ?? "Not selected"} /></dl> : <p>Select a capability and exact candidate to inspect its binding.</p>}</article>
<LabRequestForm key={bindingKey} capability={capability} target={target} probeId={candidate?.runtime_probe_id} assessmentId={candidate?.compatibility_assessment_id} generation={generation} canCheck={role !== "viewer" && current()} />
</div>;
}
function Fact({ name, value }: { name: string; value: string | number }) { return <div><dt>{name}</dt><dd>{value}</dd></div>; }
function LabRequestForm({ capability, target, probeId, assessmentId, generation, canCheck }: { capability: LabCapability | ""; target: LabTarget | null; probeId?: string; assessmentId?: string; generation: number; canCheck: boolean }) {
const [text, setText] = useState("");
const [documents, setDocuments] = useState("");
const [visionMode, setVisionMode] = useState<"text" | "image">("text");
const [file, setFile] = useState<{ base64: string; mediaType: string; name: string } | null>(null);
const [reading, setReading] = useState(false);
const [working, setWorking] = useState(false);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<LabPreflightResponse | null>(null);
const mounted = useRef(false);
const sequence = useRef(0);
const fileSequence = useRef(0);
const lock = useRef(false);
const reader = useRef<FileReader | null>(null);
const current = () => mounted.current && generation === operatorSessionVersion() && Boolean(operatorCredentialReference());
useEffect(() => { mounted.current = true; return () => { mounted.current = false; sequence.current += 1; fileSequence.current += 1; reader.current?.abort(); }; }, []);
function changed() { sequence.current += 1; setResult(null); setError(null); }
function chooseFile(event: ChangeEvent<HTMLInputElement>) {
changed(); fileSequence.current += 1; reader.current?.abort(); setFile(null); setReading(false);
const chosen = event.target.files?.[0];
if (!chosen) return;
const mediaType = chosen.type === "audio/x-wav" ? "audio/wav" : chosen.type;
const allowed = capability === "speech.transcription" ? mediaType === "audio/wav" : mediaType === "image/png" || mediaType === "image/jpeg";
if (!allowed || chosen.size === 0 || chosen.size > MAX_FILE_BYTES) { setError("Choose a non-empty PNG/JPEG image or WAV audio sample for this family, at most 360 KiB."); event.target.value = ""; return; }
const token = fileSequence.current;
const next = new FileReader(); reader.current = next; setReading(true);
next.onload = () => {
if (!current() || token !== fileSequence.current) return;
setReading(false);
const data = typeof next.result === "string" ? next.result.split(",")[1] : undefined;
if (!data) { setError("The sample could not be read."); return; }
setFile({ base64: data, mediaType, name: chosen.name });
};
next.onerror = () => { if (current() && token === fileSequence.current) { setReading(false); setError("The sample could not be read."); } };
next.readAsDataURL(chosen);
}
function input(): LabInput | null {
if (capability === "rag.embedding" && text.trim()) return { capability, payload: { input: text, input_type: "raw" } };
if (capability === "rag.reranking" && text.trim()) {
const items = documents.split(/\r?\n/).filter(value => value.trim()).map((value, index) => ({ id: `document-${index + 1}`, text: value }));
if (items.length && items.length <= 40) return { capability, payload: { query: text, documents: items, top_n: Math.min(10, items.length) } };
}
if (capability === "vision.embedding" && visionMode === "text" && text.trim()) return { capability, payload: { items: [{ text }] } };
if (capability === "vision.embedding" && visionMode === "image" && file && (file.mediaType === "image/png" || file.mediaType === "image/jpeg")) return { capability, payload: { items: [{ image_base64: file.base64, media_type: file.mediaType }] } };
if (capability === "document.ocr" && file && (file.mediaType === "image/png" || file.mediaType === "image/jpeg")) return { capability, payload: { content_base64: file.base64, media_type: file.mediaType, language_hint: "auto" } };
if (capability === "speech.transcription" && file) return { capability, payload: { audio_base64: file.base64, media_type: "audio/wav", language: "auto" } };
return null;
}
async function submit(event: FormEvent) {
event.preventDefault();
const selectedInput = input();
if (lock.current || !current() || !canCheck || !target || !selectedInput || reading) return;
const body = { target, input: selectedInput, contract_version: 1 as const, limits };
if (new TextEncoder().encode(JSON.stringify(body)).length > MAX_REQUEST_BYTES) { setError("The complete request exceeds the 512 KiB preview limit. Use a smaller sample."); return; }
lock.current = true; const token = ++sequence.current; setWorking(true); setResult(null); setError(null);
try {
const response = await api.labPreflight(body);
if (!current() || token !== sequence.current) return;
if ((response.checks_passed && (!response.binding || response.blockers.length > 0)) || response.execution_started !== false || response.permission_granted !== false || (response.binding && (response.binding.runtime_probe_id !== probeId || response.binding.compatibility_assessment_id !== assessmentId || response.binding.capability !== capability || response.binding.contract_version !== 1 || Object.entries(target).some(([key, value]) => response.binding?.[key as keyof LabTarget] !== value)))) { setError("The preflight response does not match this exact request. Refresh evidence and check again."); return; }
setResult(response);
} catch { if (current() && token === sequence.current) setError("The request could not be checked. Verify the input limits and session, then refresh evidence and retry."); }
finally { lock.current = false; if (current()) setWorking(false); }
}
const needsFile = capability === "document.ocr" || capability === "speech.transcription" || (capability === "vision.embedding" && visionMode === "image");
return <article className="panel"><h3>Small input sample</h3><p>Checks use a 60-second runtime limit, a 10-second queue limit, one concurrent run, a 64 KiB output limit and 300-second retention policy. These are proposed limits; nothing is scheduled or retained by this check.</p>
<form onSubmit={event => void submit(event)}>
<fieldset disabled={!canCheck || !target || working}><legend>Preview input</legend>
{capability === "vision.embedding" ? <label>Visual input type<select value={visionMode} onChange={event => { changed(); setVisionMode(event.target.value as "text" | "image"); setText(""); setFile(null); fileSequence.current += 1; reader.current?.abort(); setReading(false); }}><option value="text">Text</option><option value="image">Image</option></select></label> : null}
{capability && !needsFile ? <label>{capability === "rag.reranking" ? "Ranking query" : "Sample text"}<textarea value={text} maxLength={capability === "rag.embedding" ? 8192 : 4000} rows={4} onChange={event => { changed(); setText(event.target.value); }} /></label> : null}
{capability === "rag.reranking" ? <label>Documents, one per line<textarea value={documents} maxLength={60000} rows={5} onChange={event => { changed(); setDocuments(event.target.value); }} /><span>Up to 40 documents. The result limit is the smaller of 10 and the document count.</span></label> : null}
{needsFile ? <label>{capability === "speech.transcription" ? "WAV audio sample" : "Image sample"}<input type="file" accept={capability === "speech.transcription" ? ".wav,audio/wav,audio/x-wav" : ".png,.jpg,.jpeg,image/png,image/jpeg"} onChange={chooseFile} /><span>At most 360 KiB before reading; the full preview request is capped at 512 KiB. The server's configured gateway limit can be smaller.</span></label> : null}
{reading ? <p role="status">Reading sample into memory…</p> : file ? <p>Sample loaded: {file.name}</p> : null}
<button type="submit" disabled={!target || !canCheck || working || reading || !input()}>{working ? "Checking request…" : "Check request"}</button>
</fieldset>
</form>
{error ? <p role="alert" className="error-banner">{error}</p> : null}
{result ? <section aria-label="Preflight result" aria-live="polite"><h3>{result.checks_passed ? "Snapshot checks passed" : "Request blocked"}</h3><p>No inference ran. No execution permission was granted. A future run must recheck current evidence and resource availability.</p>{result.blockers.length ? <ul>{result.blockers.map(code => <li key={code}>{explanations[code] ?? "The server reported an unresolved preflight blocker. Review current evidence before retrying."} <code>{/^[A-Z_]{1,80}$/.test(code) ? code : "UNKNOWN_BLOCKER"}</code></li>)}</ul> : null}<dl className="runtime-facts"><Fact name="Input SHA-256" value={result.input_summary.sha256} /><Fact name="Input items" value={result.input_summary.item_count} /><Fact name="Encoded input bytes" value={result.input_summary.encoded_bytes} />{result.binding ? <><Fact name="Checked candidate" value={result.binding.deployment_candidate_id} /><Fact name="Profile fingerprint" value={result.binding.runtime_profile_fingerprint} /><Fact name="Assessment fingerprint" value={result.binding.assessment_fingerprint} /><Fact name="Probe runtime fingerprint" value={result.binding.probe_environment_fingerprint} /></> : null}</dl></section> : null}
</article>;
}