Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc00b56718 |
No files matched your search
@@ -5,12 +5,12 @@ 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:'Create bounded task'})).toBeDisabled();
|
||||
for(const [label,value] of Object.entries({'Task key':'audit-1','Title':'Audit schema','Department':'SEO','Commit SHA (40 lowercase hex)':'a'.repeat(40),'Budget cap in cents':'500','Scope':'Audit staging only','Acceptance criteria (one per line)':'Schema checked\nEvidence attached'}))fireEvent.change(screen.getByLabelText(label),{target:{value}});
|
||||
for(const value of ['19','10001','20.5']){fireEvent.change(screen.getByLabelText('Budget cap in cents'),{target:{value}});expect(screen.getByRole('button',{name:'Create bounded task'})).toBeDisabled();}
|
||||
fireEvent.change(screen.getByLabelText('Budget cap in cents'),{target:{value:'500'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Create bounded task'}));
|
||||
await screen.findByText('Task created by backend.');
|
||||
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();
|
||||
});
|
||||
@@ -7,9 +7,9 @@ export default function CreateOrchestrationTask({onCreated}:{onCreated:()=>void}
|
||||
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">Create bounded work</summary><form className="space-y-3 mt-4" onSubmit={async e=>{e.preventDefault();if(!valid||busy||success)return;setBusy(true);setError('');setSuccess('');try{await orchestration.create(input);setSuccess('Task created by backend.');onCreated()}catch(error){setError(error instanceof Error?error.message+' — Refresh and reconcile the task key before resubmitting.':'Create failed; reconcile task key before retry')}finally{setBusy(false)}}}>
|
||||
{([['key','Task key'],['title','Title'],['department','Department'],['commitSha','Commit SHA (40 lowercase hex)'],['budget','Budget cap in cents'],['scope','Scope'],['criteria','Acceptance criteria (one per line)']] 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>Operation mode: PREPARE · Environment: staging. Budget: 20..10000 cents. Scope: nonblank, at most 2000 characters. Acceptance criteria: 1..20 nonblank lines, at most 500 characters each. Human scope and criteria are persisted unchanged; the workflow restriction is server-owned.</p><p>Creation does not authorize work. Gate1 is a separate immutable decision. Production proposals are disabled. After an ambiguous failure, refresh and reconcile the unique task key before resubmitting.</p>
|
||||
{error&&<p role="alert">{error}</p>}{success&&<p role="status">{success}</p>}<Button type="submit" disabled={!valid||busy||!!success}>Create bounded task</Button>
|
||||
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>;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
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();
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import type {ServerAction} from '../services/orchestration';
|
||||
const labels:Record<string,string>={DRAFT:'پیشنویس',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)=>({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>;
|
||||
}
|
||||
@@ -2,18 +2,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>}
|
||||
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:'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></>}
|
||||
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>;
|
||||
}
|
||||
@@ -3,16 +3,16 @@ 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 stopped gateway, zero agents or active 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:'unknown',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}}));
|
||||
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('Inventory service: responsive (not live Hermes health)')).toBeInTheDocument();
|
||||
screen.getAllByText(/Captured at: 2020-01-01T00:00:00Z/).forEach(row=>expect(row).toHaveTextContent('stale'));
|
||||
fireEvent.change(screen.getByLabelText('Authorized runtime profile'),{target:{value:'dev'}});
|
||||
expect(await screen.findByText(/Active agents: unknown/)).toBeInTheDocument();
|
||||
expect(await screen.findByText(/historical snapshot flag: active; live activity unknown/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Gateway.*stopped/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/Active agents: 0/)).not.toBeInTheDocument();
|
||||
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()}}));
|
||||
@@ -24,21 +24,21 @@ beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async u
|
||||
if(url.endsWith('/usage'))return {data:{period_days:30,totals:{total_input:0,total_output:0,total_sessions:0,total_estimated_cost:0}}};
|
||||
throw new Error('Runtime unavailable');
|
||||
});});
|
||||
it('shows actual health identity, explicit stopped gateway, zero usage and profile-bound reads',async()=>{
|
||||
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('Authorized runtime profile'),{target:{value:'dev'}});
|
||||
expect(await screen.findByText('degraded')).toBeInTheDocument();expect(await screen.findByText('No sessions returned.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Input tokens: 0')).toBeInTheDocument();expect(screen.getByText(/Upstream estimated cost: 0/)).toBeInTheDocument();
|
||||
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(/Health unavailable/)).toBeInTheDocument();expect(screen.queryByText('Authenticated runtime health: healthy')).not.toBeInTheDocument();
|
||||
render(<RuntimeReadPanel/>);expect(await screen.findByText(/وضعیت اجرا در دسترس نیست/)).toBeInTheDocument();expect(screen.queryByText('اجرای احرازهویتشده health: healthy')).not.toBeInTheDocument();
|
||||
});
|
||||
it('rejects malformed health and never renders unknown secret fields',async()=>{
|
||||
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(/Health unavailable/)).toBeInTheDocument();expect(screen.queryByText(/secret-value/)).not.toBeInTheDocument();
|
||||
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:'Refresh runtime'}));await waitFor(()=>expect(vi.mocked(api.get).mock.calls.filter(([u])=>u.endsWith('/health'))).toHaveLength(2));
|
||||
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));
|
||||
});
|
||||
@@ -2,34 +2,34 @@ 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>Snapshot inventory · Captured at: {value.capturedAt} · Age: {value.ageSeconds} seconds · {value.freshness} · Live process: {value.liveProcess}. Even fresh snapshots are not live readiness.</p>:null}
|
||||
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:'Health unavailable — authenticated backend runtime read failed.'}))});
|
||||
runtime.profiles().then(value=>{if(active){setProfiles(value);setProfile(current=>value.some(p=>p.name===current)?current:'')}}).catch(()=>{if(active){setProfile('');setErrors(e=>({...e,profiles:'Profiles unavailable — no authorized runtime identity list.'}))}});
|
||||
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]:name+' unavailable — no fallback values.'}))};
|
||||
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="Authenticated runtime" className="bg-white border rounded-2xl p-5 space-y-4">
|
||||
<div className="flex justify-between"><h2 className="font-bold">Hermes runtime — backend authenticated reads</h2><Button onClick={()=>setRevision(r=>r+1)}>Refresh runtime</Button></div>
|
||||
<p>No browser runtime credentials or direct Hermes connection. Refresh observations are not heartbeat timestamps.</p>
|
||||
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>Inventory service: {health.ok?'responsive':'not responsive'} (not live Hermes health)</p><Snapshot value={health.provenance}/><p>{health.version} · {health.commit}</p><p>Client observed at: {observed}. Client receipt time only; not capture time or live heartbeat.</p></div>}
|
||||
<label>Authorized runtime profile<select aria-label="Authorized runtime profile" value={profile} onChange={e=>{setProfile(e.target.value);setOffset(0)}}><option value="">Select authorized profile</option>{profiles.map(p=><option key={p.name} value={p.name}>{p.name}</option>)}</select></label>
|
||||
{!profiles.length&&!errors.profiles&&<p>No authorized profiles returned.</p>}
|
||||
{profiles.map(p=><div key={p.name}>{p.name} · Gateway {p.provenance?'unknown (snapshot; not process readiness)':p.gateway_running?'running':'stopped'} · {p.is_default?'default profile':'non-default profile'}<Snapshot value={p.provenance}/></div>)}
|
||||
{status&&<div><h3>Profile status</h3><Snapshot value={status.provenance}/><p>{status.overall}</p><p>Gateway: {status.provenance?'unknown':status.gateway_running?'running':'stopped'} · State: {status.provenance?'unknown':status.gateway_state??'Unknown'} · Active agents: {status.provenance?'unknown':status.active_agents}</p></div>}
|
||||
{usage&&<div><h3>Runtime usage — {usage.period_days} days, selected profile only</h3><Snapshot value={usage.provenance}/><p>Input tokens: {usage.totals.total_input}</p><p>Output tokens: {usage.totals.total_output}</p><p>Sessions: {usage.totals.total_sessions}</p><p>Upstream estimated cost: {usage.totals.total_estimated_cost} (currency unspecified by source; not settled billing)</p><p>Do not add this to 9router totals; attribution overlaps and is not reconciled.</p></div>}
|
||||
{sessions&&<div><h3>Sessions — {sessions.total} returned total</h3><Snapshot value={sessions.provenance}/>{!sessions.sessions.length&&<p>No sessions returned.</p>}{sessions.sessions.map(s=><article key={s.id} className="border rounded p-2"><p>{s.id} · {s.profile} · {s.source} · {sessions.provenance?`historical snapshot flag: ${s.is_active?'active':'inactive'}; live activity unknown`:s.is_active?'active':'inactive'}</p></article>)}<Button disabled={offset===0} onClick={()=>setOffset(n=>Math.max(0,n-20))}>Previous sessions</Button><Button disabled={offset+20>=sessions.total} onClick={()=>setOffset(n=>n+20)}>Next sessions</Button></div>}
|
||||
{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>;
|
||||
}
|
||||
@@ -15,88 +15,69 @@ describe('command center', () => {
|
||||
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.getByRole('button',{name:'تأیید در Gate1'})).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button',{name:'RUNNING'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'Agents & departments'}));
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Unavailable');
|
||||
fireEvent.click(screen.getByRole('button',{name:'عاملها و دپارتمانها'}));
|
||||
expect(screen.getByText(/این بخش در نسخه فعلی در دسترس نیست/)).toBeInTheDocument();
|
||||
expect(vi.mocked(api.get).mock.calls.some(([url])=>url.endsWith('/agents'))).toBe(false);
|
||||
});
|
||||
it('labels deliberately omitted scope metadata unavailable, not immutable scope',async()=>{
|
||||
const {metadata:_metadata,...safeTask}=task;
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[safeTask]:safeTask}));
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
expect(await screen.findByText('Scope / acceptance criteria unavailable — omitted by the safe backend projection.')).toBeInTheDocument();
|
||||
expect(await screen.findByText('محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Immutable scope / acceptance criteria')).not.toBeInTheDocument();
|
||||
});
|
||||
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'}));
|
||||
fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));
|
||||
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(within(dialog).getByRole('button',{name:'تأیید فرمان'})).toBeDisabled();
|
||||
fireEvent.change(within(dialog).getByLabelText('زمان انقضا'),{target:{value:'2099-01-01T12:00'}});
|
||||
fireEvent.change(within(dialog).getByLabelText('دلیل'),{target:{value:'محدوده checked'}});
|
||||
fireEvent.click(within(dialog).getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
|
||||
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'}));
|
||||
expect(within(dialog).getByLabelText('دلیل')).toBeDisabled();
|
||||
expect(within(dialog).getByLabelText('زمان انقضا')).toBeDisabled();
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'تأیید فرمان'}));
|
||||
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:'SUCCEEDED',commitSha:'abc123',environment:'staging',artifacts:[{id:'artifact-1',sha256:'a'.repeat(64)}]}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:true,chat:false,runtime:false}}:url.endsWith('/tasks')?[release]:release}));
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'decision-2'}});
|
||||
it('keeps legacy Gate2 release decisions disabled without sending a command',async()=>{
|
||||
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[release]:release}));
|
||||
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}));
|
||||
expect(await screen.findByRole('button',{name:'تأیید در Gate2'})).toBeDisabled();
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
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'}));
|
||||
fireEvent.click(screen.getByRole('button',{name:'توقف اضطراری'}));
|
||||
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(screen.getByRole('button',{name:'اعمال توقف سراسری'})).toBeDisabled();
|
||||
fireEvent.change(screen.getByLabelText('سطح توقف'),{target:{value:'EMERGENCY_HALT'}});
|
||||
fireEvent.change(screen.getByLabelText('دلیل توقف'),{target:{value:'Incident'}});
|
||||
fireEvent.click(screen.getByLabelText('پیامد عملیاتی سراسری را تأیید میکنم'));
|
||||
fireEvent.click(screen.getByRole('button',{name:'اعمال توقف سراسری'}));
|
||||
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'}));
|
||||
fireEvent.click(screen.getByRole('button',{name:'گفتوگو'}));
|
||||
fireEvent.change(screen.getByLabelText('شناسه نشست'),{target:{value:'session-1'}});
|
||||
fireEvent.change(screen.getByLabelText('پیام'),{target:{value:'Explain bounded work'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'ارسال پیام مشورتی'}));
|
||||
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'}));
|
||||
@@ -104,12 +85,12 @@ describe('command center', () => {
|
||||
it('fails closed for creation, kill and chat when overview cannot authorize capabilities',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/tasks'))return {data:[task]};throw new Error('Unavailable');});
|
||||
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Tasks & approvals'}));
|
||||
expect(screen.queryByText('Create bounded work')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
|
||||
expect(screen.queryByRole('button',{name:'Apply kill switch'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'Chat'}));
|
||||
expect(screen.queryByRole('button',{name:'Send advisory message'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'وظیفهها و تأییدها'}));
|
||||
expect(screen.queryByText('ایجاد کار محدود')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'توقف اضطراری'}));
|
||||
expect(screen.queryByRole('button',{name:'اعمال توقف سراسری'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'گفتوگو'}));
|
||||
expect(screen.queryByRole('button',{name:'ارسال پیام مشورتی'})).not.toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -118,19 +99,19 @@ describe('command center', () => {
|
||||
it('requires explicit kill capability rather than generic mutations',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'now',capabilities:{mutations:true}}:url.endsWith('/tasks')?[task]:task}));
|
||||
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
|
||||
expect(screen.queryByRole('button',{name:'Apply kill switch'})).not.toBeInTheDocument();expect(api.put).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole('button',{name:'توقف اضطراری'}));
|
||||
expect(screen.queryByRole('button',{name:'اعمال توقف سراسری'})).not.toBeInTheDocument();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([{}, {scope:'STAGE_PREPARE'}, {scope:'Human scope',acceptanceCriteria:[]}])('does not claim incomplete or legacy metadata is scope evidence: %j',async metadata=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[{...task,metadata}]:{...task,metadata}}));
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
expect(await screen.findByText(/Scope \/ acceptance criteria unavailable/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Server workflow scope: unavailable in safe projection.')).toBeInTheDocument();
|
||||
expect(await screen.findByText(/محدوده و معیارهای پذیرش در دسترس نیست/)).toBeInTheDocument();
|
||||
expect(screen.getByText('محدوده گردش کار سرور: در نمای امن در دسترس نیست.')).toBeInTheDocument();
|
||||
});
|
||||
it('separates human evidence from server workflow scope without inventing a marker',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/tasks')?[task]:task}));
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
expect(await screen.findByText('Backend-reported scope / acceptance criteria')).toBeInTheDocument();
|
||||
expect(screen.getByText('Server workflow scope: unavailable in safe projection.')).toBeInTheDocument();
|
||||
expect(await screen.findByText('محدوده و معیارهای پذیرش گزارششده از سرور')).toBeInTheDocument();
|
||||
expect(screen.getByText('محدوده گردش کار سرور: در نمای امن در دسترس نیست.')).toBeInTheDocument();
|
||||
});
|
||||
@@ -4,15 +4,17 @@ import RouterUsagePanel from '../components/RouterUsagePanel';
|
||||
import RuntimeReadPanel from '../components/RuntimeReadPanel';
|
||||
import CreateOrchestrationTask from '../components/CreateOrchestrationTask';
|
||||
import { orchestration, killLevels, actionBlockReason, commandFailure } from '../services/orchestration';
|
||||
import {label,actionLabel,Records} from '../components/OrchestrationPresentation';
|
||||
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','Runtime health & sessions','Chat'] as const;
|
||||
const sections = ['نمای کلی','وظیفهها و تأییدها','اجراها و خروجیها','عاملها و دپارتمانها','مدلها و بودجهها','زمانبندیها','ممیزی و انتشارها','توقف اضطراری','مصرف و سهمیه 9router','اطلاعات اجرا و نشستها','گفتوگو'] 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>}
|
||||
const resources:Partial<Record<Section,Resource>> = {'ممیزی و انتشارها':'releases'};
|
||||
const unavailable:Partial<Record<Section,string>> = {'عاملها و دپارتمانها':'فهرست عاملها به هویت و اتصال مورد اعتماد اجرا نیاز دارد. اطلاعات نمای ثبتشده را از بخش اطلاعات اجرا و نشستها ببینید؛ این اطلاعات سلامت زنده نیست.','مدلها و بودجهها':'قرارداد خواندن سیاست مدل در سرور پیادهسازی نشده است. سقف بودجه هر وظیفه در فهرست وظیفهها قابل مشاهده است.','زمانبندیها':'مسیر مدیریت زمانبندی در این نسخه پشتیبانی نمیشود؛ زمانبندی ساختگی نمایش داده نمیشود.'};
|
||||
const errorText=(e:unknown)=> {const status=(e as {response?:{status?:number}})?.response?.status;return status?`خطای سرور (HTTP ${status})`:e instanceof Error?e.message:'پاسخ سرور در دسترس نیست'};
|
||||
function Json({value}:{value:unknown}) {return <Records value={value}/>;}
|
||||
export default function OrchestrationCommandCenter() {
|
||||
const detailEpoch=useRef(0);
|
||||
const [section,setSection]=useState<Section>('Overview');
|
||||
const [section,setSection]=useState<Section>('نمای کلی');
|
||||
const [capabilities,setCapabilities]=useState({mutations:false,chat:false,runtime:false,killSwitch:false});
|
||||
const [tasks,setTasks]=useState<Task[]>([]);
|
||||
const [selected,setSelected]=useState<Task|null>(null);
|
||||
@@ -34,7 +36,7 @@ export default function OrchestrationCommandCenter() {
|
||||
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(); orchestration.resource('overview').then(s=>setCapabilities({mutations:s.capabilities?.mutations===true,chat:s.capabilities?.chat===true,runtime:s.capabilities?.runtime===true,killSwitch:s.capabilities?.killSwitch===true})).catch(()=>setCapabilities({mutations:false,chat:false,runtime:false,killSwitch:false}));},[]);
|
||||
useEffect(()=> {
|
||||
const resource=resources[section]; setSnapshot(null);setError('');
|
||||
const resource=resources[section]; setSnapshot(null);
|
||||
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)});
|
||||
@@ -47,42 +49,43 @@ export default function OrchestrationCommandCenter() {
|
||||
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();
|
||||
setPending(null);setSelected(null);setSuccess('فرمان توسط سرور پذیرفته شد؛ وضعیت مرجع بازخوانی شد.');await loadTasks();
|
||||
} catch(e) {const failure=commandFailure(e);setBlocked(!failure.retryable);setCommandError(failure.message)} finally {setBusy(false)}
|
||||
};
|
||||
const refresh=()=>{detailEpoch.current++;setSelected(null);setPending(null);void loadTasks()};
|
||||
const filtered=tasks.filter(t=>(t.title+' '+t.department+' '+t.state).toLowerCase().includes(search.toLowerCase()));
|
||||
return <div className="space-y-5 font-vazir pb-12">
|
||||
<header className="bg-white border rounded-2xl p-5 flex justify-between gap-4"><div><h1 className="text-xl font-black">Orchestration command center</h1><p className="text-sm text-gray-600">Backend-authoritative operations · Gate1 bounded work · Gate2 immutable release binding</p></div><Button onClick={refresh} disabled={busy||loading}>Refresh authoritative state</Button></header>
|
||||
<nav aria-label="Orchestration sections" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} disabled={!!pending||busy} onClick={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
|
||||
{loading&&<p role="status">Loading measured backend state…</p>}
|
||||
{error&&<p role="alert" className="border border-red-200 bg-red-50 rounded-xl p-4">Unknown / unavailable: {error}. No fallback data. <button onClick={refresh}>Reload tasks</button></p>}
|
||||
return <div dir="rtl" lang="fa" 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">مرکز فرماندهی ارکستراسیون</h1><p className="text-sm text-gray-600">مرجع عملیات سرور است · Gate1 برای کار محدود · Gate2 و انتشار غیرفعال هستند</p></div><Button onClick={refresh} disabled={busy||loading}>بازخوانی وضعیت از سرور</Button></header>
|
||||
<nav aria-label="بخشهای ارکستراسیون" className="flex flex-wrap gap-2">{sections.map(s=><Button key={s} disabled={!!pending||busy} onClick={()=>{setSection(s);setSuccess('');setReason('');setConfirmed(false)}} variant={section===s?'primary':'outline'}>{s}</Button>)}</nav>
|
||||
{unavailable[section]&&<section className="bg-amber-50 border border-amber-200 rounded-2xl p-5 space-y-3"><h2 className="font-bold">این بخش در نسخه فعلی در دسترس نیست</h2><p>{unavailable[section]}</p><p>برای این بخش درخواست ناموفق تکراری به سرور ارسال نمیشود.</p></section>}
|
||||
{loading&&<p role="status">در حال دریافت وضعیت از سرور…</p>}
|
||||
{error&&<p role="alert" className="border border-red-200 bg-red-50 rounded-xl p-4">دریافت اطلاعات از سرور ناموفق بود: {error}. داده جایگزین نمایش داده نمیشود. <button onClick={refresh}>بازخوانی وظیفهها</button></p>}
|
||||
{success&&<p role="status">{success}</p>}
|
||||
{section==='Tasks & approvals'&&capabilities.mutations&&<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==='وظیفهها و تأییدها'&&capabilities.mutations&&<CreateOrchestrationTask onCreated={()=>void loadTasks()}/>}
|
||||
{section==='نمای کلی'&&!loading&&!error&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">فهرست وظیفههای ثبتشده</h2><p>{tasks.length} وظیفه از سرور دریافت شد. این فهرست نشاندهنده سلامت عامل یا وضعیت زنده اجرا نیست.</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">{label(state)}: {tasks.filter(t=>t.state===state).length}</span>)}</div></section>}
|
||||
{(['نمای کلی','وظیفهها و تأییدها','اجراها و خروجیها'] as Section[]).includes(section)&&<section className="bg-white border rounded-2xl p-5 space-y-4"><label>جستوجوی وظیفهها<input className="border rounded-lg p-2 m-2" value={search} onChange={e=>setSearch(e.target.value)}/></label>
|
||||
{!loading&&!error&&!tasks.length&&<p>وظیفهای از سرور دریافت نشد.</p>}
|
||||
<div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr>{['وظیفه','دپارتمان','وضعیت','حالت عملیات','سقف بودجه (سنت)','نسخه'].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>{label(t.department)}</td><td>{label(t.state)}</td><td>{label(t.operationMode)}</td><td>{t.budgetLimitCents??'نامشخص'}</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>{typeof selected.metadata?.scope==='string'&&selected.metadata.scope.trim()&&Array.isArray(selected.metadata.acceptanceCriteria)&&selected.metadata.acceptanceCriteria.length>0&&selected.metadata.acceptanceCriteria.every(value=>typeof value==='string'&&value.trim())?<h3>Backend-reported scope / acceptance criteria</h3>:<p>Scope / acceptance criteria unavailable — omitted by the safe backend projection.</p>}<p>Server workflow scope: unavailable in safe projection.</p><Json value={{operationMode:selected.operationMode,budgetLimitCents:selected.budgetLimitCents,metadata:selected.metadata}}/>
|
||||
<h3>Server-authorized actions</h3>{!selected.availableActions.length&&<p>No actions advertised. Read-only; the browser does not infer transitions.</p>}<div className="flex flex-wrap gap-2">{selected.availableActions.map(a=><Button key={a.id} disabled={!capabilities.mutations||!!actionBlockReason(selected,a)} title={!capabilities.mutations?'Backend mutations unavailable':actionBlockReason(selected,a)} onClick={()=>open(selected,a)}>{a.label}</Button>)}</div>
|
||||
<h3>Immutable approval decisions</h3><Json value={selected.decisions??[]}/>
|
||||
<h3>Runs & registered artifacts</h3>{!selected.runs?.length&&<p>No registered runs.</p>}{selected.runs?.map(r=><article key={r.id} className="border rounded-xl p-3 space-y-2"><h4>{r.id} · {r.status}</h4><p>Commit: {r.commitSha} · Environment: {r.environment}</p>{r.artifacts.map(a=><Json key={a.id} value={a}/>)}</article>)}
|
||||
<h3>Budget ledger (cents; not inferred usage)</h3><Json value={selected.budgetLedger??[]}/><h3>Ordered audit events</h3><Json value={selected.events??[]}/>
|
||||
{selected&&<section aria-label="جزئیات وظیفه" className="bg-white border rounded-2xl p-5 space-y-4"><h2 className="font-bold">{selected.title} · v{selected.version}</h2>{typeof selected.metadata?.scope==='string'&&selected.metadata.scope.trim()&&Array.isArray(selected.metadata.acceptanceCriteria)&&selected.metadata.acceptanceCriteria.length>0&&selected.metadata.acceptanceCriteria.every(value=>typeof value==='string'&&value.trim())?<h3 className="font-bold">محدوده و معیارهای پذیرش گزارششده از سرور</h3>:<p>محدوده و معیارهای پذیرش در دسترس نیست؛ سرور این اطلاعات را در نمای امن ارسال نکرده است.</p>}<p>محدوده گردش کار سرور: در نمای امن در دسترس نیست.</p><Json value={{operationMode:selected.operationMode,budgetLimitCents:selected.budgetLimitCents,metadata:selected.metadata}}/>
|
||||
<h3 className="font-bold">اقدامهای مجاز اعلامشده توسط سرور</h3>{!selected.availableActions.length&&<p>اقدامی اعلام نشده است. این نما فقط خواندنی است؛ مرورگر مجوز یا تغییر وضعیت ایجاد نمیکند.</p>}<div className="flex flex-wrap gap-2">{selected.availableActions.map(a=><Button key={a.id} disabled={!capabilities.mutations||!!actionBlockReason(selected,a)} title={!capabilities.mutations?'تغییرات از طرف سرور مجاز نیست':actionBlockReason(selected,a)} onClick={()=>open(selected,a)}>{actionLabel(a)}</Button>)}</div>
|
||||
<h3 className="font-bold">تصمیمهای تأیید تغییرناپذیر</h3><Json value={selected.decisions??[]}/>
|
||||
<h3 className="font-bold">اجراها و خروجیهای ثبتشده</h3>{!selected.runs?.length&&<p>اجرای ثبتشدهای وجود ندارد.</p>}{selected.runs?.map(r=><article key={r.id} className="border rounded-xl p-3 space-y-2"><h4>{r.id} · {label(r.status)}</h4><p>کامیت: {r.commitSha} · محیط: {r.environment}</p>{r.artifacts.map(a=><Json key={a.id} value={a}/>)}</article>)}
|
||||
<h3 className="font-bold">دفتر بودجه (سنت؛ نه مصرف تخمینی)</h3><Json value={selected.budgetLedger??[]}/><h3 className="font-bold">رویدادهای ممیزی بهترتیب</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'&&!capabilities.killSwitch&&<p>Mutation controls unavailable: backend security hardening pending.</p>}
|
||||
{section==='Kill switch'&&capabilities.killSwitch&&<section className="border border-red-300 rounded-2xl bg-white p-5 space-y-3"><h2>Global kill switch — four escalating levels</h2><p>Applies globally, not only to selected task. No implicit resume. Current active level: unknown until backend returns state.</p><label>Level<select aria-label="Kill level" value={kill} onChange={e=>{setKill(e.target.value as KillLevel);setConfirmed(false)}}>{killLevels.map(l=><option key={l}>{l}</option>)}</select></label><p>Freeze new work → stop agents → disable mutations → emergency halt.</p><label>Reason<input aria-label="Kill reason" value={reason} onChange={e=>setReason(e.target.value)} className="border p-2"/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>I confirm global operational impact</label><Button disabled={busy||!reason.trim()||!confirmed} onClick={async()=>{setBusy(true);setError('');try{const result=await orchestration.kill(kill,reason);setSuccess('Backend acknowledged kill switch: '+JSON.stringify(result));setConfirmed(false)}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Apply kill switch</Button></section>}
|
||||
{section==='9router usage & quota'&&<RouterUsagePanel/>}
|
||||
{section==='Runtime health & sessions'&&<RuntimeReadPanel/>}
|
||||
{section==='Chat'&&!capabilities.chat&&<p>Chat unsupported: trusted runtime bridge unavailable.</p>}
|
||||
{section==='Chat'&&capabilities.chat&&<section className="bg-white border rounded-2xl p-5 space-y-3"><h2>Typed backend chat bridge</h2><p>Advisory text only. No terminal, PTY, runtime token, or direct Hermes connection. Decisions use explicit approval controls.</p><label>Session ID<input value={session} onChange={e=>{setSession(e.target.value);setMessages([])}} className="border p-2"/></label><div role="log">{messages.map(m=><p key={m.id}>{m.role}: {m.content}</p>)}</div><label>Message<textarea value={message} onChange={e=>{setMessage(e.target.value);setChatKey(crypto.randomUUID())}} className="border p-2 block w-full"/></label><Button disabled={busy||!session.trim()||!message.trim()} onClick={async()=>{setBusy(true);setError('');try{const reply=await orchestration.chat(session,message,chatKey);setMessages(prev=>[...prev,{id:chatKey,role:'user',content:message},reply]);setMessage('');setChatKey(crypto.randomUUID())}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>Send advisory message</Button></section>}
|
||||
{pending&&<div role="dialog" aria-modal="true" aria-label="Confirm immutable command" className="fixed inset-0 z-50 bg-black/50 overflow-y-auto p-8"><div className="bg-white rounded-2xl p-6 max-w-2xl mx-auto space-y-4"><h2>{pending.action.label}</h2><Json value={{taskId:pending.task.id,expectedVersion:pending.task.version,idempotencyKey:pending.key,scope:pending.task.metadata,budgetLimitCents:pending.task.budgetLimitCents,operationMode:pending.task.operationMode}}/>
|
||||
{pending.action.gate&&<label className="block">Expires at<input aria-label="Expires at" type="datetime-local" value={expires} onChange={e=>setExpires(e.target.value)} disabled={busy||attempted}/></label>}
|
||||
{pending.action.gate===2&&pending.action.decision==='APPROVED'&&<label>Registered run / artifact binding<select aria-label="Registered run / artifact binding" value={binding} onChange={e=>{setBinding(e.target.value);setConfirmed(false)}} disabled={busy||attempted}><option value="">Select immutable evidence</option>{pending.task.runs?.filter(r=>r.status==='SUCCEEDED').flatMap(r=>r.artifacts.map(a=><option key={r.id+'|'+a.sha256} value={r.id+'|'+a.sha256}>{r.id} · {r.commitSha} · {r.environment} · {a.sha256}</option>))}</select></label>}
|
||||
<label className="block">Reason<input aria-label="Reason" value={reason} onChange={e=>setReason(e.target.value)} disabled={busy||attempted} className="border p-2"/></label>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)} disabled={busy}/>I reviewed the immutable scope and binding</label>
|
||||
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||blocked||!capabilities.mutations||!confirmed||!reason.trim()|| (!!pending.action.gate&&!(Date.parse(expires)>now)) || (['APPROVE_GATE1','REJECT_GATE1'].includes(pending.action.id)&&Date.parse(expires)>now+86400000) || (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>
|
||||
{snapshot&&<section className="bg-white border rounded-2xl p-5 space-y-4"><h2>{section}</h2><p>زمان دریافت از سرور: {snapshot.measuredAt}</p>{!snapshot.items.length&&<p>رکوردی از سرور دریافت نشد.</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 className="font-bold">{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>{label(k)}</dt><dd>{String(v??'نامشخص')}</dd></div>)}</dl></article>)}</div><p>تغییر تنظیمات فقط با فرمان مجاز سرور ممکن است؛ مرورگر فرمانی ایجاد نمیکند.</p></section>}
|
||||
{section==='توقف اضطراری'&&!capabilities.killSwitch&&<p>کنترل توقف اضطراری در این نسخه در دسترس نیست؛ مسیر سرور اجازه تغییر نمیدهد.</p>}
|
||||
{section==='توقف اضطراری'&&capabilities.killSwitch&&<section className="border border-red-300 rounded-2xl bg-white p-5 space-y-3"><h2>توقف سراسری — چهار سطح افزایشی</h2><p>این اقدام سراسری است و فقط به Task انتخابشده محدود نیست. ازسرگیری خودکار ندارد. سطح فعال تا دریافت وضعیت سرور نامشخص است.</p><label>سطح<select aria-label="سطح توقف" value={kill} onChange={e=>{setKill(e.target.value as KillLevel);setConfirmed(false)}}>{killLevels.map(l=><option key={l} value={l}>{label(l)}</option>)}</select></label><p>توقف کار جدید ← توقف عاملها ← منع تغییرات ← توقف اضطراری</p><label>دلیل<input aria-label="دلیل توقف" 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)}/>پیامد عملیاتی سراسری را تأیید میکنم</label><Button disabled={busy||!reason.trim()||!confirmed} onClick={async()=>{setBusy(true);setError('');try{const result=await orchestration.kill(kill,reason);setSuccess('سرور فرمان توقف را دریافت کرد: '+JSON.stringify(result));setConfirmed(false)}catch(e){setError(errorText(e))}finally{setBusy(false)}}}>اعمال توقف سراسری</Button></section>}
|
||||
{section==='مصرف و سهمیه 9router'&&<RouterUsagePanel/>}
|
||||
{section==='اطلاعات اجرا و نشستها'&&<RuntimeReadPanel/>}
|
||||
{section==='گفتوگو'&&!capabilities.chat&&<p>گفتوگو در دسترس نیست؛ پل مورد اعتماد اجرا فعال نیست.</p>}
|
||||
{section==='گفتوگو'&&capabilities.chat&&<section className="bg-white border rounded-2xl p-5 space-y-3"><h2>گفتوگوی متنی از مسیر امن سرور</h2><p>فقط متن مشورتی؛ بدون ترمینال، PTY، توکن اجرا یا اتصال مستقیم به Hermes. تصمیمها از کنترل تأیید مستقل عبور میکنند.</p><label>شناسه نشست<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>پیام<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)}}}>ارسال پیام مشورتی</Button></section>}
|
||||
{pending&&<div 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>{actionLabel(pending.action)}</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">زمان انقضا<input aria-label="زمان انقضا" type="datetime-local" value={expires} onChange={e=>setExpires(e.target.value)} disabled={busy||attempted}/></label>}
|
||||
{pending.action.gate===2&&pending.action.decision==='APPROVED'&&<label>اتصال اجرای ثبتشده به خروجی<select aria-label="اتصال اجرای ثبتشده به خروجی" value={binding} onChange={e=>{setBinding(e.target.value);setConfirmed(false)}} disabled={busy||attempted}><option value="">انتخاب شواهد تغییرناپذیر</option>{pending.task.runs?.filter(r=>r.status==='SUCCEEDED').flatMap(r=>r.artifacts.map(a=><option key={r.id+'|'+a.sha256} value={r.id+'|'+a.sha256}>{r.id} · {r.commitSha} · {r.environment} · {a.sha256}</option>))}</select></label>}
|
||||
<label className="block">دلیل<input aria-label="دلیل" 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}/>محدوده و اتصال تغییرناپذیر را بررسی کردم</label>
|
||||
{commandError&&<p role="alert">{commandError}</p>}<div className="flex gap-3"><Button disabled={busy||blocked||!capabilities.mutations||!confirmed||!reason.trim()|| (!!pending.action.gate&&!(Date.parse(expires)>now)) || (['APPROVE_GATE1','REJECT_GATE1'].includes(pending.action.id)&&Date.parse(expires)>now+86400000) || (pending.action.gate===2&&pending.action.decision==='APPROVED'&&!binding)} onClick={()=>void execute()}>تأیید فرمان</Button><Button variant="outline" disabled={busy} onClick={()=>setPending(null)}>انصراف</Button></div>
|
||||
</div></div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import {render,screen,fireEvent,waitFor} from '@testing-library/react';
|
||||
import {it,expect,vi} from 'vitest';
|
||||
import api from '../services/api';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn(),put:vi.fn(),post:vi.fn()}}));
|
||||
it('offers Persian RTL navigation and honest unavailable tabs without calling unsupported routes',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{
|
||||
if(url.endsWith('/tasks'))return {data:[]};
|
||||
if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:false}}};
|
||||
throw new Error('Unexpected request '+url);
|
||||
});
|
||||
const {container}=render(<OrchestrationCommandCenter/>);
|
||||
expect(await screen.findByRole('heading',{name:'مرکز فرماندهی ارکستراسیون'})).toBeInTheDocument();
|
||||
expect(container.firstElementChild).toHaveAttribute('dir','rtl');
|
||||
for(const tab of ['عاملها و دپارتمانها','مدلها و بودجهها','زمانبندیها']){
|
||||
fireEvent.click(screen.getByRole('button',{name:tab}));
|
||||
expect(screen.getByText(/این بخش در نسخه فعلی در دسترس نیست/)).toBeInTheDocument();
|
||||
}
|
||||
await waitFor(()=>expect(api.get).toHaveBeenCalledTimes(2));
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
});
|
||||
it('retains available-read failures in Persian instead of claiming a healthy empty inventory',async()=>{
|
||||
vi.mocked(api.get).mockRejectedValue({response:{status:503}});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('دریافت اطلاعات از سرور ناموفق بود');
|
||||
expect(screen.queryByText(/وظیفهای از سرور دریافت نشد/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
import {actionBlockReason} from '../services/orchestration';
|
||||
it('keeps Gate2 disabled even if a legacy server action advertises it',()=>{expect(actionBlockReason({operationMode:'PREPARE',state:'GATE2_PENDING'} as never,{id:'g2',label:'release',gate:2,decision:'APPROVED'})).toMatch(/Gate2.*غیرفعال/)});
|
||||
@@ -7,13 +7,13 @@ it('does not restore stale detail after authoritative refresh while detail reque
|
||||
const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[]};
|
||||
let resolve!:(v:unknown)=>void;
|
||||
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))return {data:{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}};if(url.endsWith('/tasks'))return {data:[t]};return await new Promise<unknown>(r=>{resolve=r}) as never});
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(screen.getByRole('button',{name:'Refresh authoritative state'}));
|
||||
await act(async()=>resolve({data:t}));await waitFor(()=>expect(screen.queryByText('Loading measured backend state…')).not.toBeInTheDocument());
|
||||
expect(screen.queryByRole('region',{name:'Task detail'})).not.toBeInTheDocument();
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(screen.getByRole('button',{name:'بازخوانی وضعیت از سرور'}));
|
||||
await act(async()=>resolve({data:t}));await waitFor(()=>expect(screen.queryByText('در حال دریافت وضعیت از سرور…')).not.toBeInTheDocument());
|
||||
expect(screen.queryByRole('region',{name:'جزئیات وظیفه'})).not.toBeInTheDocument();
|
||||
});
|
||||
it('keeps payload immutable when navigating after an ambiguous network failure',async()=>{
|
||||
vi.resetAllMocks();const t={id:'t',key:'t',title:'Task identity',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[{id:'g1',label:'Approve safe work',gate:1,decision:'APPROVED'}]};
|
||||
vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23',capabilities:{mutations:true}}:url.endsWith('/tasks')?[t]:t}));vi.mocked(api.post).mockRejectedValue(new Error('network'));
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(await screen.findByRole('button',{name:'Approve safe work'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('Reason'),{target:{value:'Reviewed'}});fireEvent.click(d.getByLabelText('I reviewed the immutable scope and binding'));fireEvent.click(d.getByRole('button',{name:'Confirm command'}));await d.findByRole('alert');
|
||||
fireEvent.click(screen.getByRole('button',{name:'Tasks & approvals'}));expect(d.getByLabelText('Reason')).toHaveValue('Reviewed');expect(d.getByLabelText('I reviewed the immutable scope and binding')).toBeChecked();
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Task identity'}));fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('زمان انقضا'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('دلیل'),{target:{value:'Reviewed'}});fireEvent.click(d.getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));await d.findByRole('alert');
|
||||
fireEvent.click(screen.getByRole('button',{name:'وظیفهها و تأییدها'}));expect(d.getByLabelText('دلیل')).toHaveValue('Reviewed');expect(d.getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم')).toBeChecked();
|
||||
});
|
||||
@@ -5,43 +5,43 @@ import {orchestration} from '../services/orchestration';
|
||||
import type {CreateTaskInput} from '../services/orchestration';
|
||||
import OrchestrationCommandCenter from './OrchestrationCommandCenter';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn(),post:vi.fn(),put:vi.fn()}}));
|
||||
const action={id:'g1',label:'Review Gate1',gate:1 as const,decision:'APPROVED' as const};
|
||||
const action={id:'g1',label:'تأیید در Gate1',gate:1 as const,decision:'APPROVED' as const};
|
||||
const task={id:'t',key:'t',title:'Safe proposal',department:'DEV',state:'GATE1_PENDING',version:2,operationMode:'PREPARE',budgetLimitCents:0,availableActions:[action],runs:[]};
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.endsWith('/overview')?{items:[],measuredAt:'2026-10-23T00:00:00Z',capabilities:{mutations:true,chat:false,runtime:false}}:url.endsWith('/tasks')?[task]:task}));});
|
||||
it('refuses Production creation even when called outside form',async()=>{
|
||||
await expect(orchestration.create({key:'x',title:'x',department:'DEV',operationMode:'MUTATE_PRODUCTION',budgetLimitCents:0,metadata:{commitSha:'a'.repeat(40)}} as unknown as CreateTaskInput)).rejects.toThrow(/PREPARE|advertised/);
|
||||
await expect(orchestration.create({key:'x',title:'x',department:'DEV',operationMode:'MUTATE_PRODUCTION',budgetLimitCents:0,metadata:{commitSha:'a'.repeat(40)}} as unknown as CreateTaskInput)).rejects.toThrow(/PREPARE|اعلام نشده/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects ambiguous advertised action rather than selecting a mutation path',async()=>{
|
||||
const ambiguous={...action,toState:'READY'};
|
||||
await expect(orchestration.command({...task,availableActions:[ambiguous]},ambiguous,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/advertised/);
|
||||
await expect(orchestration.command({...task,availableActions:[ambiguous]},ambiguous,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/اعلام نشده/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks release transitions even when advertised by server',async()=>{
|
||||
const release={id:'release',label:'Release',toState:'RELEASING'};
|
||||
await expect(orchestration.command({...task,availableActions:[release]},release,{idempotencyKey:'key'})).rejects.toThrow(/PREPARE|advertised/);
|
||||
await expect(orchestration.command({...task,availableActions:[release]},release,{idempotencyKey:'key'})).rejects.toThrow(/PREPARE|اعلام نشده/);
|
||||
expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects Gate2 evidence from failed runs',async()=>{
|
||||
const g2={...action,gate:2 as const};
|
||||
await expect(orchestration.command({...task,availableActions:[g2],runs:[{id:'r',status:'FAILED',commitSha:'abc',environment:'stage',artifacts:[{id:'a',sha256:'a'.repeat(64)}]}]},g2,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/successful/);
|
||||
await expect(orchestration.command({...task,availableActions:[g2],runs:[{id:'r',status:'FAILED',commitSha:'abc',environment:'stage',artifacts:[{id:'a',sha256:'a'.repeat(64)}]}]},g2,{idempotencyKey:'key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
async function dialog(){render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));fireEvent.click(await screen.findByRole('button',{name:'Review Gate1'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('Reason'),{target:{value:'Reviewed bounds'}});fireEvent.click(d.getByLabelText('I reviewed the immutable scope and binding'));return d;}
|
||||
async function dialog(){render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));fireEvent.click(await screen.findByRole('button',{name:'تأیید در Gate1'}));const d=within(screen.getByRole('dialog'));fireEvent.change(d.getByLabelText('زمان انقضا'),{target:{value:'2099-01-01T12:00'}});fireEvent.change(d.getByLabelText('دلیل'),{target:{value:'Reviewed bounds'}});fireEvent.click(d.getByLabelText('محدوده و اتصال تغییرناپذیر را بررسی کردم'));return d;}
|
||||
it('locks stale 409 command until authoritative refresh instead of retrying stale payload',async()=>{
|
||||
vi.mocked(api.post).mockRejectedValue({response:{status:409,data:{message:'Version conflict'}}});
|
||||
const d=await dialog();fireEvent.click(d.getByRole('button',{name:'Confirm command'}));
|
||||
await waitFor(()=>expect(d.getByRole('button',{name:'Confirm command'})).toBeDisabled());
|
||||
expect(await d.findByRole('alert')).toHaveTextContent(/stale/i);
|
||||
fireEvent.click(d.getByRole('button',{name:'Confirm command'}));expect(api.post).toHaveBeenCalledTimes(1);
|
||||
fireEvent.click(screen.getByRole('button',{name:'Refresh authoritative state'}));expect(screen.queryByRole('dialog')).not.toBeInTheDocument();await waitFor(()=>expect(screen.queryByText('Loading measured backend state…')).not.toBeInTheDocument());
|
||||
const d=await dialog();fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));
|
||||
await waitFor(()=>expect(d.getByRole('button',{name:'تأیید فرمان'})).toBeDisabled());
|
||||
expect(await d.findByRole('alert')).toHaveTextContent(/نسخه قدیمی/);
|
||||
fireEvent.click(d.getByRole('button',{name:'تأیید فرمان'}));expect(api.post).toHaveBeenCalledTimes(1);
|
||||
fireEvent.click(screen.getByRole('button',{name:'بازخوانی وضعیت از سرور'}));expect(screen.queryByRole('dialog')).not.toBeInTheDocument();await waitFor(()=>expect(screen.queryByText('در حال دریافت وضعیت از سرور…')).not.toBeInTheDocument());
|
||||
});
|
||||
it('does not expose authorized task mutations when capabilities are unavailable',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/overview'))throw new Error('offline');return {data:url.endsWith('/tasks')?[task]:task};});
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));await screen.findByRole('region',{name:'Task detail'});
|
||||
expect(screen.getByRole('button',{name:'Review Gate1'})).toBeDisabled();
|
||||
render(<OrchestrationCommandCenter/>);fireEvent.click(await screen.findByRole('button',{name:'Safe proposal'}));await screen.findByRole('region',{name:'جزئیات وظیفه'});
|
||||
expect(screen.getByRole('button',{name:'تأیید در Gate1'})).toBeDisabled();
|
||||
});
|
||||
it('prevents confirming an already expired approval',async()=>{
|
||||
const d=await dialog();fireEvent.change(d.getByLabelText('Expires at'),{target:{value:'2020-01-01T12:00'}});
|
||||
expect(d.getByRole('button',{name:'Confirm command'})).toBeDisabled();
|
||||
const d=await dialog();fireEvent.change(d.getByLabelText('زمان انقضا'),{target:{value:'2020-01-01T12:00'}});
|
||||
expect(d.getByRole('button',{name:'تأیید فرمان'})).toBeDisabled();
|
||||
});
|
||||
@@ -13,31 +13,28 @@ describe('orchestration adapter', () => {
|
||||
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/);
|
||||
await expect(orchestration.command(task, {id:'invented',label:'Run',toState:'RUNNING'}, {idempotencyKey:'k',reason:'reviewed'})).rejects.toThrow(/اعلام نشده/);
|
||||
await expect(orchestration.command(task, task.availableActions[0], {idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
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 () => {
|
||||
it('rejects even fully registered Gate2 evidence because release decisions are disabled', async () => {
|
||||
const run={id:'r',commitSha:'abc',environment:'staging',status:'SUCCEEDED',artifacts:[{id:'a',sha256:'a'.repeat(64)}]};
|
||||
const input={idempotencyKey:'same-key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)};
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce({data:{id:'decision'}});
|
||||
await expect(orchestration.command({...task,runs:[run]},task.availableActions[0],input)).rejects.toThrow('network');
|
||||
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'});
|
||||
await expect(orchestration.command({...task,runs:[run]},task.availableActions[0],{idempotencyKey:'same-key',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'a'.repeat(64)})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
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/);
|
||||
await expect(orchestration.command({...task,availableActions:[{id:'g1',label:'Gate1',gate:1,decision:'APPROVED'}]},{id:'g1',label:'Gate1',gate:1,decision:'APPROVED'},{idempotencyKey:'k',expiresAt:'2000-01-01T00:00:00Z'})).rejects.toThrow(/انقضا/);
|
||||
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/);
|
||||
await expect(orchestration.command(bad,task.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z',runId:'r',artifactHash:'bad'})).rejects.toThrow(/Gate2.*غیرفعال/);
|
||||
});
|
||||
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/);
|
||||
await expect(orchestration.resource('agents')).rejects.toThrow(/نامعتبر/);
|
||||
});
|
||||
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/);
|
||||
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/دلیل/);
|
||||
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/پیام/);
|
||||
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'});
|
||||
@@ -97,7 +94,7 @@ it.each([
|
||||
it('rejects canonical Gate1 decisions beyond backend 24 hour limit',async()=>{
|
||||
vi.resetAllMocks();vi.mocked(api.get).mockResolvedValue({data:{...task,availableActions:['APPROVE_GATE1']}});
|
||||
const detail=await orchestration.task('t/1');
|
||||
await expect(orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/24 hours/);
|
||||
await expect(orchestration.command(detail,detail.availableActions[0],{idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/۲۴ ساعت/);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@ import api from './api';
|
||||
export interface ServerAction { id: string; label: string; toState?: string; gate?: 1 | 2; decision?: 'APPROVED' | 'REJECTED'; disabledReason?: string }
|
||||
// Only advertised IDs select commands; task state never manufactures authorization.
|
||||
const actionCommands: Record<string, ServerAction> = {
|
||||
SUBMIT_GATE1:{id:'SUBMIT_GATE1',label:'Submit Gate1',toState:'GATE1_PENDING'},
|
||||
APPROVE_GATE1:{id:'APPROVE_GATE1',label:'Approve Gate1',gate:1,decision:'APPROVED'},
|
||||
REJECT_GATE1:{id:'REJECT_GATE1',label:'Reject Gate1',gate:1,decision:'REJECTED'},
|
||||
QUEUE_PREPARE:{id:'QUEUE_PREPARE',label:'Queue PREPARE',toState:'READY'},
|
||||
SUBMIT_GATE1:{id:'SUBMIT_GATE1',label:'ارسال برای Gate1',toState:'GATE1_PENDING'},
|
||||
APPROVE_GATE1:{id:'APPROVE_GATE1',label:'تأیید کار محدود در Gate1',gate:1,decision:'APPROVED'},
|
||||
REJECT_GATE1:{id:'REJECT_GATE1',label:'رد کار در Gate1',gate:1,decision:'REJECTED'},
|
||||
QUEUE_PREPARE:{id:'QUEUE_PREPARE',label:'صفبندی آمادهسازی',toState:'READY'},
|
||||
};
|
||||
export function normalizeActions(value:unknown):ServerAction[] {
|
||||
if(!Array.isArray(value))return [];
|
||||
@@ -38,19 +38,20 @@ export interface CommandInput { idempotencyKey: string; reason?: string; expires
|
||||
export interface TransitionDto {toState:string;expectedVersion:number;idempotencyKey:string;reason?:string}
|
||||
export interface GateDecisionDto {decision:'APPROVED'|'REJECTED';expectedVersion:number;idempotencyKey:string;expiresAt:string;notes?:string;runId?:string;artifactHash?:string;commitSha?:string;environment?:string}
|
||||
export function actionBlockReason(task:Task,action:ServerAction):string|undefined {
|
||||
if(action.disabledReason)return action.disabledReason;
|
||||
if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'Production actions are unavailable in this panel';
|
||||
if(task.state==='EXPIRED')return 'Expired proposal: create a fresh proposal';
|
||||
if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'Unsupported server action';
|
||||
if(action.gate===2)return 'Gate2 و انتشار در این پنل غیرفعال هستند';
|
||||
if(action.disabledReason)return 'اقدام توسط سرور غیرفعال شده است: '+action.disabledReason;
|
||||
if(task.operationMode==='MUTATE_PRODUCTION'||['RELEASING','PRODUCTION_VERIFYING','LIVE_VERIFIED'].includes(action.toState??''))return 'عملیات Production در این پنل در دسترس نیست';
|
||||
if(task.state==='EXPIRED')return 'پیشنهاد منقضی شده است؛ پیشنهاد جدید ایجاد کنید';
|
||||
if((action.toState&&action.gate)||(!action.toState&&(![1,2].includes(action.gate??0)||!['APPROVED','REJECTED'].includes(action.decision??''))))return 'اقدام سرور پشتیبانی نمیشود';
|
||||
return undefined;
|
||||
}
|
||||
export function commandFailure(error:unknown):{message:string;retryable:boolean} {
|
||||
const status=(error as {response?:{status?:number}})?.response?.status;
|
||||
if(status===409)return {message:'Stale version or idempotency conflict. Refresh authoritative state and review a fresh decision.',retryable:false};
|
||||
if(status===410)return {message:'Proposal or approval expired. Refresh; expired proposals require a new proposal.',retryable:false};
|
||||
if(status===401||status===403)return {message:'Backend denied this action. Refresh permissions before continuing.',retryable:false};
|
||||
if(status&&status>=400&&status<500)return {message:'Backend rejected this action (HTTP '+status+'). Refresh and review the proposal.',retryable:false};
|
||||
return {message:(error instanceof Error?error.message:'Backend request unavailable')+' — Outcome unknown. Retry only the identical payload/key, or refresh to reconcile.',retryable:true};
|
||||
if(status===409)return {message:'نسخه قدیمی یا تعارض کلید تکرار رخ داده است. وضعیت سرور را بازخوانی و تصمیم تازه را بررسی کنید.',retryable:false};
|
||||
if(status===410)return {message:'پیشنهاد یا تأیید منقضی شده است. وضعیت را بازخوانی کنید؛ پیشنهاد منقضی به پیشنهاد جدید نیاز دارد.',retryable:false};
|
||||
if(status===401||status===403)return {message:'سرور این اقدام را رد کرد. پیش از ادامه مجوزها را بازخوانی کنید.',retryable:false};
|
||||
if(status&&status>=400&&status<500)return {message:'سرور این اقدام را رد کرد (HTTP '+status+'). وضعیت را بازخوانی و پیشنهاد را بررسی کنید.',retryable:false};
|
||||
return {message:(error instanceof Error?error.message:'درخواست سرور در دسترس نیست')+' — نتیجه نامشخص است. فقط همان داده و کلید را تکرار کنید یا وضعیت را برای تطبیق بازخوانی کنید.',retryable:true};
|
||||
}
|
||||
export type Resource = 'agents' | 'model-policy' | 'schedules' | 'releases' | 'overview';
|
||||
export interface ResourceSnapshot { capabilities?: {mutations:boolean;chat:boolean;runtime:boolean;killSwitch?:boolean}; items: Array<{id:string; title?:string; status?:string; department?:string; readiness?:string; model?:string; budgetLimitCents?:number; spentCents?:number; cron?:string; timezone?:string; environment?:string; commitSha?:string; reason?:string}>; measuredAt: string }
|
||||
@@ -65,7 +66,7 @@ export function proposalError(input:CreateTaskInput):string|undefined {
|
||||
if(typeof input.metadata?.commitSha!=='string'||!/^[a-f0-9]{40}$/.test(input.metadata.commitSha))return 'Immutable commit must be 40 lowercase hex characters';
|
||||
if(typeof input.metadata?.scope!=='string'||!input.metadata.scope.trim()||input.metadata.scope.length>2000)return 'Scope must be nonblank and at most 2000 characters';
|
||||
if(!Array.isArray(input.metadata?.acceptanceCriteria)||input.metadata.acceptanceCriteria.length<1||input.metadata.acceptanceCriteria.length>20||input.metadata.acceptanceCriteria.some(value=>typeof value!=='string'||!value.trim()||value.length>500))return 'Acceptance criteria must contain 1..20 nonblank strings of at most 500 characters';
|
||||
if(!input.key.trim()||input.key.length>120||!input.title.trim()||input.title.length>255||!input.department.trim()||input.department.length>50)return 'Proposal requires key (1..120), title (1..255), department (1..50)';
|
||||
if(!input.key.trim()||input.key.length>120||!input.title.trim()||input.title.length>255||!input.department.trim()||input.department.length>50)return 'کلید (۱ تا ۱۲۰)، عنوان (۱ تا ۲۵۵) و دپارتمان (۱ تا ۵۰ نویسه) الزامی است';
|
||||
}
|
||||
export const orchestration = {
|
||||
async create(input:CreateTaskInput):Promise<unknown> {
|
||||
@@ -75,33 +76,33 @@ export const orchestration = {
|
||||
},
|
||||
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');
|
||||
if (!data?.id || !Number.isInteger(data.version)) throw new Error('پاسخ جزئیات وظیفه نامعتبر است');
|
||||
return {...data,availableActions:normalizeActions(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');
|
||||
if (!Array.isArray(data?.items) || !data.measuredAt) throw new Error('پاسخ نمای ثبتشده نامعتبر است');
|
||||
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');
|
||||
if (!killLevels.includes(level) || !reason.trim()) throw new Error('سطح و دلیل توقف الزامی است');
|
||||
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');
|
||||
if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('نشست و پیام الزامی است');
|
||||
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');
|
||||
if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('پاسخ گفتوگو نامعتبر است');
|
||||
return data;
|
||||
},
|
||||
async command(task: Task, requested: ServerAction, input: CommandInput): Promise<unknown> {
|
||||
const action = normalizeActions(task.availableActions).find(a => a.id === requested.id);
|
||||
if (!action || action.disabledReason) throw new Error('Action is not advertised or is disabled');
|
||||
if (!action || action.disabledReason) throw new Error('اقدام اعلام نشده یا غیرفعال است');
|
||||
const blocked=actionBlockReason(task,action);if(blocked)throw new Error(blocked);
|
||||
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('Version and idempotency key required');
|
||||
if (!input.idempotencyKey || !Number.isInteger(task.version)) throw new Error('نسخه و کلید جلوگیری از تکرار الزامی است');
|
||||
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');
|
||||
if(['APPROVE_GATE1','REJECT_GATE1'].includes(action.id)&&Date.parse(input.expiresAt)>Date.now()+86400000)throw new Error('Gate1 expiry must be within 24 hours');
|
||||
if (!input.expiresAt || !(Date.parse(input.expiresAt) > Date.now())) throw new Error('زمان انقضا باید در آینده باشد');
|
||||
if(['APPROVE_GATE1','REJECT_GATE1'].includes(action.id)&&Date.parse(input.expiresAt)>Date.now()+86400000)throw new Error('انقضای Gate1 باید در ۲۴ ساعت آینده باشد');
|
||||
let binding = {};
|
||||
if (action.gate === 2 && action.decision === 'APPROVED') {
|
||||
const run = task.runs?.find(r => r.id === input.runId);
|
||||
@@ -111,13 +112,13 @@ export const orchestration = {
|
||||
}
|
||||
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');
|
||||
if (!action.toState) throw new Error('اقدام سرور پشتیبانی نمیشود');
|
||||
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');
|
||||
if (!Array.isArray(rows)) throw new Error('پاسخ فهرست وظیفهها نامعتبر است');
|
||||
return rows.map(row => ({ ...row, availableActions: normalizeActions(row.availableActions) }));
|
||||
},
|
||||
};
|
||||
@@ -9,13 +9,13 @@ const snapshot={source:'9router',period:'7d',status:'available',reason:null,attr
|
||||
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('مجموع درگاه (شامل Hermes)')).toBeInTheDocument();
|
||||
expect(screen.getByText('سهم مصرف Hermes: نامشخص و گزارشنشده؛ با مجموع درگاه جمع نکنید.')).toBeInTheDocument();
|
||||
expect(screen.getByText('9router')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Unknown — not reported').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('نامشخص — گزارش نشده').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'}});
|
||||
fireEvent.change(screen.getByLabelText('بازه مصرف'),{target:{value:'today'}});
|
||||
await screen.findByText('opaque-1');
|
||||
expect(api.get).toHaveBeenLastCalledWith('/admin/router-usage',{params:{period:'today'}});
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user