import { withToken } from "@/lib/api-tokens"; import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1"; import { getJob, listJobFiles, listJobLogs } from "@/lib/jobs"; export const dynamic = "force-dynamic"; const MAX_LOG = 200; const NEXT: Record = { pending_approval: "Waiting for the user to approve it. Don't retry; check again in a few minutes.", queued: "Waiting for a free download slot.", downloading: "Downloading; check again in a minute.", verifying: "Checking the downloaded files.", completed: "Done.", failed: "Failed; see error. Tell the user; retrying the same request returns this job.", cancelled: "Cancelled or rejected by the user. Don't request it again unless the user asks.", interrupted: "Interrupted by a Kaname restart; the user can resume it.", }; /** Job state with per-file progress. The hf log only with ?log=N (last N lines, max 200). */ export const GET = withToken>("models:read", async (req, { params }) => { try { const id = (await params).id; const job = await getJob(id); if (!job) return v1Error(404, "not_found", "No job with this id."); const n = Math.min(MAX_LOG, Math.max(0, Number(new URL(req.url).searchParams.get("log")) || 0)); const files = await listJobFiles(id); const log = n > 0 ? (await listJobLogs(id, 0, n)).map((l) => `${new Date(l.ts).toISOString()} [${l.stream}] ${l.line}`) : undefined; return v1Json({ id: job.id, modelId: job.modelId, repoId: job.repoId, kind: job.kind, purpose: job.purpose, state: job.state, cancelRequested: job.cancelRequested, requestedBy: job.requestedBy, progress: { doneBytes: job.doneBytes, totalBytes: job.totalBytes, percent: job.totalBytes > 0 ? Math.round((job.doneBytes / job.totalBytes) * 1000) / 10 : 0, done: size(job.doneBytes), total: size(job.totalBytes), speedBytesPerSecond: job.speedBps, etaSeconds: job.etaSeconds, }, error: job.errorCode || job.errorMessage ? { code: job.errorCode, message: job.errorMessage } : null, files: files.map((f) => ({ path: f.path, state: f.state, doneBytes: f.doneBytes, totalBytes: f.expectedBytes })), createdAt: new Date(job.createdAt).toISOString(), startedAt: job.startedAt ? new Date(job.startedAt).toISOString() : null, finishedAt: job.finishedAt ? new Date(job.finishedAt).toISOString() : null, next: NEXT[job.state] ?? null, ...(log ? { log } : {}), }); } catch (err) { return v1Catch(err); } });