feat: add orchestrator controls to memindadm

This commit is contained in:
john
2026-07-25 07:12:53 +08:00
parent dd3fed5b14
commit 2596c8f2c6
9 changed files with 983 additions and 0 deletions
+1
View File
@@ -32,6 +32,7 @@ const NAV_SECTIONS: NavSection[] = [
{ to: '/memory-v2', label: 'Memory V2' },
{ to: '/mindsearch', label: 'MindSearch' },
{ to: '/skill-runtime', label: 'Skill Runtime' },
{ to: '/orchestrator', label: '任务编排' },
{ to: '/system-tests', label: '系统测试验证' },
{ to: '/capabilities', label: '能力' },
{ to: '/skills', label: '技能' },
+383
View File
@@ -0,0 +1,383 @@
import { useEffect, useMemo, useState } from 'react';
import {
getOrchestratorCanaryReadiness,
getOrchestratorConfig,
getOrchestratorExecutionPlans,
getOrchestratorRuntime,
getOrchestratorShadowRun,
getOrchestratorShadowRuns,
updateOrchestratorConfig,
} from '../../api/client';
import type {
OrchestratorCanaryReadiness,
OrchestratorConfig,
OrchestratorConfigState,
OrchestratorExecutionPlanList,
OrchestratorServiceHealth,
OrchestratorShadowRunDetail,
OrchestratorShadowRunList,
} from '../../types/orchestrator';
const runtimeReasons: Record<string, string> = {
mode_off: '当前为关闭模式,所有任务继续由 Native Agent Run 执行。',
service_url_missing: '尚未配置 Orchestrator 服务地址,LangGraph 不会接管任务。',
kill_switch: '环境级紧急熔断已开启,强制回退 Native。',
execution_gate_disabled: '执行交接闸门被硬锁定,当前仅生成 Dry-run 决策。',
environment_execution_gate_disabled: 'memindadm 已请求交接,但环境闸门仍关闭。',
};
const readinessLabels: Record<string, string> = {
shadow_mode: '保持 Shadow',
service_healthy: '服务健康',
durable_checkpoint: '持久化 checkpoint',
durable_executor_job_store: '持久化 Executor Job Store',
observe_only: '仅观察不执行',
sample_volume: '有效样本量',
shadow_success_rate: 'Shadow 成功率',
shadow_skip_rate: 'Shadow 跳过率',
latency_coverage: '延迟数据覆盖率',
latency_p95: '延迟 P95',
native_settled_rate: 'Native 终态覆盖率',
session_coverage: '真实会话覆盖',
sample_freshness: '最近样本新鲜度',
complete_window: '统计窗口完整',
};
function listToText(values: string[]) {
return values.join('\n');
}
function textToList(value: string) {
return [...new Set(value.split(/\r?\n|,/).map((item) => item.trim()).filter(Boolean))];
}
function formatTime(value?: number | null) {
return value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—';
}
function formatPercent(value?: number | null) {
return value == null ? '—' : `${(value * 100).toFixed(1)}%`;
}
function formatLatency(value?: number | null) {
return value == null ? '—' : `${value} ms`;
}
function shortId(value: string) {
return value.length > 16 ? `${value.slice(0, 8)}${value.slice(-6)}` : value;
}
function readinessValue(check: OrchestratorCanaryReadiness['checks'][number]) {
if (check.actual == null) return '无数据';
if (['shadow_success_rate', 'latency_coverage', 'native_settled_rate'].includes(check.id)) {
return formatPercent(Number(check.actual));
}
if (check.id === 'latency_p95') return formatLatency(Number(check.actual));
if (check.id === 'sample_freshness') return `${Number(check.actual).toFixed(1)} 小时`;
if (typeof check.actual === 'boolean') return check.actual ? '是' : '否';
return String(check.actual);
}
export function OrchestratorPage() {
const [state, setState] = useState<OrchestratorConfigState | null>(null);
const [draft, setDraft] = useState<OrchestratorConfig | null>(null);
const [workflowAllowlist, setWorkflowAllowlist] = useState('');
const [userAllowlist, setUserAllowlist] = useState('');
const [shadow, setShadow] = useState<OrchestratorShadowRunList | null>(null);
const [plans, setPlans] = useState<OrchestratorExecutionPlanList | null>(null);
const [readiness, setReadiness] = useState<OrchestratorCanaryReadiness | null>(null);
const [health, setHealth] = useState<OrchestratorServiceHealth | null>(null);
const [detail, setDetail] = useState<OrchestratorShadowRunDetail | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [checking, setChecking] = useState(false);
const [error, setError] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
const load = async () => {
setLoading(true);
setError(null);
try {
const [configState, shadowState, planState, readinessState] = await Promise.all([
getOrchestratorConfig(),
getOrchestratorShadowRuns({ hours: 24, limit: 100 }),
getOrchestratorExecutionPlans({ hours: 24, limit: 100 }),
getOrchestratorCanaryReadiness(),
]);
setState(configState);
setDraft(configState.config);
setWorkflowAllowlist(listToText(configState.config.workflowAllowlist));
setUserAllowlist(listToText(configState.config.userAllowlist));
setShadow(shadowState);
setPlans(planState);
setReadiness(readinessState);
} catch (err) {
setError(err instanceof Error ? err.message : 'Orchestrator 数据加载失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
void load();
}, []);
const normalizedDraft = useMemo(() => draft ? {
...draft,
workflowAllowlist: textToList(workflowAllowlist),
userAllowlist: textToList(userAllowlist),
} : null, [draft, workflowAllowlist, userAllowlist]);
const dirty = Boolean(
state && normalizedDraft && JSON.stringify(state.config) !== JSON.stringify(normalizedDraft),
);
const save = async () => {
if (!normalizedDraft) return;
if (['canary', 'active'].includes(normalizedDraft.mode) && !normalizedDraft.serviceUrl) {
setError('Canary / Active 模式必须先配置 Orchestrator URL。');
return;
}
if (
normalizedDraft.executionEnabled
&& !window.confirm('确认请求执行交接?环境闸门关闭时仍只会 Dry-run。')
) {
return;
}
setSaving(true);
setError(null);
setMessage(null);
try {
const result = await updateOrchestratorConfig(normalizedDraft);
setState(result);
setDraft(result.config);
setWorkflowAllowlist(listToText(result.config.workflowAllowlist));
setUserAllowlist(listToText(result.config.userAllowlist));
setMessage(`Orchestrator 配置 v${result.configVersion} 已保存。`);
} catch (err) {
setError(err instanceof Error ? err.message : '保存失败');
} finally {
setSaving(false);
}
};
const checkHealth = async () => {
setChecking(true);
setError(null);
try {
const result = await getOrchestratorRuntime();
setHealth(result.serviceHealth);
} catch (err) {
setError(err instanceof Error ? err.message : '服务检查失败');
} finally {
setChecking(false);
}
};
const openDetail = async (runId: string) => {
setError(null);
try {
setDetail(await getOrchestratorShadowRun(runId));
} catch (err) {
setError(err instanceof Error ? err.message : 'Run 详情加载失败');
}
};
if (loading) return <div className="admin-page"><p> Workflow Orchestrator</p></div>;
if (!state || !draft) {
return <div className="admin-page"><p className="banner banner-error">{error ?? '配置不可用'}</p></div>;
}
const runtimeMessage = state.runtime.reason
? (runtimeReasons[state.runtime.reason] ?? state.runtime.reason)
: state.runtime.shadowsLangGraph
? 'Shadow 已生效:Native 继续执行,LangGraph 只观察。'
: state.runtime.executesLangGraph
? '执行交接已开启。'
: '配置有效。';
return (
<div className="admin-page orchestrator-page">
<div className="admin-page-head">
<h2>Workflow Orchestrator</h2>
<p className="muted">
LangGraph Off Shadow Native Agent Run
</p>
</div>
{error && <p className="banner banner-error">{error}</p>}
{message && <p className="banner banner-info">{message}</p>}
<section className="admin-card">
<div className="orchestrator-summary">
<div><span></span><strong>v{state.configVersion}</strong></div>
<div><span></span><strong>{state.runtime.effective ? '有效' : '安全回退'}</strong></div>
<div><span></span><strong>{state.source}</strong></div>
<div><span></span><strong>{state.runtime.executionHandoff.enabled ? '已开启' : 'Dry-run 锁定'}</strong></div>
<div><span></span><strong>{formatTime(state.updatedAt)}</strong></div>
</div>
<p className={`orchestrator-state ${state.runtime.reason === 'kill_switch' ? 'danger' : ''}`}>
{runtimeMessage}
</p>
</section>
<section className="admin-card">
<div className="orchestrator-section-head">
<div>
<h2>Executor Gateway</h2>
<p className="muted"> Orchestrator </p>
</div>
</div>
<div className="orchestrator-executors">
{state.executors.map((executor) => (
<article key={executor.id}>
<div><strong>{executor.label}</strong><span>{executor.status}</span></div>
<p>{executor.capabilities.join(' · ') || '无能力声明'}</p>
<small>dispatch {executor.dispatchImplemented ? 'implemented' : 'disabled'}</small>
</article>
))}
</div>
</section>
<section className="admin-card">
<div className="orchestrator-section-head">
<div>
<h2>Shadow </h2>
<p className="muted"> 24 Native LangGraph </p>
</div>
<button type="button" className="ghost-btn" onClick={() => void load()}></button>
</div>
{readiness && (
<div className={`orchestrator-readiness ${readiness.ready ? 'ready' : ''}`}>
<div>
<strong>Canary </strong>
<b>{readiness.ready ? '达到门槛,等待人工审批' : '继续保持 Shadow'}</b>
</div>
<p>
{readiness.samples.eligibleObservations} / {readiness.thresholds.minObservations}
{' · '} smoke {readiness.samples.excludedSynthetic}
{' · '} {readiness.samples.distinctSessions} / {readiness.thresholds.minDistinctSessions}
</p>
<div className="orchestrator-checks">
{readiness.checks.map((check) => (
<span key={check.id} className={check.passed ? 'passed' : 'blocked'}>
{check.passed ? '通过' : '阻塞'} · {readinessLabels[check.id] ?? check.id}{readinessValue(check)}
</span>
))}
</div>
</div>
)}
<div className="orchestrator-metrics">
<div><span></span><strong>{shadow?.metrics.observations ?? '—'}</strong></div>
<div><span></span><strong>{formatPercent(shadow?.metrics.successRate)}</strong></div>
<div><span></span><strong>{shadow?.metrics.failures ?? '—'}</strong></div>
<div><span> P95</span><strong>{formatLatency(shadow?.metrics.latencyP95Ms)}</strong></div>
<div><span>Native / </span><strong>{shadow ? `${shadow.metrics.nativeSucceeded} / ${shadow.metrics.nativeFailed}` : '—'}</strong></div>
</div>
<div className="admin-table-wrap">
<table className="admin-table">
<thead><tr><th></th><th>Run</th><th>Shadow</th><th>Native</th><th></th><th> / Adapter</th></tr></thead>
<tbody>
{(shadow?.runs ?? []).map((run) => (
<tr key={run.eventId}>
<td>{formatTime(run.observedAt)}</td>
<td><button type="button" className="ghost-btn" onClick={() => void openDetail(run.runId)}>{shortId(run.runId)}</button></td>
<td>{run.shadowStatus}</td>
<td>{run.nativeStatus}</td>
<td>{formatLatency(run.latencyMs)}</td>
<td>{run.taskType ?? '—'}{run.synthetic ? 'smoke' : ''}<small>{run.executorAdapter ?? '—'}</small></td>
</tr>
))}
{!shadow?.runs.length && <tr><td colSpan={6}> Shadow </td></tr>}
</tbody>
</table>
</div>
{detail && (
<div className="orchestrator-detail">
<div className="orchestrator-section-head">
<div><strong>Run {detail.native.runId}</strong><p className="muted">Native {detail.native.status} · LangGraph {detail.remote.available ? 'available' : 'unavailable'}</p></div>
<button type="button" className="ghost-btn" onClick={() => setDetail(null)}></button>
</div>
<div>
<pre>{JSON.stringify(detail.remote.state, null, 2)}</pre>
<pre>{JSON.stringify(detail.remote.events, null, 2)}</pre>
</div>
</div>
)}
</section>
<section className="admin-card">
<div className="orchestrator-section-head">
<div><h2> Dry-run</h2><p className="muted"> Native</p></div>
</div>
{(plans?.metrics.handoffAllowed ?? 0) > 0 && (
<p className="banner banner-error"> handoffAllowed=true</p>
)}
<div className="orchestrator-metrics">
<div><span></span><strong>{plans?.metrics.decisions ?? '—'}</strong></div>
<div><span></span><strong>{formatPercent(plans?.metrics.candidateSelectionRate)}</strong></div>
<div><span>LangGraph / Native</span><strong>{plans ? `${plans.metrics.candidateSelections} / ${plans.metrics.nativeSelections}` : '—'}</strong></div>
<div><span>Native </span><strong>{formatPercent(plans?.metrics.nativeSettledRate)}</strong></div>
<div><span></span><strong>{plans?.metrics.distinctSessions ?? '—'}</strong></div>
</div>
<div className="admin-table-wrap">
<table className="admin-table">
<thead><tr><th></th><th>Run</th><th></th><th> </th><th></th><th>Native</th></tr></thead>
<tbody>
{(plans?.plans ?? []).map((plan) => (
<tr key={plan.eventId}>
<td>{formatTime(plan.plannedAt)}</td>
<td className="mono">{shortId(plan.runId)}</td>
<td>{plan.mode ?? '—'}</td>
<td>{plan.candidateEngine} {plan.effectiveEngine}</td>
<td>{plan.candidateReason ?? plan.reason ?? '—'}</td>
<td>{plan.nativeStatus}</td>
</tr>
))}
{!plans?.plans.length && <tr><td colSpan={6}> Dry-run </td></tr>}
</tbody>
</table>
</div>
</section>
<section className="admin-card">
<h2></h2>
<div className="orchestrator-form-grid">
<label><span></span><select value={draft.mode} onChange={(event) => setDraft({ ...draft, mode: event.target.value as OrchestratorConfig['mode'] })}>
<option value="off">Off Native only</option>
<option value="shadow">Shadow Native LangGraph </option>
<option value="canary">Canary /</option>
<option value="active">Active </option>
</select></label>
<label><span></span><select value={draft.primaryEngine} onChange={(event) => setDraft({ ...draft, primaryEngine: event.target.value })}>
{state.engines.map((engine) => <option key={engine.id} value={engine.id}>{engine.label}{engine.configured ? '' : '(未配置)'}</option>)}
</select></label>
<label><span></span><input type="number" min={0} max={100} value={draft.rolloutPercent} onChange={(event) => setDraft({ ...draft, rolloutPercent: Number(event.target.value) })} /></label>
<label><span></span><input type="number" min={500} max={60000} value={draft.requestTimeoutMs} onChange={(event) => setDraft({ ...draft, requestTimeoutMs: Number(event.target.value) })} /></label>
<label className="wide"><span>Orchestrator URL</span><input value={draft.serviceUrl} onChange={(event) => setDraft({ ...draft, serviceUrl: event.target.value })} placeholder="http://127.0.0.1:8093" /></label>
</div>
<div className="orchestrator-health">
<span>{health ? `${health.ok ? '健康' : '不可用'}${health.status}${health.latencyMs} ms` : '尚未检查服务连接'}</span>
<button type="button" className="ghost-btn" onClick={() => void checkHealth()} disabled={checking}>{checking ? '检查中…' : '测试连接'}</button>
</div>
<div className="orchestrator-toggles">
<label><input type="checkbox" checked={draft.requireHealthy} onChange={(event) => setDraft({ ...draft, requireHealthy: event.target.checked })} /></label>
<label><input type="checkbox" checked={draft.fallbackToNative} onChange={(event) => setDraft({ ...draft, fallbackToNative: event.target.checked })} />退 Native</label>
<label className="handoff"><input type="checkbox" checked={draft.executionEnabled} onChange={(event) => setDraft({ ...draft, executionEnabled: event.target.checked })} /> Kill Switch </label>
</div>
<div className="orchestrator-allowlists">
<label><span></span><textarea rows={6} value={workflowAllowlist} onChange={(event) => setWorkflowAllowlist(event.target.value)} /></label>
<label><span></span><textarea rows={6} value={userAllowlist} onChange={(event) => setUserAllowlist(event.target.value)} /></label>
</div>
<div className="admin-actions orchestrator-actions">
<button type="button" className="ghost-btn" onClick={() => void load()} disabled={saving}></button>
<button type="button" className="send-btn" onClick={() => void save()} disabled={saving || !dirty}>{saving ? '保存中…' : '保存配置'}</button>
</div>
</section>
</div>
);
}