import { useEffect, useState, useRef } from 'react'; import Button from '../components/ui/Button'; import RouterUsagePanel from '../components/RouterUsagePanel'; import RuntimeReadPanel from '../components/RuntimeReadPanel'; import CreateOrchestrationTask from '../components/CreateOrchestrationTask'; import { orchestration, killLevels, actionBlockReason, commandFailure } from '../services/orchestration'; import type { Task, ServerAction, Resource, ResourceSnapshot, KillLevel, ChatMessage } from '../services/orchestration'; const sections = ['Overview','Tasks & approvals','Runs & artifacts','Agents & departments','Models & budgets','Schedules','Audit & releases','Kill switch','9router usage & quota','Runtime health & sessions','Chat'] as const; type Section = typeof sections[number]; const resources:Partial> = {'Agents & departments':'agents','Models & budgets':'model-policy','Schedules':'schedules','Audit & releases':'releases'}; const errorText=(e:unknown)=> e instanceof Error ? e.message : 'Unknown backend error'; function Json({value}:{value:unknown}) {return
{JSON.stringify(value,null,2)}
} export default function OrchestrationCommandCenter() { const detailEpoch=useRef(0); const [section,setSection]=useState
('Overview'); const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false,killSwitch:false}); const [tasks,setTasks]=useState([]); const [selected,setSelected]=useState(null); const [snapshot,setSnapshot]=useState(null); const [error,setError]=useState(''); const [loading,setLoading]=useState(false); const [search,setSearch]=useState(''); const [pending,setPending]=useState<{task:Task;action:ServerAction;key:string}|null>(null); const [expires,setExpires]=useState(''); const [reason,setReason]=useState(''); const [binding,setBinding]=useState(''); const [confirmed,setConfirmed]=useState(false); const [attempted,setAttempted]=useState(false); const [busy,setBusy]=useState(false); const [commandError,setCommandError]=useState(''); const [success,setSuccess]=useState(''); const [blocked,setBlocked]=useState(false); const [now,setNow]=useState(Date.now()); useEffect(()=>{const timer=setInterval(()=>setNow(Date.now()),1000);return ()=>clearInterval(timer)},[]); const [kill,setKill]=useState('FREEZE_NEW_WORK'); const [session,setSession]=useState(''); const [message,setMessage]=useState(''); const [messages,setMessages]=useState([]); const [chatKey,setChatKey]=useState(()=>crypto.randomUUID()); const loadTasks=async()=> {setLoading(true);setError(''); try {setTasks(await orchestration.tasks())} catch(e){setTasks([]);setSelected(null);setError(errorText(e))} finally {setLoading(false)}}; useEffect(()=>{void loadTasks(); orchestration.resource('overview').then(s=>setCapabilities({mutations:s.capabilities?.mutations===true,chat:s.capabilities?.chat===true,runtime:s.capabilities?.runtime===true,killSwitch:s.capabilities?.killSwitch===true})).catch(()=>setCapabilities({mutations:false,chat:false,runtime:false,killSwitch:false}));},[]); useEffect(()=> { const resource=resources[section]; setSnapshot(null);setError(''); if(!resource)return; let active=true;setLoading(true); orchestration.resource(resource).then(data=>{if(active)setSnapshot(data)}).catch(e=>{if(active)setError(errorText(e))}).finally(()=>{if(active)setLoading(false)}); return ()=>{active=false}; },[section]); const select=async(task:Task)=>{const epoch=++detailEpoch.current;setSelected(null);setError('');try {const detail=await orchestration.task(task.id);if(epoch===detailEpoch.current)setSelected(detail)}catch(e){if(epoch===detailEpoch.current)setError(errorText(e))}}; const open=(task:Task,action:ServerAction)=>{if(!capabilities.mutations||actionBlockReason(task,action))return;setBlocked(false);setAttempted(false);setPending({task,action,key:crypto.randomUUID()});setExpires('');setReason('');setConfirmed(false);setBinding('');setCommandError('');setSuccess('')}; const execute=async()=> { if(!pending||busy||!confirmed||blocked||!capabilities.mutations)return; setAttempted(true);setBusy(true);setCommandError(''); try { const [runId,artifactHash]=binding.split('|'); await orchestration.command(pending.task,pending.action,{idempotencyKey:pending.key,reason,expiresAt:expires?new Date(expires).toISOString():undefined,runId,artifactHash}); setPending(null);setSelected(null);setSuccess('Command accepted by backend; refreshed authoritative state.');await loadTasks(); } catch(e) {const failure=commandFailure(e);setBlocked(!failure.retryable);setCommandError(failure.message)} finally {setBusy(false)} }; const refresh=()=>{detailEpoch.current++;setSelected(null);setPending(null);void loadTasks()}; const filtered=tasks.filter(t=>(t.title+' '+t.department+' '+t.state).toLowerCase().includes(search.toLowerCase())); return

Orchestration command center

Backend-authoritative operations · Gate1 bounded work · Gate2 immutable release binding

{loading&&

Loading measured backend state…

} {error&&

Unknown / unavailable: {error}. No fallback data.

} {success&&

{success}

} {section==='Tasks & approvals'&&capabilities.mutations&&void loadTasks()}/>} {section==='Overview'&&

Observed task inventory

{tasks.length} tasks returned by backend. This is inventory, not agent health or runtime telemetry.

{[...new Set(tasks.map(t=>t.state))].map(state=>{state}: {tasks.filter(t=>t.state===state).length})}
} {(['Overview','Tasks & approvals','Runs & artifacts','Models & budgets','Audit & releases'] as Section[]).includes(section)&&
{!loading&&!error&&!tasks.length&&

No tasks returned by backend.

}
{['Task','Department','State','Mode','Budget cap (cents)','Version'].map(h=>)}{filtered.map(t=>)}
{h}
{t.department}{t.state}{t.operationMode}{t.budgetLimitCents??'Unknown'}{t.version}
} {selected&&

{selected.title} · v{selected.version}

{typeof selected.metadata?.scope==='string'&&selected.metadata.scope.trim()&&Array.isArray(selected.metadata.acceptanceCriteria)&&selected.metadata.acceptanceCriteria.length>0&&selected.metadata.acceptanceCriteria.every(value=>typeof value==='string'&&value.trim())?

Backend-reported scope / acceptance criteria

:

Scope / acceptance criteria unavailable — omitted by the safe backend projection.

}

Server workflow scope: unavailable in safe projection.

Server-authorized actions

{!selected.availableActions.length&&

No actions advertised. Read-only; the browser does not infer transitions.

}
{selected.availableActions.map(a=>)}

Immutable approval decisions

Runs & registered artifacts

{!selected.runs?.length&&

No registered runs.

}{selected.runs?.map(r=>

{r.id} · {r.status}

Commit: {r.commitSha} · Environment: {r.environment}

{r.artifacts.map(a=>)}
)}

Budget ledger (cents; not inferred usage)

Ordered audit events

} {snapshot&&

{section}

Measured at: {snapshot.measuredAt}

{!snapshot.items.length&&

No records returned by backend.

}
{snapshot.items.map(item=>

{item.title??item.id}

{Object.entries(item).filter(([k])=>k!=='id'&&k!=='title').map(([k,v])=>
{k}
{String(v??'Unknown')}
)}
)}

Configuration mutations require backend-advertised commands; none are inferred by this client.

} {section==='Kill switch'&&!capabilities.killSwitch&&

Mutation controls unavailable: backend security hardening pending.

} {section==='Kill switch'&&capabilities.killSwitch&&

Global kill switch — four escalating levels

Applies globally, not only to selected task. No implicit resume. Current active level: unknown until backend returns state.

Freeze new work → stop agents → disable mutations → emergency halt.

} {section==='9router usage & quota'&&} {section==='Runtime health & sessions'&&} {section==='Chat'&&!capabilities.chat&&

Chat unsupported: trusted runtime bridge unavailable.

} {section==='Chat'&&capabilities.chat&&

Typed backend chat bridge

Advisory text only. No terminal, PTY, runtime token, or direct Hermes connection. Decisions use explicit approval controls.

{messages.map(m=>

{m.role}: {m.content}

)}