Complete safe admin workflow and authenticated runtime read UI
This commit is contained in:
1 parent
5507fbcb29
commit
c058295f35
11 files changed
+228
-19
No files matched your search
@@ -0,0 +1,33 @@
|
||||
# Admin v4 completion integration contract
|
||||
|
||||
Frontend-only slice based on 5507fbc. No deployment or runtime writes. The historical read-only integration document does not authorize enabling routes. Backend policy remains the authority; UI adds deny-only safety restrictions, never permissions.
|
||||
|
||||
## Workflow (existing routes retained)
|
||||
|
||||
- GET `/admin/orchestration/overview`: ResourceSnapshot with `items`, ISO `measuredAt`, `capabilities:{mutations:boolean,chat:boolean,runtime:boolean}`. Missing/failed capability read defaults false.
|
||||
- GET `/admin/orchestration/tasks`: Task[] (or `{success:true,data:Task[]}`).
|
||||
- GET `/admin/orchestration/tasks/:id`: Task. Required identity/version/state/mode/budget and server-computed `availableActions`; optional scope/acceptance metadata, runs/artifacts, immutable decisions, events and budgetLedger. Missing actions means no permission. Include structured redacted scope metadata for a useful Gate1 review; no secrets or arbitrary event payloads.
|
||||
- POST `/admin/orchestration/tasks`: existing CreateTaskInput `{key,title,department,operationMode,budgetLimitCents,metadata:{scope,acceptanceCriteria:string[]}}`. UI allows OBSERVE/PREPARE only, not Production. Key is unique business identity; after an ambiguous create, reconcile key before resubmission. Success locks the form to prevent accidental duplicate submission.
|
||||
- PUT `/admin/orchestration/tasks/:id/transition`: TransitionDto `{toState,expectedVersion,idempotencyKey,reason}`.
|
||||
- POST `/admin/orchestration/tasks/:id/gates/:gate/decide`: GateDecisionDto `{decision:'APPROVED'|'REJECTED',expectedVersion,idempotencyKey,expiresAt,notes}`; Gate2 approval additionally binds `{runId,artifactHash,commitSha,environment}` from a registered SUCCEEDED run, never editable commit/environment. Gate1 is bounded work, not release permission.
|
||||
- ServerAction `{id,label,toState? ,gate?:1|2,decision?:'APPROVED'|'REJECTED',disabledReason?}`. Exactly one of transition or gate decision. All role/policy/kill/version checks remain backend-side. Browser identity fields are never posted; actor must derive from verified JWT. HOLD/request changes only appear if advertised as supported transitions. EDIT_AND_APPROVE is unavailable without a separately reviewed DTO; no guessed mutation endpoint.
|
||||
- HTTP409 stale version/idempotency mismatch, 410 expired, 401/403 denied and other 4xx permanently lock that dialog; refresh and review afresh. Network/5xx ambiguous failures allow only identical payload/key. Inputs and navigation are locked after first attempt; authoritative refresh invalidates selection and pending detail reads. No optimistic status update.
|
||||
- Production task actions and release transitions remain disabled even if advertised. Gate2 evidence inspection is not deployment authorization. Server still enforces TTL; browser time is a usability check, not trusted authorization.
|
||||
|
||||
## Runtime read API (aligned by read-only inspection with runtime sibling)
|
||||
|
||||
Uses existing JWT Axios client, never upstream Hermes paths or tokens. No automatic runtime mutations. Tab is explicitly selected; failed auth/config/routes show unavailable.
|
||||
|
||||
- GET `/admin/orchestration/runtime/health` -> `{ok:boolean,version:string,commit:string,auth_required:true}`. Any false/missing authentication flag is rejected.
|
||||
- GET `/admin/orchestration/runtime/profiles` -> `{name:string,is_default:boolean,gateway_running:boolean}[]`, already filtered to principal grants.
|
||||
- GET `/admin/orchestration/runtime/status?profile=<authorized>` -> `{version,gateway_running,overall,active_agents,gateway_state:string|null}`.
|
||||
- GET `/admin/orchestration/runtime/sessions?profile=<authorized>&limit=20&offset=0` -> `{total:number,sessions:{id,profile,source,is_active}[]}`. UI paginates; profile mismatch is rejected.
|
||||
- GET `/admin/orchestration/runtime/usage?profile=<authorized>&days=30` -> `{period_days:number,totals:{total_input,total_output,total_sessions,total_estimated_cost}}`.
|
||||
|
||||
Runtime client explicitly projects known fields; unknown secret fields are discarded. Numeric zero survives. Cost is labelled **upstream estimate**, unspecified currency, not settled billing and never added to overlapping 9router totals. Client observation time is not server heartbeat/freshness. Profile gateway flags and active agent count are source observations, not invented readiness/department counts. Generic Resources for existing agents/model-policy/schedules/releases remain unchanged; unavailable contracts stay visibly unavailable. Runtime schedules/model-info may exist backend-side but are not guessed into generic Resources.
|
||||
|
||||
## Verification
|
||||
|
||||
Runner: disposable node:22-bookworm, --userns=host --network none; source and dependency donor read-only, private copies in /work. No donor/source build writes. Required final gates: `tsc --noEmit -p tsconfig.app.json`, `npm run build`, `npm test -- --maxWorkers=2`. Logs under `/opt/services/canina/validation/v4-panel-completion/` (outside discovery). Earlier RED proves 7 workflow failures and 2 selection/idempotency failures; runtime RED is missing new component. Existing test fixtures migrated from invented VERIFIED run status to backend SUCCEEDED status. No tests skipped or permissions inferred.
|
||||
|
||||
Not claimed: live backend browser acceptance, real authenticated runtime availability, Stage publication, CI evidence authority or Production execution. Parent owns integration and publication.
|
||||
@@ -6,9 +6,9 @@ export default function CreateOrchestrationTask({onCreated}:{onCreated:()=>void}
|
||||
const [fields,setFields]=useState({key:'',title:'',department:'',scope:'',criteria:'',budget:''});
|
||||
const [mode,setMode]=useState<CreateTaskInput['operationMode']>('PREPARE');const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [success,setSuccess]=useState('');
|
||||
const valid=Object.values(fields).every(value=>value.trim())&&Number.isSafeInteger(Number(fields.budget))&&Number(fields.budget)>=0;
|
||||
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">Create bounded work</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create({key:fields.key,title:fields.title,department:fields.department,operationMode:mode,budgetLimitCents:Number(fields.budget),metadata:{scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n').map(s=>s.trim()).filter(Boolean)}});setSuccess('Task created by backend.');onCreated()}catch(error){setError(error instanceof Error?error.message:'Create failed; reconcile task key before retry')}finally{setBusy(false)}}}>
|
||||
{([['key','Task key'],['title','Title'],['department','Department'],['scope','Bounded scope'],['criteria','Acceptance criteria (one per line)'],['budget','Budget cap in cents']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
|
||||
<label>Operation mode<select aria-label="Operation mode" value={mode} disabled={busy} onChange={e=>setMode(e.target.value as CreateTaskInput['operationMode'])}>{['OBSERVE','PREPARE','MUTATE_PRODUCTION'].map(m=><option key={m}>{m}</option>)}</select></label><p>Creation does not authorize work. Gate1 is a separate immutable decision.</p>
|
||||
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy}>Create bounded task</Button>
|
||||
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">Create bounded work</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy||success)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create({key:fields.key,title:fields.title,department:fields.department,operationMode:mode,budgetLimitCents:Number(fields.budget),metadata:{scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n').map(s=>s.trim()).filter(Boolean)}});setSuccess('Task created by backend.');onCreated()}catch(error){setError(error instanceof Error?error.message+' — Refresh and reconcile the task key before resubmitting.':'Create failed; reconcile task key before retry')}finally{setBusy(false)}}}>
|
||||
{([['key','Task key'],['title','Title'],['department','Department'],['scope','Bounded scope'],['criteria','Acceptance criteria (one per line)'],['budget','Budget cap in cents']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy||!!success} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
|
||||
<label>Operation mode<select aria-label="Operation mode" value={mode} disabled={busy||!!success} onChange={e=>setMode(e.target.value as CreateTaskInput['operationMode'])}>{['OBSERVE','PREPARE'].map(m=><option key={m}>{m}</option>)}</select></label><p>Creation does not authorize work. Gate1 is a separate immutable decision. Production proposals are disabled. After an ambiguous failure, refresh and reconcile the unique task key before resubmitting.</p>
|
||||
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy||!!success}>Create bounded task</Button>
|
||||
</form></details>;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import {render,screen,fireEvent,waitFor} from '@testing-library/react';
|
||||
import {beforeEach,it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import RuntimeReadPanel from './RuntimeReadPanel';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn()}}));
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>{
|
||||
if(url.endsWith('/health'))return {data:{ok:true,version:'v1',commit:'abc',auth_required:true}};
|
||||
if(url.endsWith('/profiles'))return {data:[{name:'dev',is_default:false,gateway_running:false}]};
|
||||
if(url.endsWith('/status'))return {data:{version:'v1',gateway_running:false,overall:'degraded',active_agents:0,gateway_state:null}};
|
||||
if(url.endsWith('/sessions'))return {data:{total:0,sessions:[]}};
|
||||
if(url.endsWith('/usage'))return {data:{period_days:30,totals:{total_input:0,total_output:0,total_sessions:0,total_estimated_cost:0}}};
|
||||
throw new Error('Runtime unavailable');
|
||||
});});
|
||||
it('shows actual health identity, explicit stopped gateway, zero usage and profile-bound reads',async()=>{
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText('v1 · abc')).toBeInTheDocument();
|
||||
fireEvent.change(await screen.findByLabelText('Authorized runtime profile'),{target:{value:'dev'}});
|
||||
expect(await screen.findByText('degraded')).toBeInTheDocument();expect(await screen.findByText('No sessions returned.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Input tokens: 0')).toBeInTheDocument();expect(screen.getByText(/Upstream estimated cost: 0/)).toBeInTheDocument();
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/runtime/sessions',{params:{profile:'dev',limit:20,offset:0}});
|
||||
});
|
||||
it('shows unavailable rather than healthy when runtime cannot be authenticated',async()=>{
|
||||
vi.mocked(api.get).mockRejectedValue(new Error('Runtime unavailable'));
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText(/Health unavailable/)).toBeInTheDocument();expect(screen.queryByText('Authenticated runtime health: healthy')).not.toBeInTheDocument();
|
||||
});
|
||||
it('rejects malformed health and never renders unknown secret fields',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:false,password:'secret-value'}:[]}));
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText(/Health unavailable/)).toBeInTheDocument();expect(screen.queryByText(/secret-value/)).not.toBeInTheDocument();
|
||||
});
|
||||
it('refreshes the authenticated runtime reads without a browser runtime connection',async()=>{
|
||||
render(<RuntimeReadPanel/>);await screen.findByText('v1 · abc');fireEvent.click(screen.getByRole('button',{name:'Refresh runtime'}));await waitFor(()=>expect(vi.mocked(api.get).mock.calls.filter(([u])=>u.endsWith('/health'))).toHaveLength(2));
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
import {runtime} from '../services/runtime';
|
||||
import type {RuntimeHealth,RuntimeProfile,RuntimeStatus,RuntimeSessions,RuntimeUsage} from '../services/runtime';
|
||||
export default function RuntimeReadPanel(){
|
||||
const [revision,setRevision]=useState(0);const [profile,setProfile]=useState('');const [offset,setOffset]=useState(0);
|
||||
const [health,setHealth]=useState<RuntimeHealth|null>(null);const [profiles,setProfiles]=useState<RuntimeProfile[]>([]);const [errors,setErrors]=useState<Record<string,string>>({});
|
||||
const [status,setStatus]=useState<RuntimeStatus|null>(null);const [sessions,setSessions]=useState<RuntimeSessions|null>(null);const [usage,setUsage]=useState<RuntimeUsage|null>(null);
|
||||
const [observed,setObserved]=useState('');
|
||||
useEffect(()=>{let active=true;setHealth(null);setProfiles([]);setErrors({});
|
||||
runtime.health().then(value=>{if(active){setHealth(value);setObserved(new Date().toISOString())}}).catch(()=>{if(active)setErrors(e=>({...e,health:'Health unavailable — authenticated backend runtime read failed.'}))});
|
||||
runtime.profiles().then(value=>{if(active){setProfiles(value);setProfile(current=>value.some(p=>p.name===current)?current:'')}}).catch(()=>{if(active){setProfile('');setErrors(e=>({...e,profiles:'Profiles unavailable — no authorized runtime identity list.'}))}});
|
||||
return ()=>{active=false};
|
||||
},[revision]);
|
||||
useEffect(()=>{let active=true;setStatus(null);setSessions(null);setUsage(null);setErrors(e=>({health:e.health,profiles:e.profiles}));if(!profile)return;
|
||||
const fail=(name:string)=>{if(active)setErrors(e=>({...e,[name]:name+' unavailable — no fallback values.'}))};
|
||||
runtime.status(profile).then(v=>{if(active)setStatus(v)}).catch(()=>fail('Status'));
|
||||
runtime.sessions(profile,offset).then(v=>{if(active)setSessions(v)}).catch(()=>fail('Sessions'));
|
||||
runtime.usage(profile).then(v=>{if(active)setUsage(v)}).catch(()=>fail('Usage'));
|
||||
return ()=>{active=false};
|
||||
},[profile,offset,revision]);
|
||||
return <section aria-label="Authenticated runtime" className="bg-white border rounded-2xl p-5 space-y-4">
|
||||
<div className="flex justify-between"><h2 className="font-bold">Hermes runtime — backend authenticated reads</h2><Button onClick={()=>setRevision(r=>r+1)}>Refresh runtime</Button></div>
|
||||
<p>No browser runtime credentials or direct Hermes connection. Refresh observations are not heartbeat timestamps.</p>
|
||||
{Object.entries(errors).filter(([,message])=>message).map(([name,message])=><p key={name} role="alert">{message}</p>)}
|
||||
{health&&<div><p>Authenticated runtime health: {health.ok?'healthy':'unhealthy'}</p><p>{health.version} · {health.commit}</p><p>Client observed at: {observed}. Source freshness unknown.</p></div>}
|
||||
<label>Authorized runtime profile<select aria-label="Authorized runtime profile" value={profile} onChange={e=>{setProfile(e.target.value);setOffset(0)}}><option value="">Select authorized profile</option>{profiles.map(p=><option key={p.name} value={p.name}>{p.name}</option>)}</select></label>
|
||||
{!profiles.length&&!errors.profiles&&<p>No authorized profiles returned.</p>}
|
||||
{profiles.map(p=><p key={p.name}>{p.name} · Gateway {p.gateway_running?'running':'stopped'} · {p.is_default?'default profile':'non-default profile'}</p>)}
|
||||
{status&&<div><h3>Profile status</h3><p>{status.overall}</p><p>Gateway: {status.gateway_running?'running':'stopped'} · State: {status.gateway_state??'Unknown'} · Active agents: {status.active_agents}</p></div>}
|
||||
{usage&&<div><h3>Runtime usage — {usage.period_days} days, selected profile only</h3><p>Input tokens: {usage.totals.total_input}</p><p>Output tokens: {usage.totals.total_output}</p><p>Sessions: {usage.totals.total_sessions}</p><p>Upstream estimated cost: {usage.totals.total_estimated_cost} (currency unspecified by source; not settled billing)</p><p>Do not add this to 9router totals; attribution overlaps and is not reconciled.</p></div>}
|
||||
{sessions&&<div><h3>Sessions — {sessions.total} returned total</h3>{!sessions.sessions.length&&<p>No sessions returned.</p>}{sessions.sessions.map(s=><article key={s.id} className="border rounded p-2"><p>{s.id} · {s.profile} · {s.source} · {s.is_active?'active':'inactive'}</p></article>)}<Button disabled={offset===0} onClick={()=>setOffset(n=>Math.max(0,n-20))}>Previous sessions</Button><Button disabled={offset+20>=sessions.total} onClick={()=>setOffset(n=>n+20)}>Next sessions</Button></div>}
|
||||
</section>;
|
||||
}
|
||||
@@ -60,8 +60,8 @@ describe('command center', () => {
|
||||
expect(screen.getByText('BLOCKED')).toBeInTheDocument();
|
||||
});
|
||||
it('binds Gate2 using registered evidence, never editable commit or environment',async()=>{
|
||||
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}],runs:[{id:'run-1',status:'VERIFIED',commitSha:'abc123',environment:'staging',artifacts:[{id:'artifact-1',sha256:'a'.repeat(64)}]}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[release]:release}));
|
||||
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}],runs:[{id:'run-1',status:'SUCCEEDED',commitSha:'abc123',environment:'staging',artifacts:[{id:'artifact-1',sha256:'a'.repeat(64)}]}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:true,chat:false,runtime:false}}:url.endsWith('/tasks')?[release]:release}));
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'decision-2'}});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
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 } from '../services/orchestration';
|
||||
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','Chat'] as const;
|
||||
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<Record<Section,Resource>> = {'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 <pre className="text-xs whitespace-pre-wrap break-all bg-gray-50 border rounded-xl p-3" dir="ltr">{JSON.stringify(value,null,2)}</pre>}
|
||||
export default function OrchestrationCommandCenter() {
|
||||
const detailEpoch=useRef(0);
|
||||
const [section,setSection]=useState<Section>('Overview');
|
||||
const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false});
|
||||
const [tasks,setTasks]=useState<Task[]>([]);
|
||||
@@ -22,6 +24,9 @@ export default function OrchestrationCommandCenter() {
|
||||
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<KillLevel>('FREEZE_NEW_WORK');
|
||||
const [session,setSession]=useState(''); const [message,setMessage]=useState('');
|
||||
const [messages,setMessages]=useState<ChatMessage[]>([]);
|
||||
@@ -35,21 +40,21 @@ export default function OrchestrationCommandCenter() {
|
||||
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)=>{setSelected(null);setError('');try {setSelected(await orchestration.task(task.id))}catch(e){setError(errorText(e))}};
|
||||
const open=(task:Task,action:ServerAction)=>{setAttempted(false);setPending({task,action,key:crypto.randomUUID()});setExpires('');setReason('');setConfirmed(false);setBinding('');setCommandError('');setSuccess('')};
|
||||
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)return;
|
||||
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) {setCommandError(errorText(e)+' — Refresh before retrying a version conflict; network retries keep the same key.')} finally {setBusy(false)}
|
||||
} catch(e) {const failure=commandFailure(e);setBlocked(!failure.retryable);setCommandError(failure.message)} finally {setBusy(false)}
|
||||
};
|
||||
const refresh=()=>{setSelected(null);setPending(null);void loadTasks()};
|
||||
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 <div className="space-y-5 font-vazir pb-12">
|
||||
<header className="bg-white border rounded-2xl p-5 flex justify-between gap-4"><div><h1 className="text-xl font-black">Orchestration command center</h1><p className="text-sm text-gray-600">Backend-authoritative operations · Gate1 bounded work · Gate2 immutable release binding</p></div><Button onClick={refresh} disabled={busy||loading}>Refresh authoritative state</Button></header>
|
||||
<nav aria-label="Orchestration sections" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} onClick={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
|
||||
<nav aria-label="Orchestration sections" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} disabled={!!pending||busy} onClick={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
|
||||
{loading&&<p role="status">Loading measured backend state…</p>}
|
||||
{error&&<p role="alert" className="border border-red-200 bg-red-50 rounded-xl p-4">Unknown / unavailable: {error}. No fallback data. <button onClick={refresh}>Reload tasks</button></p>}
|
||||
{success&&<p role="status">{success}</p>}
|
||||
@@ -60,7 +65,7 @@ export default function OrchestrationCommandCenter() {
|
||||
<div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr>{['Task','Department','State','Mode','Budget cap (cents)','Version'].map(h=><th key={h} className="text-start p-2">{h}</th>)}</tr></thead><tbody>{filtered.map(t=><tr key={t.id} className="border-t"><td className="p-2"><button className="text-purple-700 underline" onClick={()=>void select(t)}>{t.title}</button></td><td>{t.department}</td><td>{t.state}</td><td>{t.operationMode}</td><td>{t.budgetLimitCents??'Unknown'}</td><td>{t.version}</td></tr>)}</tbody></table></div>
|
||||
</section>}
|
||||
{selected&&<section aria-label="Task detail" className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">{selected.title} · v{selected.version}</h2>{selected.metadata?<h3>Backend-reported scope / acceptance criteria</h3>:<p>Scope / acceptance criteria unavailable — omitted by the safe backend projection.</p>}<Json value={{operationMode:selected.operationMode,budgetLimitCents:selected.budgetLimitCents,metadata:selected.metadata}}/>
|
||||
<h3>Server-authorized actions</h3>{!selected.availableActions.length&&<p>No actions advertised. Read-only; the browser does not infer transitions.</p>}<div className="flex flex-wrap gap-2">{selected.availableActions.map(a=><Button key={a.id} disabled={!!a.disabledReason} title={a.disabledReason} onClick={()=>open(selected,a)}>{a.label}</Button>)}</div>
|
||||
<h3>Server-authorized actions</h3>{!selected.availableActions.length&&<p>No actions advertised. Read-only; the browser does not infer transitions.</p>}<div className="flex flex-wrap gap-2">{selected.availableActions.map(a=><Button key={a.id} disabled={!capabilities.mutations||!!actionBlockReason(selected,a)} title={!capabilities.mutations?'Backend mutations unavailable':actionBlockReason(selected,a)} onClick={()=>open(selected,a)}>{a.label}</Button>)}</div>
|
||||
<h3>Immutable approval decisions</h3><Json value={selected.decisions??[]}/>
|
||||
<h3>Runs & registered artifacts</h3>{!selected.runs?.length&&<p>No registered runs.</p>}{selected.runs?.map(r=><article key={r.id} className="border rounded-xl p-3 space-y-2"><h4>{r.id} · {r.status}</h4><p>Commit: {r.commitSha} · Environment: {r.environment}</p>{r.artifacts.map(a=><Json key={a.id} value={a}/>)}</article>)}
|
||||
<h3>Budget ledger (cents; not inferred usage)</h3><Json value={selected.budgetLedger??[]}/><h3>Ordered audit events</h3><Json value={selected.events??[]}/>
|
||||
@@ -69,14 +74,15 @@ export default function OrchestrationCommandCenter() {
|
||||
{section==='Kill switch'&&!capabilities.mutations&&<p>Mutation controls unavailable: backend security hardening pending.</p>}
|
||||
{section==='Kill switch'&&capabilities.mutations&&<section className="border border-red-300 rounded-2xl bg-white p-5 space-y-3"><h2>Global kill switch — four escalating levels</h2><p>Applies globally, not only to selected task. No implicit resume. Current active level: unknown until backend returns state.</p><label>Level<select aria-label="Kill level" value={kill} onChange={e=>{setKill(e.target.value as KillLevel);setConfirmed(false)}}>{killLevels.map(l=><option key={l}>{l}</option>)}</select></label><p>Freeze new work → stop agents → disable mutations → emergency halt.</p><label>Reason<input aria-label="Kill reason" value={reason} onChange={e=>setReason(e.target.value)} className="border p-2"/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>I confirm global operational impact</label><Button disabled={busy||!reason.trim()||!confirmed} onClick={async()=>{setBusy(true);setError('');try{const result=await orchestration.kill(kill,reason);setSuccess('Backend acknowledged kill switch: '+JSON.stringify(result));setConfirmed(false)}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Apply kill switch</Button></section>}
|
||||
{section==='9router usage & quota'&&<RouterUsagePanel/>}
|
||||
{section==='Runtime health & sessions'&&<RuntimeReadPanel/>}
|
||||
{section==='Chat'&&!capabilities.chat&&<p>Chat unsupported: trusted runtime bridge unavailable.</p>}
|
||||
{section==='Chat'&&capabilities.chat&&<section className="bg-white border rounded-2xl p-5 space-y-3"><h2>Typed backend chat bridge</h2><p>Advisory text only. No terminal, PTY, runtime token, or direct Hermes connection. Decisions use explicit approval controls.</p><label>Session ID<input value={session} onChange={e=>{setSession(e.target.value);setMessages([])}} className="border p-2"/></label><div role="log">{messages.map(m=><p key={m.id}>{m.role}: {m.content}</p>)}</div><label>Message<textarea value={message} onChange={e=>{setMessage(e.target.value);setChatKey(crypto.randomUUID())}} className="border p-2 block w-full"/></label><Button disabled={busy||!session.trim()||!message.trim()} onClick={async()=>{setBusy(true);setError('');try{const reply=await orchestration.chat(session,message,chatKey);setMessages(prev=>[...prev,{id:chatKey,role:'user',content:message},reply]);setMessage('');setChatKey(crypto.randomUUID())}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Send advisory message</Button></section>}
|
||||
{pending&&<div role="dialog" aria-modal="true" aria-label="Confirm immutable command" className="fixed inset-0 z-50 bg-black/50 overflow-y-auto p-8"><div className="bg-white rounded-2xl p-6 max-w-2xl mx-auto space-y-4"><h2>{pending.action.label}</h2><Json value={{taskId:pending.task.id,expectedVersion:pending.task.version,idempotencyKey:pending.key,scope:pending.task.metadata,budgetLimitCents:pending.task.budgetLimitCents,operationMode:pending.task.operationMode}}/>
|
||||
{pending.action.gate&&<label className="block">Expires at<input aria-label="Expires at" type="datetime-local" value={expires} onChange={e=>setExpires(e.target.value)} disabled={busy||attempted}/></label>}
|
||||
{pending.action.gate===2&&pending.action.decision==='APPROVED'&&<label>Registered run / artifact binding<select aria-label="Registered run / artifact binding" value={binding} onChange={e=>{setBinding(e.target.value);setConfirmed(false)}} disabled={busy||attempted}><option value="">Select immutable evidence</option>{pending.task.runs?.flatMap(r=>r.artifacts.map(a=><option key={r.id+'|'+a.sha256} value={r.id+'|'+a.sha256}>{r.id} · {r.commitSha} · {r.environment} · {a.sha256}</option>))}</select></label>}
|
||||
{pending.action.gate===2&&pending.action.decision==='APPROVED'&&<label>Registered run / artifact binding<select aria-label="Registered run / artifact binding" value={binding} onChange={e=>{setBinding(e.target.value);setConfirmed(false)}} disabled={busy||attempted}><option value="">Select immutable evidence</option>{pending.task.runs?.filter(r=>r.status==='SUCCEEDED').flatMap(r=>r.artifacts.map(a=><option key={r.id+'|'+a.sha256} value={r.id+'|'+a.sha256}>{r.id} · {r.commitSha} · {r.environment} · {a.sha256}</option>))}</select></label>}
|
||||
<label className="block">Reason<input aria-label="Reason" value={reason} onChange={e=>setReason(e.target.value)} disabled={busy||attempted} className="border p-2"/></label>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)} disabled={busy}/>I reviewed the immutable scope and binding</label>
|
||||
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||!confirmed||!reason.trim()|| (!!pending.action.gate&&!Number.isFinite(Date.parse(expires))) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>Confirm command</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>Cancel</Button></div>
|
||||
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||blocked||!capabilities.mutations||!confirmed||!reason.trim()|| (!!pending.action.gate&&!(Date.parse(expires)>now)) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>Confirm command</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>Cancel</Button></div>
|
||||
</div></div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import {render,screen,fireEvent,within,waitFor,act} from '@testing-library/react';
|
||||
import {it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
|
||||
it('does not restore stale detail after authoritative refresh while detail request is pending',async()=>{
|
||||
const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[]};
|
||||
let resolve!:(v:unknown)=>void;
|
||||
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}};if(url.endsWith('/tasks'))return {data:[t]};return await new Promise<unknown>(r=>{resolve=r}) as never});
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(screen.getByRole('button',{name:'Refresh authoritative state'}));
|
||||
await act(async()=>resolve({data:t}));await waitFor(()=>expect(screen.queryByText('Loading measured backend state…')).not.toBeInTheDocument());
|
||||
expect(screen.queryByRole('region',{name:'Task detail'})).not.toBeInTheDocument();
|
||||
});
|
||||
it('keeps payload immutable when navigating after an ambiguous network failure',async()=>{
|
||||
vi.resetAllMocks();const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[{id:'g1',label:'Approve safe work',gate:1,decision:'APPROVED'}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}:url.endsWith('/tasks')?[t]:t}));vi.mocked(api.post).mockRejectedValue(new Error('network'));
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(await screen.findByRole('button',{name:'Approve safe work'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('Reason'),{target:{value:'Reviewed'}});fireEvent.click(d.getByLabelText('I reviewed the immutable scope and binding'));fireEvent.click(d.getByRole('button',{name:'Confirm command'}));await d.findByRole('alert');
|
||||
fireEvent.click(screen.getByRole('button',{name:'Tasks & approvals'}));expect(d.getByLabelText('Reason')).toHaveValue('Reviewed');expect(d.getByLabelText('I reviewed the immutable scope and binding')).toBeChecked();
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import {render,screen,fireEvent,within,waitFor} from '@testing-library/react';
|
||||
import {beforeEach,it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import {orchestration} from '../services/orchestration';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
|
||||
const action={id:'g1',label:'Review Gate1',gate:1 as const,decision:'APPROVED' as const};
|
||||
const task={id:'t',key:'t',title:'Safe proposal',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[action],runs:[]};
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:true,chat:false,runtime:false}}:url.endsWith('/tasks')?[task]:task}));});
|
||||
it('refuses Production creation even when called outside form',async()=>{
|
||||
await expect(orchestration.create({key:'x',title:'x',department:'DEV',operationMode:'MUTATE_PRODUCTION',budgetLimitCents:0,metadata:{scope:'x',acceptanceCriteria:['x']}})).rejects.toThrow(/Production/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects ambiguous advertised action rather than selecting a mutation path',async()=>{
|
||||
const ambiguous={...action,toState:'READY'};
|
||||
await expect(orchestration.command({...task,availableActions:[ambiguous]},ambiguous,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/Unsupported/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks release transitions even when advertised by server',async()=>{
|
||||
const release={id:'release',label:'Release',toState:'RELEASING'};
|
||||
await expect(orchestration.command({...task,availableActions:[release]},release,{idempotencyKey:'key'})).rejects.toThrow(/Production/);
|
||||
expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects Gate2 evidence from failed runs',async()=>{
|
||||
const g2={...action,gate:2 as const};
|
||||
await expect(orchestration.command({...task,availableActions:[g2],runs:[{id:'r',status:'FAILED',commitSha:'abc',environment:'stage',artifacts:[{id:'a',sha256:'a'.repeat(64)}]}]},g2,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/successful/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
async function dialog(){render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));fireEvent.click(await screen.findByRole('button',{name:'Review Gate1'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('Reason'),{target:{value:'Reviewed bounds'}});fireEvent.click(d.getByLabelText('I reviewed the immutable scope and binding'));return d;}
|
||||
it('locks stale 409 command until authoritative refresh instead of retrying stale payload',async()=>{
|
||||
vi.mocked(api.post).mockRejectedValue({response:{status:409,data:{message:'Version conflict'}}});
|
||||
const d=await dialog();fireEvent.click(d.getByRole('button',{name:'Confirm command'}));
|
||||
await waitFor(()=>expect(d.getByRole('button',{name:'Confirm command'})).toBeDisabled());
|
||||
expect(await d.findByRole('alert')).toHaveTextContent(/stale/i);
|
||||
fireEvent.click(d.getByRole('button',{name:'Confirm command'}));expect(api.post).toHaveBeenCalledTimes(1);
|
||||
fireEvent.click(screen.getByRole('button',{name:'Refresh authoritative state'}));expect(screen.queryByRole('dialog')).not.toBeInTheDocument();await waitFor(()=>expect(screen.queryByText('Loading measured backend state…')).not.toBeInTheDocument());
|
||||
});
|
||||
it('does not expose authorized task mutations when capabilities are unavailable',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))throw new Error('offline');return {data:url.endsWith('/tasks')?[task]:task};});
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));await screen.findByRole('region',{name:'Task detail'});
|
||||
expect(screen.getByRole('button',{name:'Review Gate1'})).toBeDisabled();
|
||||
});
|
||||
it('prevents confirming an already expired approval',async()=>{
|
||||
const d=await dialog();fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2020-01-01T12:00'}});
|
||||
expect(d.getByRole('button',{name:'Confirm command'})).toBeDisabled();
|
||||
});
|
||||
@@ -18,7 +18,7 @@ describe('orchestration adapter', () => {
|
||||
expect(api.put).not.toHaveBeenCalled(); expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('binds Gate2 to immutable registered run and sends version and retry-stable key', async () => {
|
||||
const run={id:'r',commitSha:'abc',environment:'staging',status:'VERIFIED',artifacts:[{id:'a',sha256:'a'.repeat(64)}]};
|
||||
const run={id:'r',commitSha:'abc',environment:'staging',status:'SUCCEEDED',artifacts:[{id:'a',sha256:'a'.repeat(64)}]};
|
||||
const input={idempotencyKey:'same-key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)};
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce({data:{id:'decision'}});
|
||||
await expect(orchestration.command({...task,runs:[run]},task.availableActions[0],input)).rejects.toThrow('network');
|
||||
|
||||
@@ -4,6 +4,23 @@ export interface Artifact { id: string; sha256: string; kind?: string; uri?: str
|
||||
export interface Run { id: string; commitSha: string; environment: string; status: string; artifacts: Artifact[] }
|
||||
export interface Task { id: string; key: string; title: string; department: string; state: string; version: number; operationMode: string; budgetLimitCents: number; metadata?: Record<string, unknown>; availableActions: ServerAction[]; runs?: Run[]; decisions?: Record<string, unknown>[]; events?: Record<string, unknown>[]; budgetLedger?: Record<string, unknown>[] }
|
||||
export interface CommandInput { idempotencyKey: string; reason?: string; expiresAt?: string; runId?: string; artifactHash?: string }
|
||||
export interface TransitionDto {toState:string;expectedVersion:number;idempotencyKey:string;reason?:string}
|
||||
export interface GateDecisionDto {decision:'APPROVED'|'REJECTED';expectedVersion:number;idempotencyKey:string;expiresAt:string;notes?:string;runId?:string;artifactHash?:string;commitSha?:string;environment?:string}
|
||||
export function actionBlockReason(task:Task,action:ServerAction):string|undefined {
|
||||
if(action.disabledReason)return action.disabledReason;
|
||||
if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'Production actions are unavailable in this panel';
|
||||
if(task.state==='EXPIRED')return 'Expired proposal: create a fresh proposal';
|
||||
if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'Unsupported server action';
|
||||
return undefined;
|
||||
}
|
||||
export function commandFailure(error:unknown):{message:string;retryable:boolean} {
|
||||
const status=(error as {response?:{status?:number}})?.response?.status;
|
||||
if(status===409)return {message:'Stale version or idempotency conflict. Refresh authoritative state and review a fresh decision.',retryable:false};
|
||||
if(status===410)return {message:'Proposal or approval expired. Refresh; expired proposals require a new proposal.',retryable:false};
|
||||
if(status===401||status===403)return {message:'Backend denied this action. Refresh permissions before continuing.',retryable:false};
|
||||
if(status&&status>=400&&status<500)return {message:'Backend rejected this action (HTTP '+status+'). Refresh and review the proposal.',retryable:false};
|
||||
return {message:(error instanceof Error?error.message:'Backend request unavailable')+' — Outcome unknown. Retry only the identical payload/key, or refresh to reconcile.',retryable:true};
|
||||
}
|
||||
export type Resource = 'agents' | 'model-policy' | 'schedules' | 'releases' | 'overview';
|
||||
export interface ResourceSnapshot { capabilities?: {mutations:boolean;chat:boolean;runtime:boolean}; items: Array<{id:string; title?:string; status?:string; department?:string; readiness?:string; model?:string; budgetLimitCents?:number; spentCents?:number; cron?:string; timezone?:string; environment?:string; commitSha?:string; reason?:string}>; measuredAt: string }
|
||||
export const killLevels = ['FREEZE_NEW_WORK','STOP_AGENTS','DISABLE_MUTATIONS','EMERGENCY_HALT'] as const;
|
||||
@@ -13,6 +30,7 @@ function unwrap<T>(data: T | {success:boolean;data:T}): T { if (data && typeof d
|
||||
export interface CreateTaskInput {key:string;title:string;department:string;operationMode:'OBSERVE'|'PREPARE'|'MUTATE_PRODUCTION';budgetLimitCents:number;metadata:{scope:string;acceptanceCriteria:string[]}}
|
||||
export const orchestration = {
|
||||
async create(input:CreateTaskInput):Promise<unknown> {
|
||||
if(input.operationMode==='MUTATE_PRODUCTION')throw new Error('Production proposals are unavailable in this panel');
|
||||
if(!Number.isSafeInteger(input.budgetLimitCents)||input.budgetLimitCents<0)throw new Error('Nonnegative integer budget required');
|
||||
if(!input.key.trim()||!input.title.trim()||!input.department.trim()||!input.metadata.scope.trim()||!input.metadata.acceptanceCriteria.length)throw new Error('Bounded scope and acceptance criteria required');
|
||||
return (await api.post('/admin/orchestration/tasks',{key:input.key,title:input.title,department:input.department,operationMode:input.operationMode,budgetLimitCents:input.budgetLimitCents,metadata:input.metadata})).data;
|
||||
@@ -40,6 +58,7 @@ export const orchestration = {
|
||||
async command(task: Task, requested: ServerAction, input: CommandInput): Promise<unknown> {
|
||||
const action = task.availableActions.find(a => a.id === requested.id);
|
||||
if (!action || action.disabledReason) throw new Error('Action is not advertised or is disabled');
|
||||
const blocked=actionBlockReason(task,action);if(blocked)throw new Error(blocked);
|
||||
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('Version and idempotency key required');
|
||||
const base = '/admin/orchestration/tasks/' + encodeURIComponent(task.id);
|
||||
if (action.gate && action.decision) {
|
||||
@@ -47,6 +66,7 @@ export const orchestration = {
|
||||
let binding = {};
|
||||
if (action.gate === 2 && action.decision === 'APPROVED') {
|
||||
const run = task.runs?.find(r => r.id === input.runId);
|
||||
if(run?.status!=='SUCCEEDED')throw new Error('Registered successful run binding required for Gate2 evidence');
|
||||
if (!run?.commitSha || !run.environment || !run.artifacts.some(a => a.sha256 === input.artifactHash)) throw new Error('Registered immutable Gate2 binding required');
|
||||
binding = {runId:run.id, artifactHash:input.artifactHash, commitSha:run.commitSha, environment:run.environment};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import api from './api';
|
||||
export interface RuntimeHealth {ok:boolean;version:string;commit:string;auth_required:true}
|
||||
export interface RuntimeProfile {name:string;is_default:boolean;gateway_running:boolean}
|
||||
export interface RuntimeStatus {version:string;gateway_running:boolean;overall:string;active_agents:number;gateway_state:string|null}
|
||||
export interface RuntimeSession {id:string;profile:string;source:string;is_active:boolean}
|
||||
export interface RuntimeSessions {total:number;sessions:RuntimeSession[]}
|
||||
export interface RuntimeUsage {period_days:number;totals:{total_input:number;total_output:number;total_sessions:number;total_estimated_cost:number}}
|
||||
function object(value:unknown):Record<string,unknown>{if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Invalid runtime contract');return value as Record<string,unknown>}
|
||||
function text(value:unknown):string{if(typeof value!=='string')throw new Error('Invalid runtime text');return value}
|
||||
function bool(value:unknown):boolean{if(typeof value!=='boolean')throw new Error('Invalid runtime flag');return value}
|
||||
function count(value:unknown):number{if(typeof value!=='number'||!Number.isFinite(value)||value<0)throw new Error('Invalid runtime count');return value}
|
||||
function list(value:unknown):unknown[]{if(!Array.isArray(value)||value.length>1000)throw new Error('Invalid runtime list');return value}
|
||||
async function read(path:string,params?:Record<string,string|number>):Promise<unknown>{const {data}=await api.get('/admin/orchestration/runtime/'+path,...(params?[{params}]:[]));const row=data&&typeof data==='object'&&!Array.isArray(data)?data:null;if(row&&'success' in row){if(row.success!==true)throw new Error('Runtime unavailable');return row.data}return data}
|
||||
export const runtime={
|
||||
async health():Promise<RuntimeHealth>{const r=object(await read('health'));if(r.auth_required!==true)throw new Error('Authenticated runtime required');return {ok:bool(r.ok),version:text(r.version),commit:text(r.commit),auth_required:true}},
|
||||
async profiles():Promise<RuntimeProfile[]>{return list(await read('profiles')).map(value=>{const r=object(value);return {name:text(r.name),is_default:bool(r.is_default),gateway_running:bool(r.gateway_running)}})},
|
||||
async status(profile:string):Promise<RuntimeStatus>{const r=object(await read('status',{profile}));return {version:text(r.version),gateway_running:bool(r.gateway_running),overall:text(r.overall),active_agents:count(r.active_agents),gateway_state:r.gateway_state===null?null:text(r.gateway_state)}},
|
||||
async sessions(profile:string,offset=0):Promise<RuntimeSessions>{const r=object(await read('sessions',{profile,limit:20,offset}));return {total:count(r.total),sessions:list(r.sessions).map(value=>{const s=object(value);if(s.profile!==profile)throw new Error('Runtime profile mismatch');return {id:text(s.id),profile:text(s.profile),source:text(s.source),is_active:bool(s.is_active)}})}},
|
||||
async usage(profile:string):Promise<RuntimeUsage>{const r=object(await read('usage',{profile,days:30}));const t=object(r.totals);return {period_days:count(r.period_days),totals:{total_input:count(t.total_input),total_output:count(t.total_output),total_sessions:count(t.total_sessions),total_estimated_cost:count(t.total_estimated_cost)}}},
|
||||
};
|
||||
Reference in new issue
Block a user