feat(admin): add backend-authoritative orchestration command center and usage view
This commit is contained in:
1 parent
e5c83e87fe
commit
c8a3f35b0a
16 files changed
+510
-373
No files matched your search
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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>;
|
||||
}
|
||||
Reference in new issue
Block a user