// The /api/live protocol, shared by the route handler and the browser's live store. Types only and // pure helpers: safe to import from client components. import type { JobFileSnapshot, JobSnapshot, LogLine } from "@/lib/jobs"; import type { WorkerStatus } from "@/lib/worker-status"; export type LiveSnapshot = { worker: WorkerStatus; jobs: JobSnapshot[]; files: JobFileSnapshot[] }; /** `model`: jobs of one model; `job`: one job; neither: open and recently finished jobs. */ export type LiveQuery = { model?: string; job?: string }; /** `snapshot` is left out when it is the version the client already has (`v` in the request). */ export type LiveResponse = { v: string; snapshot?: LiveSnapshot; logs?: LogLine[] }; /** * The poll URL. `logAfter` (job queries only): log lines after that id, 0 for the last ones; leave it * out for no logs. `v`: the snapshot version the client has. */ export function liveUrl(query: LiveQuery, opts: { logAfter?: number | null; v?: string | null } = {}): string { const p = new URLSearchParams(); if (query.model) p.set("model", query.model); if (query.job) p.set("job", query.job); if (query.job && opts.logAfter != null) p.set("logAfter", String(opts.logAfter)); if (opts.v) p.set("v", opts.v); const qs = p.toString(); return qs ? `/api/live?${qs}` : "/api/live"; } /** * The response body, built around the already serialized snapshot so it isn't serialized twice. * `version` is a hash of `snapshotJson`. */ export function liveBody(snapshotJson: string, version: string, clientVersion: string | null, logs?: LogLine[]): string { let body = `{"v":${JSON.stringify(version)}`; if (clientVersion !== version) body += `,"snapshot":${snapshotJson}`; if (logs) body += `,"logs":${JSON.stringify(logs)}`; return `${body}}`; }