import { useQuery } from '@tanstack/react-query' import { useCallback, useMemo, useState } from 'react' import { type DeploymentGroup, fetchDeployments, fetchDeploymentLog, launchDeployment, stopDeployment, type DeploymentJob, type DeploymentStep, } from '../api/deployments' import { formatAgoCompact, formatDateTimeAbsolute } from '../utils/dateTime' import { hasProblems, sumDbtCounts } from '../utils/stepCounts' import StepResultPanel, { StepCounts } from './StepResultPanel' const STATUS_STYLE: Record = { completed: 'bg-emerald-100 text-emerald-800 border-emerald-200', running: 'bg-sky-100 text-sky-800 border-sky-200', failed: 'bg-red-100 text-red-800 border-red-200', cancelled: 'bg-amber-100 text-amber-800 border-amber-200', skipped: 'bg-slate-100 text-slate-500 border-slate-200', pending: 'bg-slate-100 text-slate-500 border-slate-200', } function StatusBadge({ status }: { status: string }) { const cls = STATUS_STYLE[status] ?? STATUS_STYLE.pending return ( {status === 'running' && ( )} {status} ) } function StepRow({ job, step }: { job: DeploymentJob; step: DeploymentStep }) { const [open, setOpen] = useState(false) const { data: log, isFetching } = useQuery({ queryKey: ['deployment-log', job.job_id, step.key], queryFn: () => fetchDeploymentLog(job.job_id, step.key), enabled: open, // Keep the log fresh while the step is actively running. refetchInterval: open && step.status === 'running' ? 3_000 : false, }) return (
{step.note && (

⚠️ {step.note}

)} {open && (
{(job.group === 'load' || step.counts) && (

{hasProblems(step.counts) ? 'What was skipped or failed' : 'Counts'}

)} {step.cmd && (

$ {step.cmd}

)} {isFetching && !log && (

Loading log…

)} {log && log.lines.length > 0 ? (
              {log.lines.join('\n')}
            
) : ( !isFetching &&

No log output yet.

)}
)}
) } function stepSummary(job: DeploymentJob): string { const total = job.steps.length const done = job.steps.filter((s) => s.status === 'completed').length const failed = job.steps.filter((s) => s.status === 'failed').length const parts = [`${total} step${total === 1 ? '' : 's'}`] if (done) parts.push(`${done} done`) if (failed) parts.push(`${failed} failed`) // The headline numbers of the run, when its steps recorded them (#823). const load = job.steps.find((s) => s.counts && typeof s.counts.read === 'number')?.counts if (load) { parts.push(`${(load.read ?? 0).toLocaleString()} files read`, `${(load.loaded ?? 0).toLocaleString()} loaded`) if (load.skipped) parts.push(`${load.skipped.toLocaleString()} skipped`) if (load.errors) parts.push(`${load.errors.toLocaleString()} file ${load.errors === 1 ? 'error' : 'errors'}`) } const dbt = sumDbtCounts(job.steps) if (dbt) { parts.push(`${dbt.success.toLocaleString()} of ${dbt.models.toLocaleString()} models built`) if (dbt.error) parts.push(`${dbt.error.toLocaleString()} models failed`) } return parts.join(' · ') } function JobCard({ job, onStop, clockMs, defaultOpen = false, }: { job: DeploymentJob onStop: (jobId: string) => void clockMs: number defaultOpen?: boolean }) { const [open, setOpen] = useState(defaultOpen) const when = job.started_at ? formatDateTimeAbsolute(job.started_at) : '—' const ago = job.started_at ? formatAgoCompact(job.started_at, clockMs) : null return (
{job.live && job.status === 'running' && ( )}
{open && (
{job.steps.map((s) => ( ))}
)}
) } const COPY: Record< DeploymentGroup, { heading: string; blurb: string; realLabel: string; confirm: (steps: string[]) => string; empty: string } > = { load: { heading: 'Load analyses into the database', blurb: 'Runs the selected steps in order: analysed videos get their event rows, saved analysis files → bronze, then dbt rebuilds the gold tables and ' + 'refreshes the public views the website reads. Local warehouse only; nothing is published. A failing step stops the run.', realLabel: '▶ Run load', confirm: (steps) => `Run the load (${steps.join(', ')}) against the local warehouse?\n\n` + 'This writes bronze rows and rebuilds gold tables. Nothing is published to production.', empty: 'No loads yet. Run one above.', }, deploy: { heading: 'Launch a prod deployment', blurb: 'Runs the selected steps in order. A failing step stops the run.', realLabel: '▶ Deploy to PRODUCTION', confirm: (steps) => `Run a REAL production deployment (${steps.join(', ')})?\n\n` + 'This pushes to the Neon prod database and/or HuggingFace. This cannot be undone.', empty: 'No deployments yet. Launch one above.', }, } export default function DeploymentPanel({ group = 'deploy' }: { group?: DeploymentGroup }) { const copy = COPY[group] const { data, isPending, isError, error, refetch } = useQuery({ queryKey: ['deployments', group], queryFn: () => fetchDeployments(group), refetchInterval: (q) => { const live = q.state.data?.jobs?.some((j) => j.live && j.status === 'running') return live ? 3_000 : 15_000 }, retry: 1, }) const availableSteps = data?.available_steps ?? [] const enabled = data?.enabled ?? false const [selected, setSelected] = useState>(new Set()) // A deploy defaults to a dry run; a load only touches the local warehouse, so it runs for real. const [dryRun, setDryRun] = useState(group === 'deploy') const [launching, setLaunching] = useState(false) const [msg, setMsg] = useState(null) const [historyOpen, setHistoryOpen] = useState(false) // Default selection = every available step, once they load. const effectiveSelected = useMemo(() => { if (selected.size > 0) return selected return new Set(availableSteps.map((s) => s.key)) }, [selected, availableSteps]) const toggleStep = useCallback( (key: string) => { setSelected((prev) => { const base = prev.size > 0 ? new Set(prev) : new Set(availableSteps.map((s) => s.key)) if (base.has(key)) base.delete(key) else base.add(key) return base }) }, [availableSteps], ) const anyLive = data?.jobs?.some((j) => j.live && j.status === 'running') ?? false const onLaunch = useCallback(async () => { const steps = availableSteps.map((s) => s.key).filter((k) => effectiveSelected.has(k)) if (steps.length === 0) { setMsg('Select at least one step.') return } if (!dryRun) { const ok = window.confirm(copy.confirm(steps)) if (!ok) return } setLaunching(true) setMsg(null) try { const res = await launchDeployment({ steps, dry_run: dryRun, group }) setMsg(res.detail || 'Launched.') window.setTimeout(() => void refetch(), 1_000) } catch (e) { setMsg((e as Error).message || 'Launch failed') } finally { setLaunching(false) } }, [availableSteps, effectiveSelected, dryRun, refetch, group, copy]) const onStop = useCallback( async (jobId: string) => { if (!window.confirm(`Stop deployment ${jobId}? The running step is terminated.`)) return try { const res = await stopDeployment(jobId) setMsg(res.detail) void refetch() } catch (e) { setMsg((e as Error).message || 'Stop failed') } }, [refetch], ) const clockMs = Date.now() const jobs = data?.jobs ?? [] // Keep any in-flight deployment expanded and pinned to the top; everything // else is historical and tucked behind a collapsed "History" toggle. const activeJobs = jobs.filter((j) => j.live && j.status === 'running') const historyJobs = jobs.filter((j) => !(j.live && j.status === 'running')) return (
{/* Launch control */}

{copy.heading}

{copy.blurb}

{availableSteps.map((s) => { const on = effectiveSelected.has(s.key) return ( ) })} {availableSteps.length === 0 && ( No steps available. )}
{anyLive && ( A run is already in progress — stop it before starting another. )}
{!dryRun && !enabled && group === 'deploy' && (

Real deploys are disabled. Set DEPLOYMENTS_ALLOW_LAUNCH=1 on the API to enable, or keep Dry run on.

)} {msg &&

{msg}

}
{/* Recent jobs */} {isPending && !data && (
Loading deployments…
)} {isError && (
Could not load deployments: {(error as Error)?.message ?? 'error'}{' '}
)} {data && jobs.length === 0 && (
{copy.empty}
)} {/* In-flight deployment(s): always expanded, pinned to the top. */} {activeJobs.map((job) => ( ))} {/* Past runs: collapsed behind a single toggle so they don't dominate. */} {historyJobs.length > 0 && (
{historyOpen && historyJobs.map((job) => ( ))}
)}
) }