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
feat(chat): say why a long first wait on a local Ollama model lasts (B26)
purple1a45739c708f
diff --git a/src/components/chat/WorkingAnchor.tsx b/src/components/chat/WorkingAnchor.tsxindex 61663b65..059a6987 100644--- a/src/components/chat/WorkingAnchor.tsx+++ b/src/components/chat/WorkingAnchor.tsx@@ -95,6 +95,13 @@ export function WorkingAnchor({ isRunning, conversationId, awaitingApproval, loa><StatusChip kind={status.kind} word={status.word} detail={status.detail} seconds={elapsed} /></div>+ {/* B26: why the first wait lasts, while it is still the line shown.+ Outside the live region: the word is announced, the sentence is read. */}+ {activity?.hint && status.word === activity.label && (+ <p className="pl-11 pr-3 pb-1.5 text-xs text-gray-500 dark:text-gray-400" data-testid="working-anchor-hint">+ {activity.hint}+ </p>+ )}{/* Scrolled away from the line above, the run still shows: the mark alone, above the composer. */}<WorkingBeacon anchor={line} kind={status.kind} /></>diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex d3054a7c..82a7b5ec 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -1,6 +1,7 @@import { useRef, useState, useCallback, useEffect } from 'react'import { frameFlush } from '../lib/frame-flush'import { useRunActivityStore, toolProgressActivity, waitBeforeRetry, readingActivity, endFirstWait, hiddenThoughtArrived, waitForChatCard } from '../stores/runActivityStore'+import { watchChatFirstWait } from '../lib/first-wait-vram'import { markCannotThink } from '../lib/model-compatibility'import {type ApprovalEntry,@@ -2015,7 +2016,12 @@ export function useAgentChat() {// A7: the first wait of a turn is the model reading the request.// Said in words and with its size instead of a bare "Starting"; the// first word, shown thought or tool call takes the line back.- if (stepNo === 1) useRunActivityStore.getState().setActivity(convId, readingActivity(estPrompt))+ if (stepNo === 1) {+ useRunActivityStore.getState().setActivity(convId, readingActivity(estPrompt))+ // B26: a long first wait on a local Ollama model gets its reason+ // (lib/first-wait-vram). It ends by itself at the first sign.+ watchChatFirstWait(convId, activeModel, abort.signal)+ }// A7: one line in the log file per message, with where the first// wait went: the setup before the request, and the model reading// until its first word, thought or call. Measured instead ofdiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 875d5d99..e8a097ee 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -14,6 +14,7 @@ import { conversationChunksNow, useRAGStore } from "../stores/ragStore"import { useMemoryStore } from "../stores/memoryStore"import { useVoiceStore } from "../stores/voiceStore"import { useRunActivityStore, readingActivity, endFirstWait, hiddenThoughtArrived, waitForChatCard } from "../stores/runActivityStore"+import { watchChatFirstWait } from "../lib/first-wait-vram"import { autoSpeak } from "../lib/ttsBridge"import { retrieveContext } from "../api/rag"import { NO_EMBED_MODEL_MOBILE_MESSAGE, isSingleSlotConflict } from "../lib/model-slot"@@ -1836,6 +1837,11 @@ export function useChat() {// A7: until the first token the model reads the request; say so, with// its size, instead of a bare "Starting" (stores/runActivityStore).useRunActivityStore.getState().setActivity(convId, readingActivity(estimateMessageTokens(messages as unknown as Parameters<typeof estimateMessageTokens>[0])))+ // B26: a long first wait on a local Ollama model gets its reason: still+ // loading, or partly on the CPU because it does not fit on the card.+ // It ends by itself at the first word, on Stop, or once endFirstWait+ // below has taken the reading line back.+ watchChatFirstWait(convId, activeModel, abort.signal)for await (const chunk of stream) {// Abort fast-path: if the user hit Stop while a thinking-heavy modeldiff --git a/src/lib/__tests__/first-wait-vram.test.ts b/src/lib/__tests__/first-wait-vram.test.tsnew file mode 100644index 00000000..815b34a1--- /dev/null+++ b/src/lib/__tests__/first-wait-vram.test.ts@@ -0,0 +1,114 @@+// @vitest-environment jsdom+/**+ * B26 (3.0.9): Discord 28.10.2026, a 27B IQ2_M on an 8 GB RTX 4060 sat on+ * "Reading the conversation" without a word. The line now says why: still+ * loading, or partly on the CPU, with a smaller model that fits.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { render, screen } from '@testing-library/react'+import { createElement } from 'react'+import { firstWaitActivity, smallerModelThatFits, watchFirstWait } from '../first-wait-vram'+import { readingActivity, useRunActivityStore, type RunActivity } from '../../stores/runActivityStore'+import { WorkingAnchor } from '../../components/chat/WorkingAnchor'++const GB = 1_073_741_824+const reading = readingActivity(5600)+// Measured shape of the report: Ollama put 6.9 of 11.2 GB on the 8 GB card.+const bigOnCpu = { name: 'qwen3.8-27b:iq2_m', size: 11.2 * GB, sizeVram: 6.9 * GB, contextLength: 8192 }+const installed = [+ { name: 'qwen3.8-27b:iq2_m', size: 9.8 * GB },+ { name: 'gemma4:e4b', size: 5.1 * GB },+ { name: 'qwen3.5:4b', size: 3.4 * GB },+ { name: 'mistral-small:24b', size: 14 * GB },+]++describe('what the first wait says', () => {+ it('a model not yet in /api/ps is still loading', () => {+ expect(firstWaitActivity({ reading, model: 'qwen3.8-27b:iq2_m', loaded: [], installed }))+ .toEqual({ label: 'Loading the model', kind: 'reading', detail: 'qwen3.8-27b:iq2_m' })+ })++ it('a model partly on the CPU gets the share, the sizes and a smaller installed model that fits', () => {+ const out = firstWaitActivity({ reading, model: 'qwen3.8-27b:iq2_m', loaded: [bigOnCpu], installed })+ expect(out).toMatchObject({ label: 'Reading the conversation', kind: 'reading', detail: '5.6k tokens' })+ expect(out?.hint).toContain('Only 6.9 GB of qwen3.8-27b:iq2_m\'s 11 GB fit on your graphics card')+ expect(out?.hint).toContain('38% runs on the CPU')+ expect(out?.hint).toContain('gemma4:e4b (5.1 GB)')+ })++ it('with nothing smaller installed, it names the size that would fit', () => {+ const out = firstWaitActivity({ reading, model: 'qwen3.8-27b:iq2_m', loaded: [bigOnCpu], installed: installed.slice(0, 1) })+ expect(out?.hint).toContain('A model under 5.9 GB fits on your card')+ })++ it('all of it on the CPU says so', () => {+ const out = firstWaitActivity({ reading, model: 'big', loaded: [{ name: 'big', size: 20 * GB, sizeVram: 0, contextLength: 0 }], installed })+ expect(out?.hint).toContain('runs entirely on the CPU (20 GB)')+ })++ it('a model that fits, or an unreadable /api/ps, adds nothing', () => {+ expect(firstWaitActivity({ reading, model: 'gemma4:e4b', loaded: [{ name: 'gemma4:e4b', size: 6 * GB, sizeVram: 6 * GB, contextLength: 0 }], installed })).toBeNull()+ expect(firstWaitActivity({ reading, model: 'gemma4:e4b', loaded: null, installed })).toBeNull()+ })++ it('":latest" names the same model', () => {+ expect(firstWaitActivity({ reading, model: 'llama3', loaded: [{ name: 'llama3:latest', size: 5 * GB, sizeVram: 5 * GB, contextLength: 0 }], installed })).toBeNull()+ expect(smallerModelThatFits([{ name: 'llama3:latest', size: 1 }], 'llama3', 10 * GB)).toBeNull()+ })+})++describe('the watch', () => {+ beforeEach(() => { vi.useFakeTimers(); useRunActivityStore.setState({ activity: {} }) })+ afterEach(() => { vi.useRealTimers() })++ const store = {+ get: () => useRunActivityStore.getState().activity.c1,+ set: (a: RunActivity) => useRunActivityStore.getState().setActivity('c1', a),+ }++ it('looks after the first wait, says loading, then the CPU share, and stops at the first word', async () => {+ useRunActivityStore.getState().setActivity('c1', reading)+ const answers = [[], [bigOnCpu]]+ const readLoaded = vi.fn(async () => answers.shift() ?? [bigOnCpu])+ watchFirstWait({ conversationId: 'c1', model: 'qwen3.8-27b:iq2_m', readLoaded, readInstalled: () => installed, getActivity: store.get, setActivity: store.set, firstLookMs: 10_000, everyMs: 5_000 })++ await vi.advanceTimersByTimeAsync(9_000)+ expect(readLoaded).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(store.get()).toMatchObject({ label: 'Loading the model' })+ await vi.advanceTimersByTimeAsync(5_000)+ expect(store.get()).toMatchObject({ label: 'Reading the conversation', detail: '5.6k tokens' })+ expect(store.get()?.hint).toContain('fit on your graphics card')++ // The first word takes the line back (endFirstWait): the watch stops.+ useRunActivityStore.getState().setActivity('c1', null)+ const calls = readLoaded.mock.calls.length+ await vi.advanceTimersByTimeAsync(20_000)+ expect(readLoaded.mock.calls.length).toBe(calls)+ expect(store.get()).toBeUndefined()+ })++ it('Stop ends it before the first look', async () => {+ useRunActivityStore.getState().setActivity('c1', reading)+ const abort = new AbortController()+ const readLoaded = vi.fn(async () => [bigOnCpu])+ watchFirstWait({ conversationId: 'c1', model: 'm', signal: abort.signal, readLoaded, readInstalled: () => [], getActivity: store.get, setActivity: store.set })+ abort.abort()+ await vi.advanceTimersByTimeAsync(60_000)+ expect(readLoaded).not.toHaveBeenCalled()+ })+})++describe('the status line shows the sentence', () => {+ it('under "Reading the conversation" while that is the line', () => {+ useRunActivityStore.setState({ activity: { c9: { ...reading, hint: 'Only 6.9 GB of x fit on your graphics card.' } } })+ render(createElement(WorkingAnchor, { isRunning: true, conversationId: 'c9', message: { content: '', agentBlocks: [] } }))+ expect(screen.getByTestId('working-anchor-hint').textContent).toContain('fit on your graphics card')+ })++ it('not once the model answers', () => {+ useRunActivityStore.setState({ activity: { c9: { ...reading, hint: 'Only 6.9 GB of x fit on your graphics card.' } } })+ render(createElement(WorkingAnchor, { isRunning: true, conversationId: 'c9', message: { content: 'Hallo' } }))+ expect(screen.queryByTestId('working-anchor-hint')).toBeNull()+ })+})diff --git a/src/lib/first-wait-vram.ts b/src/lib/first-wait-vram.tsnew file mode 100644index 00000000..ec0506fc--- /dev/null+++ b/src/lib/first-wait-vram.ts@@ -0,0 +1,168 @@+/**+ * B26 (3.0.9): the first wait of a local chat turn, when it does not end.+ *+ * Discord, 28.10.2026: a 27B model at IQ2_M on an 8 GB card sat on "Reading+ * the conversation" with nothing else said, until the user gave up. Ollama+ * had put most of the model on the CPU, and reading the conversation there+ * takes minutes. LU knew nothing of it, because it never asked.+ *+ * Now it asks, once the wait is long enough to need words: /api/ps says+ * whether the model is loaded yet and how much of it sits in graphics memory+ * (`size` and `size_vram`, the same figures lib/ollama-window-fit reads).+ * Only what Ollama reports is said, nothing is predicted. While the model is+ * not listed, it is still loading. When part of it runs on the CPU, the line+ * says how much and names a smaller installed model that would fit, or the+ * size one would need.+ *+ * The words are pure, so every sentence is a test; the watch is small.+ */++import { readLoadedModels, type LoadedOllamaModel } from '../api/ollama'+import { getProviderIdFromModel } from '../api/providers/model-name'+import { cpuSharePercent } from './ollama-window-fit'+import { useModelStore } from '../stores/modelStore'+import { useRunActivityStore, type RunActivity } from '../stores/runActivityStore'++/** How long a first wait runs before LU looks why. A turn that answers sooner needs no sentence. */+export const FIRST_WAIT_LOOK_AFTER_MS = 10_000+/** How often it looks again while the wait goes on. */+export const FIRST_WAIT_LOOK_EVERY_MS = 5_000++/** Room the context and the runtime need next to the weights, so a model+ * that would only just fit is not offered as one that fits. */+const FIT_HEADROOM = 0.85++/** An installed model and its file size, as Ollama lists it. */+export interface InstalledSize {+ name: string+ size: number+}++function gigabytes(bytes: number): string {+ const gb = bytes / 1_073_741_824+ return gb >= 10 ? `${Math.round(gb)} GB` : `${Math.round(gb * 10) / 10} GB`+}++/** Ollama lists "name" and "name:latest" for the same model. */+function sameModel(a: string, b: string): boolean {+ const bare = (n: string) => (n.endsWith(':latest') ? n.slice(0, -7) : n)+ return bare(a) === bare(b)+}++/**+ * The largest installed model whose file fits in what the card holds, or+ * null. `cardBytes` is what Ollama could put in graphics memory for the model+ * that did not fit: a measured figure, not a spec sheet.+ */+export function smallerModelThatFits(installed: readonly InstalledSize[], current: string, cardBytes: number): InstalledSize | null {+ const room = cardBytes * FIT_HEADROOM+ const fits = installed+ .filter((m) => m.size > 0 && m.size <= room && !sameModel(m.name, current))+ .sort((a, b) => b.size - a.size)+ return fits[0] ?? null+}++/**+ * What the status line says after the first look. Null when there is nothing+ * to add: the model is loaded and all of it is on the card, or Ollama did not+ * answer (then nothing is known, and nothing is said).+ */+export function firstWaitActivity(input: {+ /** The reading line that stood until now. */+ reading: RunActivity+ model: string+ /** /api/ps, or null when it could not be read. */+ loaded: readonly LoadedOllamaModel[] | null+ installed: readonly InstalledSize[]+}): RunActivity | null {+ const { reading, model, loaded, installed } = input+ if (!loaded) return null+ const entry = loaded.find((m) => sameModel(m.name, model))+ if (!entry) {+ // Listed from the moment its runner starts, so not listed means the load+ // has not got that far, or the model waits behind another one.+ return { label: 'Loading the model', kind: 'reading', detail: model }+ }+ const share = cpuSharePercent(entry)+ if (share === null || share <= 0) return null+ const onCard = Math.min(entry.sizeVram, entry.size)+ const where = share >= 100+ ? `${model} runs entirely on the CPU (${gigabytes(entry.size)}), so reading the conversation can take minutes.`+ : `Only ${gigabytes(onCard)} of ${model}'s ${gigabytes(entry.size)} fit on your graphics card. The other ${share}% runs on the CPU, so reading the conversation can take minutes.`+ const smaller = onCard > 0 ? smallerModelThatFits(installed, model, onCard) : null+ const advice = smaller+ ? `A model that fits answers much faster, for example ${smaller.name} (${gigabytes(smaller.size)}).`+ : onCard > 0+ ? `A model under ${gigabytes(onCard * FIT_HEADROOM)} fits on your card and answers much faster.`+ : 'A smaller model, or one with a lower quantization, answers much faster.'+ return { ...reading, hint: `${where} ${advice}` }+}++/**+ * Watch the first wait of a local Ollama turn and say why it lasts. Stops by+ * itself once the line is no longer a reading line (the first word arrived,+ * see endFirstWait) or on `signal`. Never throws.+ */+export function watchFirstWait(opts: {+ conversationId: string+ model: string+ signal?: AbortSignal+ readLoaded: () => Promise<LoadedOllamaModel[]>+ readInstalled: () => InstalledSize[]+ getActivity: () => RunActivity | undefined+ setActivity: (activity: RunActivity) => void+ firstLookMs?: number+ everyMs?: number+}): () => void {+ let stopped = false+ let timer: ReturnType<typeof setTimeout> | null = null+ // The reading line as the run set it, so a later look can go back to it+ // (a load that finished turns "Loading the model" back into reading).+ let reading: RunActivity | null = null+ const stop = () => {+ stopped = true+ if (timer) clearTimeout(timer)+ opts.signal?.removeEventListener('abort', stop)+ }+ opts.signal?.addEventListener('abort', stop, { once: true })+ const look = async () => {+ timer = null+ if (stopped) return+ const now = opts.getActivity()+ if (now?.kind !== 'reading') { stop(); return }+ if (!reading) reading = now.label === 'Loading the model' ? null : { label: now.label, kind: now.kind, ...(now.detail ? { detail: now.detail } : {}) }+ let loaded: LoadedOllamaModel[] | null = null+ try { loaded = await opts.readLoaded() } catch { loaded = null }+ if (stopped) return+ // The first word may have come in while /api/ps was being read.+ if (opts.getActivity()?.kind !== 'reading') { stop(); return }+ const base = reading ?? { label: 'Reading the conversation', kind: 'reading' as const }+ const next = firstWaitActivity({ reading: base, model: opts.model, loaded, installed: opts.readInstalled() })+ if (next) opts.setActivity(next)+ else if (loaded) opts.setActivity(base)+ timer = setTimeout(() => void look(), opts.everyMs ?? FIRST_WAIT_LOOK_EVERY_MS)+ }+ if (!opts.signal?.aborted) timer = setTimeout(() => void look(), opts.firstLookMs ?? FIRST_WAIT_LOOK_AFTER_MS)+ else stopped = true+ return stop+}++/**+ * The watch for a chat or agent turn on `model`: only Ollama reports what it+ * loaded, so other backends get nothing. Returns the stop handle; the run+ * calls it when the turn ends, and it ends by itself at the first word.+ */+export function watchChatFirstWait(conversationId: string | null | undefined, model: string | null | undefined, signal?: AbortSignal): () => void {+ if (!conversationId || !model || getProviderIdFromModel(model) !== 'ollama') return () => {}+ return watchFirstWait({+ conversationId,+ model,+ signal,+ readLoaded: () => readLoadedModels(signal),+ readInstalled: () => useModelStore.getState().models+ .filter((m) => m.type === 'text' && getProviderIdFromModel(m.name) === 'ollama')+ .map((m) => ({ name: m.name, size: 'size' in m && typeof m.size === 'number' ? m.size : 0 })),+ getActivity: () => useRunActivityStore.getState().activity[conversationId],+ setActivity: (activity) => useRunActivityStore.getState().setActivity(conversationId, activity),+ })+}diff --git a/src/stores/__tests__/run-activity-reading.test.ts b/src/stores/__tests__/run-activity-reading.test.tsindex 2bf137a6..7e27bccd 100644--- a/src/stores/__tests__/run-activity-reading.test.ts+++ b/src/stores/__tests__/run-activity-reading.test.ts@@ -65,7 +65,9 @@ describe('reading the conversation', () => {it('both chat paths set it before the request and take it back when the turn ends', () => {const src = (f: string) => readFileSync(resolve(__dirname, '..', '..', 'hooks', f), 'utf8')const agent = src('useAgentChat.ts')- expect(agent).toMatch(/if \(stepNo === 1\) useRunActivityStore\.getState\(\)\.setActivity\(convId, readingActivity\(estPrompt\)\)/)+ expect(agent).toMatch(/if \(stepNo === 1\) \{\n\s+useRunActivityStore\.getState\(\)\.setActivity\(convId, readingActivity\(estPrompt\)\)/)+ // B26: and the watch that says why a long first wait lasts.+ expect(agent).toMatch(/watchChatFirstWait\(convId, activeModel, abort\.signal\)/)expect(agent).toMatch(/endFirstWait\(convId\)\n\s+logFirstWait\(\)\n\s+turn = ollamaTurn/)expect(agent.match(/hiddenThoughtArrived\(convId\)/g)!.length).toBe(2)// Where the first wait went lands in the log file, once per message.@@ -73,6 +75,7 @@ describe('reading the conversation', () => {expect(agent.match(/logFirstWait\(\)/g)!.length).toBe(2)const chat = src('useChat.ts')expect(chat).toMatch(/setActivity\(convId, readingActivity\(/)+ expect(chat).toMatch(/watchChatFirstWait\(convId, activeModel, abort\.signal\)/)expect(chat).toMatch(/endFirstWait\(run\.convId\)/)})})diff --git a/src/stores/runActivityStore.ts b/src/stores/runActivityStore.tsindex e3b56afb..ece0c206 100644--- a/src/stores/runActivityStore.ts+++ b/src/stores/runActivityStore.ts@@ -21,6 +21,9 @@ export interface RunActivity {detail?: string/** A named state of the run. Without it the label is a call being written. */kind?: 'compacting' | 'retrying' | 'reading' | 'thinking'+ /** A sentence under the line when the wait needs explaining (B26: a local+ * model that does not fit on the graphics card). Shown, not announced. */+ hint?: string}interface RunActivityState {@@ -34,7 +37,7 @@ export const useRunActivityStore = create<RunActivityState>((set) => ({if (!conversationId) returnset((state) => {const now = state.activity[conversationId]- if (now?.label === activity?.label && now?.detail === activity?.detail && now?.kind === activity?.kind) return state+ if (now?.label === activity?.label && now?.detail === activity?.detail && now?.kind === activity?.kind && now?.hint === activity?.hint) return stateconst next = { ...state.activity }if (activity) next[conversationId] = activityelse delete next[conversationId]