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): eine Messung fuer alle, und ein Kaltstart strandet den Knopf nicht mehr
purple760df14b64d9
diff --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 066462f6..dca2540d 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@@ -5,80 +5,156 @@* feeds it a real measurement. This file checks the wiring, which is the part a* pure-function test cannot see:*- * local -> no probe at all, and the button is on- * cloud -> exactly one probe, and its answer decides+ * local -> no probe at all, and the button is plain+ * cloud -> one probe for ALL consumers, and its answer decides+ * cloud -> a cold start that measured too early recovers by itself (S1)** The probe itself (api/embed-availability.ts) is stubbed here on purpose. What- * it asks the sidecar is covered by api/__tests__/embed-lane-readiness.test.ts;- * what the composer does with the answer is covered here.+ * it asks the sidecar is covered by api/__tests__/embed-lane-readiness.test.ts+ * and api/__tests__/embed-lane-names-the-host.test.ts; what the composer does+ * with the answer is covered here.** Run: npx vitest run src/hooks/__tests__/docs-availability-asks-the-embed-lane.test.ts*/import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import { createElement } from 'react'-import { render, screen, cleanup, waitFor } from '@testing-library/react'+import { render, screen, cleanup, waitFor, act } from '@testing-library/react'import { useDocsAvailability } from '../useDocsAvailability'+import { __resetEmbedLaneForTests, EMBED_LANE_RETRY_MS } from '../useEmbedLane'import { useSettingsStore } from '../../stores/settingsStore'import { DEFAULT_SETTINGS } from '../../lib/constants'-import { DOCS_TITLE_NO_EMBEDDINGS } from '../../lib/docs-availability'+import { DOCS_TITLE_NO_EMBEDDINGS, DOCS_TITLE_CLOUD_LOCAL } from '../../lib/docs-availability'+import type { EmbedLaneInfo } from '../../api/embed-availability'-const probe = vi.fn<() => Promise<boolean>>()-vi.mock('../../api/embed-availability', () => ({- embeddingBackendReady: () => probe(),- builtinEmbedReady: async () => false,+const probe = vi.fn<() => Promise<EmbedLaneInfo>>()+vi.mock('../../api/embed-availability', async (orig) => ({+ ...(await orig<typeof import('../../api/embed-availability')>()),+ embeddingLane: () => probe(),}))-function Probe() {+function Probe({ tag = 'state' }: { tag?: string }) {const a = useDocsAvailability()return createElement('div', {- 'data-testid': 'state',+ 'data-testid': tag,+ 'data-needs-setup': String(a.needsSetup),'data-enabled': String(a.enabled),'data-visible': String(a.visible),+ 'data-lane': String(a.lane),title: a.title,})}-const state = () => screen.getByTestId('state')+const state = (tag = 'state') => screen.getByTestId(tag)beforeEach(() => {probe.mockReset()+ __resetEmbedLaneForTests()useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'local' } })})-afterEach(() => cleanup())+afterEach(() => {+ cleanup()+ __resetEmbedLaneForTests()+ vi.useRealTimers()+})++const cloud = () =>+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud' } })describe('the composer asks the embedding lane, not the app mode', () => {- it('local mode never probes and never turns the button off', async () => {- probe.mockResolvedValue(false)+ it('local mode never probes and never damps the button', async () => {+ probe.mockResolvedValue({ lane: 'none', endpoint: null })render(createElement(Probe))await waitFor(() => expect(state().getAttribute('data-visible')).toBe('true'))- expect(state().getAttribute('data-enabled')).toBe('true')+ expect(state().getAttribute('data-needs-setup')).toBe('false')// Negative control: a probe that would say no was never even asked.expect(probe).not.toHaveBeenCalled()})- it('cloud mode with an embedding lane keeps the button on', async () => {- useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud' } })- probe.mockResolvedValue(true)+ it('cloud mode with a bundled lane keeps the button plain and pressable', async () => {+ cloud()+ probe.mockResolvedValue({ lane: 'bundled', endpoint: null })render(createElement(Probe))- await waitFor(() => expect(probe).toHaveBeenCalledTimes(1))- await waitFor(() => expect(state().getAttribute('data-enabled')).toBe('true'))- expect(state().getAttribute('title')).toContain('stay here')+ await waitFor(() => expect(state().getAttribute('data-lane')).toBe('bundled'))+ expect(state().getAttribute('data-needs-setup')).toBe('false')+ expect(state().getAttribute('title')).toBe(DOCS_TITLE_CLOUD_LOCAL)})- it('cloud mode without one shows it and says what is missing', async () => {- useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud' } })- probe.mockResolvedValue(false)+ it('cloud mode without a lane damps it, says what is missing, and stays pressable', async () => {+ cloud()+ probe.mockResolvedValue({ lane: 'none', endpoint: null })render(createElement(Probe))- await waitFor(() => expect(state().getAttribute('data-enabled')).toBe('false'))- expect(state().getAttribute('data-visible')).toBe('true')+ await waitFor(() => expect(state().getAttribute('data-needs-setup')).toBe('true'))+ expect(state().getAttribute('data-enabled')).toBe('true')expect(state().getAttribute('title')).toBe(DOCS_TITLE_NO_EMBEDDINGS)})+ it('cloud mode on a remote Ollama names the host in the tooltip', async () => {+ cloud()+ probe.mockResolvedValue({ lane: 'ollama-remote', endpoint: 'http://192.168.0.54:11434' })+ render(createElement(Probe))+ await waitFor(() => expect(state().getAttribute('data-lane')).toBe('ollama-remote'))+ expect(state().getAttribute('title')).toContain('192.168.0.54')+ })+it('a probe that throws is reported as missing, not as working', async () => {- useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud' } })+ cloud()probe.mockRejectedValue(new Error('tauri bridge missing'))render(createElement(Probe))- await waitFor(() => expect(state().getAttribute('data-enabled')).toBe('false'))- expect(state().getAttribute('title')).toBe(DOCS_TITLE_NO_EMBEDDINGS)+ await waitFor(() => expect(state().getAttribute('data-needs-setup')).toBe('true'))+ })++ it('two mounted consumers share ONE measurement', async () => {+ cloud()+ probe.mockResolvedValue({ lane: 'bundled', endpoint: null })+ render(createElement('div', null, createElement(Probe, { tag: 'a' }), createElement(Probe, { tag: 'b' })))+ await waitFor(() => expect(state('a').getAttribute('data-lane')).toBe('bundled'))+ expect(state('b').getAttribute('data-lane')).toBe('bundled')+ // The composer and the RAG panel both ask; the sidecar is asked once.+ expect(probe).toHaveBeenCalledTimes(1)+ })+})++describe('a cold start does not strand the button (S1)', () => {+ it('re-measures when the embed install announces itself', async () => {+ cloud()+ probe.mockResolvedValueOnce({ lane: 'none', endpoint: null })+ render(createElement(Probe))+ await waitFor(() => expect(state().getAttribute('data-needs-setup')).toBe('true'))++ probe.mockResolvedValue({ lane: 'bundled', endpoint: null })+ // Exactly the event api/embed-install.ts fires when the GGUF has landed+ // and the server is up.+ await act(async () => {+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))+ })+ await waitFor(() => expect(state().getAttribute('data-lane')).toBe('bundled'))+ expect(state().getAttribute('data-needs-setup')).toBe('false')+ })++ it('asks again by itself a few seconds after a no, because resumeEmbedServer is async', async () => {+ vi.useFakeTimers()+ cloud()+ probe.mockResolvedValueOnce({ lane: 'none', endpoint: null })+ render(createElement(Probe))+ await vi.waitFor(() => expect(state().getAttribute('data-needs-setup')).toBe('true'))++ probe.mockResolvedValue({ lane: 'bundled', endpoint: null })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(EMBED_LANE_RETRY_MS + 50)+ })+ await vi.waitFor(() => expect(state().getAttribute('data-lane')).toBe('bundled'))+ })++ 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()+ cloud()+ probe.mockResolvedValue({ lane: 'bundled', endpoint: null })+ render(createElement(Probe))+ await vi.waitFor(() => expect(state().getAttribute('data-lane')).toBe('bundled'))+ await act(async () => {+ await vi.advanceTimersByTimeAsync(EMBED_LANE_RETRY_MS * 4)+ })+ expect(probe).toHaveBeenCalledTimes(1)})})diff --git a/src/hooks/useDocsAvailability.ts b/src/hooks/useDocsAvailability.tsindex 3eaad521..a64561f0 100644--- a/src/hooks/useDocsAvailability.ts+++ b/src/hooks/useDocsAvailability.ts@@ -2,43 +2,18 @@* Docs-button state for the composer (A9).** Local mode answers without asking anything, exactly as before. Cloud mode- * probes the local embedding lane once per mount and reports what it found, so- * the button can be there and say why it cannot run instead of being missing.+ * reads the shared lane measurement (useEmbedLane) so the button can be there+ * and say what is going on instead of being missing.*/-import { useEffect, useState } from 'react'+import { useMemo } from 'react'import { useSettingsStore } from '../stores/settingsStore'-import { useRAGStore } from '../stores/ragStore'-import { embeddingBackendReady } from '../api/embed-availability'+import { useEmbedLane } from './useEmbedLane'import { docsAvailability, type DocsAvailability } from '../lib/docs-availability'export function useDocsAvailability(): DocsAvailability {const appMode = useSettingsStore((s) => s.settings.appMode)- // `null` = not measured yet. Local mode never measures: the rule ignores the- // probe there, and a Tauri round trip per composer mount for an answer nobody- // reads is a cost with no buyer.- const [embedReady, setEmbedReady] = useState<boolean | null>(null)-- useEffect(() => {- if (appMode !== 'cloud') {- setEmbedReady(null)- return- }- let cancelled = false- ;(async () => {- try {- const ready = await embeddingBackendReady(useRAGStore.getState().embeddingModel)- if (!cancelled) setEmbedReady(ready)- } catch {- // A probe that cannot run is not proof the lane is dead, but it is not- // proof it lives either, and the honest report is the one the user can- // act on: the tooltip names the missing part.- if (!cancelled) setEmbedReady(false)- }- })()- return () => {- cancelled = true- }- }, [appMode])-- return docsAvailability(appMode, embedReady)+ const info = useEmbedLane(appMode === 'cloud')+ // Memoised (review N1): this object is a prop on the button, and a fresh+ // identity on every keystroke in the composer is a re-render nobody asked for.+ return useMemo(() => docsAvailability(appMode, info), [appMode, info])}diff --git a/src/hooks/useEmbedLane.ts b/src/hooks/useEmbedLane.tsnew file mode 100644index 00000000..e120084a--- /dev/null+++ b/src/hooks/useEmbedLane.ts@@ -0,0 +1,109 @@+/**+ * The measured embedding lane, shared by every surface that asks.+ *+ * One measurement per app, not one per mounted component: the composer's Docs+ * button and the RAG panel's privacy line both want the same answer, and each+ * probe is a round trip to the Rust side plus, on the Ollama lane, a network+ * call. The module holds the result and the subscribers; a mount joins, it does+ * not re-ask.+ *+ * It also re-asks when it should (review S1). The first cut measured once on+ * mount, and on a cold start in Cloud mode the answer arrives before+ * `resumeEmbedServer` has the sidecar up, so the button was stuck in+ * needs-setup until the next app start. Two things fix that:+ *+ * - `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+ * in seconds and nobody should have to restart the app to see it.+ */+import { useEffect, useState } from 'react'+import { useRAGStore } from '../stores/ragStore'+import { embeddingLane, type EmbedLaneInfo } from '../api/embed-availability'++/** How long after a "nothing can embed" answer to ask once more. The sidecar+ * resume is a spawn plus a health check, well inside this. */+export const EMBED_LANE_RETRY_MS = 3000++let current: EmbedLaneInfo | null = null+let inflight: Promise<void> | null = null+let retryTimer: ReturnType<typeof setTimeout> | null = null+let listenerArmed = false+const subscribers = new Set<(v: EmbedLaneInfo | null) => void>()++function publish() {+ for (const fn of subscribers) fn(current)+}++/** Measure once. Concurrent callers share the one round trip. */+function measure(): Promise<void> {+ if (inflight) return inflight+ inflight = (async () => {+ try {+ current = await embeddingLane(useRAGStore.getState().embeddingModel)+ } catch {+ // A probe that cannot run is not proof the lane is dead, but it is not+ // proof it lives either, and the report the user can act on is the one+ // that offers the install.+ current = { lane: 'none', endpoint: null }+ } finally {+ inflight = null+ }+ publish()+ if (current?.lane === 'none' && retryTimer === null) {+ retryTimer = setTimeout(() => {+ retryTimer = null+ void measure()+ }, EMBED_LANE_RETRY_MS)+ }+ })()+ return inflight+}++function onRefresh() {+ current = null+ publish()+ 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+ if (retryTimer) clearTimeout(retryTimer)+ retryTimer = null+ subscribers.clear()+ if (listenerArmed) {+ window.removeEventListener('lu-models-refresh', onRefresh)+ listenerArmed = false+ }+}++/**+ * @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.+ * @returns the lane, or null while it is still unknown.+ */+export function useEmbedLane(active: boolean): EmbedLaneInfo | null {+ const [value, setValue] = useState<EmbedLaneInfo | null>(active ? current : null)++ useEffect(() => {+ if (!active) {+ setValue(null)+ return+ }+ subscribers.add(setValue)+ if (!listenerArmed) {+ listenerArmed = true+ window.addEventListener('lu-models-refresh', onRefresh)+ }+ setValue(current)+ if (current === null) void measure()+ return () => {+ subscribers.delete(setValue)+ }+ }, [active])++ return active ? value : null+}