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); }); });