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(chat): die Sonde misst zweimal und hoert dann auf, und sie haengt nicht am toten Host
purplebe1d88e3c4e1
diff --git a/src/api/__tests__/embed-lane-names-the-host.test.ts b/src/api/__tests__/embed-lane-names-the-host.test.tsindex 75bd52fa..76e38dff 100644--- a/src/api/__tests__/embed-lane-names-the-host.test.ts+++ b/src/api/__tests__/embed-lane-names-the-host.test.ts@@ -18,6 +18,7 @@ let bundled: { name: string; path: string }[] = []let ollamaUp = truelet ollamaModels: { name: string }[] = []let base = 'http://localhost:11434'+const connectionArgs: (number | undefined)[] = []vi.mock('../backend', () => ({backendCall: async (cmd: string) => {@@ -36,7 +37,10 @@ vi.mock('../backend', () => ({}))vi.mock('../ollama', () => ({- checkConnection: async () => ollamaUp,+ checkConnection: async (timeoutMs?: number) => {+ connectionArgs.push(timeoutMs)+ return ollamaUp+ },listModels: async () => ollamaModels,}))@@ -48,7 +52,12 @@ vi.mock('../../stores/providerStore', () => ({},}))-import { embeddingLane, embeddingBackendReady, laneIsOnThisMachine } from '../embed-availability'+import {+ embeddingLane,+ embeddingBackendReady,+ laneIsOnThisMachine,+ EMBED_PROBE_TIMEOUT_MS,+} from '../embed-availability'beforeEach(() => {embedRunning = false@@ -56,6 +65,7 @@ beforeEach(() => {ollamaUp = trueollamaModels = []base = 'http://localhost:11434'+ connectionArgs.length = 0})describe('the probe reports WHERE the text would go, not just whether it can go', () => {@@ -118,3 +128,31 @@ describe('the probe reports WHERE the text would go, not just whether it can go'expect(await embeddingBackendReady('nomic-embed-text')).toBe(false)})})++describe('the probe never hangs the UI on a dead host (review 3)', () => {+ it('asks Ollama with a short budget instead of the proxy default', async () => {+ // Without a budget the Rust proxy waits 300000 ms. A LAN box that is simply+ // switched off does not refuse the connection, it swallows it, so the Docs+ // tooltip, the install button and the privacy paragraph all froze for five+ // minutes. The paragraph froze hardest: it does not render until a lane is+ // measured at all.+ base = 'http://192.168.0.54:11434'+ ollamaModels = [{ name: 'nomic-embed-text' }]+ await embeddingLane('nomic-embed-text')+ expect(connectionArgs).toEqual([EMBED_PROBE_TIMEOUT_MS])+ expect(EMBED_PROBE_TIMEOUT_MS).toBeLessThanOrEqual(3000)+ })++ it('a host that never answers is simply "no lane", not a five minute wait', async () => {+ ollamaUp = false+ expect((await embeddingLane('nomic-embed-text')).lane).toBe('none')+ })++ it('the bundled lane short-circuits and never asks Ollama at all', async () => {+ // Negative control: the timeout matters only on the path that uses it, and+ // the everyday case must not pay for a network probe it does not need.+ embedRunning = true+ await embeddingLane('nomic-embed-text')+ expect(connectionArgs).toEqual([])+ })+})diff --git a/src/api/embed-availability.ts b/src/api/embed-availability.tsindex fc9f8bbd..f8656a95 100644--- a/src/api/embed-availability.ts+++ b/src/api/embed-availability.ts@@ -42,6 +42,19 @@ import { getOllamaBase, isOllamaLocal } from './backend'*/export type EmbedLane = 'bundled' | 'ollama-local' | 'ollama-remote' | 'none'+/**+ * How long any UI-path probe may wait on Ollama.+ *+ * The base URL points wherever the user set it. A LAN box that is simply off+ * does not refuse the connection, it swallows it, and `checkConnection` without+ * a budget inherits the Rust proxy default of 300000 ms. That froze the Docs+ * tooltip, the install button and the privacy paragraph for five minutes, the+ * paragraph because it waits for a measured lane before it renders at all.+ * Three seconds is generous for a reachable host on a LAN and short enough that+ * an unreachable one is just an answer (review point 3).+ */+export const EMBED_PROBE_TIMEOUT_MS = 3000+export interface EmbedLaneInfo {lane: EmbedLane/** The host the text would travel to, set only for `ollama-remote`. */@@ -85,7 +98,7 @@ export async function embeddingLane(embeddingModel: string): Promise<EmbedLaneIn// The bundled lane is the only one rag.ts will use here, so a pulled Ollama// model is not an answer to this question.if (isManagedBuiltinActive()) return { lane: 'none', endpoint: null }- if (!(await checkConnection())) return { lane: 'none', endpoint: null }+ if (!(await checkConnection(EMBED_PROBE_TIMEOUT_MS))) return { lane: 'none', endpoint: null }try {const models = await listModels()const has = models.some(diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex aced6608..4e4a603d 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -401,9 +401,20 @@ export async function unloadAllModels(): Promise<number> {return running.length}-export async function checkConnection(): Promise<boolean> {+/**+ * Is Ollama answering.+ *+ * `timeoutMs` matters more than it looks. Without one the Rust proxy applies its+ * own default of 300000 ms, and the base URL is user-configurable, so a LAN host+ * that is switched off does not refuse the connection, it swallows it: the probe+ * sits there for five minutes. Anything on a UI path has to pass a short budget+ * (see EMBED_PROBE_TIMEOUT_MS). A timeout counts as "not reachable", which is+ * the honest reading, because a backend that cannot answer in three seconds+ * cannot serve an embedding request either.+ */+export async function checkConnection(timeoutMs?: number): Promise<boolean> {try {- await localFetch(ollamaUrl("/tags"))+ await localFetch(ollamaUrl("/tags"), timeoutMs ? { timeoutMs } : undefined)return true} catch {return falsediff --git a/src/hooks/__tests__/docs-availability-asks-the-embed-lane.test.ts b/src/hooks/__tests__/docs-availability-asks-the-embed-lane.test.tsindex dca2540d..fbbc0813 100644--- a/src/hooks/__tests__/docs-availability-asks-the-embed-lane.test.ts+++ b/src/hooks/__tests__/docs-availability-asks-the-embed-lane.test.ts@@ -145,6 +145,47 @@ describe('a cold start does not strand the button (S1)', () => {await vi.waitFor(() => expect(state().getAttribute('data-lane')).toBe('bundled'))})+ it('a lane that stays missing is asked TWICE, not eleven times (review 1)', async () => {+ // The defect: the retry called the measurement, which scheduled another+ // retry on another negative answer. One measurement became eleven over ten+ // windows, and every cloud user without an embedding lane would have polled+ // four backend calls every three seconds forever, for an answer that does+ // not change on its own.+ vi.useFakeTimers()+ cloud()+ probe.mockResolvedValue({ lane: 'none', endpoint: null })+ render(createElement(Probe))+ await vi.waitFor(() => expect(state().getAttribute('data-needs-setup')).toBe('true'))+ expect(probe).toHaveBeenCalledTimes(1)++ await act(async () => {+ await vi.advanceTimersByTimeAsync(EMBED_LANE_RETRY_MS * 10 + 500)+ })+ expect(probe).toHaveBeenCalledTimes(2)+ })++ it('a refresh event earns one more look, and only one', async () => {+ vi.useFakeTimers()+ cloud()+ probe.mockResolvedValue({ lane: 'none', endpoint: null })+ render(createElement(Probe))+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(1))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(EMBED_LANE_RETRY_MS * 3)+ })+ expect(probe).toHaveBeenCalledTimes(2)++ await act(async () => {+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))+ })+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(3))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(EMBED_LANE_RETRY_MS * 5)+ })+ // The refresh bought exactly one retry, not a new poll.+ expect(probe).toHaveBeenCalledTimes(4)+ })+it('does not keep re-asking once the answer is good', async () => {// Negative control on the retry: it exists for the boot race, not as a poll.vi.useFakeTimers()@@ -158,3 +199,66 @@ describe('a cold start does not strand the button (S1)', () => {expect(probe).toHaveBeenCalledTimes(1)})})++describe('nothing keeps running after the last consumer leaves (review 2)', () => {+ it('unmounting cancels the pending retry', async () => {+ vi.useFakeTimers()+ cloud()+ probe.mockResolvedValue({ lane: 'none', endpoint: null })+ const view = render(createElement(Probe))+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(1))++ view.unmount()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(EMBED_LANE_RETRY_MS * 3 + 500)+ })+ // Measured before the fix: one measurement became four after unmount.+ expect(probe).toHaveBeenCalledTimes(1)+ })++ it('the refresh listener goes with it, so a stray event wakes nothing', async () => {+ cloud()+ probe.mockResolvedValue({ lane: 'bundled', endpoint: null })+ const view = render(createElement(Probe))+ await waitFor(() => expect(probe).toHaveBeenCalledTimes(1))++ view.unmount()+ await act(async () => {+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))+ })+ expect(probe).toHaveBeenCalledTimes(1)+ })++ it('switching from Cloud to Local stops the measuring for good', async () => {+ vi.useFakeTimers()+ cloud()+ probe.mockResolvedValue({ lane: 'none', endpoint: null })+ render(createElement(Probe))+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(1))++ await act(async () => {+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'local' } })+ })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(EMBED_LANE_RETRY_MS * 4)+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))+ })+ expect(probe).toHaveBeenCalledTimes(1)+ // And the button is plain again, because local mode does not read a lane.+ expect(state().getAttribute('data-needs-setup')).toBe('false')+ })++ it('a later mount still gets its own fresh look', async () => {+ // Negative control on the teardown: it must stop the poll, not the feature.+ vi.useFakeTimers()+ cloud()+ probe.mockResolvedValue({ lane: 'none', endpoint: null })+ const first = render(createElement(Probe))+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(1))+ first.unmount()++ probe.mockResolvedValue({ lane: 'bundled', endpoint: null })+ render(createElement(Probe))+ await vi.waitFor(() => expect(state().getAttribute('data-lane')).toBe('bundled'))+ })+})diff --git a/src/hooks/__tests__/rag-context-reaches-a-cloud-send.test.ts b/src/hooks/__tests__/rag-context-reaches-a-cloud-send.test.tsindex eb09b26b..e7722935 100644--- a/src/hooks/__tests__/rag-context-reaches-a-cloud-send.test.ts+++ b/src/hooks/__tests__/rag-context-reaches-a-cloud-send.test.ts@@ -206,6 +206,24 @@ describe('a retrieval that fails is said out loud, not swallowed (S4)', () => {expect(useRAGStore.getState().retrievalError).toBe(RETRIEVAL_FAILED_MESSAGE)})+ it('switching Document Chat off clears the notice too', async () => {+ // Nebenbefund from the review: it was only cleared inside the retrieval+ // block, so a user who read the warning and switched RAG off kept a stale+ // alarm over a composer that is no longer searching any documents.+ const convId = seed([chunk(0, HIT)])+ useRAGStore.getState().setRetrievalError(RETRIEVAL_FAILED_MESSAGE)+ useRAGStore.getState().setRagEnabled(convId, false)+ expect(useRAGStore.getState().retrievalError).toBeNull()+ })++ it('switching it back ON does not resurrect or invent a notice', async () => {+ // Negative control on the same line: enabling must leave the field alone.+ const convId = seed([chunk(0, HIT)])+ useRAGStore.getState().setRetrievalError(RETRIEVAL_FAILED_MESSAGE)+ useRAGStore.getState().setRagEnabled(convId, true)+ expect(useRAGStore.getState().retrievalError).toBe(RETRIEVAL_FAILED_MESSAGE)+ })+it('a later good turn clears the notice', async () => {// Negative control: a sticky warning would be its own bug, telling the user// their documents are broken forever after one hiccup.diff --git a/src/hooks/__tests__/the-install-card-has-a-working-path.test.ts b/src/hooks/__tests__/the-install-card-has-a-working-path.test.tsindex 02687ea0..85256c36 100644--- a/src/hooks/__tests__/the-install-card-has-a-working-path.test.ts+++ b/src/hooks/__tests__/the-install-card-has-a-working-path.test.ts@@ -28,12 +28,17 @@ vi.mock('../../api/engine', () => ({vi.mock('../../api/embed-availability', () => ({builtinEmbedReady: async () => false,embeddingBackendReady: async () => false,+ EMBED_PROBE_TIMEOUT_MS: 3000,}))vi.mock('../../api/embed-install', () => ({installBundledEmbedModel: (...a: any[]) => installBundled(...(a as [])),}))+const connectionArgs: (number | undefined)[] = []vi.mock('../../api/ollama', () => ({- checkConnection: async () => ollamaUp,+ checkConnection: async (timeoutMs?: number) => {+ connectionArgs.push(timeoutMs)+ return ollamaUp+ },getModelContext: async () => 8192,pullModelTauri: (...a: any[]) => pullTauri(...(a as [])),}))@@ -49,6 +54,7 @@ beforeEach(() => {ollamaUp = trueinstallBundled.mockClear()pullTauri.mockClear()+ connectionArgs.length = 0})async function install() {@@ -76,6 +82,15 @@ describe('the install card reaches a real shop from wherever it was opened', ()expect(pullTauri).not.toHaveBeenCalled()})+ it('the reachability question carries a short budget, not the 5 minute default', async () => {+ // Review point 3: the install button sat on the same unbounded probe, so a+ // dead LAN host froze the card for five minutes before it did anything.+ managed = false+ ollamaUp = true+ await install()+ expect(connectionArgs).toEqual([3000])+ })+it('Ollama running: still `ollama pull`, because that is the lane rag.ts would use', async () => {// Negative control: the new fallback must not hijack the case that worked.managed = falsediff --git a/src/hooks/useEmbedLane.ts b/src/hooks/useEmbedLane.tsindex e120084a..eee7273c 100644--- a/src/hooks/useEmbedLane.ts+++ b/src/hooks/useEmbedLane.ts@@ -14,8 +14,18 @@** - `lu-models-refresh`, which is what a finished embed install already fires* (api/embed-install.ts) and what useModels listens to for the same reason.- * - one delayed retry after a negative answer, because the boot race resolves+ * - ONE delayed retry after a negative answer, because the boot race resolves* in seconds and nobody should have to restart the app to see it.+ *+ * "One" is the load-bearing word, and the first cut got it wrong: the retry+ * called measure(), which scheduled another retry on another negative answer, so+ * one measurement became eleven over ten windows. Every cloud user without an+ * embedding lane would have polled bundled_embed_status, list_bundled_models,+ * checkConnection and listModels every three seconds, forever, for an answer+ * that was not going to change on its own. The arm below fires once per mount+ * and once per refresh event, and the whole thing is torn down when the last+ * subscriber leaves, so switching from Cloud to Local does not carry a poll+ * along with it (review points 1 and 2).*/import { useEffect, useState } from 'react'import { useRAGStore } from '../stores/ragStore'@@ -28,6 +38,9 @@ export const EMBED_LANE_RETRY_MS = 3000let current: EmbedLaneInfo | null = nulllet inflight: Promise<void> | null = nulllet retryTimer: ReturnType<typeof setTimeout> | null = null+/** Spent for this mount / this refresh. Reset only where a new reason to look+ * again exists, never by the retry itself. */+let retryUsed = falselet listenerArmed = falseconst subscribers = new Set<(v: EmbedLaneInfo | null) => void>()@@ -50,9 +63,12 @@ function measure(): Promise<void> {inflight = null}publish()- if (current?.lane === 'none' && retryTimer === null) {+ if (current?.lane === 'none' && !retryUsed && retryTimer === null && subscribers.size > 0) {+ retryUsed = trueretryTimer = setTimeout(() => {retryTimer = null+ // Nobody is looking any more: do not spend the round trip.+ if (subscribers.size === 0) returnvoid measure()}, EMBED_LANE_RETRY_MS)}@@ -61,25 +77,34 @@ function measure(): Promise<void> {}function onRefresh() {+ // A real event happened, so one more look is earned.+ retryUsed = falsecurrent = nullpublish()void measure()}-/** Test seam: the cache is module state on purpose (one per app), so a test- * needs a way back to a clean slate. */-export function __resetEmbedLaneForTests(): void {- current = null- inflight = null+/** Stop everything this module started. Called when the last subscriber goes,+ * which is also what a switch from Cloud to Local looks like from here. */+function teardown() {if (retryTimer) clearTimeout(retryTimer)retryTimer = null- subscribers.clear()+ retryUsed = falseif (listenerArmed) {window.removeEventListener('lu-models-refresh', onRefresh)listenerArmed = false}}+/** Test seam: the cache is module state on purpose (one per app), so a test+ * needs a way back to a clean slate. */+export function __resetEmbedLaneForTests(): void {+ current = null+ inflight = null+ subscribers.clear()+ teardown()+}+/*** @param active measure at all. False in local mode, which does not read the* answer, so it must not pay a round trip per composer mount either.@@ -93,15 +118,23 @@ export function useEmbedLane(active: boolean): EmbedLaneInfo | null {setValue(null)return}+ // A fresh mount is a fresh reason to look, so it gets its own retry.+ const fresh = subscribers.size === 0+ if (fresh) retryUsed = falsesubscribers.add(setValue)if (!listenerArmed) {listenerArmed = truewindow.addEventListener('lu-models-refresh', onRefresh)}setValue(current)- if (current === null) void measure()+ // Never measured yet, or the cache holds a NO and this is a new mount: a+ // user who left Cloud mode, installed an engine and came back must not read+ // a stale refusal. A cached YES is kept; nothing about it goes stale in a+ // way that hurts, and a real change fires lu-models-refresh anyway.+ if (current === null || (fresh && current.lane === 'none')) void measure()return () => {subscribers.delete(setValue)+ if (subscribers.size === 0) teardown()}}, [active])diff --git a/src/hooks/useRAG.ts b/src/hooks/useRAG.tsindex c9b02514..e332a8ed 100644--- a/src/hooks/useRAG.ts+++ b/src/hooks/useRAG.ts@@ -3,7 +3,7 @@ import { useShallow } from "zustand/react/shallow"import { useRAGStore } from "../stores/ragStore"import { indexDocument, retrieveContext } from "../api/rag"import { isManagedBuiltinActive } from "../api/engine"-import { builtinEmbedReady, embeddingBackendReady } from "../api/embed-availability"+import { builtinEmbedReady, embeddingBackendReady, EMBED_PROBE_TIMEOUT_MS } from "../api/embed-availability"import { installBundledEmbedModel } from "../api/embed-install"import { getModelContext, pullModelTauri, checkConnection } from "../api/ollama"import { useModelStore } from "../stores/modelStore"@@ -129,7 +129,7 @@ export function useRAG(conversationId: string | null) {// had no working install path from this card. Ask whether Ollama is// actually reachable, and fall to the bundled GGUF when it is not, which is// the lane rag.ts would take anyway.- const ollamaReachable = isManagedBuiltinActive() ? false : await checkConnection()+ const ollamaReachable = isManagedBuiltinActive() ? false : await checkConnection(EMBED_PROBE_TIMEOUT_MS)if (isManagedBuiltinActive() || !ollamaReachable) {try {await installBundledEmbedModel((completed, total) =>@@ -196,7 +196,7 @@ export function useRAG(conversationId: string | null) {setEmbeddingInstallPrompt(true)return null}- const ollamaUp = await checkConnection()+ const ollamaUp = await checkConnection(EMBED_PROBE_TIMEOUT_MS)if (!ollamaUp) {throw new Error("No embedding backend is running. Start the built-in engine (or Ollama) and try again."diff --git a/src/stores/ragStore.ts b/src/stores/ragStore.tsindex f74c303f..69de901b 100644--- a/src/stores/ragStore.ts+++ b/src/stores/ragStore.ts@@ -155,6 +155,10 @@ export const useRAGStore = create<RAGState>()(setRagEnabled: (conversationId, enabled) =>set((state) => ({ragEnabled: { ...state.ragEnabled, [conversationId]: enabled },+ // Switching Document Chat off answers the complaint. Leaving "your+ // documents could not be searched" standing over a composer that is+ // no longer searching documents is just a stale alarm.+ retrievalError: enabled ? state.retrievalError : null,})),setEmbeddingModel: (model) => set({ embeddingModel: model }),