Download web/src/operator/OperatorPage.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/9291c0100f4e7b8da2efcbbf1ebdea72ee1663e7/web/src/operator/OperatorPage.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable@9291c0100f4e7b8da2efcbbf1ebdea72ee1663e7/web/src/operator/OperatorPage.tsx
-
curl -L -o OperatorPage.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/9291c0100f4e7b8da2efcbbf1ebdea72ee1663e7/web/src/operator/OperatorPage.tsx
11.8 kB
| import { useEffect, useRef, useState } from "react"; | |
| import { | |
| AutomationError, createOperatorGrant, getOperatorAudit, getOperatorSetup, | |
| getOperatorVoiceSetup, getSystemData, type OperatorAudit, type OperatorGrant, | |
| type OperatorSetup, type OperatorSetupField, type OperatorVoiceSetup, type SystemData, | |
| } from "../automation/automationApi"; | |
| import { API_V1, CREDENTIALS, TOAST_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract"; | |
| import "./operator.css"; | |
| export interface OperatorPageProps { platformAdmin: boolean } | |
| const SAFE_SETUP_FIELDS: OperatorSetupField[] = [ | |
| "displayName", "timezone", "voicePurpose", "consentPolicy", "queryEnabled", "providerLabel", | |
| ]; | |
| function useRefusalToast() { | |
| const [messages, setMessages] = useState<{ id: number; text: string }[]>([]); | |
| const sequence = useRef(0); | |
| const delivered = useRef(0); | |
| useEffect(() => { | |
| if (!messages.length) return; | |
| const through = messages[messages.length - 1].id; | |
| for (const message of messages) { | |
| if (message.id <= delivered.current) continue; | |
| delivered.current = message.id; | |
| const text = message.text; | |
| window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } })); | |
| } | |
| setMessages((current) => current.filter((message) => message.id > through)); | |
| }, [messages]); | |
| return (text: string) => { | |
| if (!text) return; | |
| const message = { id: ++sequence.current, text }; | |
| setMessages((current) => [...current, message]); | |
| }; | |
| } | |
| export default function OperatorPage({ platformAdmin }: OperatorPageProps) { | |
| const refuse = useRefusalToast(); | |
| const [audit, setAudit] = useState<OperatorAudit[] | null>(null); | |
| const [system, setSystem] = useState<SystemData | null>(null); | |
| const [tenant, setTenant] = useState(""); | |
| const [setup, setSetup] = useState<OperatorSetup | null>(null); | |
| const [voice, setVoice] = useState<OperatorVoiceSetup | null>(null); | |
| const [grant, setGrant] = useState<OperatorGrant | null>(null); | |
| const [problem, setProblem] = useState(""); | |
| const [busy, setBusy] = useState(false); | |
| const [inspectorOpen, setInspectorOpen] = useState(false); | |
| const [loadError, setLoadError] = useState<{ sentence: string; detail: string } | null>(null); | |
| const [loadAttempt, setLoadAttempt] = useState(0); | |
| useEffect(() => { | |
| if (!platformAdmin) return; | |
| const controller = new AbortController(); | |
| setLoadError(null); setAudit(null); setSystem(null); | |
| void Promise.all([getOperatorAudit(controller.signal), getSystemData(controller.signal)]) | |
| .then(([a, s]) => { setAudit(a.audit); setSystem(s); }) | |
| .catch((error) => { | |
| if (controller.signal.aborted) return; | |
| const refused = error instanceof AutomationError && (error.status === 403 || error.status === 404); | |
| // S74-T13: a failed read is one plain sentence with Retry; the server text stays in the tooltip. | |
| setLoadError({ | |
| sentence: refused ? "Operator is unavailable for this account." : "Could not load the audit history and system data.", | |
| detail: error instanceof Error ? error.message : "", | |
| }); | |
| }); | |
| return () => controller.abort(); | |
| }, [platformAdmin, loadAttempt]); | |
| if (!platformAdmin) return null; | |
| async function inspectTenant() { | |
| const target = tenant.trim().toLowerCase(); | |
| if (!target) return; | |
| setBusy(true); setProblem(""); setSetup(null); setVoice(null); setGrant(null); | |
| try { | |
| const granted = await createOperatorGrant(target, ["tenant.read", "voice.read"]); | |
| setGrant(granted.grant); | |
| const tenantSetup = await getOperatorSetup(target, granted.token); | |
| const voiceSetup = await getOperatorVoiceSetup(target, granted.token); | |
| setSetup(tenantSetup); setVoice(voiceSetup); | |
| } catch (error) { | |
| const refused = error instanceof AutomationError && [401, 403, 404].includes(error.status); | |
| const text = (refused ? "That tenant or capability is unavailable. " : "") | |
| + (error instanceof Error ? error.message : "Tenant setup unavailable."); | |
| if (refused) refuse(text); | |
| else setProblem(text); | |
| } finally { | |
| // Both allowed and refused inspections append an audit result. Refresh after either path so | |
| // the visible receipt is the final server outcome, not the preflight list. | |
| try { setAudit((await getOperatorAudit()).audit); } | |
| catch (error) { | |
| const text = error instanceof Error ? error.message : "Audit refresh unavailable."; | |
| if (error instanceof AutomationError && [401, 403, 404].includes(error.status)) refuse(text); | |
| else setLoadError({ sentence: "Could not refresh the audit history.", detail: text }); | |
| } | |
| setBusy(false); | |
| } | |
| } | |
| return <section className="op-page" aria-labelledby="operator-heading"> | |
| <header className="op-head"><div><p className="op-kicker">Platform admin</p><h3 id="operator-heading">Operator</h3></div><span className="op-mask">Secrets masked</span></header> | |
| {loadError ? <div className="set-error" role="alert"> | |
| <span title={loadError.detail || undefined}>{loadError.sentence}</span> | |
| <button type="button" className="set-secondary" onClick={() => setLoadAttempt((n) => n + 1)}>Retry</button> | |
| </div> : null} | |
| {problem ? <p className="set-error" role="alert">{problem}</p> : null} | |
| <section className="op-section" aria-labelledby="operator-access-heading"><h4 id="operator-access-heading">Tenant setup</h4> | |
| <label className="set-field"><span>Exact tenant slug</span><input value={tenant} onChange={(event) => setTenant(event.currentTarget.value)} /></label> | |
| <button type="button" className="op-quiet" disabled={busy || !tenant.trim()} onClick={() => void inspectTenant()}>{busy ? "Authorizing…" : "Inspect with read grant"}</button> | |
| {grant ? <dl className="op-facts" aria-label="Minted read grant"> | |
| <div><dt>Capabilities</dt><dd>{grant.capabilities.join(", ")}</dd></div> | |
| <div><dt>Expires</dt><dd><time dateTime={new Date(grant.expiresAt * 1000).toISOString()}>{new Date(grant.expiresAt * 1000).toLocaleString()}</time></dd></div> | |
| </dl> : null} | |
| {setup ? <dl className="op-facts" aria-label="Safe tenant setup">{SAFE_SETUP_FIELDS | |
| .filter((field) => setup.setup[field] !== undefined) | |
| .map((field) => <div key={field}><dt>{field}</dt><dd>{String(setup.setup[field])}</dd></div>)}</dl> : null} | |
| {voice ? <> | |
| <dl className="op-facts" aria-label="Safe Voice setup"> | |
| <div><dt>Schema</dt><dd>{voice.voice.schemaVersion}</dd></div> | |
| <div><dt>Recipient ceiling</dt><dd>{voice.voice.maxRecipientsCeiling}</dd></div> | |
| <div><dt>Providers</dt><dd>{voice.voice.providers.map((provider) => provider.label).join(", ") || "None reported"}</dd></div> | |
| </dl> | |
| <p className="w45-safe">Secrets present: {String(voice.secretsPresent)}. Raw provider bindings: {String(voice.rawProviderBindings)}.</p> | |
| </> : null} | |
| </section> | |
| <section className="op-section" aria-labelledby="operator-audit-heading"><h4 id="operator-audit-heading">Audit history</h4> | |
| {audit === null ? (loadError ? null : <ReadSkeleton label="Loading audit history" />) : <ol className="op-audit">{audit.map((entry, index) => <li key={entry.id || `${entry.action}-${index}`}><span>{entry.action} · {entry.outcome}</span><small>{entry.actor}, {entry.tenant}</small></li>)}</ol>} | |
| </section> | |
| <OperatorIntents /> | |
| <section className="op-section" aria-labelledby="system-data-heading"><div className="op-section-head"><h4 id="system-data-heading">System data</h4><button type="button" className="op-quiet" disabled={!system} aria-expanded={inspectorOpen} onClick={() => setInspectorOpen((open) => !open)}>{inspectorOpen ? "Close inspector" : "Open inspector"}</button></div> | |
| {system === null && !loadError ? <ReadSkeleton label="Loading system data" /> : null} | |
| {inspectorOpen && system ? <dl className="op-facts op-system-data" aria-label="Read-only system data inspector">{system.databases.map((row) => <div key={row.key}><dt>{row.label || row.key}</dt><dd>{row.fields.length} field definitions · read only</dd></div>)}</dl> : null} | |
| </section> | |
| </section>; | |
| } | |
| interface IntentRow { ts: number; tenant: string; tool: string; action: string; outcome: string; intent: string } | |
| interface IntentList { rows: IntentRow[]; tools: string[]; total: number; unavailableTenants: string[] } | |
| function OperatorIntents() { | |
| const [data, setData] = useState<IntentList | null>(null); | |
| const [tool, setTool] = useState(""); | |
| const [problem, setProblem] = useState(""); | |
| const [attempt, setAttempt] = useState(0); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| setData(null); setProblem(""); | |
| void (async () => { | |
| try { | |
| const response = await fetch(`${API_V1}/feedback/intents?tool=${encodeURIComponent(tool)}`, { | |
| credentials: CREDENTIALS, cache: "no-store", signal: controller.signal, | |
| }); | |
| if (checkTenant(response)) return; | |
| if (response.status === 401) signal(UNAUTHORIZED_EVENT); | |
| if (!response.ok) { | |
| throw new Error(response.status === 403 | |
| ? "Intents are unavailable for this account." : "Could not load intents."); | |
| } | |
| const body: IntentList = await response.json(); | |
| if (!controller.signal.aborted) setData(body); | |
| } catch (error) { | |
| if (!controller.signal.aborted) setProblem(error instanceof Error ? error.message : "Could not load intents."); | |
| } | |
| })(); | |
| return () => controller.abort(); | |
| }, [tool, attempt]); | |
| return <section className="op-section" aria-labelledby="operator-intents-heading"> | |
| <h4 id="operator-intents-heading">Intents</h4> | |
| <div className="set-field"> | |
| <label className="set-label" htmlFor="operator-intents-tool">Tool</label> | |
| <select id="operator-intents-tool" className="pg-select" value={tool} onChange={(event) => setTool(event.currentTarget.value)}> | |
| <option value="">All tools</option> | |
| {Array.from(new Set([...(data?.tools ?? []), ...(tool ? [tool] : [])])).sort().map((name) => <option key={name} value={name}>{name}</option>)} | |
| </select> | |
| </div> | |
| {problem || data?.unavailableTenants.length ? <div className="set-error" role="alert"> | |
| <span>{problem || "Some intent history could not be loaded."}</span> | |
| <button type="button" className="set-secondary" onClick={() => setAttempt((value) => value + 1)}>Retry</button> | |
| </div> : null} | |
| {data === null ? (problem ? null : <ReadSkeleton label="Loading intents" />) : data.rows.length ? <div className="padmin-tablewrap" role="region" aria-label="Intent history" tabIndex={0}><table className="set-table" aria-label="Intents"> | |
| <thead><tr>{["Time", "Tenant", "Tool", "Action", "Outcome", "Intent"].map((heading) => <th key={heading} scope="col">{heading}</th>)}</tr></thead> | |
| <tbody>{data.rows.map((row, index) => <tr key={`${row.tenant}-${row.ts}-${index}`} data-intent-row> | |
| <td><time dateTime={new Date(row.ts * 1000).toISOString()}>{new Date(row.ts * 1000).toLocaleString()}</time></td> | |
| <td>{row.tenant}</td><td>{row.tool}</td><td>{row.action}</td><td>{row.outcome}</td><td>{row.intent || "Not provided"}</td> | |
| </tr>)}</tbody> | |
| </table></div> : data.unavailableTenants.length ? null : <p className="set-help">{tool ? "No calls for this tool." : "No calls yet."}</p>} | |
| </section>; | |
| } | |
| /** The shared Settings skeleton while a protected read is in flight. */ | |
| function ReadSkeleton({ label }: { label: string }) { | |
| return <div className="set-skeleton" role="status" aria-label={label} aria-busy="true"> | |
| <span className="set-skeleton-line" aria-hidden="true" /> | |
| <span className="set-skeleton-line" aria-hidden="true" /> | |
| <span className="set-skeleton-line" aria-hidden="true" /> | |
| </div>; | |
| } | |