diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a17a8b..9270807 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of step 1 (Hugging Face downloader) is released as a minor version. +## [Unreleased] + +### Fixed + +- **Several open tabs no longer stall Kaname.** Every tab with live progress kept one or two + connections open, and over plain HTTP a browser allows six per server: the third tab loaded + slowly and a fourth not at all. Live updates are now short requests, one poller per tab shared by + everything on the page, paused while the tab is in the background. The server also no longer + grows in memory while a tab stays open, and an idle page no longer redraws every 5 seconds. + ## [0.16.0] - 2026-10-30 A new look, a search for everything (⌘K / Ctrl+K), removing single files, and an easier deployment diff --git a/README.md b/README.md index b4069bd..4394e7c 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,8 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname Three containers from the same image; web and worker share one SQLite database: -- **web:** Next.js UI and API, OIDC login (Auth.js); live updates via Server-Sent Events. +- **web:** Next.js UI and API, OIDC login (Auth.js); live updates by polling once a second from + the visible tab (paused in background tabs, so any number of tabs can stay open). - **worker:** runs the download queue, spawns `hf download --revision --include `, and measures progress from bytes on disk; runs benchmarks against endpoints (BetterBench, the quality eval). Only one worker runs at a time. diff --git a/src/app/api/live/route.ts b/src/app/api/live/route.ts new file mode 100644 index 0000000..a6d9506 --- /dev/null +++ b/src/app/api/live/route.ts @@ -0,0 +1,43 @@ +import { createHash } from "node:crypto"; +import { withAuth } from "@/lib/api-auth"; +import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs"; +import { liveBody, type LiveSnapshot } from "@/lib/live-protocol"; +import { getWorkerStatus } from "@/lib/worker-status"; + +export const dynamic = "force-dynamic"; + +/** + * Live job state, polled by the browser about once per second while the tab is visible (one poller + * per query and tab, see src/lib/live-store.ts). Short requests instead of a stream per component: + * over HTTP/1.1 a browser allows 6 connections per host, and open streams used them up. + * ?model= jobs of one model (+ files of its newest job) + * ?job= one job with per-file progress; with &logAfter= also the log lines after + * that id (0: the last 1000) + * (none) open and recently finished jobs (library view) + * &v= the snapshot version the client has; an unchanged snapshot is left out + */ +export const GET = withAuth(async (req) => { + const sp = new URL(req.url).searchParams; + const modelId = sp.get("model"); + const jobId = sp.get("job"); + const json = JSON.stringify(await buildSnapshot(modelId, jobId)); + const version = createHash("sha1").update(json).digest("base64url").slice(0, 16); + const logs = jobId && sp.has("logAfter") ? await listJobLogs(jobId, Number(sp.get("logAfter")) || 0) : undefined; + return new Response(liveBody(json, version, sp.get("v"), logs), { + headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }, + }); +}); + +async function buildSnapshot(modelId: string | null, jobId: string | null): Promise { + const worker = await getWorkerStatus(); + if (jobId) { + const job = await getJob(jobId); + return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] }; + } + if (modelId) { + const jobs = await listModelJobs(modelId); + const files = jobs[0] ? await listJobFiles(jobs[0].id) : []; + return { worker, jobs, files }; + } + return { worker, jobs: await listLiveJobs(), files: [] }; +} diff --git a/src/app/api/stream/route.ts b/src/app/api/stream/route.ts deleted file mode 100644 index 7fe7e55..0000000 --- a/src/app/api/stream/route.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { withAuth } from "@/lib/api-auth"; -import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs"; -import { getWorkerStatus } from "@/lib/worker-status"; - -export const dynamic = "force-dynamic"; - -const INTERVAL_MS = 1_000; -const KEEPALIVE_MS = 15_000; - -/** - * Server-Sent Events with live job state, polled from the DB once per second. - * ?model= jobs of one model (+ files of its newest job) - * ?job= one job with per-file progress and incremental log lines - * (none) open and recently finished jobs (library view) - * Events: "snapshot" (only when something changed) and "logs" (new lines). - */ -export const GET = withAuth(async (req) => { - const url = new URL(req.url); - const modelId = url.searchParams.get("model"); - const jobId = url.searchParams.get("job"); - let logCursor = Number(url.searchParams.get("logAfter") ?? 0) || 0; - - const encoder = new TextEncoder(); - const signal = req.signal; - - const stream = new ReadableStream({ - async start(controller) { - let last = ""; - let lastWrite = Date.now(); - const write = (chunk: string) => { - controller.enqueue(encoder.encode(chunk)); - lastWrite = Date.now(); - }; - const send = (event: string, data: unknown) => write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); - - try { - write("retry: 3000\n\n"); - while (!signal.aborted) { - const snapshot = await buildSnapshot(modelId, jobId); - const serialized = JSON.stringify(snapshot); - if (serialized !== last) { - send("snapshot", snapshot); - last = serialized; - } - if (jobId) { - const lines = await listJobLogs(jobId, logCursor); - if (lines.length > 0) { - logCursor = lines[lines.length - 1].id; - send("logs", lines); - } - } - if (Date.now() - lastWrite > KEEPALIVE_MS) write(": keepalive\n\n"); - await sleep(INTERVAL_MS, signal); - } - } catch { - // client went away or the stream was closed - } finally { - try { - controller.close(); - } catch {} - } - }, - }); - - return new Response(stream, { - headers: { - "Content-Type": "text/event-stream; charset=utf-8", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no", - }, - }); -}); - -async function buildSnapshot(modelId: string | null, jobId: string | null) { - const worker = await getWorkerStatus(); - if (jobId) { - const job = await getJob(jobId); - return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] }; - } - if (modelId) { - const jobs = await listModelJobs(modelId); - const files = jobs[0] ? await listJobFiles(jobs[0].id) : []; - return { worker, jobs, files }; - } - return { worker, jobs: await listLiveJobs(), files: [] }; -} - -function sleep(ms: number, signal: AbortSignal) { - return new Promise((resolve) => { - const t = setTimeout(resolve, ms); - signal.addEventListener("abort", () => { - clearTimeout(t); - resolve(); - }); - }); -} diff --git a/src/components/job-actions.ts b/src/components/job-actions.ts index dbd2a7a..871203c 100644 --- a/src/components/job-actions.ts +++ b/src/components/job-actions.ts @@ -1,10 +1,14 @@ "use client"; import { toast } from "sonner"; +import { pokeLive } from "@/lib/live-store"; async function post(url: string): Promise { const res = await fetch(url, { method: "POST" }); - if (res.ok) return true; + if (res.ok) { + pokeLive(); // show the new job state now instead of on the next poll + return true; + } const body = await res.json().catch(() => ({})); toast.error(body.error?.message ?? `Request failed (${res.status})`); return false; @@ -31,21 +35,3 @@ export async function startUpdate(modelId: string): Promise { if (ok) toast.success("Update queued"); return ok; } - -export async function approveJob(jobId: string): Promise { - const ok = await post(`/api/jobs/${jobId}/approve`); - if (ok) toast.success("Approved; the download is queued"); - return ok; -} - -/** Returns whether the model left the library (it was only added by this request), or null on error. */ -export async function rejectJob(jobId: string): Promise<{ removedModel: boolean } | null> { - const res = await fetch(`/api/jobs/${jobId}/reject`, { method: "POST" }); - const body = await res.json().catch(() => ({})); - if (!res.ok) { - toast.error(body.error?.message ?? `Request failed (${res.status})`); - return null; - } - toast.info(body.removedModel ? "Rejected; the model was removed from the library" : "Rejected"); - return body; -} diff --git a/src/components/worker-indicator.tsx b/src/components/worker-indicator.tsx index 94d76f6..4475184 100644 --- a/src/components/worker-indicator.tsx +++ b/src/components/worker-indicator.tsx @@ -1,25 +1,12 @@ "use client"; -import { useEffect, useState } from "react"; import { Badge } from "@/components/ui/badge"; +import { useWorkerStatus } from "@/hooks/use-live"; import type { WorkerStatus } from "@/lib/worker-status"; -/** Polls /api/status and shows whether the background worker is alive. */ +/** Shows whether the background worker is alive (from the page's live poll, or /api/status). */ export function WorkerIndicator({ initial }: { initial: WorkerStatus }) { - const [status, setStatus] = useState(initial); - - useEffect(() => { - const tick = async () => { - try { - const res = await fetch("/api/status", { cache: "no-store" }); - if (res.ok) setStatus((await res.json()).worker); - } catch { - // keep last known state - } - }; - const id = setInterval(tick, 10_000); - return () => clearInterval(id); - }, []); + const status = useWorkerStatus(initial); // Online: just a green dot (details on hover); offline stays spelled out. if (status.online) { diff --git a/src/hooks/use-live.ts b/src/hooks/use-live.ts index a714ee9..7f245b7 100644 --- a/src/hooks/use-live.ts +++ b/src/hooks/use-live.ts @@ -1,58 +1,33 @@ "use client"; import { useRouter } from "next/navigation"; -import { useEffect, useRef, useState } from "react"; -import type { JobFileSnapshot, JobSnapshot, LogLine } from "@/lib/jobs"; +import { useCallback, useSyncExternalStore } from "react"; +import type { LiveQuery } from "@/lib/live-protocol"; +import { EMPTY_LIVE, type LiveState, liveStore } from "@/lib/live-store"; import type { WorkerStatus } from "@/lib/worker-status"; -export type LiveSnapshot = { worker: WorkerStatus; jobs: JobSnapshot[]; files: JobFileSnapshot[] }; - -export const TERMINAL_STATES = ["completed", "failed", "cancelled", "interrupted"]; -const MAX_LOG_LINES = 5000; - /** - * Subscribe to /api/stream. Re-renders on every snapshot; refreshes server components - * (model status, library) when a job reaches a terminal state. + * Live job state for a query (see src/lib/live-store.ts). Components showing the same query share + * one poller. When a job reaches a terminal state, server components are refreshed (model status, + * library). */ -export function useLive(query: { model?: string; job?: string } = {}, withLogs = false) { +export function useLive(query: LiveQuery = {}, withLogs = false): LiveState { const router = useRouter(); - const [snapshot, setSnapshot] = useState(null); - const [logs, setLogs] = useState([]); - const [connected, setConnected] = useState(false); - const states = useRef(new Map()); + const { model, job } = query; + const subscribe = useCallback( + (listener: () => void) => liveStore().subscribe({ model, job }, withLogs, listener, () => router.refresh()), + [model, job, withLogs, router], + ); + const getSnapshot = useCallback(() => liveStore().get({ model, job }, withLogs), [model, job, withLogs]); + return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); +} - const params = new URLSearchParams(); - if (query.model) params.set("model", query.model); - if (query.job) params.set("job", query.job); - const url = `/api/stream${params.size ? `?${params}` : ""}`; +const getServerSnapshot = () => EMPTY_LIVE; +const subscribeWorker = (listener: () => void) => liveStore().subscribeWorker(listener); +const getWorker = () => liveStore().getWorker(); +const noWorker = () => null; - useEffect(() => { - const es = new EventSource(url); - es.onopen = () => setConnected(true); - es.onerror = () => setConnected(false); - es.addEventListener("snapshot", (e) => { - const snap = JSON.parse((e as MessageEvent).data) as LiveSnapshot; - let finished = false; - for (const j of snap.jobs) { - const prev = states.current.get(j.id); - if (prev && prev !== j.state && TERMINAL_STATES.includes(j.state)) finished = true; - states.current.set(j.id, j.state); - } - setSnapshot(snap); - if (finished) router.refresh(); - }); - if (withLogs) { - es.addEventListener("logs", (e) => { - const lines = JSON.parse((e as MessageEvent).data) as LogLine[]; - setLogs((prev) => { - const seen = prev.length ? prev[prev.length - 1].id : 0; - const merged = prev.concat(lines.filter((l) => l.id > seen)); - return merged.length > MAX_LOG_LINES ? merged.slice(-MAX_LOG_LINES) : merged; - }); - }); - } - return () => es.close(); - }, [url, withLogs, router]); - - return { snapshot, logs, connected }; +/** The worker status: from the live poll when one runs, otherwise /api/status every 10 s. */ +export function useWorkerStatus(initial: WorkerStatus): WorkerStatus { + return useSyncExternalStore(subscribeWorker, getWorker, noWorker) ?? initial; } diff --git a/src/lib/live-protocol.ts b/src/lib/live-protocol.ts new file mode 100644 index 0000000..ee310a9 --- /dev/null +++ b/src/lib/live-protocol.ts @@ -0,0 +1,38 @@ +// 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}}`; +} diff --git a/src/lib/live-store.test.ts b/src/lib/live-store.test.ts new file mode 100644 index 0000000..0717601 --- /dev/null +++ b/src/lib/live-store.test.ts @@ -0,0 +1,221 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import type { JobSnapshot } from "./jobs"; +import type { LiveResponse } from "./live-protocol"; +import { createLiveStore, EMPTY_LIVE, KEEP_MS, type LiveEnv, POLL_MS, RETRY_MS, STATUS_POLL_MS } from "./live-store"; + +const worker = { online: true, hfVersion: null, modelsDirFreeBytes: 1, modelsDirTotalBytes: 2 }; + +function job(id: string, state: string): JobSnapshot { + return { + id, + modelId: "m1", + repoId: "org/repo", + kind: "download", + purpose: null, + state, + attempt: 1, + totalBytes: 10, + doneBytes: 0, + speedBps: null, + etaSeconds: null, + exitCode: null, + errorCode: null, + errorMessage: null, + result: null, + cancelRequested: false, + createdAt: 0, + startedAt: null, + finishedAt: null, + }; +} + +const settle = () => new Promise((r) => setImmediate(r)); + +/** A fake browser: manual clock, scripted responses, visibility switch. */ +function fakeEnv() { + let now = 0; + let seq = 0; + const timers = new Map void }>(); + const calls: string[] = []; + const onVisible: (() => void)[] = []; + const state = { + visible: true, + fail: false, + respond: (url: string): unknown => (url.startsWith("/api/status") ? { worker } : ({ v: "1", snapshot: { worker, jobs: [], files: [] } } satisfies LiveResponse)), + }; + const env: LiveEnv = { + fetch: async (url) => { + calls.push(url); + if (state.fail) throw new Error("offline"); + return { ok: true, json: async () => state.respond(url) }; + }, + setTimeout: (fn, ms) => { + timers.set(++seq, { at: now + ms, fn }); + return seq; + }, + clearTimeout: (t) => void timers.delete(t as number), + visible: () => state.visible, + onVisible: (fn) => void onVisible.push(fn), + }; + return { + env, + calls, + state, + /** Runs timers that are due within `ms`, in order, letting each poll finish. */ + async advance(ms: number) { + const end = now + ms; + for (;;) { + await settle(); // let running polls finish and schedule their next one + const next = [...timers.entries()].filter(([, t]) => t.at <= end).sort((a, b) => a[1].at - b[1].at)[0]; + if (!next) break; + timers.delete(next[0]); + now = next[1].at; + next[1].fn(); + } + now = end; + }, + async show() { + state.visible = true; + onVisible.forEach((fn) => fn()); + await settle(); + }, + }; +} + +const live = (calls: string[]) => calls.filter((c) => c.startsWith("/api/live")); + +describe("live store", () => { + it("components showing the same query share one poller", async () => { + const f = fakeEnv(); + const store = createLiveStore(f.env); + let a = 0; + let b = 0; + store.subscribe({ model: "m1" }, false, () => a++); + store.subscribe({ model: "m1" }, false, () => b++); + await settle(); + assert.deepEqual(f.calls, ["/api/live?model=m1"]); + assert.equal(a, 1); + assert.equal(b, 1); + await f.advance(POLL_MS); + assert.equal(f.calls.length, 2); + }); + + it("an unchanged snapshot keeps the same state and wakes nobody", async () => { + const f = fakeEnv(); + const store = createLiveStore(f.env); + let renders = 0; + store.subscribe({}, false, () => renders++); + await settle(); + const first = store.get({}); + f.state.respond = () => ({ v: "1" }); + await f.advance(POLL_MS); + assert.equal(f.calls[1], "/api/live?v=1"); + assert.equal(store.get({}), first); + assert.equal(renders, 1); + }); + + it("pauses while the tab is hidden and polls at once when it is shown", async () => { + const f = fakeEnv(); + const store = createLiveStore(f.env); + store.subscribe({}, false, () => {}); + await settle(); + f.state.visible = false; + await f.advance(60_000); + assert.equal(f.calls.length, 1); + await f.show(); + assert.equal(f.calls.length, 2); + await f.advance(POLL_MS); + assert.equal(f.calls.length, 3); + }); + + it("follows the log with a cursor", async () => { + const f = fakeEnv(); + const store = createLiveStore(f.env); + const line = (id: number) => ({ id, ts: id, stream: "stdout", line: `line ${id}` }); + f.state.respond = () => ({ v: "1", snapshot: { worker, jobs: [], files: [] }, logs: [line(1), line(2)] }); + store.subscribe({ job: "j1" }, true, () => {}); + await settle(); + assert.equal(f.calls[0], "/api/live?job=j1&logAfter=0"); + f.state.respond = () => ({ v: "1", logs: [line(3)] }); + await f.advance(POLL_MS); + assert.equal(f.calls[1], "/api/live?job=j1&logAfter=2&v=1"); + assert.deepEqual( + store.get({ job: "j1" }, true).logs.map((l) => l.id), + [1, 2, 3], + ); + }); + + it("refreshes once when a job finishes, however many components show it", async () => { + const f = fakeEnv(); + const store = createLiveStore(f.env); + let refreshes = 0; + f.state.respond = () => ({ v: "a", snapshot: { worker, jobs: [job("j1", "downloading")], files: [] } }); + store.subscribe({}, false, () => {}, () => refreshes++); + store.subscribe({}, false, () => {}, () => refreshes++); + await settle(); + assert.equal(refreshes, 0); + f.state.respond = () => ({ v: "b", snapshot: { worker, jobs: [job("j1", "completed")], files: [] } }); + await f.advance(POLL_MS); + assert.equal(refreshes, 1); + }); + + it("stops when nothing shows the query and keeps its data for a moment", async () => { + const f = fakeEnv(); + const store = createLiveStore(f.env); + const off = store.subscribe({}, false, () => {}); + await settle(); + off(); + await f.advance(POLL_MS * 3); + assert.equal(f.calls.length, 1); + assert.notEqual(store.get({}), EMPTY_LIVE); + await f.advance(KEEP_MS); + assert.equal(store.get({}), EMPTY_LIVE); + }); + + it("backs off while requests fail", async () => { + const f = fakeEnv(); + const store = createLiveStore(f.env); + f.state.fail = true; + store.subscribe({}, false, () => {}); + await settle(); + await f.advance(RETRY_MS[0] - 1); + assert.equal(f.calls.length, 1); + await f.advance(1); + assert.equal(f.calls.length, 2); + await f.advance(RETRY_MS[1]); + assert.equal(f.calls.length, 3); + f.state.fail = false; + await f.advance(RETRY_MS[2]); + await f.advance(POLL_MS); + assert.equal(f.calls.length, 5); + }); + + it("takes the worker status from the live poll, else from /api/status every 10 s", async () => { + const f = fakeEnv(); + const store = createLiveStore(f.env); + store.subscribeWorker(() => {}); + await f.advance(STATUS_POLL_MS); + assert.deepEqual(f.calls, ["/api/status"]); + assert.deepEqual(store.getWorker(), worker); + const off = store.subscribe({}, false, () => {}); + await f.advance(STATUS_POLL_MS * 3); + assert.equal(f.calls.filter((c) => c === "/api/status").length, 1); + assert.ok(live(f.calls).length > 10); + off(); + await f.advance(STATUS_POLL_MS); + assert.equal(f.calls.filter((c) => c === "/api/status").length, 2); + }); + + it("poke polls every shown query at once", async () => { + const f = fakeEnv(); + const store = createLiveStore(f.env); + store.subscribe({ model: "m1" }, false, () => {}); + store.subscribe({ job: "j1" }, false, () => {}); + await settle(); + assert.equal(f.calls.length, 2); + store.poke(); + await settle(); + assert.equal(f.calls.length, 4); + }); +}); diff --git a/src/lib/live-store.ts b/src/lib/live-store.ts new file mode 100644 index 0000000..75ce56a --- /dev/null +++ b/src/lib/live-store.ts @@ -0,0 +1,269 @@ +// Live job state in the browser: one poller per query and tab, shared by every component that shows +// it (the library header and table, a model's download card and job history, …). Short requests to +// /api/live instead of a stream per component: over HTTP/1.1 a browser allows 6 connections per +// host, and open streams used them up after a few tabs. Polling pauses while the tab is hidden. +// +// The worker status rides along: components that only need it (the menu's worker dot) read it from +// whatever is polled; with nothing polled, /api/status is asked every 10 s. + +import type { LogLine } from "@/lib/jobs"; +import { type LiveQuery, type LiveResponse, type LiveSnapshot, liveUrl } from "@/lib/live-protocol"; +import type { WorkerStatus } from "@/lib/worker-status"; + +export type LiveState = { snapshot: LiveSnapshot | null; logs: LogLine[] }; + +export const TERMINAL_STATES = ["completed", "failed", "cancelled", "interrupted"]; +export const POLL_MS = 1_000; +export const STATUS_POLL_MS = 10_000; +/** After failed polls: wait this long before the next try (the last value repeats). */ +export const RETRY_MS = [3_000, 6_000, 12_000, 30_000]; +/** A query nobody shows any more keeps its data this long, so going back shows it at once. */ +export const KEEP_MS = 10_000; +const MAX_LOG_LINES = 5000; + +export const EMPTY_LIVE: LiveState = { snapshot: null, logs: [] }; + +/** What the store needs from the browser (injected so it can be tested without one). */ +export type LiveEnv = { + fetch: (url: string) => Promise<{ ok: boolean; json(): Promise }>; + setTimeout: (fn: () => void, ms: number) => unknown; + clearTimeout: (timer: unknown) => void; + visible: () => boolean; + /** Calls `fn` whenever the tab becomes visible again. */ + onVisible: (fn: () => void) => void; +}; + +type Listener = () => void; + +type Entry = { + query: LiveQuery; + withLogs: boolean; + state: LiveState; + /** Version of the snapshot in `state` (the server leaves an unchanged snapshot out). */ + version: string | null; + /** Id of the newest log line received. */ + logCursor: number; + listeners: Set; + /** Called (one of them) when a job of this query reaches a terminal state. */ + onFinish: Set<() => void>; + jobStates: Map; + timer: unknown; + inFlight: boolean; + /** A poll was asked for while one was running: run another right after it. */ + again: boolean; + failures: number; + dropTimer: unknown; +}; + +export function liveKey(query: LiveQuery, withLogs: boolean): string { + return `${query.model ?? ""}|${query.job ?? ""}|${withLogs ? 1 : 0}`; +} + +const sameWorker = (a: WorkerStatus, b: WorkerStatus) => + a.online === b.online && + a.hfVersion === b.hfVersion && + a.modelsDirFreeBytes === b.modelsDirFreeBytes && + a.modelsDirTotalBytes === b.modelsDirTotalBytes; + +export function createLiveStore(env: LiveEnv) { + const entries = new Map(); + let worker: WorkerStatus | null = null; + const workerListeners = new Set(); + let statusTimer: unknown = null; + let statusInFlight = false; + + const polling = () => [...entries.values()].some((e) => e.listeners.size > 0); + + function setWorker(next: WorkerStatus) { + if (worker && sameWorker(worker, next)) return; + worker = next; + for (const l of [...workerListeners]) l(); + } + + function schedule(e: Entry, ms: number) { + env.clearTimeout(e.timer); + e.timer = null; + // Hidden tab: nothing is scheduled; onVisible starts again. + if (e.listeners.size === 0 || !env.visible()) return; + e.timer = env.setTimeout(() => void poll(e), ms); + } + + async function poll(e: Entry): Promise { + env.clearTimeout(e.timer); + e.timer = null; + if (e.inFlight) { + e.again = true; + return; + } + if (e.listeners.size === 0 || !env.visible()) return; + e.inFlight = true; + let ok = false; + try { + const url = liveUrl(e.query, { v: e.version, logAfter: e.withLogs ? e.logCursor : null }); + const res = await env.fetch(url); + if (res.ok) { + apply(e, (await res.json()) as LiveResponse); + ok = true; + } + } catch { + // network error or a bad body: try again later + } + e.inFlight = false; + e.failures = ok ? 0 : e.failures + 1; + if (e.again) { + e.again = false; + return poll(e); + } + schedule(e, ok ? POLL_MS : RETRY_MS[Math.min(e.failures, RETRY_MS.length) - 1]); + } + + function apply(e: Entry, r: LiveResponse) { + let state = e.state; + let finished = false; + if (r.snapshot) { + e.version = r.v; + state = { ...state, snapshot: r.snapshot }; + for (const j of r.snapshot.jobs) { + const prev = e.jobStates.get(j.id); + if (prev && prev !== j.state && TERMINAL_STATES.includes(j.state)) finished = true; + e.jobStates.set(j.id, j.state); + } + setWorker(r.snapshot.worker); + } + if (r.logs && r.logs.length > 0) { + const seen = state.logs.length ? state.logs[state.logs.length - 1].id : 0; + const fresh = r.logs.filter((l) => l.id > seen); + if (fresh.length > 0) { + const merged = state.logs.concat(fresh); + state = { ...state, logs: merged.length > MAX_LOG_LINES ? merged.slice(-MAX_LOG_LINES) : merged }; + } + e.logCursor = Math.max(e.logCursor, r.logs[r.logs.length - 1].id); + } + if (state !== e.state) { + e.state = state; + for (const l of [...e.listeners]) l(); + } + // Every handler refreshes the same page; one is enough. + if (finished) [...e.onFinish][0]?.(); + } + + function scheduleStatus() { + if (statusTimer != null || statusInFlight || workerListeners.size === 0 || polling() || !env.visible()) return; + statusTimer = env.setTimeout(() => void pollStatus(), STATUS_POLL_MS); + } + + function stopStatus() { + env.clearTimeout(statusTimer); + statusTimer = null; + } + + async function pollStatus() { + statusTimer = null; + if (statusInFlight || workerListeners.size === 0 || polling() || !env.visible()) return; + statusInFlight = true; + try { + const res = await env.fetch("/api/status"); + if (res.ok) setWorker(((await res.json()) as { worker: WorkerStatus }).worker); + } catch { + // keep the last known status + } + statusInFlight = false; + scheduleStatus(); + } + + env.onVisible(() => { + for (const e of entries.values()) if (e.listeners.size > 0 && e.timer == null) void poll(e); + if (workerListeners.size > 0 && !polling() && statusTimer == null) void pollStatus(); + }); + + return { + /** Current state of a query (the same object until something changes). */ + get(query: LiveQuery, withLogs = false): LiveState { + return entries.get(liveKey(query, withLogs))?.state ?? EMPTY_LIVE; + }, + + subscribe(query: LiveQuery, withLogs: boolean, listener: Listener, onFinish?: () => void): () => void { + const key = liveKey(query, withLogs); + let e = entries.get(key); + if (!e) { + e = { + query: { model: query.model, job: query.job }, + withLogs, + state: EMPTY_LIVE, + version: null, + logCursor: 0, + listeners: new Set(), + onFinish: new Set(), + jobStates: new Map(), + timer: null, + inFlight: false, + again: false, + failures: 0, + dropTimer: null, + }; + entries.set(key, e); + } + const entry = e; + env.clearTimeout(entry.dropTimer); + entry.dropTimer = null; + entry.listeners.add(listener); + if (onFinish) entry.onFinish.add(onFinish); + stopStatus(); // the live snapshot carries the worker status now + if (entry.listeners.size === 1 && entry.timer == null && !entry.inFlight) void poll(entry); + + return () => { + entry.listeners.delete(listener); + if (onFinish) entry.onFinish.delete(onFinish); + if (entry.listeners.size > 0) return; + env.clearTimeout(entry.timer); + entry.timer = null; + entry.dropTimer = env.setTimeout(() => { + if (entry.listeners.size === 0 && entries.get(key) === entry) entries.delete(key); + }, KEEP_MS); + scheduleStatus(); + }; + }, + + /** Latest worker status seen (from a live snapshot or /api/status), null until there is one. */ + getWorker(): WorkerStatus | null { + return worker; + }, + + subscribeWorker(listener: Listener): () => void { + workerListeners.add(listener); + scheduleStatus(); + return () => { + workerListeners.delete(listener); + if (workerListeners.size === 0) stopStatus(); + }; + }, + + /** Poll every shown query now (after starting or cancelling a job, for instant feedback). */ + poke() { + for (const e of entries.values()) if (e.listeners.size > 0) void poll(e); + }, + }; +} + +export type LiveStore = ReturnType; + +let store: LiveStore | null = null; + +/** The tab's store, created on first use (never on the server). */ +export function liveStore(): LiveStore { + return (store ??= createLiveStore({ + fetch: (url) => fetch(url, { cache: "no-store" }), + setTimeout: (fn, ms) => window.setTimeout(fn, ms), + clearTimeout: (t) => window.clearTimeout(t as number | undefined), + visible: () => document.visibilityState === "visible", + onVisible: (fn) => + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") fn(); + }), + })); +} + +/** Poll now, if anything is shown (no-op on the server). */ +export function pokeLive() { + if (typeof window !== "undefined" && store) store.poke(); +} diff --git a/src/lib/worker-status.ts b/src/lib/worker-status.ts index 025d63f..2be379f 100644 --- a/src/lib/worker-status.ts +++ b/src/lib/worker-status.ts @@ -5,33 +5,38 @@ import { workerState } from "@/lib/db/schema"; /** The worker writes a heartbeat every 5s; after this long without one we call it offline. */ const OFFLINE_AFTER_MS = 20_000; +const MIB = 1024 * 1024; +/** + * What the UI shows about the worker. No heartbeat time on purpose: it changes every 5 s, and the + * live snapshot (see /api/live) would then change every 5 s even when nothing else did. + */ export type WorkerStatus = { online: boolean; - heartbeatAt: string | null; hfVersion: string | null; + /** Free/total bytes of the models folder, rounded to whole MiB for the same reason. */ modelsDirFreeBytes: number | null; modelsDirTotalBytes: number | null; }; const OFFLINE: WorkerStatus = { online: false, - heartbeatAt: null, hfVersion: null, modelsDirFreeBytes: null, modelsDirTotalBytes: null, }; +const toMiB = (bytes: number | null) => (bytes == null ? null : Math.round(bytes / MIB) * MIB); + export async function getWorkerStatus(): Promise { try { const row = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") }); if (!row) return OFFLINE; return { online: Date.now() - row.heartbeatAt.getTime() < OFFLINE_AFTER_MS, - heartbeatAt: row.heartbeatAt.toISOString(), hfVersion: row.hfVersion, - modelsDirFreeBytes: row.modelsDirFreeBytes, - modelsDirTotalBytes: row.modelsDirTotalBytes, + modelsDirFreeBytes: toMiB(row.modelsDirFreeBytes), + modelsDirTotalBytes: toMiB(row.modelsDirTotalBytes), }; } catch { // Table missing (worker never ran migrations yet) or DB unavailable.