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(null); const [system, setSystem] = useState(null); const [tenant, setTenant] = useState(""); const [setup, setSetup] = useState(null); const [voice, setVoice] = useState(null); const [grant, setGrant] = useState(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

Platform admin

Operator

Secrets masked
{loadError ?
{loadError.sentence}
: null} {problem ?

{problem}

: null}

Tenant setup

{grant ?
Capabilities
{grant.capabilities.join(", ")}
Expires
: null} {setup ?
{SAFE_SETUP_FIELDS .filter((field) => setup.setup[field] !== undefined) .map((field) =>
{field}
{String(setup.setup[field])}
)}
: null} {voice ? <>
Schema
{voice.voice.schemaVersion}
Recipient ceiling
{voice.voice.maxRecipientsCeiling}
Providers
{voice.voice.providers.map((provider) => provider.label).join(", ") || "None reported"}

Secrets present: {String(voice.secretsPresent)}. Raw provider bindings: {String(voice.rawProviderBindings)}.

: null}

Audit history

{audit === null ? (loadError ? null : ) :
    {audit.map((entry, index) =>
  1. {entry.action} · {entry.outcome}{entry.actor}, {entry.tenant}
  2. )}
}

System data

{system === null && !loadError ? : null} {inspectorOpen && system ?
{system.databases.map((row) =>
{row.label || row.key}
{row.fields.length} field definitions · read only
)}
: null}
; } 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(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

Intents

{problem || data?.unavailableTenants.length ?
{problem || "Some intent history could not be loaded."}
: null} {data === null ? (problem ? null : ) : data.rows.length ?
{["Time", "Tenant", "Tool", "Action", "Outcome", "Intent"].map((heading) => )}{data.rows.map((row, index) => )}
{heading}
{row.tenant}{row.tool}{row.action}{row.outcome}{row.intent || "Not provided"}
: data.unavailableTenants.length ? null :

{tool ? "No calls for this tool." : "No calls yet."}

}
; } /** The shared Settings skeleton while a protected read is in flight. */ function ReadSkeleton({ label }: { label: string }) { return
; }