Skip to content

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.

fix(engine): revive offloaded built-in engine before sends; free ComfyUI VRAM before engine start

purpleece8695188b9
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index ce3ddc8d..7f56032f 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -303,6 +303,16 @@ fn start_bundled_engine_blocking(
// Different model (or dead) → stop the old process before spawning.
stop_engine_locked(state);
+ // Mirror image of the Create-tab handoff: a render leaves ComfyUI's
+ // checkpoint cached in VRAM (`includeComfyui:false` keeps it warm between
+ // runs). On a single-GPU box the returning chat engine then fights that
+ // cache for memory — llama-server with `-ngl 999` loses as a CUDA OOM
+ // (RTX 5080 field report: ACE-Step → chat = crash until app restart). Ask
+ // ComfyUI to drop its cache first; best-effort no-op when it isn't running.
+ if crate::commands::process::free_comfyui_memory() {
+ println!("[Engine] asked ComfyUI to free VRAM before engine start");
+ }
+
let binary = resolve_engine_binary(app).ok_or_else(|| {
format!(
"Bundled engine binary not found ({}). Run scripts/build-llama.sh to produce the sidecar.",
diff --git a/src/api/__tests__/builtin-ensure.test.ts b/src/api/__tests__/builtin-ensure.test.ts
new file mode 100644
index 00000000..ffa77cc8
--- /dev/null
+++ b/src/api/__tests__/builtin-ensure.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Self-heal for the managed built-in engine (the "lazy reload" half of the
+ * Create-tab VRAM offload). The provider awaits ensureBuiltinEngineAlive()
+ * before every send on a managed slot; these tests pin the contract:
+ * no-op on healthy/unmanaged/foreign models, restart with the right GGUF path
+ * when the engine is down, and coalescing of concurrent sends.
+ *
+ * Run: npx vitest run src/api/__tests__/builtin-ensure.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+let managed = true
+let enabled = true
+vi.mock('../../stores/providerStore', () => ({
+ useProviderStore: {
+ getState: () => ({ providers: { openai: { enabled, managed } } }),
+ },
+}))
+
+const backendCall = vi.fn()
+vi.mock('../backend', () => ({
+ backendCall: (...args: any[]) => backendCall(...args),
+}))
+
+import { ensureBuiltinEngineAlive } from '../builtin-ensure'
+
+const MODELS = { models: [{ name: 'qwen2.5-0.5b', path: '/models/qwen2.5-0.5b.gguf' }] }
+
+function mockEngine(opts: { healthy: boolean; list?: unknown }) {
+ backendCall.mockImplementation(async (cmd: string) => {
+ if (cmd === 'bundled_engine_status') return { running: opts.healthy, healthy: opts.healthy }
+ if (cmd === 'list_bundled_models') return opts.list ?? MODELS
+ if (cmd === 'start_bundled_engine') return { status: 'started' }
+ throw new Error(`unexpected command ${cmd}`)
+ })
+}
+
+const callsTo = (cmd: string) => backendCall.mock.calls.filter((c) => c[0] === cmd)
+
+describe('ensureBuiltinEngineAlive', () => {
+ beforeEach(() => {
+ backendCall.mockReset()
+ managed = true
+ enabled = true
+ })
+
+ it('does nothing when the openai slot is not the managed engine', async () => {
+ managed = false
+ await ensureBuiltinEngineAlive('qwen2.5-0.5b')
+ expect(backendCall).not.toHaveBeenCalled()
+ })
+
+ it('only probes when the engine is already healthy', async () => {
+ mockEngine({ healthy: true })
+ await ensureBuiltinEngineAlive('qwen2.5-0.5b')
+ expect(callsTo('bundled_engine_status')).toHaveLength(1)
+ expect(callsTo('start_bundled_engine')).toHaveLength(0)
+ })
+
+ it('restarts a dead engine with the bundled GGUF path (prefixed name too)', async () => {
+ mockEngine({ healthy: false })
+ await ensureBuiltinEngineAlive('openai::qwen2.5-0.5b')
+ const starts = callsTo('start_bundled_engine')
+ expect(starts).toHaveLength(1)
+ expect(starts[0][1]).toEqual({ modelPath: '/models/qwen2.5-0.5b.gguf' })
+ })
+
+ it('leaves foreign models alone (openai-compat server that is not ours)', async () => {
+ mockEngine({ healthy: false })
+ await ensureBuiltinEngineAlive('gpt-4o-mini')
+ expect(callsTo('start_bundled_engine')).toHaveLength(0)
+ })
+
+ it('coalesces concurrent sends into one probe/restart', async () => {
+ let release!: (v: { running: boolean; healthy: boolean }) => void
+ const gate = new Promise<{ running: boolean; healthy: boolean }>((r) => (release = r))
+ backendCall.mockImplementation(async (cmd: string) => {
+ if (cmd === 'bundled_engine_status') return gate
+ if (cmd === 'list_bundled_models') return MODELS
+ if (cmd === 'start_bundled_engine') return { status: 'started' }
+ throw new Error(`unexpected command ${cmd}`)
+ })
+ const a = ensureBuiltinEngineAlive('qwen2.5-0.5b')
+ const b = ensureBuiltinEngineAlive('qwen2.5-0.5b')
+ release({ running: false, healthy: false })
+ await Promise.all([a, b])
+ expect(callsTo('bundled_engine_status')).toHaveLength(1)
+ expect(callsTo('start_bundled_engine')).toHaveLength(1)
+ })
+
+ it('swallows a failing status probe (non-Tauri context) without throwing', async () => {
+ backendCall.mockRejectedValue(new Error('not in tauri'))
+ await expect(ensureBuiltinEngineAlive('qwen2.5-0.5b')).resolves.toBeUndefined()
+ })
+
+ it('propagates a failed restart so the chat shows the real reason', async () => {
+ backendCall.mockImplementation(async (cmd: string) => {
+ if (cmd === 'bundled_engine_status') return { running: true, healthy: false }
+ if (cmd === 'list_bundled_models') return MODELS
+ if (cmd === 'start_bundled_engine') throw new Error('CUDA out of memory\n--- engine log ---\nggml_cuda_init failed')
+ throw new Error(`unexpected command ${cmd}`)
+ })
+ await expect(ensureBuiltinEngineAlive('qwen2.5-0.5b')).rejects.toThrow(/CUDA out of memory/)
+ })
+})
diff --git a/src/api/__tests__/rag-embeddings-routing.test.ts b/src/api/__tests__/rag-embeddings-routing.test.ts
index 13bf921c..1b779352 100644
--- a/src/api/__tests__/rag-embeddings-routing.test.ts
+++ b/src/api/__tests__/rag-embeddings-routing.test.ts
@@ -13,10 +13,14 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
// Mutable flag the mock reads so each test can flip the active backend.
let builtinActive = false
+const ensureEmbed = vi.fn()
vi.mock('../engine', () => ({
isManagedBuiltinActive: () => builtinActive,
embedBaseUrl: () => 'http://127.0.0.1:8128/v1',
+ // Post-offload self-heal: rag awaits this before hitting :8128.
+ ensureBundledEmbedAlive: (...args: any[]) => ensureEmbed(...args),
+ bundledEmbedStatus: async () => ({ running: false, healthy: false }),
}))
const localFetch = vi.fn()
@@ -34,6 +38,7 @@ function jsonResponse(body: unknown, status = 200): Response {
describe('generateEmbeddings routing', () => {
beforeEach(() => {
localFetch.mockReset()
+ ensureEmbed.mockReset()
builtinActive = false
})
@@ -55,6 +60,9 @@ describe('generateEmbeddings routing', () => {
expect(JSON.parse(opts.body).input).toEqual(['a', 'b'])
// Sorted back into input order.
expect(out).toEqual([[0.1, 0.2], [0.3, 0.4]])
+ // The post-offload self-heal MUST run before the request — a Create render
+ // stops the embed sidecar, and without this await RAG dies on a dead port.
+ expect(ensureEmbed).toHaveBeenCalledTimes(1)
})
it('falls back to Ollama /api/embed when the built-in engine is NOT active', async () => {
diff --git a/src/api/builtin-ensure.ts b/src/api/builtin-ensure.ts
new file mode 100644
index 00000000..d96f1372
--- /dev/null
+++ b/src/api/builtin-ensure.ts
@@ -0,0 +1,77 @@
+/**
+ * Self-heal for the managed built-in engine (llama-server on 127.0.0.1:8127).
+ *
+ * The Create tab and the music/video lanes call `offload_local_models` before
+ * a render to free VRAM, which STOPS the bundled chat engine — by design, with
+ * the promise that it "reloads lazily on the next message". This module is
+ * that lazy reload: the OpenAI provider calls it right before a send when its
+ * slot is the app-managed engine (`config.managed === true`). Without it the
+ * first message after a render hits a dead port, and to the user the whole
+ * backend looks crashed until an app restart (RTX 5080 field report: use
+ * Create/ACE-Step once → chat dead until relaunch).
+ *
+ * Deliberately imports only `backend` + the provider store so it can sit
+ * below `api/providers` without an import cycle.
+ */
+
+import { backendCall } from './backend'
+import { useProviderStore } from '../stores/providerStore'
+
+interface EngineStatusLite {
+ running: boolean
+ healthy: boolean
+}
+
+interface BundledList {
+ models?: Array<{ name: string; path: string }>
+}
+
+// Coalesce concurrent sends (chat + title generation) into ONE health-check /
+// restart. start_bundled_engine blocks until /health is green, so awaiting the
+// same promise is exactly "wait for the restart the other call kicked off".
+let inflight: Promise<void> | null = null
+
+/** True when the `openai` slot is the app-managed built-in engine. */
+export function isManagedBuiltinSlot(): boolean {
+ const cfg = useProviderStore.getState().providers.openai
+ return !!cfg?.enabled && cfg.managed === true
+}
+
+/**
+ * Make sure the built-in engine is up before a send. No-op when the slot is
+ * not managed, the engine is already healthy, or `modelName` is not a bundled
+ * GGUF (nothing we own to heal). Throws only when an actual restart attempt
+ * fails — that error carries llama-server's stderr tail and IS the honest
+ * thing to show in the chat instead of a bare "fetch failed".
+ */
+export async function ensureBuiltinEngineAlive(modelName: string): Promise<void> {
+ if (!isManagedBuiltinSlot()) return
+ if (inflight) return inflight
+ inflight = (async () => {
+ try {
+ let status: EngineStatusLite | null
+ try {
+ status = await backendCall<EngineStatusLite>('bundled_engine_status')
+ } catch {
+ return // non-Tauri context (tests/browser) — nothing to manage
+ }
+ if (status?.healthy) return
+
+ let models: Array<{ name: string; path: string }>
+ try {
+ const res = await backendCall<BundledList>('list_bundled_models')
+ models = res?.models ?? []
+ } catch {
+ return
+ }
+ const bare = modelName.includes('::') ? modelName.split('::')[1] : modelName
+ const hit = models.find((m) => m.name === bare)
+ if (!hit) return // not a bundled GGUF — some other openai-compat server
+
+ await backendCall('start_bundled_engine', { modelPath: hit.path })
+ } finally {
+ inflight = null
+ }
+ })()
+ return inflight
+}
diff --git a/src/api/engine.ts b/src/api/engine.ts
index 4dab416e..5926792c 100644
--- a/src/api/engine.ts
+++ b/src/api/engine.ts
@@ -93,6 +93,44 @@ export function bundledEmbedStatus() {
return backendCall<EngineStatus>('bundled_embed_status')
}
+// Embedding-model GGUFs: never offered in the chat dropdown, and the
+// candidates for the bundled embeddings server. Single source of truth —
+// useModels and the RAG self-heal below share it.
+const EMBEDDING_GGUF_PATTERNS = [/embed/, /nomic-embed/, /bge-/, /e5-/, /gte-/, /sentence-/]
+export function isEmbeddingGgufName(name: string): boolean {
+ const lower = name.toLowerCase()
+ return EMBEDDING_GGUF_PATTERNS.some((p) => p.test(lower))
+}
+
+// Coalesce concurrent RAG calls into one status-probe/restart.
+let embedEnsureInflight: Promise<void> | null = null
+
+/**
+ * Revive the bundled embeddings server after a VRAM offload stopped it —
+ * Create/Music renders call `offload_local_models`, which kills BOTH managed
+ * sidecars with the promise of a lazy reload. This is the embed half of that
+ * reload (the chat half lives in `builtin-ensure.ts`); RAG awaits it before
+ * hitting :8128. Best-effort: a real start failure surfaces on the embeddings
+ * request itself with the server's honest error.
+ */
+export async function ensureBundledEmbedAlive(): Promise<void> {
+ if (embedEnsureInflight) return embedEnsureInflight
+ embedEnsureInflight = (async () => {
+ try {
+ const status = await bundledEmbedStatus()
+ if (status?.healthy) return
+ const models = await listBundledModels()
+ const embed = models.find((m) => isEmbeddingGgufName(m.name))
+ if (embed) await startBundledEmbed(embed.path)
+ } catch {
+ /* best-effort — embedViaBuiltin reports the real error */
+ } finally {
+ embedEnsureInflight = null
+ }
+ })()
+ return embedEnsureInflight
+}
+
/** List downloaded GGUFs in the app models dir. Refreshes the name→path map. */
export async function listBundledModels(): Promise<BundledModel[]> {
const res = await backendCall<{ dir: string; models: BundledModel[] }>('list_bundled_models')
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index 6832b617..bea0d4e5 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -18,6 +18,7 @@ import { parseSSEStream } from '../sse'
import { repairJson } from '../../lib/tool-call-repair'
import { signalCreditsExhausted } from '../../lib/credits-exhausted'
import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost } from '../backend'
+import { ensureBuiltinEngineAlive } from '../builtin-ensure'
// Transport routing lives in the `useLocalProxy` getter (below) plus the shared
// host helpers in backend.ts. A direct webview fetch only works for hosts the
@@ -285,6 +286,12 @@ export class OpenAIProvider implements ProviderClient {
// the TokenCounter honest — a char/4 estimate can't see the system prompt.
body.stream_options = { include_usage: true }
+ // Managed built-in engine: Create/Music renders stop the llama-server
+ // child to free VRAM ("reloads lazily on the next message") — this is that
+ // lazy reload. Restart-before-send instead of letting the fetch hit a dead
+ // 127.0.0.1:8127 and look like a crashed backend.
+ if (this.config.managed === true) await ensureBuiltinEngineAlive(model)
+
if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)
const fetcher = this.useLocalProxy ? localFetchStream : fetch
let res = await fetcher(`${this.baseUrl}/chat/completions`, {
@@ -453,6 +460,10 @@ export class OpenAIProvider implements ProviderClient {
if (options?.thinking === true) body.reasoning_effort = 'high'
else if (options?.thinking === false) body.reasoning_effort = 'minimal'
+ // Same self-heal as chatStream: agent/tool turns after a Create render
+ // must revive the offloaded built-in engine before hitting its port.
+ if (this.config.managed === true) await ensureBuiltinEngineAlive(model)
+
if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)
const fetcher = this.useLocalProxy ? localFetch : fetch
let res = await fetcher(`${this.baseUrl}/chat/completions`, {
diff --git a/src/api/rag.ts b/src/api/rag.ts
index 6cec9c68..0ac5b154 100644
--- a/src/api/rag.ts
+++ b/src/api/rag.ts
@@ -1,7 +1,7 @@
import { v4 as uuid } from "uuid"
import type { DocumentMeta, TextChunk, RAGContext, VectorSearchResult } from "../types/rag"
import { ollamaUrl, localFetch } from "./backend"
-import { isManagedBuiltinActive, embedBaseUrl, bundledEmbedStatus } from "./engine"
+import { isManagedBuiltinActive, embedBaseUrl, bundledEmbedStatus, ensureBundledEmbedAlive } from "./engine"
export async function extractText(file: File): Promise<string> {
const ext = file.name.split(".").pop()?.toLowerCase()
@@ -72,6 +72,9 @@ export async function generateEmbeddings(
// onboarding — use it whenever it is running. Otherwise fall back to the
// Ollama `/api/embed` path (still supported as an "Advanced" backend).
if (isManagedBuiltinActive()) {
+ // A Create/Music render may have offloaded the embed sidecar — revive it
+ // before the request instead of failing with "cannot reach :8128".
+ await ensureBundledEmbedAlive()
return embedViaBuiltin(texts, model)
}
try {
diff --git a/src/hooks/useModels.ts b/src/hooks/useModels.ts
index a31058f6..db82426a 100644
--- a/src/hooks/useModels.ts
+++ b/src/hooks/useModels.ts
@@ -10,25 +10,18 @@ import { getEnabledProviders, prefixModelName, getProviderIdFromModel } from '..
import {
listBundledModels, bundledToAIModels, activateBuiltinModel, isManagedBuiltinActive,
bundledEngineStatus, bundledEmbedStatus, startBundledEmbed,
+ isEmbeddingGgufName as isEmbeddingModel,
} from '../api/engine'
import type { BundledModel } from '../api/engine'
import type { PullProgress, AIModel, ModelCategory, ImageModel, VideoModel, CloudModel } from '../types/models'
const VIDEO_PATTERNS = [/wan/, /svd/, /animatediff/, /animate/, /video/, /cogvideo/, /ltx/i, /framepack/, /mochi/, /cosmos/, /hunyuan/, /pyramidflow/, /allegro/]
-// Embedding models that should never appear in the chat model dropdown
-const EMBEDDING_PATTERNS = [/embed/, /nomic-embed/, /bge-/, /e5-/, /gte-/, /sentence-/]
-
function isVideoModel(name: string): boolean {
const lower = name.toLowerCase()
return VIDEO_PATTERNS.some((p) => p.test(lower))
}
-function isEmbeddingModel(name: string): boolean {
- const lower = name.toLowerCase()
- return EMBEDDING_PATTERNS.some((p) => p.test(lower))
-}
-
// Boot-resume for the managed built-in engine (2.5.7): the llama-server
// children are reaped on app quit and nothing on the Rust side respawns them,
// so after a relaunch the persisted active model points at a dead