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): der Use-Knopf repariert nur den eigenen Motor, und nur einmal
purplecf41f1edd6d0
diff --git a/src/api/__tests__/builtin-engine-port-wiring.test.ts b/src/api/__tests__/builtin-engine-port-wiring.test.tsnew file mode 100644index 00000000..a028045b--- /dev/null+++ b/src/api/__tests__/builtin-engine-port-wiring.test.ts@@ -0,0 +1,71 @@+/**+ * Review S7 on the GH #118 fix: the port sync was unit-tested on its own, but+ * nothing held the WIRING. A start, a swap or a status probe that forgets to+ * call it puts the app back where the ticket started, asking a port nobody is+ * listening on while the engine answers one port away.+ *+ * Run: npx vitest run src/api/__tests__/builtin-engine-port-wiring.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'++const backendCall = vi.fn()+vi.mock('../backend', () => ({+ backendCall: (...args: unknown[]) => backendCall(...args),+ isTauri: () => true,+ isMacOS: () => false,+}))++const { useProviderStore } = await import('../../stores/providerStore')+const { startBundledEngine, swapBundledModel, bundledEngineStatus, ENGINE_PORT } = await import(+ '../engine'+)++const DEFAULTS = structuredClone(useProviderStore.getState().providers)+const slotUrl = () => useProviderStore.getState().providers.openai.baseUrl++beforeEach(() => {+ useProviderStore.setState({ providers: structuredClone(DEFAULTS) })+ backendCall.mockReset()+})++describe('the slot follows every call that can move the engine', () => {+ it('start_bundled_engine', async () => {+ backendCall.mockResolvedValue({ status: 'started', port: 8137, model_path: '/m.gguf' })+ await startBundledEngine('/m.gguf')+ expect(slotUrl()).toBe('http://127.0.0.1:8137/v1')+ })++ it('swap_bundled_model', async () => {+ backendCall.mockResolvedValue({ status: 'started', port: 8139, model_path: '/m.gguf' })+ await swapBundledModel('/m.gguf')+ expect(slotUrl()).toBe('http://127.0.0.1:8139/v1')+ })++ it('a running status probe', async () => {+ backendCall.mockResolvedValue({ running: true, healthy: true, port: 8141, model_path: '/m.gguf' })+ await bundledEngineStatus()+ expect(slotUrl()).toBe('http://127.0.0.1:8141/v1')+ })+})++describe('a fallback port does not outlive the conflict (S5)', () => {+ it('a stopped engine puts the slot back on the preferred port', async () => {+ backendCall.mockResolvedValue({ status: 'started', port: 8137, model_path: '/m.gguf' })+ await startBundledEngine('/m.gguf')+ expect(slotUrl()).toBe('http://127.0.0.1:8137/v1')++ // Next app start: 8127 is free again, the engine is not running yet.+ backendCall.mockResolvedValue({ running: false, healthy: false, port: ENGINE_PORT, model_path: null })+ await bundledEngineStatus()+ expect(slotUrl()).toBe(`http://127.0.0.1:${ENGINE_PORT}/v1`)+ })++ // Negative control: the reset must not fire while the engine IS up, or every+ // status probe would point the slot away from a healthy fallback engine.+ it('a running engine on a fallback port is never reset', async () => {+ backendCall.mockResolvedValue({ running: true, healthy: true, port: 8137, model_path: '/m.gguf' })+ await bundledEngineStatus()+ await bundledEngineStatus()+ expect(slotUrl()).toBe('http://127.0.0.1:8137/v1')+ })+})diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.tsindex 718b4232..d55707c9 100644--- a/src/api/builtin-ensure.ts+++ b/src/api/builtin-ensure.ts@@ -357,10 +357,17 @@ export async function ensureBuiltinAgentCtx(modelName: string): Promise<void> {const raised = { ...(tuning ?? {}), ctx: want }try {- await trackEngineSwap(backendCall(status?.running ? 'swap_bundled_model' : 'start_bundled_engine', {- modelPath: hit.path,- tuning: raised,- }))+ // S2: this restart moves the engine like any other, so the slot has to be+ // told. Without it an agent run that raised the context could leave the+ // slot pointing at the port the engine had before a fallback.+ syncBuiltinEnginePort(+ (await trackEngineSwap(+ backendCall<EngineStartResult>(+ status?.running ? 'swap_bundled_model' : 'start_bundled_engine',+ { modelPath: hit.path, tuning: raised },+ ),+ ))?.port,+ )announceContextReload()} catch {refusedCtxByPath.set(hit.path, want)@@ -467,10 +474,28 @@ export async function diagnoseBuiltinEngine(? opts.preferModel.split('::')[1]: opts.preferModel: ''- const pick = runnable.find((m) => m.name === bare) ?? runnable[0]+ // A caller that NAMES a model gets that model or an honest no. Falling+ // through to runnable[0] would load a stranger's GGUF into VRAM and report+ // success, and the caller's own pick would swap it right back out (review+ // B1). Only a caller that named nothing accepts whatever is installed.+ const pick = bare ? runnable.find((m) => m.name === bare) : runnable[0]+ if (!pick) {+ return {+ ok: false,+ repaired: false,+ reason: `The built-in engine has no model file named "${bare}". It may have been deleted, moved, or the download did not finish. Open Models and install it again.`,+ }+ }try {const tuning = useSettingsStore.getState().settings.builtinEngine- const started = await backendCall<EngineStartResult>('start_bundled_engine', { modelPath: pick.path, tuning })+ // Through the swap gate (S6): a send that arrives while this start is+ // still loading has to wait it out instead of hitting the dead port. Every+ // other start in this file is registered, and this one starts the engine+ // from a button the user just pressed, so it is the likeliest of all to+ // overlap with a send.+ const started = await trackEngineSwap(+ backendCall<EngineStartResult>('start_bundled_engine', { modelPath: pick.path, tuning }),+ )syncBuiltinEnginePort(started?.port)return { ok: true, reason: '', repaired: true }} catch (e) {diff --git a/src/api/engine.ts b/src/api/engine.tsindex d7616a29..c3676e74 100644--- a/src/api/engine.ts+++ b/src/api/engine.ts@@ -73,6 +73,11 @@ export interface EngineStatus {/** Loopback base URL of the managed embeddings server (P5). Mirrors the Rust* `DEFAULT_EMBED_PORT` (8128). Document-Chat/RAG POSTs `/v1/embeddings` here* when the built-in engine is active, instead of Ollama's `/api/embed`. */+/** Preferred loopback port of the managed chat engine. Mirrors the Rust+ * `DEFAULT_ENGINE_PORT`. Since GH #118 it is a preference, not a promise: the+ * engine takes the next free port when this one is held. */+export const ENGINE_PORT = 8127+export const EMBED_PORT = 8128export function embedBaseUrl(): string {return `http://127.0.0.1:${EMBED_PORT}/v1`@@ -131,10 +136,12 @@ export function stopBundledEngine() {/** Engine health + which model is loaded on which port. */export async function bundledEngineStatus() {const status = await backendCall<EngineStatus>('bundled_engine_status')- // A RUNNING engine is the only honest source for the port. A stopped one- // reports the preferred port as a placeholder, and following that would undo- // a fallback the next start is about to reuse.- if (status?.running) syncBuiltinEnginePort(status.port)+ // Running: the port the engine really holds. Stopped: back to the preferred+ // port, because the next start begins its walk at 8127 and a fallback port+ // must not outlive the conflict that caused it. The slot is persisted, so+ // without the reset a one-off collision would keep the app on 8129 for good+ // and the Settings test would read "failed" on a free 8127 (review S5).+ syncBuiltinEnginePort(status?.running ? status.port : ENGINE_PORT)return status}diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsxindex 3e10913e..efe8bae0 100644--- a/src/components/models/DiscoverModels.tsx+++ b/src/components/models/DiscoverModels.tsx@@ -27,6 +27,7 @@ import { diagnoseBuiltinEngine } from '../../api/builtin-ensure'import { BUILTIN_BACKEND_ID } from '../../lib/onboarding-backend'import type { InstalledModelLike } from '../../lib/lmstudio-match'import { findInstalledForDiscoverModel } from '../../lib/discover-installed'+import { isBuiltinEngineEntry } from '../../lib/lmstudio-match'import { resolveTextDownloadTarget } from '../../lib/text-download-target'import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir, parseHfUrl, extractGgufQuant, isShardedOrIncompatibleGguf } from '../../lib/hf-to-provider'import { GlassCard } from '../ui/GlassCard'@@ -191,6 +192,11 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:? vramFilteredBundles.filter((b) => b.name.toLowerCase().includes(search.toLowerCase()) || b.description.toLowerCase().includes(search.toLowerCase())): vramFilteredBundles+ // Which model the Use button is currently loading. A GGUF start blocks for+ // seconds to minutes, and without this the button stayed live and a second+ // click queued a second start behind the first (review S6).+ const [usingModel, setUsingModel] = useState<string | null>(null)+// Text-model installed check.//// Lives in lib/discover-installed.ts since 2.6.8, unit-tested, because the@@ -221,18 +227,32 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:* The repair runs BEFORE the pick, because diagnoseBuiltinEngine starts the* engine on exactly this model when it is dead, and the pick then swaps only* when something else is loaded. The other order would start twice.+ *+ * Review B1: the repair is asked ONLY for a row that really belongs to the+ * app's own engine. An Ollama or LM Studio row has its own lifecycle, and+ * sending it through the built-in diagnosis would either boot a stranger's+ * GGUF that the pick then swaps straight back out, or, on a box with no+ * built-in GGUF at all, answer a click on a perfectly installed Ollama model+ * with "no chat model to load yet".*/const handleUseInstalled = async (model: DiscoverModel) => {- const name = installedEntryFor(model)?.name- if (!name) return+ const entry = installedEntryFor(model)+ const name = entry?.name+ if (!name || usingModel) returnsetInstallError(null)+ setUsingModel(name)try {- const diagnosis = await diagnoseBuiltinEngine({ repair: true, preferModel: name })- if (!diagnosis.ok && diagnosis.reason) setInstallError(diagnosis.reason)+ if (isBuiltinEngineEntry(entry)) {+ const diagnosis = await diagnoseBuiltinEngine({ repair: true, preferModel: name })+ if (!diagnosis.ok && diagnosis.reason) setInstallError(diagnosis.reason)+ }+ setActiveModel(name)} catch (e) {log.warn('[DiscoverModels] built-in engine repair failed', { err: e })+ setActiveModel(name)+ } finally {+ setUsingModel(null)}- setActiveModel(name)}const [installingBundle, setInstallingBundle] = useState<string | null>(null)@@ -597,8 +617,13 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:} catch (e) {setInstallError(`Model downloaded, but the built-in engine failed to start: ${e instanceof Error ? e.message : String(e)}`)}- window.dispatchEvent(new CustomEvent('lu-models-refresh'))}+ // Outside the built-in branch too: an LM Studio or openai-compat download+ // lands in a folder the next model refresh reads, and until something+ // asks for that refresh the tile keeps offering Get for a file that is+ // already on the disk. That is the badge half of GH #118 wearing another+ // backend's clothes.+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))} catch (e) {log.error('GGUF download failed', { err: e })setInstallError(`Download failed: ${e instanceof Error ? e.message : String(e)}`)@@ -659,6 +684,7 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:onDownload={handleTextDownload}onUse={handleUseInstalled}canUse={canUseInstalled}+ isUsing={(m) => installedEntryFor(m)?.name === usingModel && usingModel !== null}onInfo={setInfoModel}onOpenUrl={(u) => openExternal(u)}highlight={highlight}@@ -923,6 +949,7 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:onDownload={handleTextDownload}onUse={handleUseInstalled}canUse={canUseInstalled}+ isUsing={(m) => installedEntryFor(m)?.name === usingModel && usingModel !== null}onInfo={setInfoModel}onOpenUrl={(u) => openExternal(u)}/>diff --git a/src/components/models/ModelTiles.tsx b/src/components/models/ModelTiles.tsxindex 2cdbf013..ee35e902 100644--- a/src/components/models/ModelTiles.tsx+++ b/src/components/models/ModelTiles.tsx@@ -160,10 +160,12 @@ export interface ModelTileProps {/** Can `onUse` do anything for THIS row, i.e. is the local model behind it* known by name. */canUse?: (m: DiscoverModel) => boolean+ /** Is a Use click for THIS row already running (S6). */+ isUsing?: (m: DiscoverModel) => booleanhighlight?: boolean}-export function ModelTile({ variants, vramGb, isInstalled, dlState, onDownload, onInfo, onOpenUrl, onUse, canUse, highlight }: ModelTileProps) {+export function ModelTile({ variants, vramGb, isInstalled, dlState, onDownload, onInfo, onOpenUrl, onUse, canUse, isUsing, highlight }: ModelTileProps) {const [pickerOpen, setPickerOpen] = useState(false)const [chosen, setChosen] = useState<string | null>(null)const pickerRef = useRef<HTMLDivElement>(null)@@ -183,6 +185,7 @@ export function ModelTile({ variants, vramGb, isInstalled, dlState, onDownload,installed,downloading,loadable: !!onUse && (canUse ? canUse(sel) : true),+ using: !!isUsing?.(sel),})useEffect(() => {@@ -281,6 +284,10 @@ export function ModelTile({ variants, vramGb, isInstalled, dlState, onDownload,><Check size={11} className="text-emerald-500/80" /> Use</button>+ ) : action === 'using' ? (+ <span className="flex items-center gap-1.5 px-2 py-1 text-[0.62rem] text-gray-500 dark:text-gray-400">+ <Loader2 size={11} className="animate-spin" /> Loading…+ </span>) : action === 'installed' ? (<span className="flex items-center gap-1 px-2 py-1 rounded-md bg-gray-100 dark:bg-white/[0.06] text-gray-600 dark:text-gray-300 text-[0.62rem] font-medium"><Check size={11} className="text-emerald-500/80" /> Installeddiff --git a/src/hooks/useModels.ts b/src/hooks/useModels.tsindex c34f5999..c6ca7c46 100644--- a/src/hooks/useModels.ts+++ b/src/hooks/useModels.ts@@ -13,7 +13,8 @@ import {import { parseNDJSONStream } from '../api/stream'import { log } from '../lib/logger'import { cloudModelRow } from '../lib/cloud-model-row'-import { RESUME_ATTEMPTS, resumeBackoffMs } from '../lib/engine-resume-policy'+import { runEngineResume } from '../lib/engine-resume-policy'+import { engineStartIsWorthRetrying } from '../lib/engine-start-failure'import { useModelStore } from '../stores/modelStore'import { useProviderStore } from '../stores/providerStore'import { useSettingsStore } from '../stores/settingsStore'@@ -46,29 +47,33 @@ let builtinResumeAttempted = falseconst wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))async function resumeBuiltinEngines(bundled: BundledModel[]) {- for (let attempt = 0; attempt < RESUME_ATTEMPTS; attempt++) {- try {- const status = await bundledEngineStatus()- if (status.running) break+ // The embeddings server is a different process on a different port with a+ // different model, so it starts NOW and not behind up to three chat-engine+ // attempts. Waiting its turn is how a slow chat start used to take+ // Document-Chat down with it (review S3).+ const embedResumed = resumeEmbedServer(bundled)+ const outcome = await runEngineResume({+ status: () => bundledEngineStatus(),+ eligible: () => {const { activeModel } = useModelStore.getState()- if (- !activeModel ||- getProviderIdFromModel(activeModel) !== 'openai' ||- !bundled.some((m) => prefixModelName('openai', m.name) === activeModel)- ) {- break // nothing to resume, and no number of retries changes that- }- // False means the GGUF is gone from disk. Retrying cannot conjure it.- if (await activateBuiltinModel(activeModel)) break- break- } catch (err) {- log.warn('[useModels] built-in engine resume failed', { attempt: attempt + 1, err })- const delay = resumeBackoffMs(attempt)- if (delay === null) break- await wait(delay)- }- }- await resumeEmbedServer(bundled)+ return (+ !!activeModel &&+ getProviderIdFromModel(activeModel) === 'openai' &&+ bundled.some((m) => prefixModelName('openai', m.name) === activeModel)+ )+ },+ activate: () => activateBuiltinModel(useModelStore.getState().activeModel as string),+ // Only a start that DIED is worth repeating. A health-budget timeout means+ // the engine is still loading, and repeating it spends the whole budget+ // again (up to ten minutes on a big GGUF) plus another ComfyUI cache drop+ // and another Ollama eviction (review S3).+ worthRetrying: engineStartIsWorthRetrying,+ sleep: wait,+ onError: (attempt, err) =>+ log.warn('[useModels] built-in engine resume failed', { attempt, err }),+ })+ log.info('[useModels] built-in engine resume', outcome)+ await embedResumed}/** One arm at a time. fetchModels runs from several mounted components, and adiff --git a/src/lib/__tests__/discover-installed.test.ts b/src/lib/__tests__/discover-installed.test.tsindex 1734a2b5..76d99ca4 100644--- a/src/lib/__tests__/discover-installed.test.ts+++ b/src/lib/__tests__/discover-installed.test.ts@@ -17,7 +17,7 @@ import {isDiscoverModelInstalled,type DownloadStatuses,} from '../discover-installed'-import type { InstalledModelLike } from '../lmstudio-match'+import { isBuiltinEngineEntry, type InstalledModelLike } from '../lmstudio-match'const CYDONIA = {filename: 'Cydonia-24B-v4.1-Q4_K_M.gguf',@@ -106,3 +106,43 @@ describe('the other disk sources keep working', () => {).toBe(false)})})++describe('who owns an installed row (review B1)', () => {+ it('marks a built-in entry as ours, so the engine repair may run', () => {+ expect(isBuiltinEngineEntry(findInstalledForDiscoverModel(CYDONIA, NO_DOWNLOADS, ON_DISK))).toBe(+ true,+ )+ })++ // The finding: an Ollama or LM Studio row went through the built-in+ // diagnosis, which either booted a stranger's GGUF that the pick swapped+ // straight back out, or, with no built-in GGUF on the box, answered a click+ // on a perfectly installed Ollama model with "no chat model to load yet".+ it('does not claim an Ollama row', () => {+ const ollama = [{ provider: 'ollama', model: 'llama3.2:latest', name: 'llama3.2:latest' }]+ const entry = findInstalledForDiscoverModel({ ollamaModel: 'llama3.2' }, NO_DOWNLOADS, ollama)+ expect(entry?.name).toBe('llama3.2:latest')+ expect(isBuiltinEngineEntry(entry)).toBe(false)+ })++ it('does not claim an LM Studio row', () => {+ const lms = [+ {+ provider: 'openai',+ providerName: 'LM Studio',+ name: 'openai::Cydonia-24B-v4.1-Q4_K_M.gguf',+ model: 'Cydonia-24B-v4.1-Q4_K_M.gguf',+ },+ ]+ const entry = findInstalledForDiscoverModel(CYDONIA, NO_DOWNLOADS, lms)+ expect(entry?.name).toBe('openai::Cydonia-24B-v4.1-Q4_K_M.gguf')+ expect(isBuiltinEngineEntry(entry)).toBe(false)+ })++ it('does not claim a session download, which carries no owner yet', () => {+ const downloads = { [CYDONIA.filename]: { status: 'complete' } }+ expect(+ isBuiltinEngineEntry(findInstalledForDiscoverModel(CYDONIA, downloads, [])),+ ).toBe(false)+ })+})diff --git a/src/lib/__tests__/engine-resume-policy.test.ts b/src/lib/__tests__/engine-resume-policy.test.tsindex 2abaac76..49146622 100644--- a/src/lib/__tests__/engine-resume-policy.test.ts+++ b/src/lib/__tests__/engine-resume-policy.test.ts@@ -5,8 +5,9 @@** Run: npx vitest run src/lib/__tests__/engine-resume-policy.test.ts*/-import { describe, it, expect } from 'vitest'-import { RESUME_ATTEMPTS, resumeBackoffMs } from '../engine-resume-policy'+import { describe, it, expect, vi } from 'vitest'+import { RESUME_ATTEMPTS, resumeBackoffMs, runEngineResume } from '../engine-resume-policy'+import { engineStartIsWorthRetrying } from '../engine-start-failure'describe('resumeBackoffMs', () => {it('waits between the tries, and waits longer the second time', () => {@@ -35,3 +36,106 @@ describe('resumeBackoffMs', () => {expect(delays.filter((d) => d !== null)).toHaveLength(RESUME_ATTEMPTS - 1)})})++describe('runEngineResume: the loop itself (review S7)', () => {+ const noSleep = async () => {}+ const always = () => true++ it('does nothing when the engine is already up', async () => {+ const activate = vi.fn()+ const out = await runEngineResume({+ status: async () => ({ running: true }),+ eligible: always,+ activate,+ worthRetrying: always,+ sleep: noSleep,+ })+ expect(out.outcome).toBe('already-running')+ expect(activate).not.toHaveBeenCalled()+ })++ it('starts once when there is something to resume', async () => {+ const activate = vi.fn(async () => true)+ const out = await runEngineResume({+ status: async () => ({ running: false }),+ eligible: always,+ activate,+ worthRetrying: always,+ sleep: noSleep,+ })+ expect(out.outcome).toBe('started')+ expect(activate).toHaveBeenCalledTimes(1)+ expect(out.sleptMs).toEqual([])+ })++ it('does not retry what there is nothing to retry for', async () => {+ const activate = vi.fn()+ const out = await runEngineResume({+ status: async () => ({ running: false }),+ eligible: () => false,+ activate,+ worthRetrying: always,+ sleep: noSleep,+ })+ expect(out.outcome).toBe('not-eligible')+ expect(out.attempts).toBe(1)+ expect(activate).not.toHaveBeenCalled()+ })++ it('retries a death, waits longer each time, and stops at the ceiling', async () => {+ // The failure the ticket needed a second chance for.+ const activate = vi.fn(async () => {+ throw new Error('The built-in engine started and exited again before it could serve on port 8127.')+ })+ const slept: number[] = []+ const out = await runEngineResume({+ status: async () => ({ running: false }),+ eligible: always,+ activate,+ worthRetrying: engineStartIsWorthRetrying,+ sleep: async (ms) => { slept.push(ms) },+ })+ expect(out.outcome).toBe('gave-up')+ expect(activate).toHaveBeenCalledTimes(RESUME_ATTEMPTS)+ expect(slept).toHaveLength(RESUME_ATTEMPTS - 1)+ expect(slept[1]).toBeGreaterThan(slept[0])+ })++ // The S3 finding: repeating a health-budget timeout spends the same budget+ // again, up to ten minutes on a big GGUF, and re-runs the ComfyUI cache drop+ // and the Ollama eviction every time.+ it('never repeats a health-budget timeout', async () => {+ const activate = vi.fn(async () => {+ throw new Error('The built-in engine did not become healthy on port 8127 within 220s')+ })+ const slept: number[] = []+ const out = await runEngineResume({+ status: async () => ({ running: false }),+ eligible: always,+ activate,+ worthRetrying: engineStartIsWorthRetrying,+ sleep: async (ms) => { slept.push(ms) },+ })+ expect(out.outcome).toBe('gave-up')+ expect(activate).toHaveBeenCalledTimes(1)+ expect(slept).toEqual([])+ })++ it('a second attempt that works ends the loop', async () => {+ let calls = 0+ const activate = vi.fn(async () => {+ calls += 1+ if (calls === 1) throw new Error('exited again before it could serve')+ return true+ })+ const out = await runEngineResume({+ status: async () => ({ running: false }),+ eligible: always,+ activate,+ worthRetrying: engineStartIsWorthRetrying,+ sleep: noSleep,+ })+ expect(out.outcome).toBe('started')+ expect(out.attempts).toBe(2)+ })+})diff --git a/src/lib/__tests__/engine-start-failure.test.ts b/src/lib/__tests__/engine-start-failure.test.tsnew file mode 100644index 00000000..79eaf758--- /dev/null+++ b/src/lib/__tests__/engine-start-failure.test.ts@@ -0,0 +1,71 @@+/**+ * Review S3: the boot resume repeats a failed start up to three times, and a+ * repeat is only right for a start that DIED. The messages here are the ones+ * `start_failure_message` in src-tauri/src/commands/engine.rs really produces;+ * a Rust test holds up the other end of that contract.+ *+ * Run: npx vitest run src/lib/__tests__/engine-start-failure.test.ts+ */+import { describe, it, expect } from 'vitest'+import { engineStartFailureText, engineStartIsWorthRetrying } from '../engine-start-failure'++describe('engineStartIsWorthRetrying', () => {+ it('repeats a start that died, which is what the ticket needed', () => {+ // The whole reason the retry exists: a start that lost a race at login.+ expect(+ engineStartIsWorthRetrying(+ new Error(+ 'The built-in engine started and exited again before it could serve on port 8127. It was tried twice. This looks like a graphics-card problem.',+ ),+ ),+ ).toBe(true)+ expect(engineStartIsWorthRetrying(new Error('Engine start task failed to run: panic'))).toBe(+ true,+ )+ })++ // The finding itself: a slow load is not a failure, and repeating it spends+ // the whole health budget again, up to ten minutes on a big GGUF, plus a+ // ComfyUI cache drop and an Ollama eviction per attempt.+ it('never repeats a health-budget timeout', () => {+ expect(+ engineStartIsWorthRetrying(+ new Error(+ 'The built-in engine did not become healthy on port 8127 within 220s (the budget scales with model size, and huge GGUFs can take minutes on a cold first load).',+ ),+ ),+ ).toBe(false)+ })++ it('never repeats a fact about the machine that 1.5 seconds cannot change', () => {+ for (const msg of [+ 'The built-in engine could not open a local port. Every port it may use between 8127 and 8148 is taken or blocked on this machine.',+ 'The built-in engine program (lu-llama-server.exe) is missing from this installation. Reinstall Locally Uncensored.',+ 'Model file not found: C:\\models\\gone.gguf',+ 'The built-in engine has no model file named "Cydonia-24B-v4.1-Q4_K_M".',+ ]) {+ expect(engineStartIsWorthRetrying(new Error(msg))).toBe(false)+ }+ })++ it('reads a plain string, which is what Tauri actually throws', () => {+ expect(engineStartIsWorthRetrying('did not become healthy on port 8127')).toBe(false)+ expect(engineStartIsWorthRetrying('exited again before it could serve')).toBe(true)+ })++ // Negative control: silence is not evidence of hopelessness, and treating it+ // as such would put the resume back to a single attempt.+ it('repeats when there is no message at all', () => {+ expect(engineStartIsWorthRetrying(undefined)).toBe(true)+ expect(engineStartIsWorthRetrying(null)).toBe(true)+ expect(engineStartIsWorthRetrying(new Error(''))).toBe(true)+ })+})++describe('engineStartFailureText', () => {+ it('unwraps the three shapes a Tauri failure arrives in', () => {+ expect(engineStartFailureText(new Error('boom'))).toBe('boom')+ expect(engineStartFailureText('boom')).toBe('boom')+ expect(engineStartFailureText(undefined)).toBe('')+ })+})diff --git a/src/lib/__tests__/model-tile-action.test.ts b/src/lib/__tests__/model-tile-action.test.tsindex 736a2cf7..cb2a01e6 100644--- a/src/lib/__tests__/model-tile-action.test.ts+++ b/src/lib/__tests__/model-tile-action.test.ts@@ -39,6 +39,14 @@ describe('modelTileAction', () => {)})+ it('shows the load in flight and stops taking clicks (review S6)', () => {+ // A GGUF start blocks for seconds to minutes. Without this the button+ // stayed live and a second click queued a second start behind the first.+ expect(modelTileAction({ ...base, installed: true, loadable: true, using: true })).toBe('using')+ // Negative control: without the flag the very same row is clickable again.+ expect(modelTileAction({ ...base, installed: true, loadable: true })).toBe('use')+ })+it('an external-only row can only ever be viewed', () => {expect(modelTileAction({ externalOnly: true, installed: true, downloading: true, loadable: true }),@@ -53,7 +61,9 @@ describe('a tile is never a dead end', () => {for (const installed of [false, true]) {for (const downloading of [false, true]) {for (const loadable of [false, true]) {- states.push({ externalOnly, installed, downloading, loadable })+ for (const using of [false, true]) {+ states.push({ externalOnly, installed, downloading, loadable, using })+ }}}}@@ -61,9 +71,14 @@ describe('a tile is never a dead end', () => {for (const s of states) {const action = modelTileAction(s)if (tileActionIsClickable(action)) continue- // The two states that legitimately offer no click: a download that is- // already running, and an installed row nothing here can load.- expect(action === 'downloading' || (action === 'installed' && !s.loadable)).toBe(true)+ // The three states that legitimately offer no click: a download that is+ // already running, a load that is already running, and an installed row+ // nothing here can load.+ expect(+ action === 'downloading' ||+ action === 'using' ||+ (action === 'installed' && !s.loadable),+ ).toBe(true)}})diff --git a/src/lib/engine-resume-policy.ts b/src/lib/engine-resume-policy.tsindex ae38ca0a..aa9ad4b3 100644--- a/src/lib/engine-resume-policy.ts+++ b/src/lib/engine-resume-policy.ts@@ -25,3 +25,59 @@ export function resumeBackoffMs(attempt: number): number | null {if (attempt >= RESUME_ATTEMPTS - 1) return nullreturn RESUME_BACKOFF_MS[attempt] ?? RESUME_BACKOFF_MS[RESUME_BACKOFF_MS.length - 1]}++/** What one resume run ended as. */+export type ResumeOutcome =+ /** The engine was already up. */+ | 'already-running'+ /** There was nothing to resume (no active model, or another backend). */+ | 'not-eligible'+ /** An activation was issued. */+ | 'started'+ /** Every attempt failed, or a failure that no retry repairs came back. */+ | 'gave-up'++export interface ResumeDeps {+ /** Ask the app whether its own engine is up. */+ status: () => Promise<{ running?: boolean } | null | undefined>+ /** Is there a built-in model to resume at all. */+ eligible: () => boolean+ /** Start the engine on the active model. */+ activate: () => Promise<unknown>+ /** True when a failed start is worth another attempt. */+ worthRetrying: (err: unknown) => boolean+ sleep: (ms: number) => Promise<void>+ onError?: (attempt: number, err: unknown) => void+}++/**+ * The bounded resume loop itself, with its four dependencies handed in, so the+ * decisions can be asserted without a React tree, a Tauri backend or a real+ * wait (review S7). `useModels` supplies the real ones.+ */+export async function runEngineResume(deps: ResumeDeps): Promise<{+ outcome: ResumeOutcome+ attempts: number+ sleptMs: number[]+}> {+ const sleptMs: number[] = []+ for (let attempt = 0; attempt < RESUME_ATTEMPTS; attempt++) {+ try {+ const status = await deps.status()+ if (status?.running) return { outcome: 'already-running', attempts: attempt + 1, sleptMs }+ if (!deps.eligible()) return { outcome: 'not-eligible', attempts: attempt + 1, sleptMs }+ // Whatever it answers, one activation per pass is all there is to do: a+ // refusal means the GGUF is gone from the disk, and no retry conjures it.+ await deps.activate()+ return { outcome: 'started', attempts: attempt + 1, sleptMs }+ } catch (err) {+ deps.onError?.(attempt + 1, err)+ if (!deps.worthRetrying(err)) return { outcome: 'gave-up', attempts: attempt + 1, sleptMs }+ const delay = resumeBackoffMs(attempt)+ if (delay === null) return { outcome: 'gave-up', attempts: attempt + 1, sleptMs }+ sleptMs.push(delay)+ await deps.sleep(delay)+ }+ }+ return { outcome: 'gave-up', attempts: RESUME_ATTEMPTS, sleptMs }+}diff --git a/src/lib/engine-start-failure.ts b/src/lib/engine-start-failure.tsnew file mode 100644index 00000000..5a6e3869--- /dev/null+++ b/src/lib/engine-start-failure.ts@@ -0,0 +1,45 @@+/**+ * Is a failed engine start worth trying again.+ *+ * Review S3 on the GH #118 fix: the boot resume repeats a start up to three+ * times, and a repeat is only ever right for a start that DIED. The other+ * failures cost far more than they can win. A health-budget timeout means the+ * engine is still loading, and the budget scales with the GGUF, so a repeat+ * spends up to ten minutes a second and a third time, and each attempt also+ * drops ComfyUI's VRAM cache and evicts Ollama's loaded models on the way in.+ * A missing binary, a missing model file and a completely blocked block of+ * ports are all facts about the machine that 1.5 seconds do not change.+ *+ * Tauri hands a command failure across as a plain string, so this reads the+ * message. The Rust side keeps its half of the contract in a test+ * (`a_slow_load_stays_recognisable_as_a_timeout_for_the_frontend`): the+ * timeout message always carries "did not become healthy", and no death+ * message ever does.+ */++/** Failures that no amount of waiting repairs. Lower-cased fragments. */+const HOPELESS = [+ // the engine is alive and still loading, the budget simply ran out+ 'did not become healthy',+ // the walk over every candidate port came back empty+ 'could not open a local port',+ // the sidecar is not in this installation+ 'is missing from this installation',+ // the GGUF the caller named is gone+ 'model file not found',+ 'has no model file named',+]++/** The message behind an unknown thrown value. */+export function engineStartFailureText(err: unknown): string {+ if (err instanceof Error) return err.message+ if (typeof err === 'string') return err+ return String(err ?? '')+}++/** True when starting again has a chance of a different answer. */+export function engineStartIsWorthRetrying(err: unknown): boolean {+ const msg = engineStartFailureText(err).toLowerCase()+ if (!msg) return true // no message at all is not evidence of hopelessness+ return !HOPELESS.some((m) => msg.includes(m))+}diff --git a/src/lib/lmstudio-match.ts b/src/lib/lmstudio-match.tsindex 9c83e1b3..9208338d 100644--- a/src/lib/lmstudio-match.ts+++ b/src/lib/lmstudio-match.ts@@ -75,8 +75,8 @@ function isLmStudioEntry(m: InstalledModelLike): boolean {* with `provider: 'openai'` and `providerName: 'Built-in Engine'`, and its* `model` is the file stem, so the same filename matcher fits it exactly.*/-function isBuiltinEntry(m: InstalledModelLike): boolean {- if (m.provider !== 'openai') return false+export function isBuiltinEngineEntry(m: InstalledModelLike | null | undefined): boolean {+ if (!m || m.provider !== 'openai') return falsereturn (m.providerName || '').toLowerCase().includes('built-in engine')}@@ -104,6 +104,10 @@ export function matchesLmStudioInstalled(* offered "Get" for a file that was already on disk. `list_bundled_models`* reads that disk on every model refresh, so the evidence was there the whole* time, just never asked.+ *+ * The boolean face of `findLocalGgufInstalled`. The app itself asks the entry+ * version (lib/discover-installed.ts) because it needs the picker id, and the+ * regression suite for this matcher's quant precision asks this one.*/export function matchesLocalGgufInstalled(filename: string,@@ -126,7 +130,7 @@ export function findLocalGgufInstalled(filename: string,installed: InstalledModelLike[],): InstalledModelLike | null {- return findInstalled(filename, installed.filter((m) => isLmStudioEntry(m) || isBuiltinEntry(m)))+ return findInstalled(filename, installed.filter((m) => isLmStudioEntry(m) || isBuiltinEngineEntry(m)))}function findInstalled(filename: string, lms: InstalledModelLike[]): InstalledModelLike | null {diff --git a/src/lib/model-tile-action.ts b/src/lib/model-tile-action.tsindex dd942faf..506f57a3 100644--- a/src/lib/model-tile-action.ts+++ b/src/lib/model-tile-action.ts@@ -16,6 +16,9 @@ export type ModelTileAction =| 'view'/** A download is in flight. Waiting IS the state, and it shows progress. */| 'downloading'+ /** The Use click is in flight: the engine is loading this GGUF. Seconds to+ * minutes, so the button has to say so and stop taking clicks (S6). */+ | 'using'/** On the disk, and this surface can load it into the chat. */| 'use'/** On the disk, and loading it is not this surface's job (image/video). */@@ -31,6 +34,8 @@ export interface ModelTileActionInput {downloading: boolean/** Does the caller know WHICH local model this row is, so it can be loaded. */loadable: boolean+ /** A Use click for this row is already running. */+ using?: boolean}/**@@ -40,12 +45,13 @@ export interface ModelTileActionInput {export function modelTileAction(input: ModelTileActionInput): ModelTileAction {if (input.externalOnly) return 'view'if (input.downloading) return 'downloading'+ if (input.using) return 'using'if (input.installed) return input.loadable ? 'use' : 'installed'return 'get'}-/** True when the state offers the user something to click. `downloading` is- * the one state that legitimately does not: it is already doing the thing. */+/** True when the state offers the user something to click. `downloading` and+ * `using` legitimately do not: they are already doing the thing. */export function tileActionIsClickable(action: ModelTileAction): boolean {- return action !== 'downloading' && action !== 'installed'+ return action !== 'downloading' && action !== 'installed' && action !== 'using'}