Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Fixes 5: Ollama gets ComfyUI's busy-vs-down rules: a late answer isn't "down"

Claudedb8c86d7bb6c
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index e6020efe..b3d4a3a9 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -1,8 +1,6 @@
import "server-only";
import fs from "node:fs";
-import net from "node:net";
import path from "node:path";
-import { Worker } from "node:worker_threads";
import { tracksFor, type MotionPaths } from "@/lib/motion-paths";
import { nanoid } from "nanoid";
import {
@@ -59,6 +57,7 @@ import { probeAvi } from "../avi-probe";
import { probeWebm } from "../webm-probe";
import { adoptFile, readRef, scratchDir } from "../storage";
import { zipToFile } from "../zip";
+import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";
import { ProviderError, type ProviderAdapter, type RemoteOutput } from "./types";
export const WORKFLOW_DIR = path.join(process.cwd(), "workflows", "comfyui");
@@ -414,86 +413,32 @@ async function bundleFrames(outputs: ComfyOutput[], generationId: string): Promi
}
// ---------------------------------------------------------------------------
-// Reachability. Routing (chooseRoute) is synchronous, so the first check for a server URL is a blocking probe
-// (a worker thread does the fetch); after that the cached result is refreshed in the background every 10 s.
-// A server that refuses the connection (or a name that doesn't resolve) is down at once. One that doesn't answer
-// GET /system_stats in time may only be busy: a CPU ComfyUI working on a job can take seconds to. So a late answer
-// keeps the server reachable when it answered lately. When it didn't, and its port takes a connection, it gets one
-// longer look (none again for a while once one goes unanswered): reachable if it answers then. A port that takes the
-// connection isn't enough on its own: an ssh tunnel or a proxy whose ComfyUI is gone (or a hung ComfyUI) takes it too.
+// Reachability: GET /system_stats by the busy-vs-down rules in ./reach (a late answer is busy when the server
+// answered lately; else the longer look when its port takes a connection). A busy server keeps the RAM it last said.
declare global {
/** Reachability of the ComfyUI server, its RAM (bytes) when /system_stats said, when it last answered, and when a longer look last went unanswered. */
- var __fuobeComfyReach: { ok: boolean; at: number; url: string; ram?: number; seen?: number; silent?: number } | undefined;
- /** The check under way: callers in the meantime share its answer. */
- var __fuobeComfyProbe: { url: string; done: Promise<boolean> } | undefined;
-}
-
-/**
- * How long a check waits for /system_stats, then for the port to take a connection, then for the longer look; how long
- * an answer (or an unanswered longer look) counts as recent.
- */
-export const REACH = { answerMs: 2000, connectMs: 3000, lookMs: 10_000, answeredLatelyMs: 2 * 60_000 };
-
-/** Host and port of a server address, for the connection check (undefined when it isn't a URL). */
-function hostPort(url: string): { host: string; port: number } | undefined {
- try {
- const u = new URL(url);
- return { host: u.hostname.replace(/^\[|\]$/g, ""), port: Number(u.port) || (u.protocol === "https:" ? 443 : 80) };
- } catch {
- return undefined;
- }
-}
-
-/** Whether the server's port takes a TCP connection within `timeoutMs` (a refusal says no at once). */
-function takesConnection(url: string, timeoutMs: number): Promise<boolean> {
- const at = hostPort(url);
- if (!at) return Promise.resolve(false);
- return new Promise((resolve) => {
- const socket = net.connect(at);
- const done = (ok: boolean) => {
- clearTimeout(timer);
- socket.destroy();
- resolve(ok);
- };
- const timer = setTimeout(() => done(false), timeoutMs);
- socket.once("connect", () => done(true)).once("error", () => done(false));
- });
+ var __fuobeComfyReach: (Reach & { ram?: number }) | undefined;
}
/** What GET /system_stats got: an answer (with the RAM it says), a no (an HTTP error, a refused connection), or nothing in time. */
-async function askComfy(url: string, timeoutMs = REACH.answerMs): Promise<{ answer: "yes"; ram?: number } | { answer: "no" | "late" }> {
- try {
- const r = await fetch(`${url}/system_stats`, { headers: authHeaders(), signal: AbortSignal.timeout(timeoutMs) });
- if (!r.ok) return { answer: "no" };
- const total = ((await r.json().catch(() => null)) as { system?: { ram_total?: unknown } } | null)?.system?.ram_total;
- return { answer: "yes", ...(typeof total === "number" && total > 0 ? { ram: total } : {}) };
- } catch (e) {
- return { answer: (e as Error)?.name === "TimeoutError" ? "late" : "no" };
- }
+function askComfy(url: string, timeoutMs: number) {
+ return ask<number>(`${url}/system_stats`, timeoutMs, {
+ headers: authHeaders(),
+ read: async (r) => {
+ const total = ((await r.json()) as { system?: { ram_total?: unknown } } | null)?.system?.ram_total;
+ return typeof total === "number" && total > 0 ? total : undefined;
+ },
+ });
}
async function checkComfy(url: string): Promise<boolean> {
- let asked = await askComfy(url);
const prev = globalThis.__fuobeComfyReach?.url === url ? globalThis.__fuobeComfyReach : undefined;
- const lately = (t?: number) => !!t && Date.now() - t < REACH.answeredLatelyMs;
- // Late is busy, not down, when it answered lately. Otherwise it gets the longer look, when its port takes a
- // connection and no longer look went unanswered lately (a silent server isn't waited on at every check).
- const busy = asked.answer === "late" && lately(prev?.seen);
- let silent = prev?.silent;
- if (asked.answer === "late" && !busy && !lately(silent) && (await takesConnection(url, REACH.connectMs))) {
- asked = await askComfy(url, REACH.lookMs);
- if (asked.answer !== "yes") silent = Date.now();
- }
- const at = Date.now();
- // A busy server keeps the RAM and the time of its last answer; a down one, when it last went silent.
- const ram = asked.answer === "yes" ? (asked.ram ?? prev?.ram) : prev?.ram;
- const seen = asked.answer === "yes" ? at : prev?.seen;
- const ok = asked.answer === "yes" || busy;
- const reach = ok ? { ok, at, url, ...(ram ? { ram } : {}), ...(seen ? { seen } : {}) } : { ok, at, url, ...(silent ? { silent } : {}) };
+ const { reach, asked } = await checkReach(url, prev, (ms) => askComfy(url, ms));
+ const ram = (asked.answer === "yes" ? asked.value : undefined) ?? prev?.ram;
// The address may have changed while this ran: the new one's check speaks for it.
- if (url === baseUrl()) globalThis.__fuobeComfyReach = reach;
- return ok;
+ if (url === baseUrl()) globalThis.__fuobeComfyReach = reach.ok && ram ? { ...reach, ram } : reach;
+ return reach.ok;
}
/** Is the ComfyUI server reachable? Cached for 10 s (`force` checks now); one check runs at a time. */
@@ -501,13 +446,7 @@ export async function probeComfy(force = false): Promise<boolean> {
const url = baseUrl();
const cur = globalThis.__fuobeComfyReach;
if (!force && cur && cur.url === url && Date.now() - cur.at < 10_000) return cur.ok;
- const running = globalThis.__fuobeComfyProbe;
- if (running?.url === url) return running.done;
- const done: Promise<boolean> = checkComfy(url).finally(() => {
- if (globalThis.__fuobeComfyProbe?.done === done) globalThis.__fuobeComfyProbe = undefined;
- });
- globalThis.__fuobeComfyProbe = { url, done };
- return done;
+ return sharedCheck("comfy", url, () => checkComfy(url));
}
/** The connected ComfyUI's RAM in bytes, as the last reachability check read it (whole-clip tools' budget). */
@@ -516,41 +455,17 @@ export function comfyRam(): number | undefined {
return cur?.ok && cur.url === baseUrl() ? cur.ram : undefined;
}
-// flag[0]: the answer (1 yes, 2 no or refused, 3 none in time); flag[1]: 1 once the port took the connection.
-const PROBE_WORKER = `const { workerData } = require("node:worker_threads");
-const flag = new Int32Array(workerData.sab);
-if (workerData.at) {
- const socket = require("node:net").connect(workerData.at);
- socket.once("connect", () => (Atomics.store(flag, 1, 1), socket.destroy())).once("error", () => {});
-}
-fetch(workerData.url, { headers: workerData.headers, signal: AbortSignal.timeout(workerData.timeout) })
- .then((r) => Atomics.store(flag, 0, r.ok ? 1 : 2), (e) => Atomics.store(flag, 0, e && e.name === "TimeoutError" ? 3 : 2))
- .finally(() => Atomics.notify(flag, 0));`;
-
/**
- * Blocking reachability check: a few ms for a server that answers or a refused port, at most `timeoutMs` otherwise.
- * A server that takes the connection but doesn't answer in time is taken as busy, so reachable, for now; one that
- * doesn't even take it as unreachable. Either way the unhurried check (probeComfy) goes on in the background to say
- * for sure.
+ * Blocking reachability check (reachSync): a few ms for a server that answers or a refused port, at most `timeoutMs`
+ * otherwise; a server that takes the connection but doesn't answer in time is busy for now, and probeComfy goes on in
+ * the background to say for sure.
*/
export function probeComfySync(timeoutMs = 1500): boolean {
const url = baseUrl();
- let answer = 0;
- let connected = false;
- try {
- const sab = new SharedArrayBuffer(8);
- const flag = new Int32Array(sab);
- const worker = new Worker(PROBE_WORKER, { eval: true, workerData: { sab, url: `${url}/system_stats`, at: hostPort(url), headers: authHeaders(), timeout: timeoutMs } });
- Atomics.wait(flag, 0, 0, timeoutMs + 1000);
- answer = Atomics.load(flag, 0);
- connected = Atomics.load(flag, 1) === 1;
- void worker.terminate();
- } catch {}
- const at = Date.now();
- const ok = answer === 1 || (answer !== 2 && connected);
- globalThis.__fuobeComfyReach = { ok, at, url, ...(answer === 1 ? { seen: at } : {}) };
- if (answer !== 1 && answer !== 2) void probeComfy(true).catch(() => false);
- return ok;
+ const { reach, sure } = reachSync(url, `${url}/system_stats`, timeoutMs, authHeaders());
+ globalThis.__fuobeComfyReach = reach;
+ if (!sure) void probeComfy(true).catch(() => false);
+ return reach.ok;
}
// ---------------------------------------------------------------------------
diff --git a/src/server/providers/llm.ts b/src/server/providers/llm.ts
index 9eb9207c..cbb06c66 100644
--- a/src/server/providers/llm.ts
+++ b/src/server/providers/llm.ts
@@ -1,5 +1,4 @@
import "server-only";
-import { Worker } from "node:worker_threads";
import Anthropic from "@anthropic-ai/sdk";
import { nanoid } from "nanoid";
import { getModel } from "@/lib/catalog";
@@ -8,6 +7,7 @@ import type { GenInput, ModelRoute, Operation } from "@/lib/catalog/types";
import { engineMode, getSetting } from "../settings";
import { toDataUri } from "../storage";
import { comfyProvider } from "./comfyui";
+import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";
import type { PollResult, ProviderAdapter, RemoteOutput } from "./types";
/**
@@ -39,44 +39,42 @@ export function textOutput(text: string, cues?: Cue[] | null, meta: Record<strin
// Which LLM
declare global {
- var __fuobeOllamaReach: { ok: boolean; at: number; url: string } | undefined;
+ /** Reachability of Ollama: when it last answered, and when a longer look last went unanswered (./reach). */
+ var __fuobeOllamaReach: Reach | undefined;
var __fuobeLlmJobs: Map<string, LlmJob> | undefined;
}
const ollamaUrl = () => getSetting("ollamaUrl").replace(/\/+$/, "");
const PROBE_MS = 15_000;
-/** Is Ollama answering? Cached for 15 s; routing reads the cached answer (see llmBackends). */
+/**
+ * Is Ollama answering GET /api/tags? By the busy-vs-down rules ComfyUI has (./reach): a refused port or an HTTP
+ * error is down at once; no answer in time is busy when it answered lately, else it gets the longer look when its
+ * port takes a connection. Cached for 15 s (`force` checks now); one check runs at a time. Routing reads the cached
+ * answer (see llmBackends).
+ */
export async function probeOllama(force = false): Promise<boolean> {
const cur = globalThis.__fuobeOllamaReach;
const url = ollamaUrl();
if (!force && cur && cur.url === url && Date.now() - cur.at < PROBE_MS) return cur.ok;
- const ok = await fetch(`${url}/api/tags`, { signal: AbortSignal.timeout(1500) })
- .then((r) => r.ok)
- .catch(() => false);
- globalThis.__fuobeOllamaReach = { ok, at: Date.now(), url };
- return ok;
+ return sharedCheck("ollama", url, async () => {
+ const { reach } = await checkReach(url, globalThis.__fuobeOllamaReach, (ms) => ask(`${url}/api/tags`, ms));
+ // The address may have changed while this ran: the new one's check speaks for it.
+ if (url === ollamaUrl()) globalThis.__fuobeOllamaReach = reach;
+ return reach.ok;
+ });
}
-const PROBE_WORKER = `const { workerData } = require("node:worker_threads");
-const flag = new Int32Array(workerData.sab);
-fetch(workerData.url, { signal: AbortSignal.timeout(workerData.timeout) })
- .then((r) => Atomics.store(flag, 0, r.ok ? 1 : 2), () => Atomics.store(flag, 0, 2))
- .finally(() => Atomics.notify(flag, 0));`;
-
-/** Blocking check (a few ms for a refused port, at most `timeoutMs` for a host that doesn't answer). */
+/**
+ * Blocking check (reachSync): a few ms for an Ollama that answers or a refused port, at most `timeoutMs` otherwise.
+ * One that takes the connection but doesn't answer in time is busy for now, and probeOllama goes on in the background
+ * to say for sure.
+ */
function probeOllamaSync(url: string, timeoutMs = 1500): boolean {
- let ok = false;
- try {
- const sab = new SharedArrayBuffer(4);
- const flag = new Int32Array(sab);
- const worker = new Worker(PROBE_WORKER, { eval: true, workerData: { sab, url: `${url}/api/tags`, timeout: timeoutMs } });
- Atomics.wait(flag, 0, 0, timeoutMs + 1000);
- ok = Atomics.load(flag, 0) === 1;
- void worker.terminate();
- } catch {}
- globalThis.__fuobeOllamaReach = { ok, at: Date.now(), url };
- return ok;
+ const { reach, sure } = reachSync(url, `${url}/api/tags`, timeoutMs);
+ globalThis.__fuobeOllamaReach = reach;
+ if (!sure) void probeOllama(true).catch(() => false);
+ return reach.ok;
}
/**
@@ -88,7 +86,7 @@ function ollamaReady(): boolean {
const cur = globalThis.__fuobeOllamaReach;
const url = ollamaUrl();
if (!cur || cur.url !== url) return probeOllamaSync(url);
- if (Date.now() - cur.at > PROBE_MS) void probeOllama();
+ if (Date.now() - cur.at > PROBE_MS) void probeOllama().catch(() => false);
return cur.ok;
}
diff --git a/src/server/providers/reach.ts b/src/server/providers/reach.ts
new file mode 100644
index 00000000..7e1f4507
--- /dev/null
+++ b/src/server/providers/reach.ts
@@ -0,0 +1,147 @@
+import "server-only";
+import net from "node:net";
+import { Worker } from "node:worker_threads";
+
+// ---------------------------------------------------------------------------
+// Reachability of the servers on your own machine (ComfyUI, Ollama). Routing is synchronous, so the first check for
+// an address is a blocking probe (a worker thread does the fetch); after that the cached result is refreshed in the
+// background. A server that refuses the connection, answers with an HTTP error, or has a name that doesn't resolve is
+// down at once. One that doesn't answer in time may only be busy: a CPU ComfyUI working on a job, or an Ollama
+// loading a model, can take seconds to. So a late answer keeps the server reachable when it answered lately. When it
+// didn't, and its port takes a connection, it gets one longer look (none again for a while once one goes
+// unanswered): reachable if it answers then. A port that takes the connection isn't enough on its own: an ssh tunnel
+// or a proxy whose server is gone (or a hung server) takes it too.
+
+/**
+ * How long a check waits for an answer, then for the port to take a connection, then for the longer look; how long
+ * an answer (or an unanswered longer look) counts as recent.
+ */
+export const REACH = { answerMs: 2000, connectMs: 3000, lookMs: 10_000, answeredLatelyMs: 2 * 60_000 };
+
+/** What the last check of a server address found: when it last answered (`seen`), when a longer look last went unanswered (`silent`). */
+export interface Reach {
+ ok: boolean;
+ at: number;
+ url: string;
+ seen?: number;
+ silent?: number;
+}
+
+/** What one question got: an answer (with what was read from it), a no (an HTTP error, a refused connection), or nothing in time. */
+export type Asked<T> = { answer: "yes"; value?: T } | { answer: "no" | "late" };
+
+/** Host and port of a server address, for the connection check (undefined when it isn't a URL). */
+export function hostPort(url: string): { host: string; port: number } | undefined {
+ try {
+ const u = new URL(url);
+ return { host: u.hostname.replace(/^\[|\]$/g, ""), port: Number(u.port) || (u.protocol === "https:" ? 443 : 80) };
+ } catch {
+ return undefined;
+ }
+}
+
+/** Whether the server's port takes a TCP connection within `timeoutMs` (a refusal says no at once). */
+export function takesConnection(url: string, timeoutMs: number): Promise<boolean> {
+ const at = hostPort(url);
+ if (!at) return Promise.resolve(false);
+ return new Promise((resolve) => {
+ const socket = net.connect(at);
+ const done = (ok: boolean) => {
+ clearTimeout(timer);
+ socket.destroy();
+ resolve(ok);
+ };
+ const timer = setTimeout(() => done(false), timeoutMs);
+ socket.once("connect", () => done(true)).once("error", () => done(false));
+ });
+}
+
+/** GET `url` within `timeoutMs`; `read` takes what the caller wants from a good answer (the body is dropped otherwise). */
+export async function ask<T = never>(url: string, timeoutMs: number, opts: { headers?: Record<string, string>; read?: (r: Response) => Promise<T | undefined> } = {}): Promise<Asked<T>> {
+ try {
+ const r = await fetch(url, { headers: opts.headers, signal: AbortSignal.timeout(timeoutMs) });
+ if (!r.ok || !opts.read) void r.body?.cancel().catch(() => {});
+ if (!r.ok) return { answer: "no" };
+ const value = opts.read ? await opts.read(r).catch(() => undefined) : undefined;
+ return { answer: "yes", ...(value !== undefined ? { value } : {}) };
+ } catch (e) {
+ return { answer: (e as Error)?.name === "TimeoutError" ? "late" : "no" };
+ }
+}
+
+/**
+ * One unhurried check of the server at `url` by the rules above. `askAt` puts the question with a timeout; `prev` is
+ * what the last check of this address found. A busy server keeps the time of its last answer; a down one, when it
+ * last went silent.
+ */
+export async function checkReach<T>(url: string, prev: Reach | undefined, askAt: (timeoutMs: number) => Promise<Asked<T>>): Promise<{ reach: Reach; asked: Asked<T> }> {
+ const last = prev?.url === url ? prev : undefined;
+ let asked = await askAt(REACH.answerMs);
+ const lately = (t?: number) => !!t && Date.now() - t < REACH.answeredLatelyMs;
+ // Late is busy, not down, when it answered lately. Otherwise it gets the longer look, when its port takes a
+ // connection and no longer look went unanswered lately (a silent server isn't waited on at every check).
+ const busy = asked.answer === "late" && lately(last?.seen);
+ let silent = last?.silent;
+ if (asked.answer === "late" && !busy && !lately(silent) && (await takesConnection(url, REACH.connectMs))) {
+ asked = await askAt(REACH.lookMs);
+ if (asked.answer !== "yes") silent = Date.now();
+ }
+ const at = Date.now();
+ const seen = asked.answer === "yes" ? at : last?.seen;
+ const ok = asked.answer === "yes" || busy;
+ return { asked, reach: ok ? { ok, at, url, ...(seen ? { seen } : {}) } : { ok, at, url, ...(silent ? { silent } : {}) } };
+}
+
+/**
+ * One check at a time per server: callers while one runs share its answer. `key` names the server (its check under
+ * way is kept in `globalThis.__fuobeReachChecks`); a check for another address runs on its own.
+ */
+export function sharedCheck(key: string, url: string, run: () => Promise<boolean>): Promise<boolean> {
+ const checks = (globalThis.__fuobeReachChecks ??= new Map());
+ const running = checks.get(key);
+ if (running?.url === url) return running.done;
+ const done: Promise<boolean> = run().finally(() => {
+ if (checks.get(key)?.done === done) checks.delete(key);
+ });
+ checks.set(key, { url, done });
+ return done;
+}
+
+declare global {
+ /** The reachability checks under way, by server ("comfy", "ollama"). */
+ var __fuobeReachChecks: Map<string, { url: string; done: Promise<boolean> }> | undefined;
+}
+
+// flag[0]: the answer (1 yes, 2 no or refused, 3 none in time); flag[1]: 1 once the port took the connection.
+const PROBE_WORKER = `const { workerData } = require("node:worker_threads");
+const flag = new Int32Array(workerData.sab);
+if (workerData.at) {
+ const socket = require("node:net").connect(workerData.at);
+ socket.once("connect", () => (Atomics.store(flag, 1, 1), socket.destroy())).once("error", () => {});
+}
+fetch(workerData.url, { headers: workerData.headers, signal: AbortSignal.timeout(workerData.timeout) })
+ .then((r) => Atomics.store(flag, 0, r.ok ? 1 : 2), (e) => Atomics.store(flag, 0, e && e.name === "TimeoutError" ? 3 : 2))
+ .finally(() => Atomics.notify(flag, 0));`;
+
+/**
+ * The blocking first check of the server at `url` (GET `askUrl`): a few ms for a server that answers or a refused
+ * port, at most `timeoutMs` otherwise. A server that takes the connection but doesn't answer in time is taken as busy,
+ * so reachable, for now; one that doesn't even take it as unreachable. `sure` is false then: the caller has the
+ * unhurried check (checkReach) go on in the background to say for sure.
+ */
+export function reachSync(url: string, askUrl: string, timeoutMs: number, headers?: Record<string, string>): { reach: Reach; sure: boolean } {
+ let answer = 0;
+ let connected = false;
+ try {
+ const sab = new SharedArrayBuffer(8);
+ const flag = new Int32Array(sab);
+ const worker = new Worker(PROBE_WORKER, { eval: true, workerData: { sab, url: askUrl, at: hostPort(url), headers, timeout: timeoutMs } });
+ Atomics.wait(flag, 0, 0, timeoutMs + 1000);
+ answer = Atomics.load(flag, 0);
+ connected = Atomics.load(flag, 1) === 1;
+ void worker.terminate();
+ } catch {}
+ const at = Date.now();
+ const ok = answer === 1 || (answer !== 2 && connected);
+ return { reach: { ok, at, url, ...(answer === 1 ? { seen: at } : {}) }, sure: answer === 1 || answer === 2 };
+}
diff --git a/tests/comfy-reach.test.ts b/tests/comfy-reach.test.ts
index 3594a357..e8557433 100644
--- a/tests/comfy-reach.test.ts
+++ b/tests/comfy-reach.test.ts
@@ -12,7 +12,8 @@ process.env.FUOBE_DATA_DIR = dir;
process.env.COMFYUI_URL = "http://127.0.0.1:9";
const { setSetting } = await import("@/server/settings");
-const { comfyProvider, comfyRam, probeComfy, REACH } = await import("@/server/providers/comfyui");
+const { comfyProvider, comfyRam, probeComfy } = await import("@/server/providers/comfyui");
+const { REACH } = await import("@/server/providers/reach");
const gens = await import("@/server/generations");
const { db } = await import("@/server/db");
const { saveFile } = await import("@/server/storage");
@@ -57,7 +58,7 @@ const until = async <T>(f: () => T | undefined | null | false, ms = 20_000): Pro
/** Forget what the probes found, as a fresh start does. */
const forget = () => {
globalThis.__fuobeComfyReach = undefined;
- globalThis.__fuobeComfyProbe = undefined;
+ globalThis.__fuobeReachChecks?.delete("comfy");
};
beforeAll(async () => {
diff --git a/tests/ollama-reach.test.ts b/tests/ollama-reach.test.ts
new file mode 100644
index 00000000..62311918
--- /dev/null
+++ b/tests/ollama-reach.test.ts
@@ -0,0 +1,180 @@
+import fs from "node:fs";
+import http from "node:http";
+import net from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.setConfig({ testTimeout: 30_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-ollama-reach-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const llm = await import("@/server/providers/llm");
+const { REACH } = await import("@/server/providers/reach");
+
+/** A stand-in Ollama: /api/tags answers `status` after `delay` ms (busy loading a model, it answers late but takes the connection). */
+let delay = 0;
+let status = 200;
+let asked = 0;
+const server = http.createServer((req, res) => {
+ if (req.url !== "/api/tags") return void res.writeHead(404).end();
+ asked++;
+ setTimeout(() => {
+ if (res.destroyed) return;
+ res.writeHead(status, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ models: [{ name: "qwen3:8b" }] }));
+ }, delay);
+});
+let ollamaUrl = "";
+const reach = { ...REACH };
+/** An open-source translation: Ollama runs it when it answers (ComfyUI, its fallback, is off here). */
+const ROUTE = { endpoint: "ollama", op: "translate" as const };
+
+/** A port nothing listens on: connecting is refused at once. */
+async function closedPort(): Promise<number> {
+ const s = net.createServer();
+ await new Promise<void>((r) => s.listen(0, "127.0.0.1", r));
+ const { port } = s.address() as net.AddressInfo;
+ await new Promise((r) => s.close(r));
+ return port;
+}
+
+/** What `f` gives once it's truthy (polled every 100 ms, for at most `ms`). */
+const until = async <T>(f: () => T | undefined | null | false, ms = 20_000): Promise<T> => {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = f();
+ if (v) return v;
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await new Promise((r) => setTimeout(r, 100));
+ }
+};
+
+/** Forget what the probes found, as a fresh start does. */
+const forget = () => {
+ globalThis.__fuobeOllamaReach = undefined;
+ globalThis.__fuobeReachChecks?.delete("ollama");
+};
+
+beforeAll(async () => {
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ ollamaUrl = `http://127.0.0.1:${(server.address() as net.AddressInfo).port}`;
+ // Checks give up sooner here, so a late answer is quick to make (a 3 s answer still makes the longer look).
+ Object.assign(REACH, { answerMs: 300, connectMs: 1000, lookMs: 5000 });
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "ollama");
+});
+afterAll(() => {
+ Object.assign(REACH, reach);
+ server.closeAllConnections();
+ server.close();
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+beforeEach(() => {
+ delay = 0;
+ status = 200;
+ setSetting("ollamaUrl", ollamaUrl);
+ forget();
+});
+
+describe("Ollama reachability under load", () => {
+ it("a busy Ollama that answered before stays reachable", async () => {
+ expect(await llm.probeOllama(true)).toBe(true);
+ // Busy with a long generation: the answer comes long after the check gives up (and after the old 1.5 s limit).
+ delay = 2000;
+ for (let i = 0; i < 2; i++) expect(await llm.probeOllama(true)).toBe(true);
+ expect(llm.llmBackends(ROUTE)).toEqual(["ollama"]);
+ // Back to answering: still reachable, and the answer counts again.
+ delay = 0;
+ expect(await llm.probeOllama(true)).toBe(true);
+ expect(globalThis.__fuobeOllamaReach?.seen).toBeGreaterThan(Date.now() - 1000);
+ });
+
+ it("a refused port is unreachable at once, in the blocking first check and the background one", async () => {
+ setSetting("ollamaUrl", `http://127.0.0.1:${await closedPort()}`);
+ let t0 = Date.now();
+ expect(llm.llmBackends(ROUTE)).toEqual([]);
+ expect(Date.now() - t0).toBeLessThan(1500);
+ t0 = Date.now();
+ expect(await llm.probeOllama(true)).toBe(false);
+ expect(Date.now() - t0).toBeLessThan(500);
+ });
+
+ it("an HTTP error is down at once, without the longer look", async () => {
+ status = 503;
+ const t0 = Date.now();
+ expect(await llm.probeOllama(true)).toBe(false);
+ expect(Date.now() - t0).toBeLessThan(500);
+ expect(asked).toBeGreaterThan(0);
+ });
+
+ it("no answer in time is busy when Ollama answered lately, unreachable when it didn't and its port refuses", async () => {
+ const url = `http://127.0.0.1:${await closedPort()}`;
+ setSetting("ollamaUrl", url);
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ throw new DOMException("The operation was aborted due to timeout", "TimeoutError");
+ }) as typeof fetch;
+ try {
+ expect(await llm.probeOllama(true)).toBe(false);
+ // It answered a minute ago: busy, so still reachable.
+ globalThis.__fuobeOllamaReach = { ok: true, at: Date.now() - 60_000, url, seen: Date.now() - 60_000 };
+ expect(await llm.probeOllama(true)).toBe(true);
+ // Its last answer is long past, and nothing takes the connection.
+ globalThis.__fuobeOllamaReach = { ok: true, at: Date.now() - 60_000, url, seen: Date.now() - REACH.answeredLatelyMs - 1000 };
+ expect(await llm.probeOllama(true)).toBe(false);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ });
+
+ it("the first check of a slow but alive Ollama says reachable (blocking, then in the longer look)", async () => {
+ delay = 3000;
+ // The routing question right after start: Ollama takes the connection while it's busy.
+ const t0 = Date.now();
+ expect(llm.llmBackends(ROUTE)).toEqual(["ollama"]);
+ expect(Date.now() - t0).toBeLessThan(3000);
+ forget();
+ expect(await llm.probeOllama(true)).toBe(true);
+ // Callers while a check runs share it: one quick ask, one longer look.
+ forget();
+ asked = 0;
+ expect(await Promise.all([llm.probeOllama(true), llm.probeOllama(true), llm.probeOllama()])).toEqual([true, true, true]);
+ expect(asked).toBe(2);
+ });
+
+ it("a port that takes the connection but never answers (a tunnel or proxy whose Ollama is gone) is unreachable after the longer look", async () => {
+ const silent = net.createServer(() => {});
+ await new Promise<void>((r) => silent.listen(0, "127.0.0.1", r));
+ try {
+ setSetting("ollamaUrl", `http://127.0.0.1:${(silent.address() as net.AddressInfo).port}`);
+ // The first, blocking check can only see the connection taken, as for a busy Ollama; the background check says for sure.
+ llm.llmBackends(ROUTE);
+ await until(() => globalThis.__fuobeOllamaReach?.ok === false);
+ // Found silent: no longer look again for a while, so the next checks are quick.
+ const t0 = Date.now();
+ for (let i = 0; i < 2; i++) expect(await llm.probeOllama(true)).toBe(false);
+ expect(Date.now() - t0).toBeLessThan(2 * REACH.answerMs + 500);
+ expect(llm.llmBackends(ROUTE)).toEqual([]);
+ } finally {
+ silent.close();
+ }
+ });
+
+ it("a late Ollama that answers the longer look is reachable; a check of an address changed meanwhile keeps to itself", async () => {
+ delay = 1000;
+ const old = llm.probeOllama(true);
+ // While that check runs, the address changes and the new one is checked.
+ setSetting("ollamaUrl", `http://127.0.0.1:${await closedPort()}`);
+ expect(await llm.probeOllama(true)).toBe(false);
+ const now = globalThis.__fuobeOllamaReach;
+ expect(await old).toBe(true);
+ expect(globalThis.__fuobeOllamaReach).toBe(now);
+ setSetting("ollamaUrl", ollamaUrl);
+ forget();
+ expect(await llm.probeOllama(true)).toBe(true);
+ expect(globalThis.__fuobeOllamaReach?.seen).toBeGreaterThan(Date.now() - 1000);
+ });
+});