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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(models): stop knocking on an absent ollama every 1.5 seconds
purplefbca02ba17aa
diff --git a/src/api/backend.ts b/src/api/backend.tsindex 2fbbc92c..fc5bc4ff 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -9,6 +9,16 @@*/import { log } from "../lib/logger";+import { shouldLogRepeat } from "../lib/probe-backoff";++// Hosts whose proxy failure has already been logged, host -> timestamp. Keeps+// a dead local backend from filling the console with the same line forever.+const proxyWarnSeen = new Map<string, number>();++/** Test-only: forget which hosts have already had their warning. */+export function __resetProxyWarnLogForTests(): void {+ proxyWarnSeen.clear();+}let _invoke: ((cmd: string, args?: Record<string, unknown>) => Promise<unknown>) | null = null;@@ -164,7 +174,14 @@ export async function localFetch(return new Response(httpErr.body, { status: httpErr.status })}- log.warn('[localFetch] Proxy failed, trying direct fetch', { err: proxyErrMsg })+ // One line per host per minute, not one per attempt. A backend that is+ // not installed used to write two console lines every 1.5 seconds, over+ // forty inside a single chat round, and the real errors drowned in it+ // (counter-check round 2, 2026-08-29). The poller behind it now backs off+ // as well; this is the belt for anything else that keeps trying.+ if (shouldLogRepeat(proxyWarnSeen, hostnameOf(url), Date.now())) {+ log.warn('[localFetch] Proxy failed, trying direct fetch (repeats within the next minute are not logged)', { err: 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 sitdiff --git a/src/components/models/ModelSelector.tsx b/src/components/models/ModelSelector.tsxindex e83210c0..e01eddce 100644--- a/src/components/models/ModelSelector.tsx+++ b/src/components/models/ModelSelector.tsx@@ -14,6 +14,7 @@ import { canUseTools, resolveToolSupport, type ToolSupport } from '../../lib/tooimport { backendCall } from '../../api/backend'import { listLoadedLmStudioModels, loadLmStudioModel, unloadLmStudioModel } from '../../api/lmstudio'import { isLmStudioProvider } from '../../lib/hf-to-provider'+import { nextProbeDelayMs } from '../../lib/probe-backoff'import type { AIModel } from '../../types/models'// ── Local-mode cloud discovery (2.5.8): an "LU Cloud" section at the list's@@ -496,7 +497,16 @@ export function ModelSelector({ openUpward = false, surface = 'chat' }: ModelSelif (!open) returnsetSelectError(null) // fresh open — drop any stale auto-load errorlet cancelled = false- const refresh = () => {+ let timer: ReturnType<typeof setTimeout> | undefined+ // Consecutive failed probes. A backend that answers keeps the brisk 1.5 s+ // beat; one that is not installed is asked about less and less often, up+ // to a minute. Counter-check round 2 (2026-08-29) found the app knocking+ // on localhost:11434 every 1.5 s forever on a box with no Ollama at all,+ // over forty console lines inside a single chat round, drowning out the+ // errors somebody was actually looking for.+ let misses = 0++ const refresh = async () => {// Skip the tick entirely while the window is hidden/minimized — there's// nothing to repaint and we re-sync the moment it's visible again. Stops a// backgrounded app from hitting Ollama / LM Studio every 1.5 s (#70).@@ -515,17 +525,39 @@ export function ModelSelector({ openUpward = false, surface = 'chat' }: ModelSel} else if (!cancelled) {setLmsLoaded((prev) => (prev.size ? new Set() : prev))}- void listRunningModels().then((list) => { if (!cancelled) setOllamaLoaded((prev) => sameStringSet(prev, list) ? prev : new Set(list)) }).catch(() => {})+ try {+ const list = await listRunningModels()+ misses = 0+ if (!cancelled) setOllamaLoaded((prev) => sameStringSet(prev, list) ? prev : new Set(list))+ } catch {+ misses += 1+ }}- refresh()- const id = setInterval(refresh, 1500)++ // setTimeout chain rather than setInterval: the gap has to grow, and a+ // fixed interval cannot.+ const tick = () => {+ void refresh().finally(() => {+ if (cancelled) return+ timer = setTimeout(tick, nextProbeDelayMs(misses))+ })+ }+ tick()+// Re-sync immediately when the user comes back to the window (the hidden- // ticks above were skipped, so the loaded-state could be stale).- const onVisible = () => { if (typeof document !== 'undefined' && !document.hidden) refresh() }+ // ticks above were skipped, so the loaded-state could be stale). Coming+ // back is also a good moment to give a backend that was down another quick+ // chance, so the ladder resets here.+ const onVisible = () => {+ if (typeof document === 'undefined' || document.hidden || cancelled) return+ misses = 0+ if (timer) clearTimeout(timer)+ tick()+ }document.addEventListener('visibilitychange', onVisible)return () => {cancelled = true- clearInterval(id)+ if (timer) clearTimeout(timer)document.removeEventListener('visibilitychange', onVisible)}}, [open])diff --git a/src/lib/__tests__/probe-backoff.test.ts b/src/lib/__tests__/probe-backoff.test.tsnew file mode 100644index 00000000..1841681c--- /dev/null+++ b/src/lib/__tests__/probe-backoff.test.ts@@ -0,0 +1,115 @@+/**+ * Counter-check round 2, side finding 6 (installed Windows build, 2026-08-29).+ *+ * On a box with no Ollama installed, the app knocked on+ * http://localhost:11434/api/ps every 1.5 seconds, forever, and wrote two+ * console lines per attempt:+ *+ * [localFetch] Proxy failed, trying direct fetch err: proxy_localhost: ...+ * Failed to load resource: net::ERR_CONNECTION_REFUSED+ *+ * Over forty hits inside a single chat round. Nothing broke, but the real+ * errors drowned in it during exactly the kind of fault-finding this run was.+ *+ * Run: npx vitest run src/lib/__tests__/probe-backoff.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, resolve } from 'node:path'+import {+ nextProbeDelayMs,+ shouldLogRepeat,+ PROBE_BASE_MS,+ PROBE_MAX_MS,+} from '../probe-backoff'++describe('nextProbeDelayMs', () => {+ it('keeps the brisk beat while the backend answers', () => {+ expect(nextProbeDelayMs(0)).toBe(PROBE_BASE_MS)+ expect(PROBE_BASE_MS).toBe(1500)+ })++ it('doubles the gap on every consecutive miss', () => {+ expect([1, 2, 3, 4, 5].map((n) => nextProbeDelayMs(n))).toEqual([3000, 6000, 12000, 24000, 48000])+ })++ it('stops climbing at one minute', () => {+ expect(nextProbeDelayMs(6)).toBe(PROBE_MAX_MS)+ expect(nextProbeDelayMs(50)).toBe(PROBE_MAX_MS)+ expect(PROBE_MAX_MS).toBe(60_000)+ })++ // NEGATIVE CONTROL: a long-lived window must not turn 2 ** many into+ // Infinity or NaN, and nonsense input must not produce a nonsense gap.+ it('never returns a broken number', () => {+ for (const n of [400, 1e9, -3, NaN, Infinity, undefined as unknown as number]) {+ const d = nextProbeDelayMs(n)+ expect(Number.isFinite(d)).toBe(true)+ expect(d).toBeGreaterThanOrEqual(PROBE_BASE_MS)+ expect(d).toBeLessThanOrEqual(PROBE_MAX_MS)+ }+ })++ it('honours a caller supplied base and cap', () => {+ expect(nextProbeDelayMs(0, 200, 1000)).toBe(200)+ expect(nextProbeDelayMs(9, 200, 1000)).toBe(1000)+ })+})++describe('shouldLogRepeat', () => {+ it('lets the first failure through and swallows the storm behind it', () => {+ const seen = new Map<string, number>()+ expect(shouldLogRepeat(seen, 'localhost', 0)).toBe(true)+ // The forty attempts of one chat round, at the old 1.5 s beat. The+ // fortieth lands exactly on the minute mark and is allowed to speak again,+ // which is the point: one line a minute instead of forty a round.+ for (let i = 1; i <= 39; i++) {+ expect(shouldLogRepeat(seen, 'localhost', i * 1500)).toBe(false)+ }+ expect(shouldLogRepeat(seen, 'localhost', 40 * 1500)).toBe(true)+ })++ it('speaks up again once the window has passed', () => {+ const seen = new Map<string, number>()+ shouldLogRepeat(seen, 'localhost', 0)+ expect(shouldLogRepeat(seen, 'localhost', 59_999)).toBe(false)+ expect(shouldLogRepeat(seen, 'localhost', 60_000)).toBe(true)+ })++ // NEGATIVE CONTROL: throttling one host must never silence another. A+ // genuinely new error has to stay visible, which is the whole point.+ it('throttles per host, not globally', () => {+ const seen = new Map<string, number>()+ expect(shouldLogRepeat(seen, 'localhost', 0)).toBe(true)+ expect(shouldLogRepeat(seen, '127.0.0.1', 10)).toBe(true)+ expect(shouldLogRepeat(seen, '192.168.0.54', 20)).toBe(true)+ })+})++// ── Wiring ───────────────────────────────────────────────────────────────────+// The dropdown cannot be rendered here (the suite runs on the node+// environment), so the source is the evidence for the two call sites.+const here = dirname(fileURLToPath(import.meta.url))+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')++describe('the pollers actually back off', () => {+ const selector = read('../../components/models/ModelSelector.tsx')++ it('the model dropdown reschedules with the ladder', () => {+ expect(selector).toContain("import { nextProbeDelayMs } from '../../lib/probe-backoff'")+ expect(selector).toContain('setTimeout(tick, nextProbeDelayMs(misses))')+ })++ // NEGATIVE CONTROL: the fixed 1.5 s interval must be gone. A backoff that+ // still runs next to a setInterval would poll just as often.+ it('the fixed 1.5 second interval is gone', () => {+ expect(selector).not.toContain('setInterval(refresh, 1500)')+ })++ it('the proxy fallback logs one line per host per window', () => {+ const backend = read('../../api/backend.ts')+ expect(backend).toContain("import { shouldLogRepeat } from \"../lib/probe-backoff\"")+ expect(backend).toContain('shouldLogRepeat(proxyWarnSeen, hostnameOf(url), Date.now())')+ })+})diff --git a/src/lib/probe-backoff.ts b/src/lib/probe-backoff.tsnew file mode 100644index 00000000..a31ad8e9--- /dev/null+++ b/src/lib/probe-backoff.ts@@ -0,0 +1,68 @@+/**+ * How long to wait before knocking on a local backend again.+ *+ * WHAT WENT WRONG (counter-check round 2, installed Windows build,+ * 2026-08-29). With Ollama not installed at all, the app kept asking+ * `http://localhost:11434/api/ps` every 1.5 seconds and wrote two console+ * lines per attempt:+ *+ * [localFetch] Proxy failed, trying direct fetch err: proxy_localhost: ...+ * Failed to load resource: net::ERR_CONNECTION_REFUSED+ *+ * Over forty hits inside a single chat round. Harmless to the product, ruinous+ * to fault-finding: the real errors drown in it.+ *+ * A backend that answers is worth polling briskly, because the loaded/unloaded+ * toggle has to self-correct within a beat (David 2026-06-12: "on und offload+ * button sehr delayed"). A backend that is not there is worth asking about+ * less and less often, up to a minute, because the answer only changes when+ * somebody starts it and one minute is a fine time to notice that.+ */++export const PROBE_BASE_MS = 1500+export const PROBE_MAX_MS = 60_000++/**+ * Delay before the next probe. Zero consecutive failures means the backend is+ * answering, so the brisk base interval stands. Each failure doubles it, and+ * the ladder stops at one minute:+ *+ * 0 -> 1.5s 1 -> 3s 2 -> 6s 3 -> 12s 4 -> 24s 5 -> 48s 6+ -> 60s+ */+export function nextProbeDelayMs(+ consecutiveFailures: number,+ base: number = PROBE_BASE_MS,+ cap: number = PROBE_MAX_MS,+): number {+ const fails = Number.isFinite(consecutiveFailures) && consecutiveFailures > 0+ ? Math.floor(consecutiveFailures)+ : 0+ if (fails === 0) return base+ // Cap the exponent before it is used, so a long-running app cannot compute+ // 2 ** 400 and hand back Infinity.+ const steps = Math.min(fails, 20)+ return Math.min(cap, base * 2 ** steps)+}++/**+ * Should this repeated failure be written to the console.+ *+ * The backoff alone already thins the noise out, but the first failures still+ * arrive at the base interval and a second poller can double them. This keeps+ * one line per key per window and swallows the rest, so a genuinely new error+ * from somewhere else stays visible.+ *+ * The clock is passed in, never read here, so the rule is testable without a+ * fake timer.+ */+export function shouldLogRepeat(+ seen: Map<string, number>,+ key: string,+ now: number,+ windowMs = 60_000,+): boolean {+ const last = seen.get(key)+ if (last !== undefined && now - last < windowMs) return false+ seen.set(key, now)+ return true+}