Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
web: typed client for /v1/images/generations and model capabilities
JustVugg01e9a2d029de
diff --git a/web/src/lib/api.test.ts b/web/src/lib/api.test.tsindex 97ae2ebf..a5348cda 100644--- a/web/src/lib/api.test.ts+++ b/web/src/lib/api.test.ts@@ -1,6 +1,9 @@import { afterEach, describe, expect, it, vi } from "vitest"-import { askBrio, extractSSE, getHealth, getProfile, serverEndpoint, streamChat } from "./api"+import {+ askBrio, extractSSE, extractSSEEvents, generateImage, generatesImages, getHealth, getProfile,+ listModelInfo, serverEndpoint, streamChat, type GenerateImageOptions, type ImageProgress,+} from "./api"afterEach(() => vi.unstubAllGlobals())@@ -146,3 +149,205 @@ describe("askBrio", () => {.rejects.toThrow("options must be a non-empty array")})})++describe("extractSSEEvents", () => {+ it("keeps the event name of each frame and defaults to message", () => {+ const parsed = extractSSEEvents(+ 'event: image_generation.progress\ndata: {"stage":"encode"}\n\n'+ + "data: [DONE]\n\n"+ + "event: image_generation.completed\ndata: {\"cre")+ expect(parsed.events).toEqual([+ { event: "image_generation.progress", data: '{"stage":"encode"}' },+ { event: "message", data: "[DONE]" },+ ])+ expect(parsed.rest).toBe('event: image_generation.completed\ndata: {"cre')+ })++ it("skips comments and empty frames, joins multi-line data, accepts CRLF", () => {+ const parsed = extractSSEEvents(": keepalive\r\n\r\nevent: x\r\ndata: a\r\ndata: b\r\n\r\nevent: lonely\r\n\r\n")+ expect(parsed.events).toEqual([{ event: "x", data: "a\nb" }])+ expect(parsed.rest).toBe("")+ })+})++describe("model capabilities", () => {+ it("reads capabilities from /v1/models and recognises an image model", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [+ { id: "qwen-image-2.1-colibri", object: "model", capabilities: ["image_generation", 7] },+ { id: "glm-5.2-colibri", object: "model" },+ ] }))))+ const models = await listModelInfo("http://x/v1", "")+ expect(models).toEqual([+ { id: "qwen-image-2.1-colibri", capabilities: ["image_generation"] },+ { id: "glm-5.2-colibri" },+ ])+ expect(models.map(generatesImages)).toEqual([true, false])+ })+})++describe("generateImage", () => {+ const encoder = new TextEncoder()+ const sse = (event: string, data: unknown) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`+ const answer = {+ created: 1790000000,+ data: [{ b64_json: "iVBORw0KGgo=", revised_prompt: null }],+ colibri: { width: 768, height: 512, seed: 1234, steps: 8, timings: { encode: 1.2, denoise: 80, decode: 9.1 } },+ }+ const events = [+ sse("image_generation.progress", { stage: "encode", step: 0, steps: 8, elapsed: 0.1 }),+ sse("image_generation.progress", { stage: "denoise", step: 3, steps: 8, elapsed: 12.3 }),+ sse("image_generation.partial_image", { b64_json: "UFJFVklFVw==", partial_image_index: 0 }),+ sse("image_generation.progress", { stage: "decode", step: 8, steps: 8, elapsed: 80.5 }),+ sse("image_generation.completed", answer),+ "data: [DONE]\n\n",+ ].join("")++ /* A body cut at arbitrary byte offsets, the way the network delivers it,+ optionally left open after the last chunk like a kept-alive connection. */+ const streamed = (text: string, { cut = 37, close = true } = {}) => new Response(new ReadableStream<Uint8Array>({+ start(controller) {+ for (let at = 0; at < text.length; at += cut) controller.enqueue(encoder.encode(text.slice(at, at + cut)))+ if (close) controller.close()+ },+ }), { headers: { "content-type": "text/event-stream" } })++ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), {+ status, headers: { "content-type": "application/json" },+ })++ const options = (extra: Partial<GenerateImageOptions> = {}): GenerateImageOptions => ({+ baseUrl: "http://localhost:8000/v1/",+ apiKey: "secret",+ model: "qwen-image-2.1-colibri",+ prompt: "a hummingbird",+ width: 768,+ height: 512,+ steps: 8,+ seed: 1234,+ signal: new AbortController().signal,+ ...extra,+ })++ const bodyOf = (call: unknown[]) => JSON.parse(String((call[1] as RequestInit).body)) as Record<string, unknown>++ it("streams progress, previews and the result, and posts the contract's body", async () => {+ const fetchMock = vi.fn().mockResolvedValue(streamed(events))+ vi.stubGlobal("fetch", fetchMock)+ const progress: ImageProgress[] = []+ const previews: Array<[string, number]> = []+ const image = await generateImage(options({+ onProgress: (item) => progress.push(item),+ onPartial: (url, index) => previews.push([url, index]),+ }))++ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(fetchMock.mock.calls[0][0]).toBe("http://localhost:8000/v1/images/generations")+ expect((fetchMock.mock.calls[0][1] as RequestInit).headers).toMatchObject({ Authorization: "Bearer secret" })+ expect(bodyOf(fetchMock.mock.calls[0])).toEqual({+ model: "qwen-image-2.1-colibri", prompt: "a hummingbird", size: "768x512", n: 1,+ response_format: "b64_json", steps: 8, seed: 1234, stream: true,+ })+ expect(progress.map((item) => [item.stage, item.step, item.steps])).toEqual([+ ["encode", 0, 8], ["denoise", 3, 8], ["decode", 8, 8],+ ])+ expect(previews).toEqual([["data:image/png;base64,UFJFVklFVw==", 0]])+ expect(image).toEqual({+ prompt: "a hummingbird", width: 768, height: 512, steps: 8, seed: 1234,+ url: "data:image/png;base64,iVBORw0KGgo=", timings: { encode: 1.2, denoise: 80, decode: 9.1 },+ })+ })++ it("stops reading at [DONE] even when the connection stays open", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(streamed(events, { close: false })))+ await expect(generateImage(options())).resolves.toMatchObject({ seed: 1234 })+ })++ it("reports the seed the engine used over the one that was asked for", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(streamed(+ sse("image_generation.completed", { ...answer, colibri: { ...answer.colibri, seed: 99 } }) + "data: [DONE]\n\n")))+ await expect(generateImage(options())).resolves.toMatchObject({ seed: 99 })+ })++ it("shows the server's own message for an HTTP 400 and does not retry", async () => {+ const fetchMock = vi.fn().mockResolvedValue(json({ error: {+ message: "Width and height must be multiples of 32 between 256 and 2048.", type: "invalid_request_error", param: "size",+ } }, 400))+ vi.stubGlobal("fetch", fetchMock)+ await expect(generateImage(options())).rejects.toThrow("Width and height must be multiples of 32 between 256 and 2048.")+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it("surfaces a busy engine (503) as its message", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(json({ error: { message: "The image engine is busy." } }, 503)))+ await expect(generateImage(options())).rejects.toThrow("The image engine is busy.")+ })++ it("fails with the event's message when the stream carries an error", async () => {+ const fetchMock = vi.fn().mockResolvedValue(streamed(+ sse("image_generation.progress", { stage: "encode", step: 0, steps: 8, elapsed: 0 })+ + sse("error", { error: { message: "engine crashed" } })))+ vi.stubGlobal("fetch", fetchMock)+ await expect(generateImage(options())).rejects.toThrow("engine crashed")+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it("does not start over when the stream breaks after it began", async () => {+ const fetchMock = vi.fn().mockResolvedValue(streamed(+ sse("image_generation.progress", { stage: "denoise", step: 2, steps: 8, elapsed: 20 })))+ vi.stubGlobal("fetch", fetchMock)+ await expect(generateImage(options())).rejects.toThrow("before the image was finished")+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it("falls back to one plain request when the stream closes before any event", async () => {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(streamed(""))+ .mockResolvedValueOnce(json(answer))+ vi.stubGlobal("fetch", fetchMock)+ await expect(generateImage(options())).resolves.toMatchObject({ url: "data:image/png;base64,iVBORw0KGgo=" })+ expect(fetchMock).toHaveBeenCalledTimes(2)+ expect(bodyOf(fetchMock.mock.calls[1])).toMatchObject({ stream: false, seed: 1234 })+ })++ it("falls back when the server refuses the stream parameter", async () => {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(json({ error: { message: "stream is not supported", param: "stream" } }, 400))+ .mockResolvedValueOnce(json(answer))+ vi.stubGlobal("fetch", fetchMock)+ await expect(generateImage(options())).resolves.toMatchObject({ seed: 1234 })+ expect(bodyOf(fetchMock.mock.calls[1])).toMatchObject({ stream: false })+ })++ it("takes a plain JSON answer to a stream request as the result", async () => {+ const fetchMock = vi.fn().mockResolvedValue(json(answer))+ vi.stubGlobal("fetch", fetchMock)+ await expect(generateImage(options())).resolves.toMatchObject({ width: 768, height: 512 })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it("rejects with AbortError when cancelled mid-stream, without a fallback request", async () => {+ const fetchMock = vi.fn((_url: string, init: RequestInit) => Promise.resolve(new Response(new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(encoder.encode(sse("image_generation.progress", { stage: "denoise", step: 1, steps: 8, elapsed: 3 })))+ init.signal?.addEventListener("abort", () => controller.error(new DOMException("The operation was aborted.", "AbortError")))+ },+ }), { headers: { "content-type": "text/event-stream" } })))+ vi.stubGlobal("fetch", fetchMock)+ const controller = new AbortController()+ const run = generateImage(options({ signal: controller.signal, onProgress: () => controller.abort() }))+ await expect(run).rejects.toMatchObject({ name: "AbortError" })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it("rejects with AbortError when cancelled before the answer arrives", async () => {+ const fetchMock = vi.fn((_url: string, init: RequestInit) => new Promise<Response>((_, reject) => {+ init.signal?.addEventListener("abort", () => reject(new DOMException("The operation was aborted.", "AbortError")))+ }))+ vi.stubGlobal("fetch", fetchMock)+ const controller = new AbortController()+ const run = generateImage(options({ signal: controller.signal }))+ controller.abort()+ await expect(run).rejects.toMatchObject({ name: "AbortError" })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })+})diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex a99792d0..0e6f4199 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -19,10 +19,17 @@ export interface ChatMessage {the message so it travels with the transcript through slot switches andarchives; never sent to the server. */finish?: string+ /* Both turns of a text-to-image exchange, the prompt and its picture, carry+ mode "image". They stay in the conversation on screen but are never sent to+ a text model, which would read a question followed by an empty answer. */+ mode?: "image"+ /* The picture of an image turn: the request while it runs, then the result.+ `url` appears only once the image is finished. */+ generated?: GeneratedImage}interface OpenAIError {- error?: { message?: string }+ error?: { message?: string; param?: string | null }}export interface SchedulerHealth {@@ -122,11 +129,28 @@ async function responseError(response: Response) {}}-export async function listModels(baseUrl: string, apiKey: string, signal?: AbortSignal) {+export interface ModelInfo {+ id: string+ /* What a model does beyond chat. colibri marks an image model with+ "image_generation": it answers /v1/images/generations and refuses chat. */+ capabilities?: string[]+}++export async function listModelInfo(baseUrl: string, apiKey: string, signal?: AbortSignal): Promise<ModelInfo[]> {const response = await fetch(endpoint(baseUrl, "models"), { headers: headers(apiKey), signal })if (!response.ok) throw new Error(await responseError(response))- const body = (await response.json()) as { data?: Array<{ id: string }> }- return (body.data || []).map((model) => model.id)+ const body = (await response.json()) as { data?: Array<{ id: string; capabilities?: unknown }> }+ return (body.data || []).map(({ id, capabilities }) => Array.isArray(capabilities)+ ? { id, capabilities: capabilities.filter((item): item is string => typeof item === "string") }+ : { id })+}++export async function listModels(baseUrl: string, apiKey: string, signal?: AbortSignal) {+ return (await listModelInfo(baseUrl, apiKey, signal)).map((model) => model.id)+}++export function generatesImages(model: ModelInfo | undefined) {+ return !!model?.capabilities?.includes("image_generation")}export async function getHealth(baseUrl: string, apiKey = "", signal?: AbortSignal): Promise<HealthResponse> {@@ -153,6 +177,32 @@ export function extractSSE(buffer: string) {return { data, rest }}+export interface SSEEvent {+ event: string+ data: string+}++/* extractSSE with the event names kept. The image endpoint tells progress,+ previews and the result apart by the `event:` line, not by the payload, so the+ name has to survive parsing. A frame without an event line is a "message" (the+ SSE default), which is how `data: [DONE]` arrives; comment lines such as+ ": keepalive" and frames without data are dropped, as the spec says. */+export function extractSSEEvents(buffer: string): { events: SSEEvent[]; rest: string } {+ const frames = buffer.split(/\r?\n\r?\n/)+ const rest = frames.pop() || ""+ const events: SSEEvent[] = []+ for (const frame of frames) {+ let event = "message"+ const data: string[] = []+ for (const line of frame.split(/\r?\n/)) {+ if (line.startsWith("event:")) event = line.slice(6).trim() || "message"+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""))+ }+ if (data.length) events.push({ event, data: data.join("\n") })+ }+ return { events, rest }+}+export interface StreamChatOptions {baseUrl: stringapiKey: string@@ -272,3 +322,190 @@ export async function askBrio(if (!response.ok) throw new Error(await responseError(response))return (await response.json()) as BrioResponse}++/* ---- text-to-image ----------------------------------------------------------+ * POST /v1/images/generations, in the OpenAI shape plus colibri's `steps`,+ * `seed` and the `colibri` block of the answer. With `stream: true` the gateway+ * sends named SSE events: progress while the engine works, partial_image when+ * it has a preview, completed with the same object the plain request returns. */++export type ImageStage = "encode" | "denoise" | "decode"++export interface ImageProgress {+ stage: ImageStage+ step: number+ steps: number+ elapsed: number+}++export interface ImageTimings {+ encode?: number+ denoise?: number+ decode?: number+}++export interface ImageGenerationResponse {+ created: number+ data: Array<{ b64_json?: string; url?: string; revised_prompt?: string | null }>+ colibri?: { width: number; height: number; seed: number; steps: number; timings?: ImageTimings }+}++/* One picture of the conversation. The request fields are known from the+ start; url, seconds and timings arrive with the result, and seed becomes the+ one the engine reports having used. */+export interface GeneratedImage {+ prompt: string+ width: number+ height: number+ steps: number+ seed: number+ url?: string+ seconds?: number+ timings?: ImageTimings+}++export interface GenerateImageOptions {+ baseUrl: string+ apiKey: string+ model: string+ prompt: string+ width: number+ height: number+ steps: number+ seed: number+ signal: AbortSignal+ onProgress?: (progress: ImageProgress) => void+ /* A preview as a data URI, small and noisy: the latent of the step so far. */+ onPartial?: (url: string, index: number) => void+}++/* The stream did not work as a stream (no body, or a close before the first+ event), so the same request is worth making once without it. Not raised for+ an HTTP error, an abort or a stream that broke halfway: those would only+ start the same generation over, or hide the server's own message. */+class StreamUnavailable extends Error {}++const IMAGE_EVENT = {+ progress: "image_generation.progress",+ partial: "image_generation.partial_image",+ completed: "image_generation.completed",+}++function imageRequest(options: GenerateImageOptions, stream: boolean) {+ return {+ method: "POST",+ headers: headers(options.apiKey),+ signal: options.signal,+ body: JSON.stringify({+ model: options.model,+ prompt: options.prompt,+ size: `${options.width}x${options.height}`,+ n: 1,+ response_format: "b64_json",+ steps: options.steps,+ seed: options.seed,+ stream,+ }),+ }+}++async function imageError(response: Response) {+ const fallback = `${response.status} ${response.statusText}`+ try {+ const body = (await response.json()) as OpenAIError+ if (response.status === 400 && body.error?.param === "stream") return new StreamUnavailable(body.error.message || fallback)+ return new Error(body.error?.message || fallback)+ } catch {+ return new Error(fallback)+ }+}++function streamError(data: string) {+ try {+ const body = JSON.parse(data) as OpenAIError & { message?: string }+ return new Error(body.error?.message || body.message || data)+ } catch {+ return new Error(data)+ }+}++async function streamImage(options: GenerateImageOptions): Promise<ImageGenerationResponse> {+ const response = await fetch(endpoint(options.baseUrl, "images/generations"), imageRequest(options, true))+ if (!response.ok) throw await imageError(response)+ /* A server that ignores `stream` answers with the plain object: that is the+ result, not a failure, and asking again would generate a second picture. */+ if ((response.headers.get("content-type") || "").includes("application/json")) {+ return (await response.json()) as ImageGenerationResponse+ }+ if (!response.body) throw new StreamUnavailable("The server returned an empty stream.")++ const reader = response.body.getReader()+ const decoder = new TextDecoder()+ let buffer = ""+ let seen = false+ let finished = false+ let result: ImageGenerationResponse | null = null++ const consume = ({ event, data }: SSEEvent) => {+ seen = true+ if (data === "[DONE]") { finished = true; return }+ if (event === "error") throw streamError(data)+ const payload = JSON.parse(data) as Record<string, unknown>+ if (payload.error) throw streamError(data)+ if (event === IMAGE_EVENT.progress) options.onProgress?.(payload as unknown as ImageProgress)+ else if (event === IMAGE_EVENT.partial && typeof payload.b64_json === "string") {+ options.onPartial?.(`data:image/png;base64,${payload.b64_json}`, Number(payload.partial_image_index) || 0)+ } else if (event === IMAGE_EVENT.completed) result = payload as unknown as ImageGenerationResponse+ }++ /* [DONE] ends the read even if the connection stays open; an error event+ cancels the body so the gateway sees the client leave. */+ try {+ while (!finished) {+ const { value, done } = await reader.read()+ buffer += decoder.decode(value, { stream: !done })+ const parsed = extractSSEEvents(buffer)+ buffer = parsed.rest+ parsed.events.forEach(consume)+ if (done) break+ }+ } catch (cause) {+ reader.cancel().catch(() => undefined)+ throw cause+ }+ if (finished) reader.cancel().catch(() => undefined)+ if (result) return result+ if (!seen) throw new StreamUnavailable("The server closed the stream without sending anything.")+ throw new Error("The server closed the stream before the image was finished.")+}++async function requestImage(options: GenerateImageOptions): Promise<ImageGenerationResponse> {+ const response = await fetch(endpoint(options.baseUrl, "images/generations"), imageRequest(options, false))+ if (!response.ok) throw await imageError(response)+ return (await response.json()) as ImageGenerationResponse+}++/* Streams when it can, so the page can show the stage and the previews; falls+ back to one plain request when streaming is not available. */+export async function generateImage(options: GenerateImageOptions): Promise<GeneratedImage> {+ let answer: ImageGenerationResponse+ try {+ answer = await streamImage(options)+ } catch (cause) {+ if (!(cause instanceof StreamUnavailable) || options.signal.aborted) throw cause+ answer = await requestImage(options)+ }+ const picture = answer.data?.[0]+ const url = picture?.b64_json ? `data:image/png;base64,${picture.b64_json}` : picture?.url+ if (!url) throw new Error("The server answered without an image.")+ const info = answer.colibri+ return {+ prompt: options.prompt,+ width: info?.width ?? options.width,+ height: info?.height ?? options.height,+ steps: info?.steps ?? options.steps,+ seed: info?.seed ?? options.seed,+ url,+ ...(info?.timings ? { timings: info.timings } : {}),+ }+}diff --git a/web/src/lib/images.test.ts b/web/src/lib/images.test.tsnew file mode 100644index 00000000..3b900bd3--- /dev/null+++ b/web/src/lib/images.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from "vitest"++import type { ChatMessage } from "./api"+import {+ SIZE_PRESETS, chatTurns, clampSteps, dataUrlBlob, duration, elapsedClock, imageFileName,+ parseSeed, parseSize, progressFraction, randomSeed, snapSide, validSide,+} from "./images"++describe("image sizes", () => {+ it("offers only sizes the engine accepts", () => {+ for (const preset of SIZE_PRESETS) {+ expect(validSide(preset.width) && validSide(preset.height), `${preset.width}x${preset.height}`).toBe(true)+ }+ })++ it("snaps a typed side to the nearest multiple of 32 inside 256..2048", () => {+ expect([1000, 432, 100, 5000, 768].map(snapSide)).toEqual([992, 448, 256, 2048, 768])+ expect(validSide(432)).toBe(false)+ })++ it("parses a stored size and refuses one the engine would refuse", () => {+ expect(parseSize("1024x576")).toEqual({ width: 1024, height: 576 })+ expect(parseSize("768x432")).toBeNull()+ expect(parseSize("garbage")).toBeNull()+ expect(parseSize(null)).toBeNull()+ })+})++describe("steps and seed", () => {+ it("keeps steps a whole number from 1 to 100", () => {+ expect([0, 8, 8.6, 500, Number.NaN].map(clampSteps)).toEqual([1, 8, 9, 100, 8])+ })++ it("reads an empty seed as random and refuses anything that is not a whole number", () => {+ expect(parseSeed("")).toBeNull()+ expect(parseSeed(" 42 ")).toBe(42)+ expect(parseSeed("-1")).toBeUndefined()+ expect(parseSeed("1.5")).toBeUndefined()+ expect(parseSeed("99999999999999999999")).toBeUndefined()+ })++ it("draws seeds that fit a signed 32-bit integer", () => {+ expect(randomSeed(() => 0)).toBe(0)+ expect(randomSeed(() => 1 - 2 ** -53)).toBe(2 ** 31 - 1)+ })+})++describe("progressFraction", () => {+ it("grows through encode, every denoising step and decode", () => {+ const at = (stage: "encode" | "denoise" | "decode", step: number) => progressFraction({ stage, step, steps: 8, elapsed: 0 })+ const series = [at("encode", 0), at("denoise", 0), at("denoise", 4), at("denoise", 8), at("decode", 8)]+ expect(series[0]).toBeGreaterThan(0)+ for (let i = 1; i < series.length; i++) expect(series[i]).toBeGreaterThanOrEqual(series[i - 1])+ expect(series[4]).toBeLessThan(1)+ expect(progressFraction(null)).toBe(0)+ })++ it("never leaves 0..1 on odd numbers from the server", () => {+ expect(progressFraction({ stage: "denoise", step: 50, steps: 8, elapsed: 0 })).toBeLessThan(1)+ expect(progressFraction({ stage: "denoise", step: -3, steps: 0, elapsed: 0 })).toBeGreaterThan(0)+ })+})++describe("transcript and files", () => {+ it("keeps image exchanges out of what a text model is sent", () => {+ const turns: ChatMessage[] = [+ { id: "1", role: "user", content: "hello" },+ { id: "2", role: "assistant", content: "hi" },+ { id: "3", role: "user", content: "a fox", mode: "image" },+ { id: "4", role: "assistant", content: "", mode: "image",+ generated: { prompt: "a fox", width: 512, height: 512, steps: 8, seed: 1 } },+ { id: "5", role: "user", content: "thanks" },+ ]+ expect(chatTurns(turns).map((item) => item.id)).toEqual(["1", "2", "5"])+ })++ it("formats the clock and the duration", () => {+ expect(elapsedClock(92.7)).toBe("1:32")+ expect(elapsedClock(4)).toBe("0:04")+ expect(duration(7.44)).toBe("7.4 s")+ expect(duration(42.2)).toBe("42 s")+ expect(duration(92.4)).toBe("1 min 32 s")+ })++ it("names the download after the prompt and the seed", () => {+ expect(imageFileName("Un colibrì, sotto la pioggia!", 42)).toBe("colibri-un-colibri-sotto-la-pioggia-42.png")+ expect(imageFileName("!!!", 7)).toBe("colibri-image-7.png")+ })++ it("turns a data URI back into the PNG bytes", async () => {+ const blob = dataUrlBlob("data:image/png;base64,iVBORw0KGgo=")+ expect(blob.type).toBe("image/png")+ expect([...new Uint8Array(await blob.arrayBuffer())]).toEqual([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ })+})diff --git a/web/src/lib/images.ts b/web/src/lib/images.tsnew file mode 100644index 00000000..63304378--- /dev/null+++ b/web/src/lib/images.ts@@ -0,0 +1,123 @@+import type { ChatMessage, ImageProgress } from "./api"++/* The engine takes sides that are multiples of 32 between 256 and 2048 and+ answers an error otherwise (qwenimage READY: min_side, max_side, multiple). */+export const SIDE = { min: 256, max: 2048, multiple: 32 } as const++export interface ImageSize {+ width: number+ height: number+}++/* Every preset is a multiple of 32 on both sides, so none of them can be+ refused. 16:9 at that granularity exists only as multiples of 512x288. */+export const SIZE_PRESETS: ReadonlyArray<ImageSize & { ratio: string }> = [+ { width: 512, height: 512, ratio: "1:1" },+ { width: 768, height: 512, ratio: "3:2" },+ { width: 512, height: 768, ratio: "2:3" },+ { width: 1024, height: 576, ratio: "16:9" },+ { width: 576, height: 1024, ratio: "9:16" },+ { width: 1024, height: 1024, ratio: "1:1" },+]++export const DEFAULT_SIZE: ImageSize = { width: 768, height: 512 }+export const DEFAULT_STEPS = 8+export const MAX_STEPS = 100+/* A seed the UI draws itself fits a signed 32-bit integer, whatever the engine+ keeps it in. The gateway is still sent an explicit seed every time, so a new+ seed is really new even on a server that would fall back to a fixed one. */+export const MAX_RANDOM_SEED = 2 ** 31++export const sizeKey = ({ width, height }: ImageSize) => `${width}x${height}`++export function presetOf(size: ImageSize) {+ return SIZE_PRESETS.find((preset) => preset.width === size.width && preset.height === size.height)+}++export function validSide(value: number) {+ return Number.isInteger(value) && value >= SIDE.min && value <= SIDE.max && value % SIDE.multiple === 0+}++/* What a custom side becomes when the field is left: the nearest multiple of+ 32 inside the range, so a typed 1000 turns into 992 instead of an error. */+export function snapSide(value: number) {+ if (!Number.isFinite(value)) return DEFAULT_SIZE.width+ const snapped = Math.round(value / SIDE.multiple) * SIDE.multiple+ return Math.min(SIDE.max, Math.max(SIDE.min, snapped))+}++export function parseSize(text: string | null): ImageSize | null {+ const match = /^(\d+)x(\d+)$/.exec(text || "")+ if (!match) return null+ const size = { width: Number(match[1]), height: Number(match[2]) }+ return validSide(size.width) && validSide(size.height) ? size : null+}++export function clampSteps(value: number) {+ if (!Number.isFinite(value)) return DEFAULT_STEPS+ return Math.min(MAX_STEPS, Math.max(1, Math.round(value)))+}++/* An empty field means "draw a new seed"; anything else must be a whole+ number the page can hold exactly. */+export function parseSeed(text: string): number | null | undefined {+ const trimmed = text.trim()+ if (!trimmed) return null+ if (!/^\d+$/.test(trimmed)) return undefined+ const seed = Number(trimmed)+ return Number.isSafeInteger(seed) ? seed : undefined+}++export function randomSeed(random: () => number = Math.random) {+ return Math.floor(random() * MAX_RANDOM_SEED)+}++/* Share of the whole job done, for the bar. Encoding and decoding each cost+ about one denoising step on the engine, so the job is steps + 2 units. The+ encode stage shows half a unit, so the bar is not empty while the prompt is+ read. */+export function progressFraction(progress: ImageProgress | null) {+ if (!progress) return 0+ const steps = Math.max(1, Math.round(progress.steps) || 1)+ const step = Math.min(steps, Math.max(0, Math.round(progress.step) || 0))+ switch (progress.stage) {+ case "encode": return 0.5 / (steps + 2)+ case "denoise": return (1 + step) / (steps + 2)+ case "decode": return (steps + 1) / (steps + 2)+ default: return 0+ }+}++/* The turns a text model is shown: everything but the image exchanges. */+export function chatTurns(messages: ChatMessage[]) {+ return messages.filter((item) => item.mode !== "image")+}++export function elapsedClock(seconds: number) {+ const whole = Math.max(0, Math.floor(seconds))+ return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`+}++export function duration(seconds: number, locale = "en") {+ if (seconds < 60) {+ return `${seconds.toLocaleString(locale, { maximumFractionDigits: seconds < 10 ? 1 : 0 })} s`+ }+ const whole = Math.round(seconds)+ return `${Math.floor(whole / 60)} min ${whole % 60} s`+}++/* A name that says what the file is and which seed makes it again. */+export function imageFileName(prompt: string, seed: number) {+ const words = prompt.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "")+ .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48).replace(/-+$/, "")+ return `colibri-${words || "image"}-${seed}.png`+}++export function dataUrlBlob(url: string) {+ const comma = url.indexOf(",")+ const type = /^data:([^;,]+)/.exec(url)?.[1] || "image/png"+ const binary = atob(url.slice(comma + 1))+ const bytes = new Uint8Array(binary.length)+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)+ return new Blob([bytes], { type })+}