An open-source, faster Devin alternative
TypeScript
feat(security): instant swarm launch — navigate first, boot sandboxes in background
Mohamed Habib via Computer33d88c9d6697
diff --git a/web/src/managed-agents/security/ProjectSwarm.tsx b/web/src/managed-agents/security/ProjectSwarm.tsxindex 946abf0f..c87d1d16 100644--- a/web/src/managed-agents/security/ProjectSwarm.tsx+++ b/web/src/managed-agents/security/ProjectSwarm.tsx@@ -11,6 +11,7 @@ import {} from '../api'import {latestManifestId,+ manifestSettling,parseRunManifest,parseRunReport,runManifestDocumentId,@@ -58,6 +59,11 @@ export default function ProjectSwarm() {})return parseRunManifest(read.document.text)},+ // While cells are still booting the manifest is rewritten as each session id+ // lands; poll it so those ids reach the live view, then stop once every cell+ // has started (or failed to).+ refetchInterval: (query) =>+ query.state.data && manifestSettling(query.state.data) ? 2_500 : false,})return (diff --git a/web/src/managed-agents/security/SecurityOnboarding.tsx b/web/src/managed-agents/security/SecurityOnboarding.tsxindex d559e65c..6a8865c2 100644--- a/web/src/managed-agents/security/SecurityOnboarding.tsx+++ b/web/src/managed-agents/security/SecurityOnboarding.tsx@@ -31,6 +31,7 @@ import {getManagedTemplateInstallation,inspectManagedTemplate,putAgentRuntimeVariable,+ replaceManagedMemoryDocument,startManagedAgentSession,} from '../api'import { installedTemplateAgentId } from '../template-continuation'@@ -47,6 +48,7 @@ import {serializeRunManifest,swarmCells,type LaunchedCell,+ type SwarmCell,type SwarmPayload,} from './catalog'@@ -58,6 +60,101 @@ const STEPS = ['Connect GitHub', 'Deploy swarm', 'Launch swarm'] as consttype DeployResult = { projectId: string; projectAgentId: string }+// Boot every cell's sandbox in the background, after the launch has already+// written the manifest and navigated. Each cell: create its findings document+// (a session can't bind to a missing one), start its session, then flip the+// cell to `started` with its id — or `failed`. The manifest is rewritten as each+// cell resolves, so the run page lights them up incrementally. We are the only+// writer of this document, so we just carry the latest etag forward; writes are+// coalesced so a burst of resolutions collapses into one trailing write.+async function launchCellsInBackground(args: {+ projectId: string+ runId: string+ agentId: string+ payload: SwarmPayload+ cells: SwarmCell[]+ manifestEtag: string+}) {+ const { projectId, runId, agentId, payload, cells } = args+ const launched: LaunchedCell[] = cells.map((cell) => ({+ cell,+ sessionId: '',+ launch: 'starting',+ }))+ const docTarget = {+ projectId,+ resource: SECURITY_FINDINGS_RESOURCE,+ environment: 'default' as const,+ id: runManifestDocumentId(runId),+ }++ let etag = args.manifestEtag+ let writing = false+ let dirty = false+ const flush = async () => {+ if (writing) {+ dirty = true+ return+ }+ writing = true+ try {+ do {+ dirty = false+ const res = await replaceManagedMemoryDocument({+ ...docTarget,+ etag,+ text: serializeRunManifest({+ runId,+ model: payload.model,+ target: payload.target,+ cells: launched,+ }),+ })+ etag = res.etag+ } while (dirty)+ } catch {+ // Best-effort: a dropped manifest write only delays a cell lighting up on+ // the run page; its agent work is already running.+ } finally {+ writing = false+ }+ }++ await Promise.all(+ cells.map(async (cell, i) => {+ try {+ const id = cellDocumentId(runId, cell)+ await createManagedMemoryDocument({+ projectId,+ resource: SECURITY_FINDINGS_RESOURCE,+ environment: 'default',+ id,+ title: `${cell.repository} · ${cell.cveId}`,+ text: '{}',+ })+ const { sessionId } = await startManagedAgentSession(+ agentId,+ composeCellPrompt(payload, cell),+ {+ memory: {+ [SECURITY_FINDINGS_RESOURCE]: {+ scope: 'document',+ id,+ access: 'read-write',+ },+ },+ },+ )+ launched[i] = { cell, sessionId, launch: 'started' }+ } catch {+ launched[i] = { cell, sessionId: '', launch: 'failed' }+ }+ await flush()+ }),+ )+ await flush()+}+async function waitForInstallation(id: string) {const deadline = Date.now() + 10 * 60_000let installation = await getManagedTemplateInstallation(id)@@ -166,15 +263,23 @@ export default function SecurityOnboarding() {})// Launch fans the payload's repository × CVE matrix out into one bound session- // per cell. Each cell gets its own findings document, created first (a binding- // to a missing document fails admission), then a session bound read-write to- // it. The session ids are recorded in a run manifest document so the swarm- // page can rebuild the grid after we navigate to it — the ids don't survive in- // React state across the route change.+ // per cell. The slow part is booting each cell's sandbox, so we don't block the+ // UI on it: we write the run manifest immediately with every cell `starting`,+ // navigate to the run page, then boot the sandboxes in the background (see+ // launchCellsInBackground), flipping each cell to `started` with its session id+ // as it comes up. The manifest is the source of truth across the route change —+ // the ids don't survive in React state.const launch = useMutation({mutationFn: async (payload: SwarmPayload,- ): Promise<{ projectId: string; runId: string }> => {+ ): Promise<{+ projectId: string+ runId: string+ agentId: string+ payload: SwarmPayload+ cells: SwarmCell[]+ manifestEtag: string+ }> => {if (!deployed) throw new Error('Deploy the swarm before launching.')const cells = swarmCells(payload)if (cells.length === 0) {@@ -187,36 +292,14 @@ export default function SecurityOnboarding() {}const runId = `run-${crypto.randomUUID()}`const agentId = `${deployed.projectAgentId}@default`- const launched = await Promise.all(- cells.map(async (cell): Promise<LaunchedCell> => {- const id = cellDocumentId(runId, cell)- await createManagedMemoryDocument({- projectId: deployed.projectId,- resource: SECURITY_FINDINGS_RESOURCE,- environment: 'default',- id,- title: `${cell.repository} · ${cell.cveId}`,- text: '{}',- })- const { sessionId } = await startManagedAgentSession(- agentId,- composeCellPrompt(payload, cell),- {- memory: {- [SECURITY_FINDINGS_RESOURCE]: {- scope: 'document',- id,- access: 'read-write',- },- },- },- )- return { cell, sessionId }- }),- )- // Persist the run so the swarm page is reachable by URL and survives a- // reload. agentWrites stays disabled — only cell findings are agent-owned.- await createManagedMemoryDocument({+ const starting: LaunchedCell[] = cells.map((cell) => ({+ cell,+ sessionId: '',+ launch: 'starting',+ }))+ // One fast write makes the run reachable by URL; agentWrites stays disabled+ // — only cell findings are agent-owned.+ const created = await createManagedMemoryDocument({projectId: deployed.projectId,resource: SECURITY_FINDINGS_RESOURCE,environment: 'default',@@ -226,16 +309,34 @@ export default function SecurityOnboarding() {runId,model: payload.model,target: payload.target,- cells: launched,+ cells: starting,}),agentWrites: 'disabled',})- return { projectId: deployed.projectId, runId }+ return {+ projectId: deployed.projectId,+ runId,+ agentId,+ payload,+ cells,+ manifestEtag: created.etag,+ }},- onSuccess: ({ projectId, runId }) =>- navigate(+ onSuccess: ({ projectId, runId, agentId, payload, cells, manifestEtag }) => {+ void navigate(`/projects/${encodeURIComponent(projectId)}/swarms/${encodeURIComponent(runId)}`,- ),+ )+ // Fire-and-forget: this outlives the unmount on navigation, booting the+ // sandboxes and filling the manifest as they come up.+ void launchCellsInBackground({+ projectId,+ runId,+ agentId,+ payload,+ cells,+ manifestEtag,+ })+ },onError: (error) => notifyError("Couldn't start the swarm.", error),})diff --git a/web/src/managed-agents/security/SwarmGrid.tsx b/web/src/managed-agents/security/SwarmGrid.tsxindex 5923f541..3007b120 100644--- a/web/src/managed-agents/security/SwarmGrid.tsx+++ b/web/src/managed-agents/security/SwarmGrid.tsx@@ -263,13 +263,15 @@ function CellTile({</p>) : null}<div className="mt-2 flex items-center gap-3">- <Link- to={`/projects/${encodeURIComponent(projectId)}/sessions/${encodeURIComponent(state.sessionId)}`}- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs hover:underline"- >- <ArrowUpRight className="size-3" />- Open session- </Link>+ {state.sessionId ? (+ <Link+ to={`/projects/${encodeURIComponent(projectId)}/sessions/${encodeURIComponent(state.sessionId)}`}+ className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs hover:underline"+ >+ <ArrowUpRight className="size-3" />+ Open session+ </Link>+ ) : null}{state.finding?.pullRequest ? (<ahref={state.finding.pullRequest}@@ -315,10 +317,12 @@ function CellBadge({</span>)}+ const label =+ phase === 'running' ? 'Running' : phase === 'starting' ? 'Starting…' : 'Queued'return (<span className="text-muted-foreground inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs"><Loader2 className="size-3 animate-spin" />- {phase === 'running' ? 'Running' : 'Queued'}+ {label}</span>)}diff --git a/web/src/managed-agents/security/SwarmMap.tsx b/web/src/managed-agents/security/SwarmMap.tsxindex ee47d9e6..8dcc3ba4 100644--- a/web/src/managed-agents/security/SwarmMap.tsx+++ b/web/src/managed-agents/security/SwarmMap.tsx@@ -16,7 +16,7 @@ function cellColor(state: CellState): CellColor {const phase = cellPhase(state)if (phase === 'failed') return 'grey'if (phase === 'running') return 'orange'- if (phase === 'queued') return 'grey'+ if (phase === 'queued' || phase === 'starting') return 'grey'const d = state.finding?.dispositionif (d === 'exposed') return 'red'if (d === 'needs-review') return 'amber'diff --git a/web/src/managed-agents/security/SwarmPanels.tsx b/web/src/managed-agents/security/SwarmPanels.tsxindex 3ddc2c29..0fbaf470 100644--- a/web/src/managed-agents/security/SwarmPanels.tsx+++ b/web/src/managed-agents/security/SwarmPanels.tsx@@ -10,6 +10,7 @@ import { cellPhase, type CellState, type SwarmCounts } from './useSwarmRun'// A cell's status word + color, shared by the feed and the dispatch list.function cellStatus(state: CellState): { label: string; color: string } {const phase = cellPhase(state)+ if (phase === 'starting') return { label: 'starting', color: PALETTE.ink }if (phase === 'running') return { label: 'running', color: PALETTE.orange }if (phase === 'queued') return { label: 'queued', color: PALETTE.grey }if (phase === 'failed') return { label: 'failed', color: PALETTE.red }diff --git a/web/src/managed-agents/security/catalog.test.ts b/web/src/managed-agents/security/catalog.test.tsindex 08f2a8f5..5015388f 100644--- a/web/src/managed-agents/security/catalog.test.ts+++ b/web/src/managed-agents/security/catalog.test.ts@@ -5,6 +5,7 @@ import {composeCellPrompt,latestManifestId,listManifestDocs,+ manifestSettling,parseCellFinding,parseRunManifest,runManifestDocumentId,@@ -109,8 +110,16 @@ describe('run manifest', () => {model: 'GLM-5.3',target: 'https://app.example.com',cells: [- { cell: { repository: 'acme/web', cveId: 'CVE-2026-1' }, sessionId: 's1' },- { cell: { repository: 'acme/api', cveId: 'CVE-2026-1' }, sessionId: 's2' },+ {+ cell: { repository: 'acme/web', cveId: 'CVE-2026-1' },+ sessionId: 's1',+ launch: 'started',+ },+ {+ cell: { repository: 'acme/api', cveId: 'CVE-2026-1' },+ sessionId: 's2',+ launch: 'started',+ },],}@@ -125,6 +134,40 @@ describe('run manifest', () => {expect(parseRunManifest(serializeRunManifest(manifest))).toEqual(manifest)})+ it('defaults launch for a pre-incremental manifest: started with an id, else starting', () => {+ const parsed = parseRunManifest(+ JSON.stringify({+ runId: 'run-old',+ cells: [+ { cell: { repository: 'a/b', cveId: 'CVE-1' }, sessionId: 's1' },+ { cell: { repository: 'a/c', cveId: 'CVE-1' }, sessionId: '' },+ ],+ }),+ )+ expect(parsed?.cells.map((c) => c.launch)).toEqual(['started', 'starting'])+ })++ it('is settling while any cell is still starting, and not once all have an outcome', () => {+ const starting: SwarmRunManifest = {+ ...manifest,+ cells: [+ { ...manifest.cells[0], sessionId: '', launch: 'starting' },+ manifest.cells[1],+ ],+ }+ expect(manifestSettling(starting)).toBe(true)+ expect(manifestSettling(manifest)).toBe(false)+ expect(+ manifestSettling({+ ...manifest,+ cells: [+ { ...manifest.cells[0], sessionId: '', launch: 'failed' },+ manifest.cells[1],+ ],+ }),+ ).toBe(false)+ })+it('rejects malformed or empty manifests', () => {expect(parseRunManifest('not json')).toBeNull()expect(parseRunManifest('{}')).toBeNull()diff --git a/web/src/managed-agents/security/catalog.ts b/web/src/managed-agents/security/catalog.tsindex 08a99fad..369729a5 100644--- a/web/src/managed-agents/security/catalog.ts+++ b/web/src/managed-agents/security/catalog.ts@@ -87,12 +87,21 @@ export type SwarmCell = {readonly cveId: string}-// A cell once its session has been started: the launch pairs each cell with the-// session id `startManagedAgentSession` returns, so the grid can poll that-// session's liveness directly instead of discovering it by label.+// Where a cell is in the launch itself, before any agent work. The launch writes+// the manifest instantly with every cell `starting`, navigates, then boots the+// sandboxes in the background and flips each to `started` (with its session id)+// or `failed` as it resolves. So the run page is reachable in one write instead+// of blocking on every sandbox.+export type CellLaunchStatus = 'starting' | 'started' | 'failed'++// A cell in the run manifest: paired with the session id+// `startManagedAgentSession` returns once it is booted, so the grid can poll that+// session's liveness directly instead of discovering it by label. `sessionId` is+// empty until the cell reaches `started`.export type LaunchedCell = {readonly cell: SwarmCellreadonly sessionId: string+ readonly launch: CellLaunchStatus}// Expand the payload into the matrix of cells. Fan-out needs explicit@@ -174,9 +183,18 @@ export function parseRunManifest(text: string): SwarmRunManifest | null {) {return null}+ // Back-compat: a manifest written before incremental launch has no `launch`+ // field — a cell there with a session id is already `started`.+ const launch: CellLaunchStatus =+ e.launch === 'starting' || e.launch === 'started' || e.launch === 'failed'+ ? e.launch+ : e.sessionId+ ? 'started'+ : 'starting'cells.push({cell: { repository: cell.repository, cveId: cell.cveId },sessionId: e.sessionId,+ launch,})}if (cells.length === 0) return null@@ -188,6 +206,13 @@ export function parseRunManifest(text: string): SwarmRunManifest | null {}}+// True while any cell is still booting its sandbox — the run page keeps polling+// the manifest until every cell has started or failed, so session ids appear as+// they come up.+export function manifestSettling(manifest: SwarmRunManifest): boolean {+ return manifest.cells.some((c) => c.launch === 'starting')+}+// From a page of findings-resource documents, the id of the most recently// updated run manifest — the run the swarm page shows by default. Null when no// swarm has run in the project yet.diff --git a/web/src/managed-agents/security/useSwarmRun.ts b/web/src/managed-agents/security/useSwarmRun.tsindex 4eef1f06..7227272e 100644--- a/web/src/managed-agents/security/useSwarmRun.ts+++ b/web/src/managed-agents/security/useSwarmRun.ts@@ -13,6 +13,7 @@ import {SECURITY_FINDINGS_RESOURCE,serializeRunReport,type CellFinding,+ type CellLaunchStatus,type LaunchedCell,type ReportCell,type ReportDisposition,@@ -32,12 +33,13 @@ export type SessionProgress = {export type CellState = {cell: SwarmCellsessionId: string+ launch: CellLaunchStatusprogress?: SessionProgressfinding: CellFinding | nullphase: CellPhase}-export type CellPhase = 'done' | 'failed' | 'running' | 'queued'+export type CellPhase = 'done' | 'failed' | 'running' | 'queued' | 'starting'export type SwarmCounts = {exposed: number@@ -62,12 +64,17 @@ function turnCompleted(progress: SessionProgress | undefined): boolean {return progress?.lastTurnStatus === 'completed'}-// A cell's session is terminal when it will do no more work: it failed, or its-// turn completed (whether or not it left a finding).+// A cell's session is terminal when it will do no more work: its launch failed,+// its session failed, or its turn completed (whether or not it left a finding).+// A cell still `starting` (its sandbox is booting, no session id yet) is never+// terminal — the run keeps polling the manifest until it comes up.function cellTerminal(progress: SessionProgress | undefined,finding: CellFinding | null,+ launch: CellLaunchStatus,): boolean {+ if (launch === 'failed') return true+ if (launch === 'starting') return falsereturn finding != null || sessionFailed(progress) || turnCompleted(progress)}@@ -78,8 +85,11 @@ function computeCellPhase(progress: SessionProgress | undefined,finding: CellFinding | null,confirmed: boolean,+ launch: CellLaunchStatus,): CellPhase {if (finding) return 'done'+ if (launch === 'failed') return 'failed'+ if (launch === 'starting') return 'starting'if (sessionFailed(progress)) return 'failed'if (turnCompleted(progress)) return confirmed ? 'failed' : 'running'const status = progress?.status@@ -124,6 +134,7 @@ export function statesFromReport(report: SwarmRunReport): {const states: CellState[] = report.cells.map((c) => ({cell: { repository: c.repository, cveId: c.cveId },sessionId: c.sessionId ?? '',+ launch: c.disposition === 'failed' ? 'failed' : 'started',finding:c.disposition === 'failed'? null@@ -165,8 +176,10 @@ export function useSwarmRun({const sessions = useQuery({queryKey: ['swarm-sessions', projectId, runId],queryFn: async () => {+ // A cell still booting has no session id yet; poll only the started ones.+ const started = cells.filter((c) => c.sessionId)const entries = await Promise.all(- cells.map(async ({ sessionId }) => {+ started.map(async ({ sessionId }) => {const session = await getManagedAgentSession(sessionId)const turns = session.turnsconst lastTurnStatus =@@ -184,16 +197,20 @@ export function useSwarmRun({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+ const id = cellDocumentId(runId, cell)+ try {+ const read = await getManagedMemoryDocument({+ projectId,+ resource: SECURITY_FINDINGS_RESOURCE,+ environment: 'default',+ id,+ })+ return [id, parseCellFinding(read.document.text)] as const+ } catch {+ // A cell still booting hasn't had its findings document created yet;+ // treat it as having no finding rather than failing the whole poll.+ return [id, null] as const+ }}),)return Object.fromEntries(entries)@@ -206,10 +223,11 @@ export function useSwarmRun({[sessions.data],)- const base = cells.map(({ cell, sessionId }) => ({+ const base = cells.map(({ cell, sessionId, launch }) => ({cell,sessionId,- progress: progressBySession[sessionId],+ launch,+ progress: sessionId ? progressBySession[sessionId] : undefined,finding: findings.data?.[cellDocumentId(runId, cell)] ?? null,}))@@ -221,13 +239,14 @@ export function useSwarmRun({// before its turn completed. Both timestamps are plain query values, read in// render; the stop flags are the only refs, written in effects.const allTerminal =- base.length > 0 && base.every((s) => cellTerminal(s.progress, s.finding))+ base.length > 0 &&+ base.every((s) => cellTerminal(s.progress, s.finding, s.launch))const confirmed =allTerminal && findings.dataUpdatedAt >= sessions.dataUpdatedAtconst states: CellState[] = base.map((s) => ({...s,- phase: computeCellPhase(s.progress, s.finding, confirmed),+ phase: computeCellPhase(s.progress, s.finding, confirmed, s.launch),}))const counts = tallyCounts(states)