feat(admin): add backend-authoritative orchestration command center and usage view

This commit is contained in:
devops committed 2026-10-22 18:54:24 +00:00
1 parent e5c83e87fe
commit c8a3f35b0a
16 files changed
+510 -373

No files matched your search

@@ -0,0 +1,14 @@
import {fireEvent,render,screen} from '@testing-library/react';
import {it,expect,vi} from 'vitest';
import api from '../services/api';
import CreateOrchestrationTask from './CreateOrchestrationTask';
vi.mock('../services/api',()=>({default:{post:vi.fn()}}));
it('submits explicit bounded scope and acceptance criteria, only after valid input',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{id:'new'}});const done=vi.fn();render(<CreateOrchestrationTask onCreated={done}/>);
expect(screen.getByRole('button',{name:'Create bounded task'})).toBeDisabled();
for(const [label,value] of Object.entries({'Task key':'audit-1','Title':'Audit schema','Department':'SEO','Bounded scope':'Staging schema audit only','Acceptance criteria (one per line)':'Report all failures','Budget cap in cents':'500'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
fireEvent.click(screen.getByRole('button',{name:'Create bounded task'}));
await screen.findByText('Task created by backend.');
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',expect.objectContaining({operationMode:'PREPARE',budgetLimitCents:500,metadata:{scope:'Staging schema audit only',acceptanceCriteria:['Report all failures']}}));
expect(done).toHaveBeenCalledOnce();
});
@@ -0,0 +1,14 @@
import {useState} from 'react';
import Button from './ui/Button';
import {orchestration} from '../services/orchestration';
import type {CreateTaskInput} from '../services/orchestration';
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>
</form></details>;
}
@@ -0,0 +1,9 @@
import { render,screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { it,expect,vi } from 'vitest';
import Sidebar from './Sidebar';
vi.mock('../services/api',()=>({default:{get:vi.fn().mockResolvedValue({data:{success:true,data:{}}})}}));
it('exposes command center inside existing authenticated navigation',async()=>{
render(<MemoryRouter initialEntries={['/orchestration']}><Sidebar isOpen setIsOpen={vi.fn()}/></MemoryRouter>);
expect(await screen.findByRole('link',{name:'Orchestration command center'})).toHaveAttribute('href','/orchestration');
});
@@ -0,0 +1,19 @@
import {useEffect,useState} from 'react';
import Button from './ui/Button';
import {routerUsage,usagePeriods} from '../services/routerUsage';
import type {RouterUsageSnapshot,UsageCounters,UsagePeriod} from '../services/routerUsage';
const shown=(value:unknown)=>value===null||value===undefined?'Unknown — not reported':String(value);
function Counters({data}:{data:UsageCounters|null}) {return <dl className="grid grid-cols-2 gap-2">{(['requests','inputTokens','outputTokens','cacheReadTokens','cacheWriteTokens','reasoningTokens','errors'] as const).map(key=><div key={key}><dt>{key}</dt><dd>{shown(data?.[key])}</dd></div>)}</dl>}
export default function RouterUsagePanel(){
const [data,setData]=useState<RouterUsageSnapshot|null>(null);const [error,setError]=useState('');const [revision,setRevision]=useState(0);const [loading,setLoading]=useState(false);const [period,setPeriod]=useState<UsagePeriod>('7d');
useEffect(()=>{let active=true;setLoading(true);setError('');setData(null);routerUsage.snapshot(period).then(value=>{if(active)setData(value)}).catch(e=>{if(active)setError(e instanceof Error?e.message:'Usage unavailable')}).finally(()=>{if(active)setLoading(false)});return()=>{active=false}},[revision,period]);
return <section className="bg-white border rounded-2xl p-5 space-y-4"><header className="flex justify-between"><h2 className="font-bold">9router usage & provider-reported quota</h2><Button disabled={loading} onClick={()=>setRevision(n=>n+1)}>Refresh usage</Button></header>
<label>Usage period<select aria-label="Usage period" value={period} onChange={e=>setPeriod(e.target.value as UsagePeriod)}>{usagePeriods.map(p=><option key={p}>{p}</option>)}</select></label>
<p>Gateway totals include all clients. Provider/model/account breakdowns overlap; never add them together. Cache/reasoning counters may overlap token counts. No derived totals or quota estimates.</p>
<p>Hermes attribution: Unknown — not reported; do not add to gateway totals.</p>
{loading&&<p role="status">Loading gateway usage…</p>}{error&&<p role="alert">Unknown / unavailable: {error}</p>}
{data&&<><dl><dt>Source</dt><dd>{data.source}</dd><dt>Retrieved at (not source freshness)</dt><dd>{shown(data.freshness.retrievedAt)}</dd><dt>Source updated at</dt><dd>{shown(data.freshness.sourceUpdatedAt)}</dd><dt>Stale</dt><dd>{shown(data.freshness.stale)}</dd><dt>Reported period</dt><dd>{data.period}</dd></dl><article className="border p-4 rounded-xl"><h3>Gateway totals (includes Hermes)</h3><Counters data={data.data.totals}/></article>
{(['providers','models','accounts'] as const).map(group=><section key={group}><h3 className="font-bold">{group}</h3>{!data.data[group].length&&<p>No {group} reported.</p>}<div className="grid md:grid-cols-2 gap-4">{data.data[group].map((row,i)=><article key={i} className="border p-4 rounded-xl"><h4>{shown(row.provider)} · {shown(row.model)}</h4>{row.accountId&&<p>{row.accountId}</p>}<Counters data={row}/>{group==='accounts'&&<dl><dt>Provider-reported quota remaining</dt><dd>{shown(row.quota?.remaining)}</dd><dt>Provider-reported quota reset</dt><dd>{shown(row.quota?.resetAt)}</dd><dt>Quota availability reason</dt><dd>{shown(row.quota?.reason)}</dd></dl>}</article>)}</div></section>)}
<p>Quota is unknown: upstream quota GET refreshes credentials, so this read-only adapter does not call it.</p></>}
</section>;
}
@@ -117,6 +117,7 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
title: 'حاکمیت، تاییدات و وظایف',
icon: CheckSquare,
items: [
{ icon: Building2, label: 'Orchestration command center', path: '/orchestration' },
{ icon: Building2, label: 'نمای وضعیت دپارتمان‌ها', path: '/governance/hq' },
{ icon: Briefcase, label: 'اقدامات مدیریتی و همکاری‌ها', path: '/manager-actions' },
{ icon: CheckSquare, label: 'مجوزهای عملیاتی', path: '/approvals' },