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,34 @@
# Admin orchestration v4 adapter contract
All client traffic uses existing authenticated Axios client (`src/services/api.ts`). Relative `/admin/...` paths are served below `/api`. No runtime secrets, Hermes tokens, PTY, terminal websocket or direct gateway credentials may enter these DTOs. Backend must project/redact task metadata, artifacts, audit payloads and chat text before returning them. Browser does not enforce authorization.
## Implemented core API observed in sibling core worktree
- GET `/admin/orchestration/tasks`: bare Task[] or `{success:true,data:Task[]}`.
- GET `/admin/orchestration/tasks/:id`: immutable task detail with runs/artifacts, decisions, events and budgetLedger.
- POST `/admin/orchestration/tasks`: key,title,department,operationMode,budgetLimitCents,metadata {scope,acceptanceCriteria[]} (no execution authorization).
- PUT `/admin/orchestration/tasks/:id/transition`: toState,expectedVersion,idempotencyKey,reason.
- POST `/admin/orchestration/tasks/:id/gates/{1|2}/decide`: decision,expectedVersion,idempotencyKey,expiresAt,notes. Gate2 APPROVED additionally binds runId,artifactHash,commitSha,environment to registered immutable run and artifact.
- PUT `/admin/orchestration/kill-switch`: level,reason. Levels FREEZE_NEW_WORK,STOP_AGENTS,DISABLE_MUTATIONS,EMERGENCY_HALT. No invented reset/resume route.
Task fields and optional service DTOs are declared in `src/services/orchestration.ts`.
## Required integration additions (fail closed until backend provides)
Task `availableActions: {id,label,toState?,gate?:1|2,decision?:APPROVED|REJECTED,disabledReason?}[]` must be advertised by backend after permission, state, gate, policy and kill-switch evaluation. Browser never derives transitions from state. Missing actions means read-only, not an invitation to synthesize controls. Backend core inspected initially did not advertise these actions. This is an integration blocker for execution.
Optional read-only resources GET `/admin/orchestration/{agents|model-policy|schedules|releases}` return `{items:[{id,title?,status?,department?,readiness?,model?,budgetLimitCents?,spentCents?,cron?,timezone?,environment?,commitSha?,reason?}],measuredAt:ISO8601}`. May be wrapped in `{success:true,data:...}`. 404/403/network/malformed replies render unavailable, not mock cards. These endpoint contracts are proposals requiring backend reconciliation, not claims that endpoints exist. Schedule editing, model policy editing, budget adjustments, agent start/stop and release execution require separately advertised typed backend commands; intentionally not implemented against guessed routes. Existing task run/evidence, decisions, ledger and ordered events remain inspectable independent of optional feeds.
POST `/admin/orchestration/chat/messages`: {sessionId,message,idempotencyKey} -> {id,role:'assistant',content}. Advisory-only bridge; no browser runtime connection or auto-execution of text. Backend must bind sessions to authenticated user and redact sensitive output.
## Retry and concurrency
Command dialog snapshots immutable task version and allocates one key. On first attempt inputs lock; failed retries use identical payload/key. Cancel and refresh to reconcile 409 conflict; refresh invalidates selection and dialog. Successful command refetches authoritative tasks; no optimistic status. Backend must enforce idempotency transactionally, compare payload bindings and versions; frontend is not a safety boundary. Task creation is keyed by unique business key; reconcile ambiguous failures by refreshing before retry.
## 9router usage concrete contract (aligned with backend worker b0f4636)
GET `/admin/router-usage?period=today|24h|7d|30d|60d|all` default7d; authenticated admin. Response: source,period,status available|unavailable,reason,data null|{totals,providers[],models[],accounts[]},freshness {retrievedAt,sourceUpdatedAt,stale},attribution {scope:9router_total,hermes:null,additive:false}.
Metrics: requests,inputTokens,outputTokens,cacheReadTokens,cacheWriteTokens,reasoningTokens,errors. Last three unsupported=null. Account quota {status:unknown,remaining:null,resetAt:null,reason:upstream_quota_get_mutates_credentials}. No upstream quota GET because it refreshes credentials. No estimates or raw credentials. Nullable provider/model/account IDs are sanitized by backend.
Breakdowns overlap and are never summed. Hermes attribution unknown, not zero and not added. Retrieved timestamp is not source freshness. SourceUpdatedAt and stale remain explicitly unknown. Frontend explicitly projects DTO fields and rejects malformed/unavailable replies. No direct gateway connection.
## Monitoring
Existing payment stats/health and SMS credit are read independently. Only returned values displayed. Request failures remain unknown with source and client observation timestamp. Database/Redis/Post/OCR/uptime/environment/agent runtime remain unknown without measured endpoints. No fabricated 14-day uptime, Production label, derived DB ping, SMS count or healthy post service.
## Verification caveats
All verification uses disposable node:22-bookworm Docker runners against this worktree. Plain `npm run typecheck` uses solution-style config and does not verify app files. `tsc --noEmit -p tsconfig.app.json` exposes pre-existing errors in legacy Approvals/Audit/HQ/Tasks imports and Orders/Symptoms types; report these separately, not as a green full application typecheck. Build warning: unresolved existing Shabnam font remains runtime-resolved.
@@ -0,0 +1,21 @@
# Verification and remaining integration work
Remote branch: feature/orchestration-v4-admin. All source changes limited to frontend/admin-panel. No push, deployment, production container command, or live operational mutation performed.
Disposable node:22-bookworm runners, --userns=host:
- Full `vitest run --maxWorkers=2`: 57 files, 326 tests passed, zero failed.
- Scoped ESLint for all new services/components/tests plus Monitoring: exit 0.
- `npm run typecheck` (solution config): exit 0, not an app check.
- `tsc --noEmit -p tsconfig.app.json`: exit 2, 33 pre-existing diagnostics (legacy unused imports/locals, Orders requiresRx type, Symptoms ConfirmModal props). No diagnostics in new files or Monitoring. Baseline captured before implementation had same legacy errors.
- `npm run build`: exit 0; pre-existing unresolved Shabnam font warning.
TDD red/green cycles exercised adapter missing exports, unadvertised actions, incomplete/expired Gate2 bindings, exact version/idempotency payloads and retry lock, task creation bounds, UI explicit confirmation, monitoring fake values and failures, navigation, router usage contract migration/unavailable state. Full UI tests use mocked HTTP boundary with realistic backend DTOs; they are not a live backend integration test. Additional UI tests cover immutable artifact binding, kill authorization failure, readiness BLOCKED response, chat escaping and typed bridge. Router usage aligned to concrete backend b0f4636 contract.
Remaining gaps / do not claim full end-to-end operation:
- Backend must advertise availableActions. Initial core worktree lacks them; client intentionally fails closed read-only without actions.
- Agents/model-policy/schedules/releases snapshots and typed chat bridge are proposed contracts, not initially present core routes. UI displays explicit unavailable errors, never synthetic content. Mutating model policy/schedules/agent operations not implemented against guessed endpoints.
- Kill switch current level cannot be read until backend exposes a status contract. No invented resume command.
- No live auth credentials used; endpoint auth/RBAC and cross-worker DTO integration still need isolated stack smoke tests.
- Legacy Approvals/Tasks/HQ/Audit pages remain separately available and unchanged. New v4 control center is at /orchestration inside existing protected layout; these legacy pages are not v4 authority and should be retired/migrated during integration.
- Full app typecheck is not green due existing errors listed above.
- Browser chat is advisory; no Hermes terminal or raw runtime connection.
@@ -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' },
@@ -2,17 +2,30 @@ import { act,fireEvent,render,screen } from '@testing-library/react';
import { afterEach,beforeEach,describe,expect,it,vi } from 'vitest';
import api from '../services/api';
import MonitoringPage from './MonitoringPage';
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn(), put: vi.fn(), post: vi.fn() } }));
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
describe('MonitoringPage', () => {
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async (url) => ({ data: url === '/payment/admin/stats' ? { todayVolume: '125000', todayVerified: 4, successRate: 0 } : url === '/payment/admin/health' ? { status: 'ONLINE', latencyMs: 250 } : { credit: 0 } })); });
afterEach(() => vi.useRealTimers());
const load = async () => { render(<MonitoringPage />); await screen.findByText('1 رویداد ثبت شده'); };
it('renders real volume and preserves zero success rate and SMS balance', async () => { await load(); expect(screen.getByText('۱۲۵٬۰۰۰ تومان')).toBeInTheDocument(); expect(screen.getByText('0%')).toBeInTheDocument(); expect(screen.getAllByText(/۰ پیامک/).length).toBeGreaterThan(0); });
it('shows offline gateway and SMS on rejected endpoints instead of false healthy states', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); await load(); expect(screen.getAllByText('غیرفعال / قطعی')).toHaveLength(2); expect(screen.queryByText('98.4%')).not.toBeInTheDocument(); });
it('honors explicit offline health response even when latency is low', async () => { vi.mocked(api.get).mockImplementation(async (url) => ({ data: url.includes('health') ? { status: 'OFFLINE', latencyMs: 10 } : { credit: 12 } })); await load(); expect(screen.getByText('غیرفعال / قطعی')).toBeInTheDocument(); });
it('shows slow gateway warning and refreshes all three read-only endpoints', async () => { vi.mocked(api.get).mockImplementation(async (url) => ({ data: url.includes('health') ? { latencyMs: 2000 } : { credit: 12 } })); await load(); expect(screen.getByText('کاهش سرعت / هشدار')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: /بروزرسانی زنده/ })); await screen.findByText('2 رویداد ثبت شده'); expect(api.get).toHaveBeenCalledTimes(6); expect(api.post).not.toHaveBeenCalled(); });
it('polls after 30 seconds and cleans timer on unmount', async () => { vi.useFakeTimers(); const view = render(<MonitoringPage />); await act(async () => { await Promise.resolve(); }); expect(api.get).toHaveBeenCalledTimes(3); for (let i=0; i<30; i++) await act(async () => { vi.advanceTimersByTime(1000); }); expect(api.get).toHaveBeenCalledTimes(6); view.unmount(); await act(async () => { vi.advanceTimersByTime(60000); }); expect(api.get).toHaveBeenCalledTimes(6); });
vi.mock('../services/api',()=>({default:{get:vi.fn()}}));
describe('measured monitoring',()=>{
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.includes('/stats')?{todayVolume:0,todayVerified:0,successRate:0}:url.includes('/health')?{status:'ONLINE',latencyMs:0}:{credit:0}}))});
afterEach(()=>vi.useRealTimers());
it('preserves measured zero but never manufactures database health, post latency, uptime or environment',async()=>{
render(<MonitoringPage/>);await screen.findByText('0%');
expect(screen.getByText('0 ms')).toBeInTheDocument();
expect(screen.getByText('۰ پیامک')).toBeInTheDocument();
expect(screen.getByText('Database: Unknown — no measured endpoint')).toBeInTheDocument();
expect(screen.getByText('Environment: Unknown — no measured endpoint')).toBeInTheDocument();
expect(screen.queryByText('Production')).not.toBeInTheDocument();
expect(screen.queryByText(/۱۴ روز/)).not.toBeInTheDocument();
});
it('marks failures unknown rather than online and permits measured refresh',async()=>{
vi.mocked(api.get).mockRejectedValue(new Error('connection refused'));
render(<MonitoringPage/>);expect(await screen.findAllByText(/connection refused/)).toHaveLength(3);
expect(screen.queryByText('ONLINE')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'Refresh measurements'}));
await screen.findAllByText(/connection refused/);expect(api.get).toHaveBeenCalledTimes(6);
});
it('polls and cancels on unmount',async()=>{
vi.useFakeTimers();const view=render(<MonitoringPage/>);await act(async()=>{});
expect(api.get).toHaveBeenCalledTimes(3);
await act(async()=>{vi.advanceTimersByTime(30000)});expect(api.get).toHaveBeenCalledTimes(6);
view.unmount();await act(async()=>{vi.advanceTimersByTime(60000)});expect(api.get).toHaveBeenCalledTimes(6);
});
});
+27 -360
View File
@@ -1,364 +1,31 @@
import {
Activity,
CheckCircle2,
Clock,
CreditCard,
Database,
FileText,
MessageSquare,
RefreshCw,
Truck
} from 'lucide-react';
import { useCallback,useEffect,useState } from 'react';
import { toast } from 'react-hot-toast';
import Badge from '../components/ui/Badge';
import { useCallback, useEffect, useRef, useState } from 'react';
import Button from '../components/ui/Button';
import Skeleton from '../components/ui/Skeleton';
import api from '../services/api';
interface MonitoringStats {
timestamp: string;
zibal: {
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
latencyMs: number;
merchantId?: string;
todayVolumeTomans: number;
todayTxCount: number;
successRate: number;
};
melipayamak: {
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
credit: number | string;
latencyMs: number;
todaySmsSent: number;
patternActive: boolean;
};
post: {
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
latencyMs: number;
trackingActive: boolean;
};
system: {
backendStatus: 'HEALTHY' | 'DEGRADED';
dbStatus: 'CONNECTED' | 'DISCONNECTED';
dbLatencyMs: number;
uptimeSeconds: number;
environment: string;
};
}
type Measurement = {data:Record<string,unknown>|null;error:string|null;observedAt:string};
const endpoints = ['/payment/admin/stats','/payment/admin/health','/settings/sms/credit'] as const;
const value=(v:unknown,suffix='') => v===null||v===undefined ? 'Unknown — not measured' : String(v)+suffix;
export default function MonitoringPage() {
const [stats, setStats] = useState<MonitoringStats | null>(null);
const [, setIsLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const [autoRefresh] = useState(true);
const [refreshInterval] = useState(30); // seconds
const [countdown, setCountdown] = useState(30);
const [logs, setLogs] = useState<any[]>([]);
const fetchMonitoringData = useCallback(async (silent = false) => {
try {
if (!silent) setIsRefreshing(true);
const startTime = Date.now();
// Parallel real queries to live endpoints
const [txStatsRes, healthRes, smsRes] = await Promise.allSettled([
api.get('/payment/admin/stats').catch(() => ({ data: null })),
api.get('/payment/admin/health').catch(() => ({ data: null })),
api.get('/settings/sms/credit').catch(() => ({ data: null })),
]);
const roundTripMs = Date.now() - startTime;
const txStats = txStatsRes.status === 'fulfilled' ? txStatsRes.value?.data : null;
const health = healthRes.status === 'fulfilled' ? healthRes.value?.data : null;
const sms = smsRes.status === 'fulfilled' ? smsRes.value?.data : null;
const smsCreditVal = typeof sms === 'object' && sms !== null ? sms.credit ?? sms.balance ?? sms.data : sms;
const newStats: MonitoringStats = {
timestamp: new Date().toLocaleTimeString('fa-IR'),
zibal: {
status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
latencyMs: health?.latencyMs ?? 0,
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
successRate: txStats?.successRate ?? 0,
},
melipayamak: {
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE',
credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص',
latencyMs: 0,
todaySmsSent: 48,
patternActive: true,
},
post: {
status: 'ONLINE',
latencyMs: 0,
trackingActive: true,
},
system: {
backendStatus: 'HEALTHY',
dbStatus: 'CONNECTED',
dbLatencyMs: Math.max(12, roundTripMs - 120),
uptimeSeconds: 86400 * 14 + 3600 * 5,
environment: 'Production',
},
};
setStats(newStats);
// Append live log
setLogs((prev) => [
{
id: Date.now(),
time: new Date().toLocaleTimeString('fa-IR'),
service: 'HealthCheck',
type: 'INFO',
message: `پایش بلادرنگ انجام شد. زیبال: ${newStats.zibal.latencyMs}ms | پیامک: ${newStats.melipayamak.credit} | سیستم: ${newStats.system.dbLatencyMs}ms`,
},
...prev.slice(0, 19),
]);
} catch (e) {
console.error('Failed to load monitoring data', e);
if (!silent) toast.error('خطا در دریافت وضعیت سرور و سرویس‌های واسط');
} finally {
setIsLoading(false);
setIsRefreshing(false);
setCountdown(refreshInterval);
}
}, [refreshInterval]);
useEffect(() => {
fetchMonitoringData();
}, [fetchMonitoringData]);
// Auto-refresh countdown ticker
useEffect(() => {
if (!autoRefresh) return;
const interval = setInterval(() => {
setCountdown((prev) => {
if (prev <= 1) {
fetchMonitoringData(true);
return refreshInterval;
}
return prev - 1;
});
}, 1000);
return () => clearInterval(interval);
}, [autoRefresh, refreshInterval, fetchMonitoringData]);
const getStatusBadge = (status: 'ONLINE' | 'DEGRADED' | 'OFFLINE' | 'HEALTHY' | 'CONNECTED' | 'DISCONNECTED') => {
switch (status) {
case 'ONLINE':
case 'HEALTHY':
case 'CONNECTED':
return <Badge variant="success" size="sm">آنلاین و فعال</Badge>;
case 'DEGRADED':
return <Badge variant="warning" size="sm">کاهش سرعت / هشدار</Badge>;
case 'OFFLINE':
case 'DISCONNECTED':
return <Badge variant="danger" size="sm">غیرفعال / قطعی</Badge>;
default:
return <Badge variant="slate" size="sm">نامشخص</Badge>;
}
};
return (
<div className="space-y-6 font-vazir pb-12" dir="rtl">
{/* Top Action Header */}
<div className="bg-white p-5 sm:p-6 rounded-3xl border border-gray-100 shadow-xs flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-3.5">
<div className="w-12 h-12 rounded-2xl bg-gradient-to-tr from-purple-600 to-indigo-600 text-white flex items-center justify-center shadow-lg shadow-purple-500/20 shrink-0">
<Activity className="w-6 h-6 animate-pulse" />
</div>
<div>
<h1 className="text-xl font-black text-gray-900 flex items-center gap-2">
مرکز مانیتورینگ بلادرنگ سیستم و درگاه‌ها
<span className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-ping inline-block" />
</h1>
<p className="text-xs text-gray-500 font-medium mt-1">
پایش آنلاین وضعیت اتصالات بانکی زیبال، سامانه پیامک ملی‌پیامک، وب‌سرویس پستی و دیتابیس
</p>
</div>
</div>
<div className="flex items-center gap-2.5 self-end md:self-center">
<div className="flex items-center gap-2 bg-gray-50 border border-gray-200 px-3 py-1.5 rounded-2xl text-xs font-bold text-gray-600">
<Clock className="w-3.5 h-3.5 text-purple-600" />
<span>بروزرسانی بعدی: {countdown} ثانیه</span>
</div>
<Button
variant="outline"
size="sm"
startIcon={RefreshCw}
isLoading={isRefreshing}
onClick={() => fetchMonitoringData(false)}
>
بروزرسانی زنده
</Button>
</div>
</div>
{/* Main Service Cards Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
{/* Zibal Payment Gateway */}
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
<div className="flex items-center justify-between">
<div className="w-10 h-10 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center">
<CreditCard className="w-5 h-5" />
</div>
{stats ? getStatusBadge(stats.zibal.status) : <Skeleton className="w-16 h-6 rounded-full" />}
</div>
<div>
<h3 className="font-black text-gray-900 text-sm">درگاه پرداخت زیبال (شاپرک)</h3>
<p className="text-[11px] text-gray-400 font-medium">سرویس پرداخت و استرداد آنلاین</p>
</div>
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">تاخیر پاسخگویی (Latency):</span>
<span className="font-mono font-black text-blue-600">{stats?.zibal.latencyMs || 142} ms</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">حجم تراکنش‌های امروز:</span>
<span className="font-mono font-bold text-gray-900">{stats ? `${stats.zibal.todayVolumeTomans.toLocaleString('fa-IR')} تومان` : '...'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">درصد موفقیت (Success Rate):</span>
<span className="font-mono font-bold text-emerald-600">{stats?.zibal.successRate ?? 0}%</span>
</div>
</div>
</div>
{/* Melipayamak SMS Gateway */}
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
<div className="flex items-center justify-between">
<div className="w-10 h-10 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
<MessageSquare className="w-5 h-5" />
</div>
{stats ? getStatusBadge(stats.melipayamak.status) : <Skeleton className="w-16 h-6 rounded-full" />}
</div>
<div>
<h3 className="font-black text-gray-900 text-sm">سامانه پیامک (ملی‌پیامک)</h3>
<p className="text-[11px] text-gray-400 font-medium">ارسال پترن کد تایید و لاگ وضعیت سفارش</p>
</div>
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">موجودی پنل:</span>
<span className="font-mono font-black text-emerald-700">{stats?.melipayamak.credit || '...'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">تاخیر وب‌سرویس SOAP:</span>
<span className="font-mono font-black text-emerald-600">{stats?.melipayamak.latencyMs || 88} ms</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">ارسال‌های امروز:</span>
<span className="font-mono font-bold text-gray-900">{stats?.melipayamak.todaySmsSent || 48} پیامک</span>
</div>
</div>
</div>
{/* Postal Tracking Service */}
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
<div className="flex items-center justify-between">
<div className="w-10 h-10 rounded-2xl bg-amber-50 text-amber-600 flex items-center justify-center">
<Truck className="w-5 h-5" />
</div>
{stats ? getStatusBadge(stats.post.status) : <Skeleton className="w-16 h-6 rounded-full" />}
</div>
<div>
<h3 className="font-black text-gray-900 text-sm">سامانه رهگیری پستی و تیپاکس</h3>
<p className="text-[11px] text-gray-400 font-medium">استعلام آنلاین وضعیت بارنامه و مرسولات</p>
</div>
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">وضعیت اتصال:</span>
<span className="font-bold text-amber-700">برقرار و فعال</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">پاسخگویی سرور پست:</span>
<span className="font-mono font-black text-amber-600">{stats?.post.latencyMs || 155} ms</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">سرویس بارکدخوان:</span>
<span className="font-bold text-emerald-600">فعال (OCR / Text)</span>
</div>
</div>
</div>
{/* Database & Core System */}
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
<div className="flex items-center justify-between">
<div className="w-10 h-10 rounded-2xl bg-purple-50 text-purple-600 flex items-center justify-center">
<Database className="w-5 h-5" />
</div>
{stats ? getStatusBadge(stats.system.dbStatus) : <Skeleton className="w-16 h-6 rounded-full" />}
</div>
<div>
<h3 className="font-black text-gray-900 text-sm">پایگاه داده و سرور اصلی</h3>
<p className="text-[11px] text-gray-400 font-medium">PostgreSQL / Redis Cache</p>
</div>
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-gray-500">پینگ دیتابیس:</span>
<span className="font-mono font-black text-purple-600">{stats?.system.dbLatencyMs || 18} ms</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">محیط استقرار:</span>
<span className="font-bold text-gray-900">{stats?.system.environment || 'Production'}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-500">آپتایم سرور:</span>
<span className="font-mono font-bold text-emerald-600">۱۴ روز و ۵ ساعت</span>
</div>
</div>
</div>
</div>
{/* Live Activity & Inspection Feed */}
<div className="bg-white rounded-3xl p-6 border border-gray-100 shadow-xs space-y-4">
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
<h3 className="font-black text-gray-900 text-sm flex items-center gap-2">
<FileText className="w-4 h-4 text-purple-600" />
لاگ بلادرنگ بررسی سلامت سرویس‌ها (Live Health Inspection Log)
</h3>
<span className="text-xs text-gray-400 font-bold">{logs.length} رویداد ثبت شده</span>
</div>
<div className="space-y-2 overflow-x-auto">
{logs.length === 0 ? (
<div className="text-center py-6 text-xs text-gray-400">در حال دریافت لاگ‌های زنده...</div>
) : (
logs.map((log) => (
<div
key={log.id}
className="flex items-center justify-between p-3 rounded-2xl bg-gray-50 border border-gray-100 text-xs gap-3"
>
<div className="flex items-center gap-3">
<span className="font-mono font-bold text-gray-400">{log.time}</span>
<Badge variant="blue" size="sm">{log.service}</Badge>
<span className="font-medium text-gray-700">{log.message}</span>
</div>
<span className="font-bold text-emerald-600 flex items-center gap-1 shrink-0">
<CheckCircle2 className="w-3.5 h-3.5" />
موفق
</span>
</div>
))
)}
</div>
</div>
</div>
);
const [measurements,setMeasurements]=useState<Measurement[]>([]);
const [loading,setLoading]=useState(false); const active=useRef(true);const inFlight=useRef(false);
const refresh=useCallback(async()=>{
if(inFlight.current)return;inFlight.current=true;setLoading(true);
const results=await Promise.all(endpoints.map(async url=>{
try {const {data:raw}=await api.get(url);const data=raw?.success===true?raw.data:raw;
if(!data||typeof data!=='object'||raw?.success===false)throw new Error('Invalid measurement response');
return {data,error:null,observedAt:new Date().toISOString()};
}catch(e){return {data:null,error:e instanceof Error?e.message:'Request failed',observedAt:new Date().toISOString()}}
}));
if(active.current){setMeasurements(results);setLoading(false)}inFlight.current=false;
},[]);
useEffect(()=>{active.current=true;void refresh();const timer=setInterval(()=>void refresh(),30000);return()=>{active.current=false;clearInterval(timer)}},[refresh]);
const [stats,health,sms]=measurements;const tx=stats?.data;const gateway=health?.data;const credit=sms?.data?.credit??sms?.data?.balance;
return <div className="space-y-5 font-vazir pb-12"><header className="bg-white p-5 border rounded-2xl flex justify-between"><div><h1 className="font-black text-xl">Measured service monitoring</h1><p>Only backend-reported values. Unknown is not healthy. Polling every 30 seconds.</p></div><Button disabled={loading} onClick={()=>void refresh()}>Refresh measurements</Button></header>
{loading&&<p role="status">Loading measurements…</p>}
<div className="grid md:grid-cols-3 gap-4">{['Payment statistics','Payment gateway health','SMS credit'].map((title,index)=><section key={title} className="bg-white border rounded-2xl p-5 space-y-3"><h2 className="font-bold">{title}</h2><p className="text-xs break-all">Source: {endpoints[index]}</p><p>Observed at: {measurements[index]?.observedAt??'Unknown'}</p>{measurements[index]?.error&&<p role="alert" className="text-red-700">Unknown — {measurements[index].error}</p>}
{index===0&&<dl><dt>Today volume (toman)</dt><dd>{value(tx?.todayVolume)}</dd><dt>Verified transactions</dt><dd>{value(tx?.todayVerified??tx?.verifiedCount)}</dd><dt>Success rate</dt><dd>{value(tx?.successRate,'%')}</dd></dl>}
{index===1&&<dl><dt>Reported status</dt><dd>{value(gateway?.status)}</dd><dt>Reported latency</dt><dd>{value(gateway?.latencyMs,' ms')}</dd><dt>Merchant</dt><dd>{value(gateway?.activeMerchant??gateway?.merchantId)}</dd></dl>}
{index===2&&<p>{typeof credit==='number'?credit.toLocaleString('fa-IR')+' پیامک':value(credit)}</p>}
</section>)}</div>
<section className="bg-amber-50 border rounded-2xl p-5 space-y-2"><h2 className="font-bold">Uninstrumented services</h2>{['Database','Redis','Post service','OCR','Uptime','Environment','SMS sent today','SMS latency','Agent runtime'].map(label=><p key={label}>{label}: Unknown — no measured endpoint</p>)}</section>
</div>;
}
@@ -0,0 +1,95 @@
import { render, screen, fireEvent, within } from '@testing-library/react';
import { beforeEach, describe, 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()} }));
const task={id:'t1',key:'bounded-1',title:'Bounded SEO audit',department:'SEO',state:'GATE1_PENDING',version:4,operationMode:'PREPARE',budgetLimitCents:500,availableActions:[{id:'g1',label:'Approve bounded work',gate:1,decision:'APPROVED'}],runs:[],metadata:{scope:'Only staging',acceptanceCriteria:['Audit schema']}};
describe('command center', () => {
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async url => {
if(url.endsWith('/tasks')) return {data:[task]};
if(url.endsWith('/tasks/t1')) return {data:task};
throw new Error('Unavailable: '+url);
}); });
it('loads server tasks, immutable bounds and only server actions; unavailable data is never fabricated', async () => {
render(<OrchestrationCommandCenter />);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
expect(await screen.findByText(/Only staging/)).toBeInTheDocument();
expect(screen.getByRole('button',{name:'Approve bounded work'})).toBeInTheDocument();
expect(screen.queryByRole('button',{name:'RUNNING'})).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button',{name:'Agents & departments'}));
expect(await screen.findByRole('alert')).toHaveTextContent('Unavailable');
});
it('requires explicit confirmation and expiry; retains idempotency across failed retry', async () => {
vi.mocked(api.post).mockRejectedValue(new Error('network failure'));
render(<OrchestrationCommandCenter />);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
fireEvent.click(await screen.findByRole('button',{name:'Approve bounded work'}));
const dialog=screen.getByRole('dialog');
expect(within(dialog).getByRole('button',{name:'Confirm command'})).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});
fireEvent.change(within(dialog).getByLabelText('Reason'),{target:{value:'Scope checked'}});
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
expect(await within(dialog).findByRole('alert')).toHaveTextContent('network failure');
expect(within(dialog).getByLabelText('Reason')).toBeDisabled();
expect(within(dialog).getByLabelText('Expires at')).toBeDisabled();
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
await within(dialog).findByRole('alert');
expect(api.post).toHaveBeenCalledTimes(2);
const first=vi.mocked(api.post).mock.calls[0][1];
expect(first).toEqual(expect.objectContaining({expectedVersion:4,decision:'APPROVED'}));
expect(vi.mocked(api.post).mock.calls[1][1]).toEqual(first);
});
it('shows measured readiness snapshot and unknown optional services without synthetic cards',async()=>{
vi.mocked(api.get).mockImplementation(async url=>{
if(url.endsWith('/tasks'))return {data:[]};
return {data:{measuredAt:'2026-10-22T12:00:00Z',items:[{id:'agent-1',title:'SEO worker',status:'BLOCKED',readiness:'Missing model policy',department:'SEO'}]}};
});
render(<OrchestrationCommandCenter/>);
fireEvent.click(screen.getByRole('button',{name:'Agents & departments'}));
expect(await screen.findByText('Missing model policy')).toBeInTheDocument();
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}));
vi.mocked(api.post).mockResolvedValue({data:{id:'decision-2'}});
render(<OrchestrationCommandCenter/>);
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
fireEvent.click(await screen.findByRole('button',{name:'Approve release'}));
const dialog=screen.getByRole('dialog');
fireEvent.change(within(dialog).getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});
fireEvent.change(within(dialog).getByLabelText('Reason'),{target:{value:'Evidence reviewed'}});
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
expect(within(dialog).getByRole('button',{name:'Confirm command'})).toBeDisabled();
fireEvent.change(within(dialog).getByLabelText('Registered run / artifact binding'),{target:{value:'run-1|'+'a'.repeat(64)}});
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
await screen.findByText(/Command accepted/);
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks/t1/gates/2/decide',expect.objectContaining({runId:'run-1',artifactHash:'a'.repeat(64),commitSha:'abc123',environment:'staging',expectedVersion:4}));
});
it('requires global impact confirmation for each kill level and reports backend rejection',async()=>{
vi.mocked(api.put).mockRejectedValue(new Error('Forbidden: role'));
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
expect(screen.getAllByRole('option')).toHaveLength(4);
expect(screen.getByRole('button',{name:'Apply kill switch'})).toBeDisabled();
fireEvent.change(screen.getByLabelText('Kill level'),{target:{value:'EMERGENCY_HALT'}});
fireEvent.change(screen.getByLabelText('Kill reason'),{target:{value:'Incident'}});
fireEvent.click(screen.getByLabelText('I confirm global operational impact'));
fireEvent.click(screen.getByRole('button',{name:'Apply kill switch'}));
expect(await screen.findByRole('alert')).toHaveTextContent('Forbidden: role');
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/kill-switch',{level:'EMERGENCY_HALT',reason:'Incident'});
});
it('sends advisory chat via typed bridge and renders text, not HTML',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{id:'reply',role:'assistant',content:'<script>unsafe</script>'}});
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
fireEvent.click(screen.getByRole('button',{name:'Chat'}));
fireEvent.change(screen.getByLabelText('Session ID'),{target:{value:'session-1'}});
fireEvent.change(screen.getByLabelText('Message'),{target:{value:'Explain bounded work'}});
fireEvent.click(screen.getByRole('button',{name:'Send advisory message'}));
expect(await screen.findByText('assistant: <script>unsafe</script>')).toBeInTheDocument();
expect(document.querySelector('script')).toBeNull();
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/chat/messages',expect.objectContaining({sessionId:'session-1',message:'Explain bounded work'}));
});
});
@@ -0,0 +1,79 @@
import { useEffect, useState } from 'react';
import Button from '../components/ui/Button';
import RouterUsagePanel from '../components/RouterUsagePanel';
import CreateOrchestrationTask from '../components/CreateOrchestrationTask';
import { orchestration, killLevels } 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;
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 [section,setSection]=useState<Section>('Overview');
const [tasks,setTasks]=useState<Task[]>([]);
const [selected,setSelected]=useState<Task|null>(null);
const [snapshot,setSnapshot]=useState<ResourceSnapshot|null>(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 [kill,setKill]=useState<KillLevel>('FREEZE_NEW_WORK');
const [session,setSession]=useState(''); const [message,setMessage]=useState('');
const [messages,setMessages]=useState<ChatMessage[]>([]);
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()},[]);
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)=>{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 execute=async()=> {
if(!pending||busy||!confirmed)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)}
};
const refresh=()=>{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>
{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>}
{section==='Tasks & approvals'&&<CreateOrchestrationTask onCreated={()=>void loadTasks()}/>}
{section==='Overview'&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">Observed task inventory</h2><p>{tasks.length} tasks returned by backend. This is inventory, not agent health or runtime telemetry.</p><div className="flex flex-wrap gap-3">{[...new Set(tasks.map(t=>t.state))].map(state=><span key={state} className="border rounded-xl p-3">{state}: {tasks.filter(t=>t.state===state).length}</span>)}</div></section>}
{(['Overview','Tasks & approvals','Runs & artifacts','Models & budgets','Audit & releases'] as Section[]).includes(section)&&<section className="bg-white border rounded-2xl p-5 space-y-4"><label>Filter tasks<input className="border rounded-lg p-2 m-2" value={search} onChange={e=>setSearch(e.target.value)}/></label>
{!loading&&!error&&!tasks.length&&<p>No tasks returned by backend.</p>}
<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><h3>Immutable scope / acceptance criteria</h3><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>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??[]}/>
</section>}
{snapshot&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2>{section}</h2><p>Measured at: {snapshot.measuredAt}</p>{!snapshot.items.length&&<p>No records returned by backend.</p>}<div className="grid md:grid-cols-2 gap-3">{snapshot.items.map(item=><article key={item.id} className="border rounded-xl p-4"><h3>{item.title??item.id}</h3><dl>{Object.entries(item).filter(([k])=>k!=='id'&&k!=='title').map(([k,v])=><div key={k} className="flex justify-between gap-3"><dt>{k}</dt><dd>{String(v??'Unknown')}</dd></div>)}</dl></article>)}</div><p>Configuration mutations require backend-advertised commands; none are inferred by this client.</p></section>}
{section==='Kill switch'&&<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==='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>}
<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>
</div></div>}
</div>;
}
@@ -54,6 +54,7 @@ const ManagerActionsPage = lazyWithRetry(() => import('../pages/ManagerActionsPa
const ApprovalsPage = lazyWithRetry(() => import('../pages/ApprovalsPage'));
const AuditHistoryPage = lazyWithRetry(() => import('../pages/AuditHistoryPage'));
const TasksManagementPage = lazyWithRetry(() => import('../pages/TasksManagementPage'));
const OrchestrationCommandCenter = lazyWithRetry(() => import('../pages/OrchestrationCommandCenter'));
const CompanyOrchestrationHQ = lazyWithRetry(() => import('../pages/CompanyOrchestrationHQ'));
export interface AdminRouteConfig {
@@ -124,6 +125,7 @@ export const router = createBrowserRouter([
{ path: 'manager-actions/*', element: <ManagerActionsPage /> },
{ path: 'history/*', element: <AuditHistoryPage /> },
{ path: 'tasks/*', element: <TasksManagementPage /> },
{ path: 'orchestration/*', element: <OrchestrationCommandCenter /> },
{ path: 'governance/hq/*', element: <CompanyOrchestrationHQ /> },
],
},
@@ -0,0 +1,54 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import api from './api';
import { orchestration } from './orchestration';
import type { Task } from './orchestration';
vi.mock('./api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }));
const task = {id:'t/1',version:7,state:'GATE2_PENDING',availableActions:[{id:'approve',label:'Approve',gate:2,decision:'APPROVED'}]} as Task;
describe('orchestration adapter', () => {
beforeEach(() => vi.resetAllMocks());
it('loads bare task lists through existing authenticated client and fails closed without actions', async () => {
vi.mocked(api.get).mockResolvedValue({data:[{id:'t1',title:'Bounded work',version:2,state:'READY'}]});
const tasks = await orchestration.tasks();
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/tasks');
expect(tasks[0].availableActions).toEqual([]);
});
it('rejects unadvertised transitions and incomplete Gate2 binding without a request', async () => {
await expect(orchestration.command(task, {id:'invented',label:'Run',toState:'RUNNING'}, {idempotencyKey:'k',reason:'reviewed'})).rejects.toThrow(/advertised/);
await expect(orchestration.command(task, task.availableActions[0], {idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/binding/);
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 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');
await orchestration.command({...task,runs:[run]},task.availableActions[0],input);
expect(api.post).toHaveBeenLastCalledWith('/admin/orchestration/tasks/t%2F1/gates/2/decide',{expectedVersion:7,idempotencyKey:'same-key',decision:'APPROVED',expiresAt:input.expiresAt,notes:undefined,runId:'r',artifactHash:'a'.repeat(64),commitSha:'abc',environment:'staging'});
});
it('refuses expired approvals and unknown artifacts', async () => {
await expect(orchestration.command(task,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2000-01-01T00:00:00Z'})).rejects.toThrow(/expiry/);
const bad={...task,runs:[{id:'r',commitSha:'abc',environment:'staging',status:'DONE',artifacts:[]}]};
await expect(orchestration.command(bad,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'bad'})).rejects.toThrow(/binding/);
});
it('loads immutable detail and rejects malformed optional resources', async () => {
vi.mocked(api.get).mockResolvedValueOnce({data:{success:true,data:{...task,runs:[]}}}).mockResolvedValueOnce({data:{nonsense:true}});
expect((await orchestration.task('t/1')).version).toBe(7);
await expect(orchestration.resource('agents')).rejects.toThrow(/Invalid/);
});
it('requires kill reason and uses only typed message bridge', async () => {
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/reason/);
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/message/);
vi.mocked(api.put).mockResolvedValue({data:{active:true}});
await orchestration.kill('STOP_AGENTS','Incident review');
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/kill-switch',{level:'STOP_AGENTS',reason:'Incident review'});
vi.mocked(api.post).mockResolvedValue({data:{id:'reply',role:'assistant',content:'Review complete'}});
expect(await orchestration.chat('session','Review task','key')).toEqual({id:'reply',role:'assistant',content:'Review complete'});
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/chat/messages',{sessionId:'session',message:'Review task',idempotencyKey:'key'});
});
it('creates bounded work without permitting invalid caps or client-supplied state',async()=>{
await expect(orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:-1,metadata:{scope:'staging',acceptanceCriteria:['report']}})).rejects.toThrow(/budget/);
vi.mocked(api.post).mockResolvedValue({data:{id:'new-task'}});
await orchestration.create({key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:0,metadata:{scope:'staging',acceptanceCriteria:['report']}});
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'t',title:'Audit',department:'SEO',operationMode:'PREPARE',budgetLimitCents:0,metadata:{scope:'staging',acceptanceCriteria:['report']}});
});
});
@@ -0,0 +1,64 @@
import api from './api';
export interface ServerAction { id: string; label: string; toState?: string; gate?: 1 | 2; decision?: 'APPROVED' | 'REJECTED'; disabledReason?: string }
export interface Artifact { id: string; sha256: string; kind?: string; uri?: string }
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 type Resource = 'agents' | 'model-policy' | 'schedules' | 'releases' | 'overview';
export interface ResourceSnapshot { 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;
export type KillLevel = typeof killLevels[number];
export interface ChatMessage {id:string;role:'assistant'|'user';content:string}
function unwrap<T>(data: T | {success:boolean;data:T}): T { if (data && typeof data === 'object' && 'success' in data) {if (!data.success) throw new Error('Orchestration request failed'); return data.data;} return data as T; }
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(!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;
},
async task(id:string):Promise<Task> {
const data=unwrap<Task>((await api.get('/admin/orchestration/tasks/'+encodeURIComponent(id))).data);
if (!data?.id || !Number.isInteger(data.version)) throw new Error('Invalid task detail');
return {...data,availableActions:data.availableActions??[]};
},
async resource(name:Resource):Promise<ResourceSnapshot> {
const data=unwrap<ResourceSnapshot>((await api.get('/admin/orchestration/'+name)).data);
if (!Array.isArray(data?.items) || !data.measuredAt) throw new Error('Invalid resource snapshot');
return data;
},
async kill(level:KillLevel,reason:string):Promise<unknown> {
if (!killLevels.includes(level) || !reason.trim()) throw new Error('Kill switch level and reason required');
return (await api.put('/admin/orchestration/kill-switch',{level,reason})).data;
},
async chat(sessionId:string,message:string,idempotencyKey:string):Promise<ChatMessage> {
if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('Session and message required');
const data=unwrap<ChatMessage>((await api.post('/admin/orchestration/chat/messages',{sessionId,message,idempotencyKey})).data);
if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('Invalid typed chat reply');
return data;
},
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');
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) {
if (!input.expiresAt || !(Date.parse(input.expiresAt) > Date.now())) throw new Error('Future expiry required');
let binding = {};
if (action.gate === 2 && action.decision === 'APPROVED') {
const run = task.runs?.find(r => r.id === input.runId);
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};
}
return (await api.post(base + `/gates/${action.gate}/decide`, {expectedVersion:task.version,idempotencyKey:input.idempotencyKey,decision:action.decision,expiresAt:input.expiresAt,notes:input.reason,...binding})).data;
}
if (!action.toState) throw new Error('Unsupported server action');
return (await api.put(base + '/transition', {toState:action.toState,expectedVersion:task.version,idempotencyKey:input.idempotencyKey,reason:input.reason})).data;
},
async tasks(): Promise<Task[]> {
const { data } = await api.get('/admin/orchestration/tasks');
const rows = Array.isArray(data) ? data : data.data;
if (!Array.isArray(rows)) throw new Error('Invalid orchestration task response');
return rows.map(row => ({ ...row, availableActions: row.availableActions ?? [] }));
},
};
@@ -0,0 +1,31 @@
import {render,screen,fireEvent} from '@testing-library/react';
import {it,expect,vi} from 'vitest';
import api from './api';
import {routerUsage} from './routerUsage';
import RouterUsagePanel from '../components/RouterUsagePanel';
vi.mock('./api',()=>({default:{get:vi.fn()}}));
const metrics={requests:20,inputTokens:100,outputTokens:50,cacheReadTokens:0,cacheWriteTokens:null,reasoningTokens:null,errors:null};
const snapshot={source:'9router',period:'7d',status:'available',reason:null,attribution:{scope:'9router_total',hermes:null,additive:false},freshness:{retrievedAt:'2026-10-22T12:00:00Z',sourceUpdatedAt:null,stale:null},data:{totals:metrics,providers:[{provider:'provider-a',...metrics}],models:[{model:'model-b',provider:'provider-a',...metrics}],accounts:[{accountId:'opaque-1',provider:'provider-a',model:'model-b',...metrics,quota:{status:'unknown',remaining:null,resetAt:null,reason:'upstream_quota_get_mutates_credentials'}}]}};
it('renders concrete backend contract, unknown quota and source freshness; period selects backend filter',async()=>{
vi.mocked(api.get).mockResolvedValue({data:snapshot});render(<RouterUsagePanel/>);
expect(await screen.findByText('opaque-1')).toBeInTheDocument();
expect(screen.getByText('Gateway totals (includes Hermes)')).toBeInTheDocument();
expect(screen.getByText('Hermes attribution: Unknown — not reported; do not add to gateway totals.')).toBeInTheDocument();
expect(screen.getByText('9router')).toBeInTheDocument();
expect(screen.getAllByText('Unknown — not reported').length).toBeGreaterThan(0);
expect(screen.getAllByText('0').length).toBeGreaterThan(0);
expect(api.get).toHaveBeenCalledWith('/admin/router-usage',{params:{period:'7d'}});
fireEvent.change(screen.getByLabelText('Usage period'),{target:{value:'today'}});
await screen.findByText('opaque-1');
expect(api.get).toHaveBeenLastCalledWith('/admin/router-usage',{params:{period:'today'}});
});
it('rejects missing provenance instead of inventing freshness',async()=>{
vi.mocked(api.get).mockResolvedValue({data:{accounts:[]}});
await expect(routerUsage.snapshot()).rejects.toThrow(/Invalid/);
});
it('shows unavailable configuration honestly and discards arbitrary credential properties',async()=>{
vi.mocked(api.get).mockResolvedValueOnce({data:{...snapshot,status:'unavailable',reason:'not_configured',data:null}});
await expect(routerUsage.snapshot()).rejects.toThrow('not_configured');
vi.mocked(api.get).mockResolvedValueOnce({data:{...snapshot,token:'secret',data:{...snapshot.data,credentials:'secret'}}});
expect(JSON.stringify(await routerUsage.snapshot())).not.toContain('secret');
});
@@ -0,0 +1,20 @@
import api from './api';
export const usagePeriods=['today','24h','7d','30d','60d','all'] as const;
export type UsagePeriod=typeof usagePeriods[number];
export interface UsageCounters {requests:number|null;inputTokens:number|null;outputTokens:number|null;cacheReadTokens:number|null;cacheWriteTokens:number|null;reasoningTokens:number|null;errors:number|null}
export interface UsageRow extends UsageCounters {provider:string|null;model?:string|null;accountId?:string|null;quota?:{status:string;remaining:number|null;resetAt:string|null;reason:string|null}}
export interface RouterUsageSnapshot {source:string;period:UsagePeriod;freshness:{retrievedAt:string|null;sourceUpdatedAt:string|null;stale:boolean|null};attribution:{scope:'9router_total';hermes:null;additive:false};data:{totals:UsageCounters;providers:UsageRow[];models:UsageRow[];accounts:UsageRow[]}}
const count=(v:unknown):number|null=>typeof v==='number'&&Number.isSafeInteger(v)&&v>=0?v:null;
const text=(v:unknown):string|null=>typeof v==='string'?v:null;
function counters(raw:UsageCounters):UsageCounters {
return {requests:count(raw?.requests),inputTokens:count(raw?.inputTokens),outputTokens:count(raw?.outputTokens),cacheReadTokens:count(raw?.cacheReadTokens),cacheWriteTokens:count(raw?.cacheWriteTokens),reasoningTokens:count(raw?.reasoningTokens),errors:count(raw?.errors)};
}
function rows(list:UsageRow[]):UsageRow[]{return list.map(a=>({provider:text(a.provider),model:text(a.model),accountId:text(a.accountId),...counters(a),...(a.quota?{quota:{status:a.quota.status,remaining:count(a.quota.remaining),resetAt:text(a.quota.resetAt),reason:text(a.quota.reason)}}:{})}))}
export const routerUsage={async snapshot(period:UsagePeriod='7d'):Promise<RouterUsageSnapshot>{
const {data:raw}=await api.get('/admin/router-usage',{params:{period}});
const data=raw?.success===true?raw.data:raw;
if(data?.status==='unavailable')throw new Error('Usage unavailable: '+(data.reason??'unknown'));
if(data?.status!=='available'||data.source!=='9router'||!usagePeriods.includes(data.period)||!data.freshness||!data.data||!Array.isArray(data.data.providers)||!Array.isArray(data.data.models)||!Array.isArray(data.data.accounts))throw new Error('Invalid usage snapshot contract');
// Explicit allowlist; never forward raw gateway configuration or arbitrary response properties.
return {source:data.source,period:data.period,freshness:{retrievedAt:text(data.freshness.retrievedAt),sourceUpdatedAt:text(data.freshness.sourceUpdatedAt),stale:typeof data.freshness.stale==='boolean'?data.freshness.stale:null},attribution:{scope:'9router_total',hermes:null,additive:false},data:{totals:counters(data.data.totals),providers:rows(data.data.providers),models:rows(data.data.models),accounts:rows(data.data.accounts)}};
}};