An open-source, faster Devin alternative
TypeScript
Add Swarms list and a mission-control map view for a run
Mohamed Habib via Computer49adcbf4cb53
diff --git a/web/src/App.tsx b/web/src/App.tsxindex d13ff811..4fba6811 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -46,6 +46,9 @@ const ManagedSecurityOnboarding = lazy(const ManagedProjectSwarm = lazy(() => import('./managed-agents/security/ProjectSwarm'),)+const ManagedProjectSwarms = lazy(+ () => import('./managed-agents/security/ProjectSwarms'),+)const ModelAccessCallback = lazy(() => import('./managed-agents/ModelAccessCallback'),)@@ -123,6 +126,14 @@ export default function App() {/><Routepath="projects/:projectId/swarm"+ element={<Navigate to="../swarms" replace />}+ />+ <Route+ path="projects/:projectId/swarms"+ element={<ManagedProjectSwarms />}+ />+ <Route+ path="projects/:projectId/swarms/:runId"element={<ManagedProjectSwarm />}/><Routediff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex 03694aca..74b856d2 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -60,9 +60,9 @@ export function managedAgentsNav(options: {{items: [// Only CVE Swarm projects declare the findings resource, so the- // Swarm grid is offered just for them.+ // Swarms list is offered just for them....(options.swarmEnabled- ? [{ to: `${projectPath}/swarm`, label: 'Swarm', icon: Radar }]+ ? [{ to: `${projectPath}/swarms`, label: 'Swarms', icon: Radar }]: []),{to: `${projectPath}/deployments`,diff --git a/web/src/managed-agents/security/ProjectSwarm.tsx b/web/src/managed-agents/security/ProjectSwarm.tsxindex 67e46b6d..2bf881ac 100644--- a/web/src/managed-agents/security/ProjectSwarm.tsx+++ b/web/src/managed-agents/security/ProjectSwarm.tsx@@ -1,8 +1,10 @@+import { useState } from 'react'import { useQuery } from '@tanstack/react-query'import { Link, useParams } from 'react-router-dom'-import { Loader2, Radar } from 'lucide-react'+import { ArrowLeft, Grid3x3, Loader2, Network, Radar } from 'lucide-react'import { PageHeader } from '@/components/page-header'import { Button } from '@/components/ui/button'+import { cn } from '@/lib/utils'import {getManagedMemoryDocument,getManagedMemoryDocuments,@@ -10,27 +12,34 @@ import {import {latestManifestId,parseRunManifest,+ runManifestDocumentId,SECURITY_FINDINGS_RESOURCE,+ type SwarmRunManifest,} from './catalog'-import { SwarmGrid } from './SwarmGrid'+import { RunReportCard, SwarmGrid } from './SwarmGrid'+import { SwarmMap } from './SwarmMap'+import { useSwarmRun } from './useSwarmRun'-// The swarm page for a deployed CVE Swarm project. The launch records a run-// manifest under the findings resource; here we read the latest one back and-// render its grid, so the run is reachable by URL and survives a reload — the-// grid's own React state no longer holds the session ids.+// One swarm run. The route carries the run id; without one we fall back to the+// latest manifest in the project so older `/swarm` links still land somewhere.export default function ProjectSwarm() {- const { projectId = '' } = useParams()+ const { projectId = '', runId } = useParams()const manifest = useQuery({- queryKey: ['swarm-manifest', projectId],+ queryKey: ['swarm-manifest', projectId, runId ?? 'latest'],enabled: Boolean(projectId),queryFn: async () => {- const page = await getManagedMemoryDocuments({- projectId,- resource: SECURITY_FINDINGS_RESOURCE,- environment: 'default',- })- const id = latestManifestId(page.documents)+ let id: string | null+ if (runId) {+ id = runManifestDocumentId(runId)+ } else {+ const page = await getManagedMemoryDocuments({+ projectId,+ resource: SECURITY_FINDINGS_RESOURCE,+ environment: 'default',+ })+ id = latestManifestId(page.documents)+ }if (!id) return nullconst read = await getManagedMemoryDocument({projectId,@@ -44,28 +53,23 @@ export default function ProjectSwarm() {return (<div className="mx-auto max-w-5xl px-4 py-8">- <PageHeader- title="CVE Swarm"- description="Each cell proves whether one CVE is reachable in one repository. Open a cell to read its full session."- className="mb-6"- />+ <Link+ to={`/projects/${encodeURIComponent(projectId)}/swarms`}+ className="text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1.5 text-sm"+ >+ <ArrowLeft className="size-3.5" /> All swarms+ </Link>{manifest.isPending ? (<div className="text-muted-foreground inline-flex items-center gap-2 text-sm">- <Loader2 className="size-4 animate-spin" /> Loading the latest run…+ <Loader2 className="size-4 animate-spin" /> Loading the run…</div>) : manifest.data ? (- <SwarmGrid- projectId={projectId}- runId={manifest.data.runId}- cells={manifest.data.cells}- target={manifest.data.target}- model={manifest.data.model}- />+ <RunView projectId={projectId} manifest={manifest.data} />) : (<div className="rounded-lg border border-dashed p-10 text-center"><Radar className="text-muted-foreground mx-auto size-6" /><p className="text-muted-foreground mt-3 text-sm">- No swarm has run in this project yet.+ This swarm run could not be found.</p><Button asChild variant="outline" className="mt-4"><Link to="/security">Launch a swarm</Link>@@ -75,3 +79,93 @@ export default function ProjectSwarm() {</div>)}++function RunView({+ projectId,+ manifest,+}: {+ projectId: string+ manifest: SwarmRunManifest+}) {+ const [view, setView] = useState<'map' | 'grid'>('map')+ const run = useSwarmRun({+ projectId,+ runId: manifest.runId,+ cells: manifest.cells,+ target: manifest.target,+ model: manifest.model,+ })++ return (+ <div className="space-y-5">+ <div className="flex flex-wrap items-end justify-between gap-3">+ <PageHeader+ title="CVE Swarm"+ description={`${manifest.target || 'target'} · ${manifest.model || 'model'} · ${manifest.cells.length} cells`}+ />+ <div className="bg-muted inline-flex items-center rounded-md p-0.5">+ <ToggleButton+ active={view === 'map'}+ onClick={() => setView('map')}+ icon={Network}+ label="Map"+ />+ <ToggleButton+ active={view === 'grid'}+ onClick={() => setView('grid')}+ icon={Grid3x3}+ label="Grid"+ />+ </div>+ </div>++ {view === 'map' ? (+ <div className="space-y-4">+ <SwarmMap+ states={run.states}+ counts={run.counts}+ settled={run.settled}+ />+ {run.report ? <RunReportCard report={run.report} /> : null}+ </div>+ ) : (+ <SwarmGrid+ projectId={projectId}+ runId={manifest.runId}+ states={run.states}+ counts={run.counts}+ settled={run.settled}+ report={run.report}+ />+ )}+ </div>+ )+}++function ToggleButton({+ active,+ onClick,+ icon: Icon,+ label,+}: {+ active: boolean+ onClick: () => void+ icon: typeof Network+ label: string+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className={cn(+ 'inline-flex items-center gap-1.5 rounded px-2.5 py-1 text-xs font-medium transition-colors',+ active+ ? 'bg-background text-foreground shadow-sm'+ : 'text-muted-foreground hover:text-foreground',+ )}+ >+ <Icon className="size-3.5" />+ {label}+ </button>+ )+}diff --git a/web/src/managed-agents/security/ProjectSwarms.tsx b/web/src/managed-agents/security/ProjectSwarms.tsxnew file mode 100644index 00000000..5148fa76--- /dev/null+++ b/web/src/managed-agents/security/ProjectSwarms.tsx@@ -0,0 +1,135 @@+import { useQuery } from '@tanstack/react-query'+import { Link, useParams } from 'react-router-dom'+import { ChevronRight, Loader2, Radar } from 'lucide-react'+import { PageHeader } from '@/components/page-header'+import { Button } from '@/components/ui/button'+import {+ getManagedMemoryDocument,+ getManagedMemoryDocuments,+} from '../api'+import {+ listManifestDocs,+ parseRunManifest,+ SECURITY_FINDINGS_RESOURCE,+} from './catalog'++type RunRow = {+ runId: string+ target: string+ model: string+ cells: number+ updatedAt: string+}++// The index of every swarm run in a project: one row per manifest, newest first,+// each linking to its run detail page (map / grid). This is what the "Swarms"+// nav item lands on.+export default function ProjectSwarms() {+ const { projectId = '' } = useParams()++ const runs = useQuery({+ queryKey: ['swarm-runs', projectId],+ enabled: Boolean(projectId),+ queryFn: async (): Promise<RunRow[]> => {+ const page = await getManagedMemoryDocuments({+ projectId,+ resource: SECURITY_FINDINGS_RESOURCE,+ environment: 'default',+ })+ const manifests = listManifestDocs(page.documents)+ const rows = await Promise.all(+ manifests.map(async ({ id, updatedAt }) => {+ const read = await getManagedMemoryDocument({+ projectId,+ resource: SECURITY_FINDINGS_RESOURCE,+ environment: 'default',+ id,+ })+ const manifest = parseRunManifest(read.document.text)+ if (!manifest) return null+ return {+ runId: manifest.runId,+ target: manifest.target,+ model: manifest.model,+ cells: manifest.cells.length,+ updatedAt,+ } satisfies RunRow+ }),+ )+ return rows.filter((r): r is RunRow => r !== null)+ },+ })++ return (+ <div className="mx-auto max-w-5xl px-4 py-8">+ <PageHeader+ title="Swarms"+ description="Every CVE swarm run in this project. Open one to watch its map or grid and read its report."+ className="mb-6"+ />+ {runs.isPending ? (+ <div className="text-muted-foreground inline-flex items-center gap-2 text-sm">+ <Loader2 className="size-4 animate-spin" /> Loading runs…+ </div>+ ) : runs.data && runs.data.length > 0 ? (+ <div className="overflow-hidden rounded-lg border">+ <table className="w-full text-sm">+ <thead className="bg-muted/50 text-muted-foreground text-xs">+ <tr>+ <th className="px-4 py-2 text-left font-medium">Target</th>+ <th className="px-4 py-2 text-left font-medium">Model</th>+ <th className="px-4 py-2 text-right font-medium">Cells</th>+ <th className="px-4 py-2 text-left font-medium">Started</th>+ <th className="px-4 py-2" />+ </tr>+ </thead>+ <tbody className="divide-y">+ {runs.data.map((run) => (+ <tr key={run.runId} className="hover:bg-muted/40">+ <td className="px-4 py-3">+ <Link+ to={`/projects/${encodeURIComponent(projectId)}/swarms/${encodeURIComponent(run.runId)}`}+ className="font-medium hover:underline"+ >+ {run.target || run.runId}+ </Link>+ <div className="text-muted-foreground font-mono text-xs">+ {run.runId}+ </div>+ </td>+ <td className="text-muted-foreground px-4 py-3 font-mono text-xs">+ {run.model || '—'}+ </td>+ <td className="px-4 py-3 text-right tabular-nums">+ {run.cells}+ </td>+ <td className="text-muted-foreground px-4 py-3 text-xs">+ {new Date(run.updatedAt).toLocaleString()}+ </td>+ <td className="px-4 py-3 text-right">+ <Link+ to={`/projects/${encodeURIComponent(projectId)}/swarms/${encodeURIComponent(run.runId)}`}+ className="text-muted-foreground hover:text-foreground inline-flex items-center"+ >+ <ChevronRight className="size-4" />+ </Link>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : (+ <div className="rounded-lg border border-dashed p-10 text-center">+ <Radar className="text-muted-foreground mx-auto size-6" />+ <p className="text-muted-foreground mt-3 text-sm">+ No swarm has run in this project yet.+ </p>+ <Button asChild variant="outline" className="mt-4">+ <Link to="/security">Launch a swarm</Link>+ </Button>+ </div>+ )}+ </div>+ )+}diff --git a/web/src/managed-agents/security/SwarmGrid.tsx b/web/src/managed-agents/security/SwarmGrid.tsxindex 674aa0f9..ce75f0c8 100644--- a/web/src/managed-agents/security/SwarmGrid.tsx+++ b/web/src/managed-agents/security/SwarmGrid.tsx@@ -1,6 +1,4 @@-import { useEffect, useMemo, useRef } from 'react'import { Link } from 'react-router-dom'-import { useQuery } from '@tanstack/react-query'import {ArrowUpRight,ExternalLink,@@ -11,64 +9,12 @@ import {} from 'lucide-react'import { cn } from '@/lib/utils'import {- createManagedMemoryDocument,- getManagedAgentSession,- getManagedMemoryDocument,-} from '../api'-import {- buildRunReport,cellDocumentId,- parseCellFinding,- runReportDocumentId,- SECURITY_FINDINGS_RESOURCE,- serializeRunReport,- type CellFinding,type CveDisposition,- type LaunchedCell,type ReportCell,- type ReportDisposition,- type SwarmCell,type SwarmRunReport,} from './catalog'--// A cell is settled when its worker has either saved a verdict or its session-// has stopped without one. We poll both the run's sessions (for liveness) and-// each cell's findings document (for the verdict) until every cell settles.-//-// A cell can fail two ways: the whole session stops (status failed/cancelled),-// or — the common one — the session stays `idle` while its last turn is-// `failed` (a single-turn cell whose final generation errored). So we read the-// last turn's status, not just the session's.-type SessionProgress = {- status: string- lastTurnStatus?: string-}--type CellState = {- cell: SwarmCell- sessionId: string- progress?: SessionProgress- finding: CellFinding | null-}--function sessionFailed(progress: SessionProgress | undefined): boolean {- if (!progress) return false- if (progress.status === 'failed' || progress.status === 'cancelled')- return true- const turn = progress.lastTurnStatus- return turn === 'failed' || turn === 'errored' || turn === 'cancelled'-}--// A cell is settled — we will never poll it again — when its verdict is saved-// or it failed, i.e. its phase is 'done' or 'failed'. The grid tracks that via-// `counts.pending === 0`.-function cellPhase(state: CellState): 'done' | 'failed' | 'running' | 'queued' {- if (state.finding) return 'done'- if (sessionFailed(state.progress)) return 'failed'- const status = state.progress?.status- if (status === 'running' || status === 'idle') return 'running'- return 'queued'-}+import { cellPhase, type CellState, type SwarmCounts } from './useSwarmRun'const DISPOSITION_META: Record<CveDisposition,@@ -91,153 +37,36 @@ const DISPOSITION_META: Record<},}+// The grid view of a run: one tile per cell plus the rolled-up report once every+// cell has settled. The parent runs the swarm poll (useSwarmRun) and hands the+// computed states down, so switching between the grid and the map view does not+// restart polling.export function SwarmGrid({projectId,runId,- cells,- target = '',- model = '',+ states,+ counts,+ settled,+ report,}: {projectId: stringrunId: string- cells: readonly LaunchedCell[]- target?: string- model?: string+ states: CellState[]+ counts: SwarmCounts+ settled: boolean+ report: SwarmRunReport | null}) {- // Both polls stop the moment every cell has settled (verdict saved, or- // failed). We recompute that each render and park it in a ref the two- // refetchInterval closures read, so neither needs the other's query data.- const allSettledRef = useRef(false)-- // The run's live sessions, fetched by the ids the launch returned so each tile- // can show whether its worker is queued, running, stopped, or failed.- const sessions = useQuery({- queryKey: ['swarm-sessions', projectId, runId],- queryFn: async () => {- const entries = await Promise.all(- cells.map(async ({ sessionId }) => {- const session = await getManagedAgentSession(sessionId)- const turns = session.turns- const lastTurnStatus =- turns.length > 0 ? turns[turns.length - 1].status : undefined- return [sessionId, { status: session.status, lastTurnStatus }] as const- }),- )- return Object.fromEntries(entries)- },- refetchInterval: () => (allSettledRef.current ? false : 3_000),- })-- // Each cell's findings document. These are created up front by the launch, so- // they always exist; the worker replaces the empty placeholder when it saves.- const findings = useQuery({- queryKey: ['swarm-findings', projectId, runId],- queryFn: async () => {- const entries = await Promise.all(- cells.map(async ({ cell }) => {- const read = await getManagedMemoryDocument({- projectId,- resource: SECURITY_FINDINGS_RESOURCE,- environment: 'default',- id: cellDocumentId(runId, cell),- })- return [- cellDocumentId(runId, cell),- parseCellFinding(read.document.text),- ] as const- }),- )- return Object.fromEntries(entries)- },- refetchInterval: () => (allSettledRef.current ? false : 4_000),- })-- const progressBySession = useMemo(- () => sessions.data ?? {},- [sessions.data],- )-- const states: CellState[] = cells.map(({ cell, sessionId }) => ({- cell,- sessionId,- progress: progressBySession[sessionId],- finding: findings.data?.[cellDocumentId(runId, cell)] ?? null,- }))-- const counts = states.reduce(- (acc, state) => {- const phase = cellPhase(state)- if (phase === 'done' && state.finding)- acc[state.finding.disposition] += 1- else if (phase === 'failed') acc.failed += 1- else acc.pending += 1- return acc- },- { exposed: 0, 'not-exposed': 0, 'needs-review': 0, failed: 0, pending: 0 },- )- const settled = counts.pending === 0-- // Park the settled flag in the ref the two refetchInterval closures read, so- // both polls stop once the run is done. Written in an effect (not during- // render) so the ref update is a proper side effect.- useEffect(() => {- allSettledRef.current = settled- }, [settled])-- // Once every cell has settled, roll the verdicts into the run report. This is- // the swarm's artifact; we both show it and persist it (below) so a scheduled- // run leaves something behind.- const report: SwarmRunReport | null = settled- ? buildRunReport(- { runId, target, model, generatedAt: new Date().toISOString() },- states.map((s): ReportCell => {- const disposition: ReportDisposition = s.finding- ? s.finding.disposition- : 'failed'- return {- repository: s.cell.repository,- cveId: s.cell.cveId,- disposition,- ...(s.finding?.reasoning ? { reasoning: s.finding.reasoning } : {}),- ...(s.finding?.pullRequest- ? { pullRequest: s.finding.pullRequest }- : {}),- }- }),- )- : null-- // Persist the report exactly once, when the run first settles. create-once- // (If-None-Match:*) means a reload that re-settles the same run is a no-op —- // the first write wins and any later conflict is ignored.- const reportWrittenRef = useRef(false)- useEffect(() => {- if (!report || reportWrittenRef.current) return- reportWrittenRef.current = true- void createManagedMemoryDocument({- projectId,- resource: SECURITY_FINDINGS_RESOURCE,- environment: 'default',- id: runReportDocumentId(runId),- title: `Swarm report ${runId}`,- text: serializeRunReport(report),- agentWrites: 'disabled',- }).catch(() => {- // Already written by an earlier view of this run — leave it be.- })- }, [report, projectId, runId])-return (<div className="space-y-4"><div className="flex flex-wrap items-center gap-2 text-sm">{settled ? (<span className="text-muted-foreground">- {cells.length} cell{cells.length === 1 ? '' : 's'} complete+ {states.length} cell{states.length === 1 ? '' : 's'} complete</span>) : (<span className="text-muted-foreground inline-flex items-center gap-1.5"><Loader2 className="size-3.5 animate-spin" />- {counts.pending} of {cells.length} still running+ {counts.pending} of {states.length} still running</span>)}<SummaryPill label="Exposed" count={counts.exposed} tone="exposed" />@@ -275,7 +104,7 @@ export function SwarmGrid({// artifact — the actionable verdicts rolled up and ranked. Tier 1 computes it// from the cell findings the grid already holds; a later reducer agent can// replace this with a written narrative over the same persisted document.-function RunReportCard({ report }: { report: SwarmRunReport }) {+export function RunReportCard({ report }: { report: SwarmRunReport }) {const actionable = report.cells.filter((c) => c.disposition !== 'not-exposed',)diff --git a/web/src/managed-agents/security/SwarmMap.tsx b/web/src/managed-agents/security/SwarmMap.tsxnew file mode 100644index 00000000..efee818c--- /dev/null+++ b/web/src/managed-agents/security/SwarmMap.tsx@@ -0,0 +1,308 @@+import { useEffect, useMemo, useRef } from 'react'+import { cellPhase, type CellState, type SwarmCounts } from './useSwarmRun'++// The mission-control view of a run: a coordinator dispatches to a fan of cells,+// each colored by its real verdict, and the settled ones stream back into an+// aggregator that produces the report. It is the same data as the grid, drawn as+// a live map. Everything animated here (pulses, particles) is cosmetic; every+// position and color is derived from the actual cell states.++const PALETTE = {+ bg: '#07080a',+ ink: '#8b9199',+ text: '#e8eaed',+ orange: '#ff7a18',+ red: '#ff4d4d',+ amber: '#f5b942',+ green: '#4ade80',+ grey: '#5b6066',+ purple: '#c084fc',+} as const++type CellColor = keyof typeof PALETTE++// A cell's color is its phase, and for a settled cell its disposition. Running+// cells glow orange (work in flight); queued ones are dim.+function cellColor(state: CellState): CellColor {+ const phase = cellPhase(state)+ if (phase === 'failed') return 'grey'+ if (phase === 'running') return 'orange'+ if (phase === 'queued') return 'grey'+ const d = state.finding?.disposition+ if (d === 'exposed') return 'red'+ if (d === 'needs-review') return 'amber'+ return 'green'+}++// A cell is "active" — drawn with a bright edge and particles — while it is+// running, or once it found something worth reporting.+function cellActive(state: CellState): boolean {+ const phase = cellPhase(state)+ if (phase === 'running') return true+ return state.finding?.disposition === 'exposed' ||+ state.finding?.disposition === 'needs-review'+}++export function SwarmMap({+ states,+ counts,+ settled,+}: {+ states: CellState[]+ counts: SwarmCounts+ settled: boolean+}) {+ const canvasRef = useRef<HTMLCanvasElement>(null)+ const containerRef = useRef<HTMLDivElement>(null)+ // The draw loop reads live data from a ref so we animate continuously without+ // restarting the loop (and the effect) on every poll.+ const dataRef = useRef({ states, counts, settled })++ // Stable per-cell jitter so the fan doesn't reshuffle between polls.+ const seeds = useMemo(+ () => states.map((_, i) => ((i * 2654435761) % 1000) / 1000),+ [states],+ )+ const seedsRef = useRef(seeds)++ // Keep the refs the draw loop reads in sync with each render's live data,+ // without restarting the animation effect.+ useEffect(() => {+ dataRef.current = { states, counts, settled }+ seedsRef.current = seeds+ })++ useEffect(() => {+ const canvas = canvasRef.current+ const container = containerRef.current+ if (!canvas || !container) return+ const ctx = canvas.getContext('2d')+ if (!ctx) return++ let raf = 0+ let frame = 0+ let width = 0+ let height = 0++ const resize = () => {+ const dpr = window.devicePixelRatio || 1+ width = container.clientWidth+ height = Math.max(360, Math.round(width * 0.42))+ canvas.width = Math.round(width * dpr)+ canvas.height = Math.round(height * dpr)+ canvas.style.height = `${height}px`+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)+ }+ resize()+ const ro = new ResizeObserver(resize)+ ro.observe(container)++ const quad = (+ ax: number, ay: number, bx: number, by: number,+ cx: number, cy: number, t: number,+ ): [number, number] => {+ const u = 1 - t+ return [+ u * u * ax + 2 * u * t * bx + t * t * cx,+ u * u * ay + 2 * u * t * by + t * t * cy,+ ]+ }++ const node = (+ x: number, y: number, label: string, sub: string, color: string,+ ) => {+ const pulse = 0.5 + 0.5 * Math.sin(frame * 0.05)+ ctx.shadowColor = color+ ctx.shadowBlur = 12 + pulse * 10+ ctx.fillStyle = color+ ctx.beginPath()+ ctx.arc(x, y, 6, 0, Math.PI * 2)+ ctx.fill()+ ctx.shadowBlur = 0+ ctx.strokeStyle = color+ ctx.globalAlpha = 0.25 + pulse * 0.35+ ctx.lineWidth = 1+ ctx.beginPath()+ ctx.arc(x, y, 13 + pulse * 5, 0, Math.PI * 2)+ ctx.stroke()+ ctx.globalAlpha = 1+ ctx.font = 'bold 10px ui-monospace, "Courier New", monospace'+ ctx.fillStyle = PALETTE.text+ ctx.textAlign = 'center'+ ctx.fillText(label, x, y - 20)+ ctx.font = '8px ui-monospace, "Courier New", monospace'+ ctx.fillStyle = PALETTE.ink+ ctx.fillText(sub, x, y + 26)+ ctx.textAlign = 'left'+ }++ const draw = () => {+ frame+++ const { states: st, counts: ct, settled: done } = dataRef.current+ const sd = seedsRef.current+ const n = st.length++ ctx.fillStyle = PALETTE.bg+ ctx.fillRect(0, 0, width, height)++ const coordX = width * 0.1+ const coordY = height * 0.5+ const aggX = width * 0.9+ const aggY = height * 0.5+ const arcCx = width * 0.52+ const arcCy = height * 0.5+ const arcR = Math.min(height * 0.42, width * 0.28)+ const aStart = -Math.PI * 0.6+ const aEnd = Math.PI * 0.6++ // Cell positions on the fan.+ const pts = st.map((_, i) => {+ const t = n <= 1 ? 0.5 : i / (n - 1)+ const jitter = (sd[i] - 0.5) * (arcR * 0.06)+ const ang = aStart + t * (aEnd - aStart)+ return {+ ang,+ x: arcCx - Math.cos(ang) * (arcR + jitter),+ y: arcCy + Math.sin(ang) * (arcR + jitter),+ }+ })++ // Dispatch edges: coordinator → each cell, particles on active ones.+ ctx.lineCap = 'round'+ st.forEach((cell, i) => {+ const p = pts[i]+ const color = PALETTE[cellColor(cell)]+ const active = cellActive(cell)+ const o0y = coordY + (i - n / 2) * 0.5+ const midx = (coordX + p.x) / 2 + width * 0.03+ const midy = (coordY + p.y) / 2 - height * 0.03+ ctx.strokeStyle = color+ ctx.globalAlpha = active ? 0.3 : 0.1+ ctx.lineWidth = active ? 1.3 : 0.6+ ctx.beginPath()+ ctx.moveTo(coordX, o0y)+ ctx.quadraticCurveTo(midx, midy, p.x, p.y)+ ctx.stroke()+ if (active) {+ for (let k = 0; k < 2; k++) {+ const t = ((frame * 0.008) + sd[i] + k * 0.5) % 1+ const [px, py] = quad(coordX, o0y, midx, midy, p.x, p.y, t)+ ctx.globalAlpha = 1+ ctx.shadowColor = color+ ctx.shadowBlur = 8+ ctx.fillStyle = color+ ctx.beginPath()+ ctx.arc(px, py, 2, 0, Math.PI * 2)+ ctx.fill()+ ctx.shadowBlur = 0+ }+ }+ })+ ctx.globalAlpha = 1++ // Cell ticks on the fan.+ st.forEach((cell, i) => {+ const p = pts[i]+ const color = PALETTE[cellColor(cell)]+ const active = cellActive(cell)+ const flash = active ? 0.6 + 0.4 * Math.sin(frame * 0.08 + sd[i] * 6.28) : 0.55+ const inner = arcR - 5+ const outer = arcR + (active ? 14 : 6)+ const ix = arcCx - Math.cos(p.ang) * inner+ const iy = arcCy + Math.sin(p.ang) * inner+ const ox = arcCx - Math.cos(p.ang) * outer+ const oy = arcCy + Math.sin(p.ang) * outer+ ctx.strokeStyle = color+ ctx.globalAlpha = flash+ ctx.lineWidth = active ? 2.4 : 1.4+ if (active) {+ ctx.shadowColor = color+ ctx.shadowBlur = 8+ }+ ctx.beginPath()+ ctx.moveTo(ix, iy)+ ctx.lineTo(ox, oy)+ ctx.stroke()+ ctx.shadowBlur = 0+ })+ ctx.globalAlpha = 1++ // Return edges: settled, reportable cells → aggregator.+ st.forEach((cell, i) => {+ if (cell.finding?.disposition !== 'exposed' &&+ cell.finding?.disposition !== 'needs-review') return+ const p = pts[i]+ const color = PALETTE[cellColor(cell)]+ const mx = arcCx + width * 0.2+ const my = (p.y + aggY) / 2+ ctx.strokeStyle = color+ ctx.globalAlpha = 0.22+ ctx.lineWidth = 1.1+ ctx.beginPath()+ ctx.moveTo(p.x, p.y)+ ctx.quadraticCurveTo(mx, my, aggX, aggY)+ ctx.stroke()+ const t = (frame * 0.006 + sd[i]) % 1+ const [px, py] = quad(p.x, p.y, mx, my, aggX, aggY, t)+ ctx.globalAlpha = 1+ ctx.shadowColor = color+ ctx.shadowBlur = 8+ ctx.fillStyle = color+ ctx.beginPath()+ ctx.arc(px, py, 2, 0, Math.PI * 2)+ ctx.fill()+ ctx.shadowBlur = 0+ })+ ctx.globalAlpha = 1++ const live = ct.pending+ node(coordX, coordY, 'COORDINATOR',+ done ? `${n} dispatched` : `dispatch · ${live} live`, PALETTE.orange)+ const reportable = ct.exposed + ct['needs-review']+ node(aggX, aggY, 'AGGREGATOR',+ done ? `report · ${reportable} findings` : 'aggregating…', PALETTE.purple)++ raf = requestAnimationFrame(draw)+ }+ draw()++ return () => {+ cancelAnimationFrame(raf)+ ro.disconnect()+ }+ }, [])++ return (+ <div+ ref={containerRef}+ className="overflow-hidden rounded-lg border"+ style={{ background: PALETTE.bg }}+ >+ <canvas ref={canvasRef} className="block w-full" />+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-t border-white/10 px-4 py-2 font-mono text-[11px]">+ <LegendDot color={PALETTE.orange} label={`${counts.pending} running`} />+ <LegendDot color={PALETTE.red} label={`${counts.exposed} exposed`} />+ <LegendDot color={PALETTE.amber} label={`${counts['needs-review']} review`} />+ <LegendDot color={PALETTE.green} label={`${counts['not-exposed']} clear`} />+ {counts.failed > 0 ? (+ <LegendDot color={PALETTE.grey} label={`${counts.failed} failed`} />+ ) : null}+ <span className="ml-auto" style={{ color: PALETTE.ink }}>+ {settled ? 'run complete' : 'live'}+ </span>+ </div>+ </div>+ )+}++function LegendDot({ color, label }: { color: string; label: string }) {+ return (+ <span className="inline-flex items-center gap-1.5" style={{ color: '#c8cdd2' }}>+ <span+ className="inline-block size-2 rounded-full"+ style={{ background: color, boxShadow: `0 0 6px ${color}` }}+ />+ {label}+ </span>+ )+}diff --git a/web/src/managed-agents/security/catalog.test.ts b/web/src/managed-agents/security/catalog.test.tsindex cd8c5ed4..08f2a8f5 100644--- a/web/src/managed-agents/security/catalog.test.ts+++ b/web/src/managed-agents/security/catalog.test.ts@@ -4,6 +4,7 @@ import {cellDocumentId,composeCellPrompt,latestManifestId,+ listManifestDocs,parseCellFinding,parseRunManifest,runManifestDocumentId,@@ -151,6 +152,19 @@ describe('run manifest', () => {]),).toBeNull()})++ it('lists every manifest newest first, ignoring findings and report docs', () => {+ const docs = [+ { id: 'run-a__acme-web__cve-1', updatedAt: '2026-10-22T13:00:00Z' },+ { id: 'manifest__run-a', updatedAt: '2026-10-22T09:00:00Z' },+ { id: 'report__run-a', updatedAt: '2026-10-22T14:00:00Z' },+ { id: 'manifest__run-b', updatedAt: '2026-10-22T12:00:00Z' },+ ]+ expect(listManifestDocs(docs).map((d) => d.id)).toEqual([+ 'manifest__run-b',+ 'manifest__run-a',+ ])+ })})describe('run report', () => {diff --git a/web/src/managed-agents/security/catalog.ts b/web/src/managed-agents/security/catalog.tsindex 608079a7..c7ca0681 100644--- a/web/src/managed-agents/security/catalog.ts+++ b/web/src/managed-agents/security/catalog.ts@@ -194,10 +194,18 @@ export function parseRunManifest(text: string): SwarmRunManifest | null {export function latestManifestId(docs: readonly { id: string; updatedAt: string }[],): string | null {- const manifests = docs+ return listManifestDocs(docs)[0]?.id ?? null+}++// Every run manifest in a page of findings-resource documents, newest first.+// The Swarms index reads one row per manifest; cell findings and report docs+// (which share the resource) are filtered out by prefix.+export function listManifestDocs(+ docs: readonly { id: string; updatedAt: string }[],+): { id: string; updatedAt: string }[] {+ return docs.filter((doc) => doc.id.startsWith(SWARM_MANIFEST_PREFIX)).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))- return manifests[0]?.id ?? null}// One cell's first-run input: a single repository checked against a single CVE.diff --git a/web/src/managed-agents/security/useSwarmRun.ts b/web/src/managed-agents/security/useSwarmRun.tsnew file mode 100644index 00000000..45973c0e--- /dev/null+++ b/web/src/managed-agents/security/useSwarmRun.ts@@ -0,0 +1,205 @@+import { useEffect, useMemo, useRef } from 'react'+import { useQuery } from '@tanstack/react-query'+import {+ createManagedMemoryDocument,+ getManagedAgentSession,+ getManagedMemoryDocument,+} from '../api'+import {+ buildRunReport,+ cellDocumentId,+ parseCellFinding,+ runReportDocumentId,+ SECURITY_FINDINGS_RESOURCE,+ serializeRunReport,+ type CellFinding,+ type LaunchedCell,+ type ReportCell,+ type ReportDisposition,+ type SwarmCell,+ type SwarmRunReport,+} from './catalog'++// A cell can fail two ways: the whole session stops (status failed/cancelled),+// or — the common one — the session stays `idle` while its last turn is+// `failed` (a single-turn cell whose final generation errored). So we read the+// last turn's status, not just the session's.+export type SessionProgress = {+ status: string+ lastTurnStatus?: string+}++export type CellState = {+ cell: SwarmCell+ sessionId: string+ progress?: SessionProgress+ finding: CellFinding | null+}++export type CellPhase = 'done' | 'failed' | 'running' | 'queued'++export type SwarmCounts = {+ exposed: number+ 'not-exposed': number+ 'needs-review': number+ failed: number+ pending: number+}++function sessionFailed(progress: SessionProgress | undefined): boolean {+ if (!progress) return false+ if (progress.status === 'failed' || progress.status === 'cancelled')+ return true+ const turn = progress.lastTurnStatus+ return turn === 'failed' || turn === 'errored' || turn === 'cancelled'+}++// A cell is settled — we will never poll it again — when its verdict is saved+// or it failed, i.e. its phase is 'done' or 'failed'.+export function cellPhase(state: CellState): CellPhase {+ if (state.finding) return 'done'+ if (sessionFailed(state.progress)) return 'failed'+ const status = state.progress?.status+ if (status === 'running' || status === 'idle') return 'running'+ return 'queued'+}++export type SwarmRunData = {+ states: CellState[]+ counts: SwarmCounts+ settled: boolean+ report: SwarmRunReport | null+}++// Poll one run's sessions (for liveness) and each cell's findings document (for+// the verdict) until every cell settles, then roll the verdicts into the run+// report and persist it once. Both the grid and the map view consume this, so+// the run is polled once no matter which view is on screen.+export function useSwarmRun({+ projectId,+ runId,+ cells,+ target = '',+ model = '',+}: {+ projectId: string+ runId: string+ cells: readonly LaunchedCell[]+ target?: string+ model?: string+}): SwarmRunData {+ // Both polls stop the moment every cell has settled. We recompute that each+ // render and park it in a ref the two refetchInterval closures read, so+ // neither needs the other's query data.+ const allSettledRef = useRef(false)++ const sessions = useQuery({+ queryKey: ['swarm-sessions', projectId, runId],+ queryFn: async () => {+ const entries = await Promise.all(+ cells.map(async ({ sessionId }) => {+ const session = await getManagedAgentSession(sessionId)+ const turns = session.turns+ const lastTurnStatus =+ turns.length > 0 ? turns[turns.length - 1].status : undefined+ return [sessionId, { status: session.status, lastTurnStatus }] as const+ }),+ )+ return Object.fromEntries(entries)+ },+ refetchInterval: () => (allSettledRef.current ? false : 3_000),+ })++ const findings = useQuery({+ queryKey: ['swarm-findings', projectId, runId],+ queryFn: async () => {+ const entries = await Promise.all(+ cells.map(async ({ cell }) => {+ const read = await getManagedMemoryDocument({+ projectId,+ resource: SECURITY_FINDINGS_RESOURCE,+ environment: 'default',+ id: cellDocumentId(runId, cell),+ })+ return [+ cellDocumentId(runId, cell),+ parseCellFinding(read.document.text),+ ] as const+ }),+ )+ return Object.fromEntries(entries)+ },+ refetchInterval: () => (allSettledRef.current ? false : 4_000),+ })++ const progressBySession = useMemo(+ () => sessions.data ?? {},+ [sessions.data],+ )++ const states: CellState[] = cells.map(({ cell, sessionId }) => ({+ cell,+ sessionId,+ progress: progressBySession[sessionId],+ finding: findings.data?.[cellDocumentId(runId, cell)] ?? null,+ }))++ const counts: SwarmCounts = states.reduce(+ (acc, state) => {+ const phase = cellPhase(state)+ if (phase === 'done' && state.finding)+ acc[state.finding.disposition] += 1+ else if (phase === 'failed') acc.failed += 1+ else acc.pending += 1+ return acc+ },+ { exposed: 0, 'not-exposed': 0, 'needs-review': 0, failed: 0, pending: 0 },+ )+ const settled = counts.pending === 0++ useEffect(() => {+ allSettledRef.current = settled+ }, [settled])++ // Once every cell has settled, roll the verdicts into the run report — the+ // swarm's artifact — and persist it once (create-once, so a reload that+ // re-settles the same run is a no-op).+ const report: SwarmRunReport | null = settled+ ? buildRunReport(+ { runId, target, model, generatedAt: new Date().toISOString() },+ states.map((s): ReportCell => {+ const disposition: ReportDisposition = s.finding+ ? s.finding.disposition+ : 'failed'+ return {+ repository: s.cell.repository,+ cveId: s.cell.cveId,+ disposition,+ ...(s.finding?.reasoning ? { reasoning: s.finding.reasoning } : {}),+ ...(s.finding?.pullRequest+ ? { pullRequest: s.finding.pullRequest }+ : {}),+ }+ }),+ )+ : null++ const reportWrittenRef = useRef(false)+ useEffect(() => {+ if (!report || reportWrittenRef.current) return+ reportWrittenRef.current = true+ void createManagedMemoryDocument({+ projectId,+ resource: SECURITY_FINDINGS_RESOURCE,+ environment: 'default',+ id: runReportDocumentId(runId),+ title: `Swarm report ${runId}`,+ text: serializeRunReport(report),+ agentWrites: 'disabled',+ }).catch(() => {+ // Already written by an earlier view of this run — leave it be.+ })+ }, [report, projectId, runId])++ return { states, counts, settled, report }+}