// Runs the whole pipeline off the main thread. Protocol: check -> load -> generate, with status/progress messages. // Generate requests are "latest wins": while one runs, newer requests replace each other, so live typing never builds // a backlog and the image always catches up with the newest prompt. import * as ort from "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.bundle.min.mjs"; import { HubFiles } from "./hub.js"; import { JeverationPipeline } from "./jeveration.js"; const MODEL_ID = "linoyts/Jeveration-int8-ONNX"; ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/"; ort.env.webgpu.powerPreference = "high-performance"; let pipe = null, busy = false, pending = null; const post = (m) => self.postMessage(m); async function check() { if (!navigator.gpu) throw new Error("WebGPU is not supported by this browser."); const adapter = await navigator.gpu.requestAdapter({ powerPreference: "high-performance" }); if (!adapter) throw new Error("WebGPU is not supported (no adapter found)."); if (!adapter.features.has("shader-f16")) throw new Error("This GPU does not support fp16 shaders (shader-f16), which this model needs."); const info = adapter.info ?? {}; return { vendor: info.vendor, architecture: info.architecture, maxBufferSize: adapter.limits.maxBufferSize }; } async function drain() { if (busy) return; busy = true; while (pending) { const req = pending; pending = null; try { const out = await pipe.generate(req.prompt, { seed: req.seed }); post({ status: "image", data: { rgb: out.rgb, timings: out.timings, seed: req.seed, prompt: req.prompt, id: req.id, skipped: req.skipped } }); } catch (e) { post({ status: "error", data: String(e?.message ?? e) }); } } busy = false; } let skipped = 0; self.onmessage = async ({ data: { type, data } }) => { try { if (type === "check") post({ status: "checked", data: await check() }); if (type === "load") { const t0 = performance.now(); pipe = await JeverationPipeline.load(new HubFiles(MODEL_ID, { cacheName: "jeveration-webgpu" }), { ort, device: "webgpu", progress: (e) => post(e), }); post({ status: "ready", data: { seconds: (performance.now() - t0) / 1000 } }); } if (type === "generate") { if (pending) skipped++; pending = { ...data, skipped }; drain(); } } catch (e) { post({ status: "error", data: String(e?.message ?? e) }); } };