Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(onboarding): backend-probe timeout, prevents 5-min hang on first launch

purplea7f7b05b21ab
diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rs
index 35e91151..4b7cc869 100644
--- a/src-tauri/src/commands/proxy.rs
+++ b/src-tauri/src/commands/proxy.rs
@@ -166,13 +166,29 @@ fn validate_proxy_url(raw: &str, state: &crate::state::AppState) -> Result<(), S
/// Generic localhost proxy — fetch any localhost or configured-backend URL
/// bypassing CORS. Used for Ollama and ComfyUI API calls in production mode.
+///
+/// `timeout_ms` (optional) overrides the default 300 s timeout. Backend
+/// detection passes 2000 — without that override the onboarding "Searching
+/// for local backends..." step would freeze for 5 minutes whenever a port
+/// happens to be answered by software that takes the TCP connect but
+/// never replies HTTP (Discord report — Docker dev container on 8000,
+/// firewall throttling, another LLM tool with a slow health endpoint, ...).
+/// Long-running calls (Ollama pull, ComfyUI generate) keep the 300 s default.
#[tauri::command]
-pub async fn proxy_localhost(url: String, method: Option<String>, body: Option<String>, state: tauri::State<'_, crate::state::AppState>) -> Result<String, String> {
+pub async fn proxy_localhost(
+ url: String,
+ method: Option<String>,
+ body: Option<String>,
+ timeout_ms: Option<u64>,
+ state: tauri::State<'_, crate::state::AppState>,
+) -> Result<String, String> {
validate_proxy_url(&url, &state)?;
+ let timeout = std::time::Duration::from_millis(timeout_ms.unwrap_or(300_000));
+
let client = reqwest::Client::builder()
.user_agent("LocallyUncensored/2.0")
- .timeout(std::time::Duration::from_secs(300))
+ .timeout(timeout)
.build()
.map_err(|e| e.to_string())?;
diff --git a/src/api/backend.ts b/src/api/backend.ts
index a3f2f47f..b113aece 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -31,18 +31,50 @@ async function getInvoke() {
* Fetch a localhost URL, bypassing CORS in Tauri mode.
* In dev mode: uses normal fetch().
* In Tauri .exe: routes through Rust proxy_localhost command.
+ *
+ * `timeoutMs` is forwarded to the Rust proxy as `timeout_ms` so probes that
+ * hit "TCP connect succeeds but server never sends HTTP response" don't
+ * freeze the caller for the 5-minute default. Probe sites pass ~2000;
+ * long-running endpoints (Ollama pull, ComfyUI generate) omit it for
+ * the 300 s default. The dev-mode direct fetch path mirrors the same
+ * timeout via AbortController.
*/
export async function localFetch(
url: string,
- options?: { method?: string; body?: string; headers?: Record<string, string>; signal?: AbortSignal }
+ options?: {
+ method?: string;
+ body?: string;
+ headers?: Record<string, string>;
+ signal?: AbortSignal;
+ timeoutMs?: number;
+ }
): Promise<Response> {
if (!isTauri()) {
- return fetch(url, {
- method: options?.method || "GET",
- headers: options?.headers,
- body: options?.body,
- signal: options?.signal,
- });
+ // Mirror the Rust-side timeout in dev mode by chaining an
+ // AbortController onto whatever signal the caller provided.
+ let signal = options?.signal;
+ let abortTimer: ReturnType<typeof setTimeout> | undefined;
+ if (typeof options?.timeoutMs === "number" && options.timeoutMs > 0) {
+ const controller = new AbortController();
+ abortTimer = setTimeout(() => controller.abort(), options.timeoutMs);
+ // Plumb the user's signal too so they can still cancel manually.
+ if (options.signal) {
+ const userSig = options.signal;
+ if (userSig.aborted) controller.abort();
+ else userSig.addEventListener("abort", () => controller.abort(), { once: true });
+ }
+ signal = controller.signal;
+ }
+ try {
+ return await fetch(url, {
+ method: options?.method || "GET",
+ headers: options?.headers,
+ body: options?.body,
+ signal,
+ });
+ } finally {
+ if (abortTimer) clearTimeout(abortTimer);
+ }
}
// In Tauri: route through Rust to bypass CORS, with direct fetch fallback
@@ -54,6 +86,10 @@ export async function localFetch(
url,
method,
body: options?.body || null,
+ // Snake-case to match the Rust parameter name. Tauri's invoke layer
+ // does NOT auto-convert camelCase here — the Rust command spec uses
+ // explicit field names.
+ timeout_ms: options?.timeoutMs ?? null,
}) as string;
return new Response(text, { status: 200, headers: { "Content-Type": "application/json" } });
@@ -62,17 +98,33 @@ export async function localFetch(
console.warn('[localFetch] Proxy failed, trying direct fetch:', proxyErrMsg)
// Fallback: try direct fetch (works when ComfyUI has --enable-cors-header *)
+ // Apply the same timeout to the fallback so a hanging probe doesn't sit
+ // for minutes on this path either.
+ let signal = options?.signal;
+ let abortTimer: ReturnType<typeof setTimeout> | undefined;
+ if (typeof options?.timeoutMs === "number" && options.timeoutMs > 0) {
+ const controller = new AbortController();
+ abortTimer = setTimeout(() => controller.abort(), options.timeoutMs);
+ if (options.signal) {
+ const userSig = options.signal;
+ if (userSig.aborted) controller.abort();
+ else userSig.addEventListener("abort", () => controller.abort(), { once: true });
+ }
+ signal = controller.signal;
+ }
try {
return await fetch(url, {
method,
headers: options?.body ? { "Content-Type": "application/json" } : undefined,
body: options?.body,
- signal: options?.signal,
+ signal,
});
} catch (fetchErr) {
// Both failed — return the proxy error with details preserved
const detail = proxyErrMsg || String(fetchErr)
return new Response(JSON.stringify({ error: detail }), { status: 500 });
+ } finally {
+ if (abortTimer) clearTimeout(abortTimer);
}
}
}
diff --git a/src/lib/backend-detector.ts b/src/lib/backend-detector.ts
index 2fee901c..865d7972 100644
--- a/src/lib/backend-detector.ts
+++ b/src/lib/backend-detector.ts
@@ -15,35 +15,61 @@ export interface DetectedBackend {
port: number
}
-const PROBE_TIMEOUT = 2000 // 2 seconds
+const PROBE_TIMEOUT = 2000 // 2 seconds — backend probe must be fast or skipped
/**
* Probe a single backend URL. Returns true if reachable.
+ *
+ * Hardened against the "TCP connect succeeds, HTTP never replies" hang
+ * (Discord report — onboarding stuck on "Searching for local backends..."
+ * for 5 min when an unrelated service holds one of our default ports). Two
+ * defenses, in order:
+ *
+ * 1. The Rust-side proxy honours `timeoutMs` and aborts the underlying
+ * reqwest call. In dev mode the equivalent AbortController is wired
+ * into the direct fetch.
+ * 2. A frontend `Promise.race` against a hard deadline catches the
+ * pathological case where the proxy itself hangs (e.g. invoke()
+ * internally retries before surfacing the timeout) — the probe
+ * resolves to `false` no matter what.
+ *
+ * Both layers resolve to "not reachable", never reject, so the parent
+ * `Promise.allSettled` always settles within PROBE_TIMEOUT regardless of
+ * what the remote port is doing.
*/
async function probeBackend(baseUrl: string, isOllama: boolean): Promise<boolean> {
- const controller = new AbortController()
- const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT)
-
- try {
- const url = isOllama
- ? baseUrl.replace(/\/v1$/, '') + '/api/tags' // Ollama uses /api/tags
- : baseUrl + '/models' // OpenAI-compat uses /v1/models
+ const url = isOllama
+ ? baseUrl.replace(/\/v1$/, '') + '/api/tags' // Ollama uses /api/tags
+ : baseUrl + '/models' // OpenAI-compat uses /v1/models
- let res: Response
-
- if (isTauri()) {
- // In Tauri, use proxy to avoid CORS
- res = await localFetch(url)
- } else {
- res = await fetch(url, { signal: controller.signal })
+ const inner = (async (): Promise<boolean> => {
+ try {
+ let res: Response
+ if (isTauri()) {
+ res = await localFetch(url, { timeoutMs: PROBE_TIMEOUT })
+ } else {
+ const controller = new AbortController()
+ const t = setTimeout(() => controller.abort(), PROBE_TIMEOUT)
+ try {
+ res = await fetch(url, { signal: controller.signal })
+ } finally {
+ clearTimeout(t)
+ }
+ }
+ return res.ok
+ } catch {
+ return false
}
+ })()
+
+ // Belt-and-suspenders: even if `inner` ignores its timeout (e.g. some
+ // future invoke() code path swallows the abort), the race resolves to
+ // false at deadline so the onboarding never blocks.
+ const deadline = new Promise<boolean>(resolve => {
+ setTimeout(() => resolve(false), PROBE_TIMEOUT + 500) // small grace over the inner timeout
+ })
- return res.ok
- } catch {
- return false
- } finally {
- clearTimeout(timeout)
- }
+ return Promise.race([inner, deadline])
}
/**