import { useEffect, useState } from 'react' import { ArrowLeft, ArrowRight, Check, CircleAlert, Clock3, FileText, Play, RefreshCw, ShieldCheck, Sparkles, X } from 'lucide-react' import { useApp } from '../../context/useApp' import { useApi } from '../../api/ApiProvider' import { useApiQuery } from '../../api/useApiQuery' import { useWorkspace } from '../../api/WorkspaceContext' import { canSubmitRuns } from '../../api/permissions' import { ExecutionCenter } from '../execution-center/ExecutionCenter' import './run-set-workflow.css' type ProjectionSet = { id?: string projectId?: string name: string scenario: string status: string savedScenarioIds?: string[] validation?: Record traceScope?: string[] } type ApiProjectionSet = { id: string; project_id?: string; name: string; status: string; scenarios?: { id: string; name: string }[]; validation?: { checks?: { code: string; status: string }[] } } type ProjectOptionsState = { projectId: string; items: T[]; loading: boolean; error: Error | null } type CheckResult = { name: string; passed: boolean; detail: string; warning?: boolean } type PreflightResult = { ok: boolean; checks: { group: string; items: CheckResult[] }[]; plannedRuns: { projectionSetId: string; projectionSetName: string; scenarioId: string; scenarioName: string }[]; problems: string[] } const statusClass = (status: string) => status.toLowerCase().replaceAll(' ', '-') export function RunSetSubmissionDialog({ projectionSets, initialProjectionSetId, onClose }: { projectionSets: ProjectionSet[]; initialProjectionSetId?: string; onClose: () => void }) { const { setActiveScreen, setActiveExecutionRunSetId } = useApp() const { request, user } = useApi() const { projects, projectId: workspaceProjectId } = useWorkspace() const initialSet = projectionSets.find(set => set.id === initialProjectionSetId) const [projectId, setProjectId] = useState(initialSet?.projectId ?? workspaceProjectId ?? '') const canSubmit = canSubmitRuns(user?.roles ?? []) const [selectedSetIds, setSelectedSetIds] = useState(initialSet?.id ? [initialSet.id] : []) const [overrideScenarios, setOverrideScenarios] = useState(false) const [selectedScenarioIds, setSelectedScenarioIds] = useState([]) const [name, setName] = useState('') const [notes, setNotes] = useState('') const [preflight, setPreflight] = useState(null) const [submitting, setSubmitting] = useState(false) const [preflighting, setPreflighting] = useState(false) const [projectSetOptions, setProjectSetOptions] = useState>({ projectId: '', items: [], loading: false, error: null }) const [scenarioOptions, setScenarioOptions] = useState>({ projectId: '', items: [], loading: false, error: null }) useEffect(() => { if (!projectId) { setProjectSetOptions({ projectId: '', items: [], loading: false, error: null }) return } const controller = new AbortController() let active = true setProjectSetOptions({ projectId, items: [], loading: true, error: null }) request<{ projection_sets: ApiProjectionSet[] }>(`/v1/projects/${projectId}/projection-sets`, { signal: controller.signal }) .then(result => { if (!active) return const items = (result.projection_sets ?? []).map(item => ({ id: item.id, projectId: item.project_id ?? projectId, name: item.name, scenario: (item.scenarios ?? []).map(scenario => scenario.name).filter(Boolean).join(', ') || 'No scenarios attached', savedScenarioIds: (item.scenarios ?? []).map(scenario => scenario.id), validation: Object.fromEntries((item.validation?.checks ?? []).map(check => [check.code, check.status === 'pass'])), status: item.status === 'validated' ? 'Ready' : item.status === 'needs_review' ? 'Needs review' : 'Draft', })) setProjectSetOptions({ projectId, items, loading: false, error: null }) }) .catch(caught => { if (active && !controller.signal.aborted) setProjectSetOptions({ projectId, items: [], loading: false, error: caught instanceof Error ? caught : new Error('Could not load Projection Sets.') }) }) return () => { active = false; controller.abort() } }, [projectId, request]) useEffect(() => { if (!projectId) { setScenarioOptions({ projectId: '', items: [], loading: false, error: null }) return } const controller = new AbortController() let active = true setScenarioOptions({ projectId, items: [], loading: true, error: null }) request<{ scenario_sets: { scenarios: { id: string; name: string; status: string }[] }[] }>(`/v1/projects/${projectId}/scenario-sets`, { signal: controller.signal }) .then(result => { if (active) setScenarioOptions({ projectId, items: (result.scenario_sets ?? []).flatMap(group => group.scenarios), loading: false, error: null }) }) .catch(caught => { if (active && !controller.signal.aborted) setScenarioOptions({ projectId, items: [], loading: false, error: caught instanceof Error ? caught : new Error('Could not load scenarios.') }) }) return () => { active = false; controller.abort() } }, [projectId, request]) const queriedProjectSets = projectSetOptions.projectId === projectId ? projectSetOptions.items : null const projectSets = (queriedProjectSets ?? (projectId === workspaceProjectId ? projectionSets.filter(set => set.projectId === projectId) : [])).filter(set => set.projectId === projectId) const projectSetsLoading = Boolean(projectId && projectSetOptions.projectId !== projectId) || Boolean(projectSetOptions.projectId === projectId && projectSetOptions.loading) const projectSetsError = projectSetOptions.projectId === projectId ? projectSetOptions.error : null const scenarios = scenarioOptions.projectId === projectId ? scenarioOptions.items : [] const scenarioLoading = Boolean(projectId && (scenarioOptions.projectId !== projectId || scenarioOptions.loading)) const scenarioError = scenarioOptions.projectId === projectId ? scenarioOptions.error : null const selectedSets = projectSets.filter(set => set.id && selectedSetIds.includes(set.id)) const canPreflight = Boolean(projectId && selectedSetIds.length && selectedSets.length === selectedSetIds.length) const plannedCount = selectedSets.reduce((count, set) => { const scenarioCount = overrideScenarios ? selectedScenarioIds.length : (set.savedScenarioIds?.length ?? (set.scenario ? 1 : 0)) return count + scenarioCount }, 0) const toggleSet = (id: string) => { setSelectedSetIds(current => current.includes(id) ? current.filter(selected => selected !== id) : [...current, id]) setPreflight(null) } const toggleScenario = (id: string) => { setSelectedScenarioIds(current => current.includes(id) ? current.filter(selected => selected !== id) : [...current, id]) setPreflight(null) } const requestPreview = { project_id: projectId, projection_set_ids: selectedSetIds, scenario_ids: overrideScenarios ? selectedScenarioIds : [], name: name.trim() || 'Run Set', notes: notes.trim() || null, } const runPreflight = async () => { if (!canPreflight || projectSetsLoading || (overrideScenarios && (scenarioLoading || scenarioError)) || preflighting) return setPreflighting(true) try { const result = await request<{ ok: boolean; checks?: { label: string; status: string; message: string }[]; planned_runs?: { projection_set_id: string; scenario_id: string; name: string; ok: boolean; problems: string[] }[]; problems?: string[] }>('/v1/run-sets/preflight', { method: 'POST', body: JSON.stringify(requestPreview) }) const backendRuns = result.planned_runs ?? [] const plannedRuns = backendRuns.map(run => ({ projectionSetId: run.projection_set_id, projectionSetName: projectSets.find(set => set.id === run.projection_set_id)?.name ?? 'Projection Set', scenarioId: run.scenario_id, scenarioName: scenarios.find(scenario => scenario.id === run.scenario_id)?.name ?? run.name.split(' · ').at(-1) ?? run.name, })) const checks: PreflightResult['checks'] = [{ group: 'Backend preflight', items: (result.checks ?? []).map(item => ({ name: item.label, passed: item.status === 'pass', warning: item.status !== 'pass', detail: item.message })) }] const pairingChecks = plannedRuns.map(run => ({ name: `${run.projectionSetName} × ${run.scenarioName}`, passed: backendRuns.find(item => item.projection_set_id === run.projectionSetId && item.scenario_id === run.scenarioId)?.ok ?? false, warning: false, detail: 'Resolved by the backend.' })) checks.push({ group: 'Scenario pairings', items: pairingChecks }) setPreflight({ ok: result.ok, checks, plannedRuns, problems: result.problems ?? [] }) } catch (error) { setPreflight({ ok: false, checks: [], plannedRuns: [], problems: [error instanceof Error ? error.message : 'Backend preflight failed.'] }) } finally { setPreflighting(false) } } const submitRunSet = async () => { if (!preflight?.ok || submitting) return setSubmitting(true) try { const created = await request<{ run_set: { id: string } }>('/v1/run-sets', { method: 'POST', body: JSON.stringify(requestPreview), }) setActiveExecutionRunSetId(created.run_set.id) onClose() setActiveScreen('Runs') } catch (error) { setPreflight({ ...preflight, ok: false, problems: [error instanceof Error ? error.message : 'Run Set submission failed.'] }) } finally { setSubmitting(false) } } return
event.stopPropagation()}>
SUBMISSION

Create Run Set

Select Projection Sets to submit. Each set is paired with its saved scenarios unless you provide overrides.

Preflight and run submission are performed by the live backend.
Projection Sets {selectedSetIds.length} selected {projectSetsLoading ?

Loading Projection Sets for this project…

: projectSetsError ?

Could not load Projection Sets: {projectSetsError.message}

: projectSets.length ? projectSets.map(set => ) :

No saved Projection Sets are available for this project.

}
ScenariosOptional override
{overrideScenarios ?
{scenarioLoading ?

Loading project scenarios…

: scenarioError ?

Could not load scenarios: {scenarioError.message}

: scenarios.map(scenario => )}
:

Use each selected Projection Set’s saved scenarios.

}