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: Assist reads Ollama's last check instead of waiting on a silent port

Claudeaca3ef0836b5
diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.ts
index 19344962..1117496a 100644
--- a/src/server/assist/agent.ts
+++ b/src/server/assist/agent.ts
@@ -29,7 +29,7 @@ import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";
import { db } from "../db";
import { getGeneration } from "../generations";
import { offeredDefault } from "../model-access";
-import { ollamaModels, probeOllama as ollamaAnswers } from "../providers/llm";
+import { ollamaModels, ollamaSoon } from "../providers/llm";
import { engineMode, getSetting } from "../settings";
import { getSkill } from "../skills";
import { readRef } from "../storage";
@@ -367,13 +367,14 @@ export async function updateThread(id: string, patch: ThreadPatch): Promise<Assi
/**
* Whether Ollama answers, and the models it has: the check text steps use (providers/llm), so a busy Ollama (loading
- * a model, writing a long answer) keeps chats on it instead of the offline planner.
+ * a model, writing a long answer) keeps chats on it instead of the offline planner. Read as routing reads it, so
+ * opening Assist doesn't wait on an Ollama that never answers (ollamaSoon).
*/
async function probeOllama(): Promise<{ ok: boolean; models: string[] }> {
- const ok = await ollamaAnswers();
+ const ok = await ollamaSoon();
return { ok, models: ok ? ollamaModels() : [] };
}
-const ollamaReachable = () => ollamaAnswers();
+const ollamaReachable = () => ollamaSoon();
/**
* Which LLM drives new chats by default: Claude when a key is set (on open-source-only installs only when
diff --git a/src/server/providers/llm.ts b/src/server/providers/llm.ts
index 1128507d..c6a880b5 100644
--- a/src/server/providers/llm.ts
+++ b/src/server/providers/llm.ts
@@ -7,7 +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 { ask, checkReach, reachSync, runningCheck, sharedCheck, takesConnection, within, type Reach } from "./reach";
import type { PollResult, ProviderAdapter, RemoteOutput } from "./types";
/**
@@ -83,15 +83,39 @@ export function ollamaModels(): string[] {
return cur?.ok && cur.url === ollamaUrl() ? (cur.models ?? []) : [];
}
+/** How long a person's question (Assist) waits for what the last check of Ollama doesn't say yet. */
+const SOON_MS = 1500;
+
+/**
+ * Is Ollama answering, for a person waiting on the answer (Assist's panel, a chat's mode)? What the last check found,
+ * as routing reads it (ollamaReady): a stale answer is refreshed in the background, not waited on. It waits, at most
+ * `waitMs`, only for what nothing has said yet: the first check of an address, or the models a check under way is
+ * reading for a reachable Ollama. A first check still going then (no answer yet) counts an Ollama whose port took the
+ * connection as busy for now, so reachable, as routing's blocking check does; the check goes on to say for sure.
+ */
+export async function ollamaSoon(waitMs = SOON_MS): Promise<boolean> {
+ const url = ollamaUrl();
+ const known = globalThis.__fuobeOllamaReach?.url === url ? globalThis.__fuobeOllamaReach : undefined;
+ if (known) {
+ if (Date.now() - known.at > PROBE_MS) void probeOllama().catch(() => false);
+ const reading = known.ok && !known.models ? runningCheck("ollama", url) : undefined;
+ if (reading) await within(reading, waitMs);
+ const now = globalThis.__fuobeOllamaReach;
+ return now?.url === url ? now.ok : known.ok;
+ }
+ const port = takesConnection(url, waitMs);
+ return (await within(probeOllama().catch(() => false), waitMs)) ?? (await port);
+}
+
/**
* 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.
+ * to say for sure. One that answers gets a background check too: this one can't read the models it has (Assist lists them).
*/
function probeOllamaSync(url: string, timeoutMs = 1500): boolean {
const { reach, sure } = reachSync(url, `${url}/api/tags`, timeoutMs);
globalThis.__fuobeOllamaReach = reach;
- if (!sure) void probeOllama(true).catch(() => false);
+ if (!sure || reach.ok) void probeOllama(true).catch(() => false);
return reach.ok;
}
diff --git a/src/server/providers/reach.ts b/src/server/providers/reach.ts
index 7e1f4507..42d58841 100644
--- a/src/server/providers/reach.ts
+++ b/src/server/providers/reach.ts
@@ -107,6 +107,19 @@ export function sharedCheck(key: string, url: string, run: () => Promise<boolean
return done;
}
+/** The check of the server `key` at `url` under way, if one is (to wait on what it reads). */
+export function runningCheck(key: string, url: string): Promise<boolean> | undefined {
+ const running = globalThis.__fuobeReachChecks?.get(key);
+ return running?.url === url ? running.done : undefined;
+}
+
+/** What `p` gives within `ms`, or undefined when it takes longer (it goes on). */
+export function within<T>(p: Promise<T>, ms: number): Promise<T | undefined> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const late = new Promise<undefined>((resolve) => (timer = setTimeout(() => resolve(undefined), ms)));
+ return Promise.race([p, late]).finally(() => clearTimeout(timer));
+}
+
declare global {
/** The reachability checks under way, by server ("comfy", "ollama"). */
var __fuobeReachChecks: Map<string, { url: string; done: Promise<boolean> }> | undefined;
diff --git a/tests/ollama-reach.test.ts b/tests/ollama-reach.test.ts
index 9f745822..1fd954d0 100644
--- a/tests/ollama-reach.test.ts
+++ b/tests/ollama-reach.test.ts
@@ -1,3 +1,4 @@
+import { spawn } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import net from "node:net";
@@ -41,6 +42,10 @@ async function closedPort(): Promise<number> {
return port;
}
+/** An Ollama that answers /api/tags at once, in a process of its own; it prints its port. */
+const OTHER_PROCESS_OLLAMA = `const s = require("node:http").createServer((q, r) => q.url === "/api/tags" ? r.end(JSON.stringify({ models: [{ name: "qwen3:8b" }, { name: "llama3:8b" }] })) : r.writeHead(404).end());
+s.listen(0, "127.0.0.1", () => console.log(s.address().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;
@@ -182,6 +187,52 @@ describe("Ollama reachability under load", () => {
expect(await agent.availability()).toMatchObject({ ollama: false, ollamaModels: [] });
});
+ it("Assist doesn't wait on an Ollama that takes the connection but never answers: it reads the check, which goes on behind", async () => {
+ const agent = await import("@/server/assist/agent");
+ 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 look: no answer yet, but the port took the connection, so busy for now (as routing's first check says).
+ let t0 = Date.now();
+ expect(await agent.availability()).toMatchObject({ ollama: true, ollamaModels: [] });
+ expect(Date.now() - t0).toBeLessThan(2500);
+ // The check behind it says for sure after the longer look; Assist doesn't wait for that either.
+ await until(() => globalThis.__fuobeOllamaReach?.ok === false);
+ t0 = Date.now();
+ expect(await agent.availability()).toMatchObject({ ollama: false, ollamaModels: [] });
+ expect(await agent.resolveMode({ mode: "free" })).toMatchObject({ agent: "offline" });
+ expect(Date.now() - t0).toBeLessThan(300);
+ // Its cache is old: the answer it has, at once, and a fresh check in the background.
+ globalThis.__fuobeOllamaReach = { ...globalThis.__fuobeOllamaReach!, at: Date.now() - 60_000 };
+ t0 = Date.now();
+ expect(await agent.availability()).toMatchObject({ ollama: false });
+ expect(Date.now() - t0).toBeLessThan(300);
+ await until(() => Date.now() - (globalThis.__fuobeOllamaReach?.at ?? 0) < 10_000);
+ } finally {
+ silent.close();
+ }
+ });
+
+ it("after routing's blocking first check, Assist lists Ollama's models (that check can't read them)", async () => {
+ const agent = await import("@/server/assist/agent");
+ // An Ollama in another process, so the blocking check (which holds this thread) gets its answer.
+ const child = spawn(process.execPath, ["-e", OTHER_PROCESS_OLLAMA], { stdio: ["ignore", "pipe", "inherit"] });
+ try {
+ const port = await new Promise<number>((resolve, reject) => {
+ child.stdout.once("data", (d: Buffer) => resolve(Number(String(d).trim())));
+ child.once("exit", () => reject(new Error("the stand-in Ollama exited")));
+ });
+ setSetting("ollamaUrl", `http://127.0.0.1:${port}`);
+ expect(llm.llmBackends(ROUTE)).toEqual(["ollama"]);
+ // A sure answer: no check goes on behind it, and none has read the models yet.
+ expect(globalThis.__fuobeOllamaReach).toMatchObject({ ok: true });
+ expect(await agent.availability()).toMatchObject({ ollama: true, ollamaModels: ["qwen3:8b", "llama3:8b"] });
+ } finally {
+ child.kill();
+ }
+ });
+
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);