feat(admin): remove governance, orchestration, approvals, tasks, and audit logs modules
Deploy Canina / deploy (push) Successful in 4m14s

This commit is contained in:
parsa aghaei committed 2026-10-26 10:15:06 +03:30
1 parent 99f0c0d626
commit effe30ee58
128 files changed
+5 -14449

No files matched your search

@@ -1,16 +0,0 @@
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 exact bounded PREPARE contract only after valid commit and budget',async()=>{
vi.mocked(api.post).mockResolvedValue({data:{id:'new'}});const done=vi.fn();render(<CreateOrchestrationTask onCreated={done}/>);
expect(screen.getByRole('button',{name:'ایجاد وظیفه محدود'})).toBeDisabled();
for(const [label,value] of Object.entries({'کلید یکتای وظیفه':'audit-1','عنوان':'Audit schema','دپارتمان':'SEO','شناسه کامیت (۴۰ نویسه هگز کوچک)':'a'.repeat(40),'سقف بودجه به سنت':'500','محدوده':'Audit staging only','معیارهای پذیرش (هر معیار در یک خط)':'Schema checked\nEvidence attached'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
for(const value of ['19','10001','20.5']){fireEvent.change(screen.getByLabelText('سقف بودجه به سنت'),{target:{value}});expect(screen.getByRole('button',{name:'ایجاد وظیفه محدود'})).toBeDisabled();}
fireEvent.change(screen.getByLabelText('سقف بودجه به سنت'),{target:{value:'500'}});
fireEvent.click(screen.getByRole('button',{name:'ایجاد وظیفه محدود'}));
await screen.findByText('وظیفه توسط سرور ایجاد شد.');
expect(api.post).toHaveBeenCalledWith('/admin/orchestration/tasks',{key:'audit-1',title:'Audit schema',department:'SEO',operationMode:'PREPARE',budgetLimitCents:500,metadata:{commitSha:'a'.repeat(40),scope:'Audit staging only',acceptanceCriteria:['Schema checked','Evidence attached']}});
expect(done).toHaveBeenCalledOnce();
});
@@ -1,15 +0,0 @@
import {useState} from 'react';
import Button from './ui/Button';
import {orchestration,proposalError} from '../services/orchestration';
import type {CreateTaskInput} from '../services/orchestration';
export default function CreateOrchestrationTask({onCreated}:{onCreated:()=>void}){
const [fields,setFields]=useState({key:'',title:'',department:'',commitSha:'',budget:'',scope:'',criteria:''});
const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [success,setSuccess]=useState('');
const input:CreateTaskInput={key:fields.key,title:fields.title,department:fields.department,operationMode:'PREPARE',budgetLimitCents:Number(fields.budget),metadata:{commitSha:fields.commitSha,scope:fields.scope,acceptanceCriteria:fields.criteria.split('\n')}};
const valid=Object.values(fields).every(value=>value.trim())&&!proposalError(input);
return <details className="bg-white border rounded-2xl p-5"><summary className="font-bold cursor-pointer">ایجاد کار محدود</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy||success)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create(input);setSuccess('وظیفه توسط سرور ایجاد شد.');onCreated()}catch(error){setError(error instanceof Error?error.message+' — پیش از ارسال مجدد، کلید وظیفه را با وضعیت سرور تطبیق دهید.':'ایجاد ناموفق بود؛ پیش از تلاش مجدد کلید وظیفه را تطبیق دهید.')}finally{setBusy(false)}}}>
{([['key','کلید یکتای وظیفه'],['title','عنوان'],['department','دپارتمان'],['commitSha','شناسه کامیت (۴۰ نویسه هگز کوچک)'],['budget','سقف بودجه به سنت'],['scope','محدوده'],['criteria','معیارهای پذیرش (هر معیار در یک خط)']] as const).map(([key,label])=><label key={key} className="block">{label}<textarea aria-label={label} disabled={busy||!!success} required value={fields[key]} onChange={e=>setFields(prev=>({...prev,[key]:e.target.value}))} className="block border p-2 w-full rounded-lg"/></label>)}
<p>حالت عملیات: PREPARE · محیط: staging. بودجه: ۲۰ تا ۱۰۰۰۰ سنت. محدوده: غیرخالی، حداکثر ۲۰۰۰ نویسه. معیار پذیرش: ۱ تا ۲۰ خط غیرخالی، هر خط حداکثر ۵۰۰ نویسه. محدوده و معیارهای انسانی بدون تغییر ذخیره می‌شوند؛ محدودیت گردش کار متعلق به سرور است.</p><p>ایجاد وظیفه مجوز اجرا نیست. Gate1 تصمیمی مستقل و تغییرناپذیر است. پیشنهاد Production غیرفعال است. پس از خطای مبهم، پیش از ارسال مجدد کلید یکتا را با وضعیت سرور تطبیق دهید.</p>
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy||!!success}>ایجاد وظیفه محدود</Button>
</form></details>;
}
@@ -1,26 +0,0 @@
import {useRef,useState} from 'react';
import Button from './ui/Button';
import {commandFailure,orchestration} from '../services/orchestration';
import type {Task,EditorialFailureInput} from '../services/orchestration';
export default function EditorialRecoveryDialog({task,onClose,onSuccess}:{task:Task;onClose:()=>void;onSuccess:()=>Promise<void>}) {
const [reason,setReason]=useState('');const [confirmed,setConfirmed]=useState(false);
const [busy,setBusy]=useState(false);const [attempted,setAttempted]=useState(false);const [blocked,setBlocked]=useState(false);const [error,setError]=useState('');
const payload=useRef<EditorialFailureInput|null>(null);const inFlight=useRef(false);
const execute=async()=>{
if(inFlight.current||blocked||!confirmed||!reason.trim()||reason.length>500)return;
if(!payload.current)payload.current={runId:task.editorialRecovery!.runId,expectedVersion:task.version,idempotencyKey:crypto.randomUUID(),reason};
inFlight.current=true;setBusy(true);setAttempted(true);setError('');
try {await orchestration.editorialFailure(task,payload.current);await onSuccess();}
catch(e){const failure=commandFailure(e);setBlocked(!failure.retryable);setError(failure.message)}
finally{inFlight.current=false;setBusy(false)}
};
return <div dir="rtl" lang="fa" role="dialog" aria-modal="true" aria-label="ثبت شکست اجرای متوقف‌شده" 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>ثبت شکست اجرای متوقف‌شده</h2><p>وظیفه: {task.title} · نسخه: {task.version}</p><p>شناسه اجرا: {task.editorialRecovery!.runId}</p>
<p>فقط اجرای منقضی‌شده به شکست ثبت می‌شود. رزرو ۲۰ سنت حفظ می‌شود؛ هزینه واقعی نامشخص است، نه هزینه صفر.</p>
<p>این اقدام QA یا تأیید خودکار ایجاد نمی‌کند؛ انتشار، اجرای دوباره، افزایش بودجه یا آزادسازی رزرو انجام نمی‌شود. مجوز بازبین مستقل و اتصال اجرای منقضی را سرور دوباره بررسی می‌کند.</p>
<label className="block">دلیل شکست<textarea aria-label="دلیل شکست" maxLength={500} value={reason} disabled={busy||attempted} onChange={e=>{setReason(e.target.value);setConfirmed(false)}} className="border p-2 w-full"/></label><p>{reason.length}/500</p>
<label className="block"><input type="checkbox" checked={confirmed} disabled={busy||attempted} onChange={e=>setConfirmed(e.target.checked)}/>ثبت شکست بدون تأیید کیفیت یا آزادسازی بودجه را تأیید می‌کنم</label>
{error&&<p role="alert">{error}</p>}
<div className="flex gap-3"><Button disabled={busy||blocked||!confirmed||!reason.trim()||reason.length>500} onClick={()=>void execute()}>ثبت شکست</Button><Button disabled={busy} variant="outline" onClick={onClose}>بازخوانی و بستن</Button></div>
</div></div>;
}
@@ -1,9 +0,0 @@
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');
});
@@ -1,10 +0,0 @@
import {render,screen} from '@testing-library/react';
import {expect,it} from 'vitest';
import {Records} from './OrchestrationPresentation';
it('preserves human scope, criteria and immutable identifiers while translating protocol enums',()=>{
render(<Records value={{metadata:{scope:'READY',acceptanceCriteria:['SUCCEEDED'],commitSha:'READY'},operationMode:'PREPARE',status:'SUCCEEDED'}}/>);
expect(screen.getAllByText('READY')).toHaveLength(2);
expect(screen.getByText('SUCCEEDED')).toBeInTheDocument();
expect(screen.getByText('آماده‌سازی')).toBeInTheDocument();
expect(screen.getByText('موفق')).toBeInTheDocument();
});
@@ -1,11 +0,0 @@
import type {ServerAction} from '../services/orchestration';
const labels:Record<string,string>={GATE1_RENEWAL_REQUIRED:'مسدود — تأیید Gate1 منقضی شده؛ نیازمند تأیید مجدد مالک',DRAFT:'پیش‌نویس',GATE1_HELD:'تصمیم به تعویق افتاده',GATE1_PENDING:'در انتظار تأیید Gate1',GATE1_APPROVED:'تأییدشده در Gate1',READY:'آماده اجرا',RUNNING:'در حال اجرا',SUCCEEDED:'موفق',FAILED:'ناموفق',BLOCKED:'مسدود',EXPIRED:'منقضی',REJECTED:'ردشده',APPROVED:'تأییدشده',GATE2_PENDING:'در انتظار Gate2 (غیرفعال)',PREPARE:'آماده‌سازی',MUTATE_PRODUCTION:'تغییر Production (غیرفعال)',SEO:'بهینه‌سازی جست‌وجو (SEO)',Content:'محتوا',Tech:'فنی',operationMode:'حالت عملیات',budgetLimitCents:'سقف بودجه (سنت)',metadata:'اطلاعات ثبت‌شده',scope:'محدوده',acceptanceCriteria:'معیارهای پذیرش',commitSha:'شناسه کامیت',id:'شناسه',taskId:'شناسه وظیفه',expectedVersion:'نسخه مورد انتظار',idempotencyKey:'کلید جلوگیری از اجرای تکراری',gate:'دروازه تأیید',decision:'تصمیم',expiresAt:'زمان انقضا',createdAt:'زمان ثبت',runId:'شناسه اجرا',artifactHash:'هش خروجی',environment:'محیط',sha256:'هش SHA-256',kind:'نوع',eventType:'نوع رویداد',fromState:'وضعیت پیشین',toState:'وضعیت بعدی',sequence:'ترتیب',amountCents:'مبلغ (سنت)',status:'وضعیت',reason:'دلیل',department:'دپارتمان',staging:'آزمایشی (staging)',FREEZE_NEW_WORK:'توقف کار جدید',STOP_AGENTS:'توقف عامل‌ها',DISABLE_MUTATIONS:'منع تغییرات',EMERGENCY_HALT:'توقف اضطراری',RESERVE:'رزرو بودجه',RECONCILE:'تطبیق بودجه'};
export const label=(value:string)=>labels[value]??value;
export const actionLabel=(action:ServerAction)=>({HOLD_GATE1:'تعویق تصمیم Gate1',SUBMIT_GATE1:'ارسال برای Gate1',APPROVE_GATE1:'تأیید کار محدود در Gate1',REJECT_GATE1:'رد کار در Gate1',QUEUE_PREPARE:'صف‌بندی آماده‌سازی'}[action.id]??(action.gate?`${action.decision==='APPROVED'?'تأیید':'رد'} در Gate${action.gate}`:'اقدام سرور'));
export function Records({value,field}:{value:unknown;field?:string}){
if(value===null||value===undefined)return <span>نامشخص — گزارش نشده</span>;
if(Array.isArray(value))return value.length?<div className="space-y-3">{value.map((item,index)=><article className="border rounded-lg p-3" key={index}><Records value={item} field={field}/></article>)}</div>:<p>رکوردی ثبت نشده است.</p>;
if(typeof value==='object')return <dl className="grid gap-3 sm:grid-cols-2">{Object.entries(value).map(([key,item])=><div key={key} className="min-w-0"><dt className="text-sm text-gray-500">{label(key)}</dt><dd className="break-words"><Records value={item} field={key}/></dd></div>)}</dl>;
if(typeof value==='boolean')return <span>{value?'بله':'خیر'}</span>;
return <bdi className="break-all">{typeof value==='string'&&['state','status','fromState','toState','operationMode','department','decision','environment','kind'].includes(field??'')?label(value):String(value)}</bdi>;
}
@@ -1,20 +0,0 @@
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?'نامشخص — گزارش نشده':String(value);
const labels:Record<string,string>={requests:'درخواست‌ها',inputTokens:'توکن ورودی',outputTokens:'توکن خروجی',cacheReadTokens:'توکن خواندن حافظه نهان',cacheWriteTokens:'توکن نوشتن حافظه نهان',reasoningTokens:'توکن استدلال',errors:'خطاها',providers:'تأمین‌کننده‌ها',models:'مدل‌ها',accounts:'حساب‌ها'};
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>{labels[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:'مصرف در دسترس نیست')}).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 و سهمیه گزارش‌شده تأمین‌کننده</h2><Button disabled={loading} onClick={()=>setRevision(n=>n+1)}>بازخوانی مصرف</Button></header>
<label>بازه مصرف<select aria-label="بازه مصرف" value={period} onChange={e=>setPeriod(e.target.value as UsagePeriod)}>{usagePeriods.map(p=><option key={p}>{p}</option>)}</select></label>
<p>مجموع درگاه شامل همه مشتری‌هاست. تفکیک تأمین‌کننده، مدل و حساب هم‌پوشانی دارد؛ آن‌ها را جمع نکنید. شمارنده حافظه نهان و استدلال ممکن است با توکن‌ها هم‌پوشان باشد. مجموع یا سهمیه تخمینی محاسبه نمی‌شود.</p>
<p>سهم مصرف Hermes: نامشخص و گزارش‌نشده؛ با مجموع درگاه جمع نکنید.</p>
{loading&&<p role="status">در حال دریافت مصرف درگاه…</p>}{error&&<p role="alert">دریافت مصرف ناموفق بود: {error}</p>}
{data&&<><dl><dt>منبع</dt><dd>{data.source}</dd><dt>زمان دریافت (نه زمان تازگی منبع)</dt><dd>{shown(data.freshness.retrievedAt)}</dd><dt>زمان به‌روزرسانی منبع</dt><dd>{shown(data.freshness.sourceUpdatedAt)}</dd><dt>قدیمی بودن داده</dt><dd>{shown(data.freshness.stale)}</dd><dt>بازه گزارش‌شده</dt><dd>{data.period}</dd></dl><article className="border p-4 rounded-xl"><h3>مجموع درگاه (شامل Hermes)</h3><Counters data={data.data.totals}/></article>
{(['providers','models','accounts'] as const).map(group=><section key={group}><h3 className="font-bold">{labels[group]}</h3>{!data.data[group].length&&<p>داده‌ای برای {labels[group]} گزارش نشده است.</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>سهمیه باقی‌مانده گزارش‌شده تأمین‌کننده</dt><dd>{shown(row.quota?.remaining)}</dd><dt>زمان بازنشانی سهمیه گزارش‌شده</dt><dd>{shown(row.quota?.resetAt)}</dd><dt>دلیل وضعیت سهمیه</dt><dd>{shown(row.quota?.reason)}</dd></dl>}</article>)}</div></section>)}
<p>سهمیه نامشخص است: درخواست سهمیه به منبع، اطلاعات احراز هویت را تغییر می‌دهد؛ بنابراین این رابط فقط‌خواندنی آن را فراخوانی نمی‌کند.</p></>}
</section>;
}
@@ -1,44 +0,0 @@
import {render,screen,fireEvent,waitFor} from '@testing-library/react';
import {beforeEach,it,expect,vi} from 'vitest';
import api from '../services/api';
import RuntimeReadPanel from './RuntimeReadPanel';
const provenance={source:'snapshot',capturedAt:'2020-01-01T00:00:00Z',ageSeconds:5000,freshness:'stale',liveProcess:'unknown'};
it('labels snapshot inventory without presenting متوقف gateway, zero agents or فعال sessions as live',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:true,provenance}:url.endsWith('/profiles')?[{name:'dev',is_default:false,gateway_running:false,liveGatewayState:'unknown',provenance}]:url.endsWith('/status')?{version:'v1',gateway_running:false,overall:'نامشخص',active_agents:0,gateway_state:null,liveGatewayState:'unknown',liveActiveAgents:null,provenance}:url.endsWith('/sessions')?{total:1,sessions:[{id:'session-1',profile:'dev',source:'cli',is_active:true}],provenance}:{period_days:30,totals:{total_input:1,total_output:2,total_sessions:1,total_estimated_cost:0},provenance}}));
render(<RuntimeReadPanel/>);
expect(await screen.findByText('سرویس فهرست ثبت‌شده: پاسخ‌گو (نه سلامت زنده Hermes)')).toBeInTheDocument();
screen.getAllByText(/زمان ثبت: 2020-01-01T00:00:00Z/).forEach(row=>expect(row).toHaveTextContent('قدیمی'));
fireEvent.change(screen.getByLabelText('پروفایل اجرای مجاز'),{target:{value:'dev'}});
expect(await screen.findByText(/عامل‌های فعال: نامشخص/)).toBeInTheDocument();
expect(await screen.findByText(/پرچم تاریخی نمای ثبت‌شده: فعال; فعالیت زنده نامشخص است/)).toBeInTheDocument();
expect(screen.queryByText(/درگاه.*متوقف/)).not.toBeInTheDocument();
expect(screen.queryByText(/عامل‌های فعال: 0/)).not.toBeInTheDocument();
expect(screen.queryByText(/runtime health: healthy/)).not.toBeInTheDocument();
});
vi.mock('../services/api',()=>({default:{get:vi.fn()}}));
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>{
if(url.endsWith('/health'))return {data:{ok:true,version:'v1',commit:'abc',auth_required:true}};
if(url.endsWith('/profiles'))return {data:[{name:'dev',is_default:false,gateway_running:false}]};
if(url.endsWith('/status'))return {data:{version:'v1',gateway_running:false,overall:'degraded',active_agents:0,gateway_state:null}};
if(url.endsWith('/sessions'))return {data:{total:0,sessions:[]}};
if(url.endsWith('/usage'))return {data:{period_days:30,totals:{total_input:0,total_output:0,total_sessions:0,total_estimated_cost:0}}};
throw new Error('Runtime unavailable');
});});
it('shows actual health identity, explicit متوقف gateway, zero usage and profile-bound reads',async()=>{
render(<RuntimeReadPanel/>);expect(await screen.findByText('v1 · abc')).toBeInTheDocument();
fireEvent.change(await screen.findByLabelText('پروفایل اجرای مجاز'),{target:{value:'dev'}});
expect(await screen.findByText('degraded')).toBeInTheDocument();expect(await screen.findByText('نشستی دریافت نشد.')).toBeInTheDocument();
expect(screen.getByText('توکن ورودی: 0')).toBeInTheDocument();expect(screen.getByText(/هزینه تخمینی منبع: 0/)).toBeInTheDocument();
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/runtime/sessions',{params:{profile:'dev',limit:20,offset:0}});
});
it('shows unavailable rather than healthy when runtime cannot be authenticated',async()=>{
vi.mocked(api.get).mockRejectedValue(new Error('Runtime unavailable'));
render(<RuntimeReadPanel/>);expect(await screen.findByText(/وضعیت اجرا در دسترس نیست/)).toBeInTheDocument();expect(screen.queryByText('اجرای احرازهویت‌شده health: healthy')).not.toBeInTheDocument();
});
it('rejects malformed health and never renders نامشخص secret fields',async()=>{
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/health')?{ok:true,version:'v1',commit:'abc',auth_required:false,password:'secret-value'}:[]}));
render(<RuntimeReadPanel/>);expect(await screen.findByText(/وضعیت اجرا در دسترس نیست/)).toBeInTheDocument();expect(screen.queryByText(/secret-value/)).not.toBeInTheDocument();
});
it('refreshes the authenticated runtime reads without a browser runtime connection',async()=>{
render(<RuntimeReadPanel/>);await screen.findByText('v1 · abc');fireEvent.click(screen.getByRole('button',{name:'بازخوانی اطلاعات اجرا'}));await waitFor(()=>expect(vi.mocked(api.get).mock.calls.filter(([u])=>u.endsWith('/health'))).toHaveLength(2));
});
@@ -1,35 +0,0 @@
import {useEffect,useState} from 'react';
import Button from './ui/Button';
import {runtime} from '../services/runtime';
import type {RuntimeProvenance,RuntimeHealth,RuntimeProfile,RuntimeStatus,RuntimeSessions,RuntimeUsage} from '../services/runtime';
function Snapshot({value}:{value?:RuntimeProvenance}){return value?<p>فهرست ثبت‌شده · زمان ثبت: {value.capturedAt} · قدمت: {value.ageSeconds} ثانیه · {value.freshness==='fresh'?'تازه':'قدیمی'} · فرایند زنده: نامشخص. حتی نمای تازه، آمادگی زنده را اثبات نمی‌کند.</p>:null}
export default function RuntimeReadPanel(){
const [revision,setRevision]=useState(0);const [profile,setProfile]=useState('');const [offset,setOffset]=useState(0);
const [health,setHealth]=useState<RuntimeHealth|null>(null);const [profiles,setProfiles]=useState<RuntimeProfile[]>([]);const [errors,setErrors]=useState<Record<string,string>>({});
const [status,setStatus]=useState<RuntimeStatus|null>(null);const [sessions,setSessions]=useState<RuntimeSessions|null>(null);const [usage,setUsage]=useState<RuntimeUsage|null>(null);
const [observed,setObserved]=useState('');
useEffect(()=>{let active=true;setHealth(null);setProfiles([]);setErrors({});
runtime.health().then(value=>{if(active){setHealth(value);setObserved(new Date().toISOString())}}).catch(()=>{if(active)setErrors(e=>({...e,health:'وضعیت اجرا در دسترس نیست؛ خواندن احرازهویت‌شده از سرور ناموفق بود.'}))});
runtime.profiles().then(value=>{if(active){setProfiles(value);setProfile(current=>value.some(p=>p.name===current)?current:'')}}).catch(()=>{if(active){setProfile('');setErrors(e=>({...e,profiles:'پروفایل‌ها در دسترس نیستند؛ فهرست هویت‌های مجاز دریافت نشد.'}))}});
return ()=>{active=false};
},[revision]);
useEffect(()=>{let active=true;setStatus(null);setSessions(null);setUsage(null);setErrors(e=>({health:e.health,profiles:e.profiles}));if(!profile)return;
const fail=(name:string)=>{if(active)setErrors(e=>({...e,[name]:(({Status:'وضعیت',Sessions:'نشست‌ها',Usage:'مصرف'} as Record<string,string>)[name]??name)+' در دسترس نیست؛ مقدار جایگزین وجود ندارد.'}))};
runtime.status(profile).then(v=>{if(active)setStatus(v)}).catch(()=>fail('Status'));
runtime.sessions(profile,offset).then(v=>{if(active)setSessions(v)}).catch(()=>fail('Sessions'));
runtime.usage(profile).then(v=>{if(active)setUsage(v)}).catch(()=>fail('Usage'));
return ()=>{active=false};
},[profile,offset,revision]);
return <section aria-label="اجرای احرازهویت‌شده" className="bg-white border rounded-2xl p-5 space-y-4">
<div className="flex justify-between"><h2 className="font-bold">اطلاعات اجرای Hermes — خواندن احرازهویت‌شده از سرور</h2><Button onClick={()=>setRevision(r=>r+1)}>بازخوانی اطلاعات اجرا</Button></div>
<p>اطلاعات محرمانه اجرا وارد مرورگر نمی‌شود و اتصال مستقیم به Hermes وجود ندارد. زمان دریافت پاسخ، زمان ضربان حیات نیست.</p>
{Object.entries(errors).filter(([,message])=>message).map(([name,message])=><p key={name} role="alert">{message}</p>)}
{health&&<div><p>سرویس فهرست ثبت‌شده: {health.ok?'پاسخ‌گو':'بدون پاسخ'} (نه سلامت زنده Hermes)</p><Snapshot value={health.provenance}/><p>{health.version} · {health.commit}</p><p>زمان دریافت توسط مرورگر: {observed}. فقط زمان دریافت پاسخ است؛ نه زمان ثبت منبع یا ضربان زنده.</p></div>}
<label>پروفایل اجرای مجاز<select aria-label="پروفایل اجرای مجاز" value={profile} onChange={e=>{setProfile(e.target.value);setOffset(0)}}><option value="">انتخاب پروفایل مجاز</option>{profiles.map(p=><option key={p.name} value={p.name}>{p.name}</option>)}</select></label>
{!profiles.length&&!errors.profiles&&<p>پروفایل مجازی دریافت نشد.</p>}
{profiles.map(p=><div key={p.name}>{p.name} · درگاه {p.provenance?'نامشخص (نمای ثبت‌شده؛ نه آمادگی فرایند)':p.gateway_running?'در حال اجرا':'متوقف'} · {p.is_default?'پروفایل پیش‌فرض':'پروفایل غیرپیش‌فرض'}<Snapshot value={p.provenance}/></div>)}
{status&&<div><h3>وضعیت پروفایل</h3><Snapshot value={status.provenance}/><p>{status.overall}</p><p>درگاه: {status.provenance?'نامشخص':status.gateway_running?'در حال اجرا':'متوقف'} · وضعیت: {status.provenance?'نامشخص':status.gateway_state??'نامشخص'} · عامل‌های فعال: {status.provenance?'نامشخص':status.active_agents}</p></div>}
{usage&&<div><h3>مصرف اجرا — {usage.period_days} روز؛ فقط پروفایل انتخاب‌شده</h3><Snapshot value={usage.provenance}/><p>توکن ورودی: {usage.totals.total_input}</p><p>توکن خروجی: {usage.totals.total_output}</p><p>نشست‌ها: {usage.totals.total_sessions}</p><p>هزینه تخمینی منبع: {usage.totals.total_estimated_cost} (ارز توسط منبع مشخص نشده؛ صورت‌حساب قطعی نیست)</p><p>این مقدار را با مجموع 9router جمع نکنید؛ انتساب مصرف هم‌پوشانی دارد و تطبیق داده نشده است.</p></div>}
{sessions&&<div><h3>نشست‌ها — {sessions.total} مجموع گزارش‌شده</h3><Snapshot value={sessions.provenance}/>{!sessions.sessions.length&&<p>نشستی دریافت نشد.</p>}{sessions.sessions.map(s=><article key={s.id} className="border rounded p-2"><p>{s.id} · {s.profile} · {s.source} · {sessions.provenance?`پرچم تاریخی نمای ثبت‌شده: ${s.is_active?'فعال':'غیرفعال'}; فعالیت زنده نامشخص است`:s.is_active?'فعال':'غیرفعال'}</p></article>)}<Button disabled={offset===0} onClick={()=>setOffset(n=>Math.max(0,n-20))}>نشست‌های قبلی</Button><Button disabled={offset+20>=sessions.total} onClick={()=>setOffset(n=>n+20)}>نشست‌های بعدی</Button></div>}
</section>;
}
@@ -112,19 +112,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: MessageSquare, label: 'تحلیل مشاوره سایت', path: '/settings/smart-chat' },
],
},
{
id: 'governance',
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' },
{ icon: Briefcase, label: 'وظایف دپارتمان‌ها و ایجنت‌ها', path: '/tasks' },
{ icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' },
],
},
{
id: 'monitoring',
title: 'مرکز مانیتورینگ و سلامت',
@@ -12,9 +12,6 @@ interface TopbarProps {
}
const SEARCHABLE_PAGES = [
{ label: "اقدامات مدیریتی و همکاری‌ها (Manager Actions)", path: "/manager-actions", keywords: ["اقدامات", "مدیریتی", "همکاری", "b2b", "تامین", "استراتژی", "actions"] },
{ label: "مجوزهای عملیاتی مدیریت (Operational Approvals)", path: "/approvals", keywords: ["مجوز", "مجوزها", "تاییدات", "approvals", "عملیاتی", "تایید"] },
{ label: "وضعیت دپارتمان‌ها و ارکستراسیون (HQ)", path: "/governance/hq", keywords: ["ارکستراسیون", "دپارتمان", "hq", "governance", "وضعیت"] },
{ label: 'داشبورد (خلاصه وضعیت فروشگاه)', path: '/', keywords: ['dashboard', 'آمار', 'فروش', 'خانه'] },
{ label: 'مرکز مانیتورینگ و سلامت سرویس‌ها', path: '/monitoring', keywords: ['monitoring', 'مانیتورینگ', 'سلامت', 'پینگ', 'وضعیت', 'سرعت'] },
{ label: 'مدیریت نسخه‌های پزشکی (Prescriptions)', path: '/prescriptions', keywords: ['نسخه', 'نسخه‌ها', 'پزشک', 'دارو', 'تجویز', 'rx', 'prescription', 'بررسی نسخه'] },