import { NextRequest } from 'next/server'; import { appendRunLog, finishRun, getRun } from '@/lib/db'; import { corsJson, corsPreflight } from '../../cors'; interface ProgressBody { id?: unknown; stepIndex?: unknown; step?: unknown; ok?: unknown; detail?: unknown; /** Present only on the final call. */ finish?: unknown; error?: unknown; } /** The runner reports each step, then a final finish. */ export async function POST(req: NextRequest) { try { const body = await req.json() as ProgressBody; const id = Number(body.id); const row = getRun(id); if (!row) return corsJson({ error: 'No such run' }, { status: 404 }); if (typeof body.step === 'string') { appendRunLog(id, { at: Date.now(), step: body.step, ok: body.ok !== false, detail: typeof body.detail === 'string' ? body.detail : undefined, }, Number(body.stepIndex) || row.step_index); } if (body.finish === true) { const error = typeof body.error === 'string' && body.error ? body.error : null; finishRun(id, error ? 'error' : 'done', error); } // The runner reads this to notice the Stop button between steps. const now = getRun(id); return corsJson({ ok: true, status: now?.status ?? 'error' }); } catch (err: any) { return corsJson({ error: err?.message ?? 'Failed to record progress' }, { status: 500 }); } } export async function OPTIONS() { return corsPreflight(); }