Add hosted demo queue and limits

This commit is contained in:
Meta Vens 2026-04-25 06:25:14 +01:00
commit a77612a2bb
13 changed files with 1821 additions and 89 deletions

View file

@ -41,6 +41,45 @@ type LogItem = {
detail: string;
};
type RuntimeConfig = {
hostedDemo: boolean;
limits: {
maxUploadBytes: number;
maxInputDimension: number;
maxOutputDimension: number;
defaultSteps: number;
maxSteps: number;
queueCapacity: number;
heartbeatIntervalSeconds: number;
staleAfterSeconds: number;
};
ui: {
showDeviceControl: boolean;
showStripBackgroundControl: boolean;
};
};
type QueueSummary = {
queueDepth: number;
waitingCount: number;
queueCapacity: number;
hasActiveJob: boolean;
activeStatus: string | null;
};
type JobStateSnapshot = {
jobId: string;
status: string;
error: string | null;
queuePosition: number | null;
queueDepth: number;
waitingCount: number;
queueCapacity: number;
heartbeatIntervalSeconds: number;
staleAfterSeconds: number;
runSummary?: JsonRecord | null;
};
type LatticeSearchInfo = {
candidateCount: number;
completedCandidates: number;
@ -101,6 +140,14 @@ type AppState = {
heatmapImage: ImageAsset | null;
finalOutputImage: ImageAsset | null;
runSummary: JsonRecord | null;
runtimeConfig: RuntimeConfig | null;
queueSummary: QueueSummary | null;
queuePosition: number | null;
queueDepth: number;
waitingCount: number;
queueCapacity: number;
heartbeatIntervalSeconds: number;
staleAfterSeconds: number;
solverStepBudget: number;
lossAxisMax: number | null;
eventLog: LogItem[];
@ -129,6 +176,7 @@ function byId<T extends HTMLElement>(id: string): T {
const fileInput = byId<HTMLInputElement>("fileInput");
const dropzone = byId<HTMLButtonElement>("dropzone");
const dropzoneLabel = byId<HTMLSpanElement>("dropzoneLabel");
const inputCopy = byId<HTMLParagraphElement>("inputCopy");
const pickFileButton = byId<HTMLButtonElement>("pickFileButton");
const runButton = byId<HTMLButtonElement>("runButton");
const statusPanel = byId<HTMLDivElement>("statusPanel");
@ -164,7 +212,12 @@ const phaseXInput = byId<HTMLInputElement>("phaseXInput");
const phaseYInput = byId<HTMLInputElement>("phaseYInput");
const stepsInput = byId<HTMLInputElement>("stepsInput");
const seedInput = byId<HTMLInputElement>("seedInput");
const runControlsCopy = byId<HTMLParagraphElement>("runControlsCopy");
const queueSummaryPanel = byId<HTMLDivElement>("queueSummary");
const cancelJobButton = byId<HTMLButtonElement>("cancelJobButton");
const deviceField = byId<HTMLElement>("deviceField");
const deviceInput = byId<HTMLSelectElement>("deviceInput");
const stripBackgroundField = byId<HTMLElement>("stripBackgroundField");
const stripBackgroundInput = byId<HTMLInputElement>("stripBackgroundInput");
const skipRerankInput = byId<HTMLInputElement>("skipRerankInput");
@ -178,6 +231,8 @@ const paintInputs = {
const imageCache = new Map<string, Promise<HTMLImageElement>>();
const eventTypes = [
"job_state",
"job_canceled",
"queue_state",
"job_failed",
"stage_started",
"source_loaded",
@ -221,6 +276,14 @@ const state: AppState = {
heatmapImage: null,
finalOutputImage: null,
runSummary: null,
runtimeConfig: null,
queueSummary: null,
queuePosition: null,
queueDepth: 0,
waitingCount: 0,
queueCapacity: 0,
heartbeatIntervalSeconds: 10,
staleAfterSeconds: 30,
solverStepBudget: 0,
lossAxisMax: null,
eventLog: [],
@ -234,6 +297,8 @@ const state: AppState = {
};
let currentEventSource: EventSource | null = null;
let currentHeartbeatTimer: number | null = null;
let currentQueuePollTimer: number | null = null;
let painting = false;
let panning = false;
let activePanPointerId: number | null = null;
@ -295,6 +360,60 @@ function renderEventLog(): void {
}
}
function renderQueueSummary(): void {
queueSummaryPanel.innerHTML = "";
if (hasActiveJob()) {
const cards: Array<[string, string]> = [
["Status", formatStatusBadge(state.status)],
[
"Line",
state.queuePosition === null || state.queueDepth <= 0
? "active now"
: `${state.queuePosition} / ${Math.max(state.queueDepth, state.queuePosition)}`,
],
["Waiting", `${state.waitingCount} / ${state.queueCapacity || (state.runtimeConfig?.limits.queueCapacity ?? 0)}`],
];
for (const [label, value] of cards) {
const node = document.createElement("div");
node.className = "info-card summary-card";
node.innerHTML = `<strong>${label}</strong><span>${value}</span>`;
queueSummaryPanel.appendChild(node);
}
const note = document.createElement("p");
note.className = "muted";
note.textContent =
state.status === "queued"
? "Heartbeats keep this slot alive while you wait."
: "This run owns the worker. Leave the page and the queue slot gets reclaimed.";
queueSummaryPanel.appendChild(note);
cancelJobButton.hidden = false;
return;
}
cancelJobButton.hidden = true;
if (!state.queueSummary) {
queueSummaryPanel.innerHTML = `<p class="muted">Checking queue status.</p>`;
return;
}
const idleCards: Array<[string, string]> = [
["Worker", state.queueSummary.hasActiveJob ? "busy" : "idle"],
["Queue", String(state.queueSummary.queueDepth)],
["Waiting", `${state.queueSummary.waitingCount} / ${state.queueSummary.queueCapacity}`],
];
for (const [label, value] of idleCards) {
const node = document.createElement("div");
node.className = "info-card summary-card";
node.innerHTML = `<strong>${label}</strong><span>${value}</span>`;
queueSummaryPanel.appendChild(node);
}
const note = document.createElement("p");
note.className = "muted";
note.textContent = state.queueSummary.hasActiveJob
? "One run is chewing right now. New jobs line up behind it."
: "Nobody is using the machine. A small miracle.";
queueSummaryPanel.appendChild(note);
}
function formatStatusBadge(status: string): string {
return status.replaceAll("_", " ").toUpperCase();
}
@ -313,6 +432,62 @@ function setStage(stageKey: string, label: string, detail: string): void {
statusText.textContent = detail;
}
function hasActiveJob(): boolean {
return state.jobId !== null && ["queued", "running", "waiting"].includes(state.status);
}
function formatByteLimit(bytes: number): string {
if (bytes >= 1024 * 1024) {
return `${formatNumber(bytes / (1024 * 1024), 1)} MiB`;
}
if (bytes >= 1024) {
return `${Math.round(bytes / 1024)} KiB`;
}
return `${bytes} B`;
}
function applyQueueState(payload: Partial<JobStateSnapshot>): void {
if (typeof payload.queuePosition === "number") {
state.queuePosition = payload.queuePosition;
} else if (payload.queuePosition === null) {
state.queuePosition = null;
}
if (typeof payload.queueDepth === "number") {
state.queueDepth = payload.queueDepth;
}
if (typeof payload.waitingCount === "number") {
state.waitingCount = payload.waitingCount;
}
if (typeof payload.queueCapacity === "number") {
state.queueCapacity = payload.queueCapacity;
}
if (typeof payload.heartbeatIntervalSeconds === "number") {
state.heartbeatIntervalSeconds = payload.heartbeatIntervalSeconds;
}
if (typeof payload.staleAfterSeconds === "number") {
state.staleAfterSeconds = payload.staleAfterSeconds;
}
}
function applyRuntimeConfig(config: RuntimeConfig): void {
state.runtimeConfig = config;
deviceField.hidden = !config.ui.showDeviceControl;
stripBackgroundField.hidden = !config.ui.showStripBackgroundControl;
stepsInput.max = String(config.limits.maxSteps);
if (stepsInput.value.trim() === "" || Number(stepsInput.value) > config.limits.maxSteps || Number(stepsInput.value) === 48) {
stepsInput.value = String(config.limits.defaultSteps);
}
if (config.hostedDemo) {
deviceInput.value = "cpu";
stripBackgroundInput.checked = false;
inputCopy.textContent = `PNG up to ${formatByteLimit(config.limits.maxUploadBytes)}, max ${config.limits.maxInputDimension}x${config.limits.maxInputDimension}.`;
runControlsCopy.textContent = `Hosted demo mode. CPU only, output max ${config.limits.maxOutputDimension}px, steps clamp at ${config.limits.maxSteps}.`;
} else {
inputCopy.textContent = "Start with the ugly input.";
runControlsCopy.textContent = "Pin what you know. Search what you do not.";
}
}
function resetRunArtifacts(options: { preserveSourceImage?: boolean } = {}): void {
const preserveSourceImage = options.preserveSourceImage ?? false;
state.jobId = null;
@ -332,6 +507,9 @@ function resetRunArtifacts(options: { preserveSourceImage?: boolean } = {}): voi
state.heatmapImage = null;
state.finalOutputImage = null;
state.runSummary = null;
state.queuePosition = null;
state.queueDepth = 0;
state.waitingCount = 0;
state.solverStepBudget = 0;
state.lossAxisMax = null;
state.eventLog = [];
@ -568,7 +746,17 @@ function renderInference(): void {
function renderStatusMetrics(): void {
const items: StatusMetricItem[] = [];
const frame = getSelectedFrame();
if (state.stageKey === "inference") {
if (state.stageKey === "queued" || state.status === "queued" || state.status === "waiting") {
items.push({
label: "Line",
value:
state.queuePosition === null || state.queueDepth <= 0
? "pending"
: `${state.queuePosition} / ${Math.max(state.queueDepth, state.queuePosition)}`,
});
items.push({ label: "Waiting", value: `${state.waitingCount} / ${state.queueCapacity || (state.runtimeConfig?.limits.queueCapacity ?? 0)}` });
items.push({ label: "Heartbeat", value: `${state.heartbeatIntervalSeconds}s` });
} else if (state.stageKey === "inference") {
if (state.latticeSearch) {
items.push({ label: "Sizes", value: `${state.latticeSearch.completedCandidates} / ${state.latticeSearch.candidateCount}` });
items.push({ label: "Phases", value: String(state.latticeSearch.phaseSampleCount) });
@ -1188,22 +1376,154 @@ function endPan(pointerId: number | null = null): void {
syncEditorCursorState();
}
async function loadRuntimeConfig(): Promise<void> {
const response = await fetch("/api/config");
if (!response.ok) {
throw new Error(await response.text());
}
applyRuntimeConfig((await response.json()) as RuntimeConfig);
}
async function refreshQueueSummary(): Promise<void> {
if (hasActiveJob()) {
return;
}
const response = await fetch("/api/queue");
if (!response.ok) {
throw new Error(await response.text());
}
state.queueSummary = (await response.json()) as QueueSummary;
renderQueueSummary();
}
function stopQueuePolling(): void {
if (currentQueuePollTimer !== null) {
window.clearInterval(currentQueuePollTimer);
currentQueuePollTimer = null;
}
}
function syncQueuePolling(): void {
if (hasActiveJob()) {
stopQueuePolling();
return;
}
if (currentQueuePollTimer !== null) {
return;
}
currentQueuePollTimer = window.setInterval(() => {
void refreshQueueSummary().catch(() => undefined);
}, 10000);
}
function stopHeartbeat(): void {
if (currentHeartbeatTimer !== null) {
window.clearInterval(currentHeartbeatTimer);
currentHeartbeatTimer = null;
}
}
function applyJobSnapshot(snapshot: Partial<JobStateSnapshot>): void {
applyQueueState(snapshot);
if (typeof snapshot.status === "string") {
setJobState(snapshot.status);
}
if (snapshot.runSummary && typeof snapshot.runSummary === "object") {
state.runSummary = snapshot.runSummary;
}
}
async function sendHeartbeat(): Promise<void> {
if (!state.jobId || !hasActiveJob()) {
stopHeartbeat();
return;
}
const response = await fetch(`/api/jobs/${state.jobId}/heartbeat`, { method: "POST" });
if (response.status === 404) {
stopHeartbeat();
return;
}
if (!response.ok) {
return;
}
applyJobSnapshot((await response.json()) as JobStateSnapshot);
renderQueueSummary();
}
function syncHeartbeat(): void {
if (!hasActiveJob()) {
stopHeartbeat();
return;
}
const intervalMs = Math.max(1000, state.heartbeatIntervalSeconds * 1000);
if (currentHeartbeatTimer !== null) {
window.clearInterval(currentHeartbeatTimer);
}
currentHeartbeatTimer = window.setInterval(() => {
void sendHeartbeat().catch(() => undefined);
}, intervalMs);
}
function extractErrorDetail(payload: unknown, fallback: string): string {
if (payload && typeof payload === "object") {
const detail = (payload as JsonRecord).detail;
if (typeof detail === "string" && detail.trim()) {
return detail;
}
}
return fallback;
}
async function cancelCurrentJob(options: { keepalive?: boolean; silent?: boolean } = {}): Promise<void> {
if (!state.jobId || !hasActiveJob()) {
return;
}
const request = fetch(`/api/jobs/${state.jobId}`, {
method: "DELETE",
keepalive: options.keepalive ?? false,
});
if (options.keepalive) {
return;
}
try {
const response = await request;
if (!response.ok) {
throw new Error(await response.text());
}
const payload = (await response.json()) as JobStateSnapshot;
applyJobSnapshot(payload);
if (!options.silent) {
setStage("queued", "Cancel requested", "Asked the worker to drop this job and free the queue slot.");
}
renderQueueSummary();
} catch (error) {
if (!options.silent) {
addLog("Cancel", error instanceof Error ? error.message : "Failed to cancel the current job.");
}
}
}
function buildFormData(): FormData {
if (!state.file) {
throw new Error("No file selected");
}
const data = new FormData();
data.set("image", state.file);
const runtimeConfig = state.runtimeConfig;
const maxSteps = runtimeConfig?.limits.maxSteps ?? 48;
const defaultSteps = runtimeConfig?.limits.defaultSteps ?? 48;
const requestedSteps = parseOptionalInteger(stepsInput);
const normalizedSteps = Math.max(0, Math.min(maxSteps, requestedSteps ?? defaultSteps));
const values: Array<[string, string | null]> = [
["target_size", parseOptionalInteger(targetSizeInput)?.toString() ?? null],
["target_width", parseOptionalInteger(targetWidthInput)?.toString() ?? null],
["target_height", parseOptionalInteger(targetHeightInput)?.toString() ?? null],
["phase_x", parseOptionalFloat(phaseXInput)?.toString() ?? null],
["phase_y", parseOptionalFloat(phaseYInput)?.toString() ?? null],
["steps", String(parseOptionalInteger(stepsInput) ?? 48)],
["steps", String(normalizedSteps)],
["seed", String(parseOptionalInteger(seedInput) ?? 7)],
["device", deviceInput.value],
["strip_background", stripBackgroundInput.checked ? "true" : "false"],
["device", runtimeConfig?.hostedDemo ? "cpu" : deviceInput.value],
["strip_background", runtimeConfig?.hostedDemo ? "false" : stripBackgroundInput.checked ? "true" : "false"],
["skip_phase_rerank", skipRerankInput.checked ? "true" : "false"],
];
for (const [key, value] of values) {
@ -1215,6 +1535,7 @@ function buildFormData(): FormData {
}
async function renderEverything(): Promise<void> {
renderQueueSummary();
renderInference();
renderStatusMetrics();
renderLossChart();
@ -1225,14 +1546,42 @@ async function renderEverything(): Promise<void> {
async function handleEvent(eventName: string, payload: JsonRecord): Promise<void> {
switch (eventName) {
case "job_state":
setJobState(String(payload.status ?? "working"));
applyJobSnapshot(payload as Partial<JobStateSnapshot>);
if (payload.cancelRequested === true && state.status === "running") {
setStage(state.stageKey, state.stageLabel, String(payload.message ?? "Cancel requested. Waiting for the worker to drop the job."));
}
syncHeartbeat();
syncQueuePolling();
break;
case "queue_state":
applyQueueState(payload as Partial<JobStateSnapshot>);
state.queueSummary = {
queueDepth: state.queueDepth,
waitingCount: state.waitingCount,
queueCapacity: state.queueCapacity,
hasActiveJob: state.queueDepth > 0,
activeStatus: state.status,
};
break;
case "job_canceled":
stopHeartbeat();
setJobState("canceled");
setStage("canceled", "Job canceled", String(payload.message ?? "The queued or running job was canceled."));
addLog("Canceled", String(payload.message ?? "Canceled the job."));
runButton.disabled = false;
currentEventSource?.close();
syncQueuePolling();
void refreshQueueSummary().catch(() => undefined);
break;
case "job_failed":
stopHeartbeat();
setJobState("failed");
setStage("failed", "Run failed", String(payload.message ?? "The GUI run fell over."));
addLog("Failure", String(payload.message ?? "The run failed."));
runButton.disabled = false;
currentEventSource?.close();
syncQueuePolling();
void refreshQueueSummary().catch(() => undefined);
break;
case "stage_started":
setJobState("running");
@ -1439,12 +1788,15 @@ async function handleEvent(eventName: string, payload: JsonRecord): Promise<void
case "pipeline_completed":
state.finalOutputImage = payload.outputImage as ImageAsset;
state.runSummary = (payload.runSummary as JsonRecord | null) ?? null;
stopHeartbeat();
setJobState("completed");
setStage("completed", "Run complete", "The output is ready. If the machine still did something stupid, fix it pixel by pixel.");
addLog("Done", "Full pipeline completed.");
runButton.disabled = false;
currentEventSource?.close();
await loadEditorAsset(state.finalOutputImage);
syncQueuePolling();
void refreshQueueSummary().catch(() => undefined);
break;
default:
break;
@ -1464,9 +1816,9 @@ function connectEventStream(jobId: string): void {
});
}
stream.onerror = () => {
if (state.status === "running") {
if (hasActiveJob()) {
setJobState("waiting");
setStage(state.stageKey, state.stageLabel, "Event stream hiccup. If it stays this way, rerun it.");
setStage(state.stageKey, state.stageLabel, "Event stream hiccup. Heartbeats are still trying to keep the queue slot alive.");
}
};
}
@ -1480,9 +1832,12 @@ async function startRun(): Promise<void> {
resetRunArtifacts({ preserveSourceImage: true });
renderEventLog();
runButton.disabled = true;
state.solverStepBudget = parseOptionalInteger(stepsInput) ?? 48;
const runtimeConfig = state.runtimeConfig;
const maxSteps = runtimeConfig?.limits.maxSteps ?? 48;
const defaultSteps = runtimeConfig?.limits.defaultSteps ?? 48;
state.solverStepBudget = Math.max(0, Math.min(maxSteps, parseOptionalInteger(stepsInput) ?? defaultSteps));
setJobState("queued");
setStage("queued", "Queued", "Starting the pipeline. This should wake up almost immediately.");
setStage("queued", "Queued", "Submitting the job and trying not to trip over our own shoelaces.");
addLog("Queued", `Starting ${state.file.name}.`);
await renderEverything();
try {
@ -1491,16 +1846,28 @@ async function startRun(): Promise<void> {
body: buildFormData(),
});
if (!response.ok) {
throw new Error(await response.text());
const errorPayload = await response.json().catch(async () => ({ detail: await response.text() }));
throw new Error(extractErrorDetail(errorPayload, "Failed to start GUI job."));
}
const payload = (await response.json()) as { jobId: string };
const payload = (await response.json()) as JobStateSnapshot;
state.jobId = payload.jobId;
applyJobSnapshot(payload);
state.queueSummary = {
queueDepth: payload.queueDepth,
waitingCount: payload.waitingCount,
queueCapacity: payload.queueCapacity,
hasActiveJob: payload.queueDepth > 0,
activeStatus: payload.status,
};
connectEventStream(payload.jobId);
syncHeartbeat();
syncQueuePolling();
} catch (error) {
runButton.disabled = false;
setJobState("failed");
setStage("failed", "Run failed", error instanceof Error ? error.message : "Failed to start GUI job.");
addLog("Failure", error instanceof Error ? error.message : "Failed to start GUI job.");
syncQueuePolling();
}
}
@ -1555,6 +1922,17 @@ runButton.addEventListener("click", () => {
void startRun();
});
cancelJobButton.addEventListener("click", () => {
void cancelCurrentJob();
});
stepsInput.addEventListener("change", () => {
const maxSteps = state.runtimeConfig?.limits.maxSteps;
if (typeof maxSteps === "number" && Number(stepsInput.value) > maxSteps) {
stepsInput.value = String(maxSteps);
}
});
inspectZoomInput.addEventListener("change", () => {
const value = Number(inspectZoomInput.value);
state.viewerInspectZoom = Number.isFinite(value) && value > 0 ? value : 1;
@ -1605,6 +1983,10 @@ window.addEventListener("blur", () => {
syncEditorCursorState();
});
window.addEventListener("pagehide", () => {
void cancelCurrentJob({ keepalive: true, silent: true });
});
for (const [panel, canvas] of [
["left", leftCanvas],
["right", rightCanvas],
@ -1744,4 +2126,20 @@ syncEditorCursorState();
syncViewerInspectCursor();
zoomValue.textContent = `${state.zoom}x`;
renderEventLog();
void renderEverything();
async function initializeApp(): Promise<void> {
try {
await loadRuntimeConfig();
} catch (error) {
addLog("Config", error instanceof Error ? error.message : "Failed to load runtime config.");
}
try {
await refreshQueueSummary();
} catch (error) {
addLog("Queue", error instanceof Error ? error.message : "Failed to load queue summary.");
}
syncQueuePolling();
await renderEverything();
}
void initializeApp();