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(rag): a dropped document was accepted and then never embedded

Davidee560e02c3af
diff --git a/src/api/__tests__/embed-lane-readiness.test.ts b/src/api/__tests__/embed-lane-readiness.test.ts
new file mode 100644
index 00000000..020458d6
--- /dev/null
+++ b/src/api/__tests__/embed-lane-readiness.test.ts
@@ -0,0 +1,67 @@
+/**
+ * A dropped document was accepted and then never embedded.
+ *
+ * Measured on the Windows box on 2026-08-15 against the installed 2.6.5:
+ * built-in engine active, the app models dir holding exactly one GGUF
+ * (Hermes-3-Llama-3.2-3B, a chat model), ports 8127 and 8128 both dead. The
+ * TXT went in without a word of protest and the panel then said
+ * `Embedding failed (HTTP 500): proxy_localhost: error sending request`.
+ *
+ * Two separate defects met there:
+ *
+ * 1. The pre-flight asked the wrong question. It treated "the built-in engine
+ * is the active backend" as "the bundled lane can embed", but that lane
+ * needs an embedding GGUF, and `ensureBundledEmbedAlive` can only START
+ * one, never conjure it. Ollama on the same box HAD nomic-embed-text
+ * pulled, which is why the second half of the pre-flight would have said
+ * yes as well: rag.ts never asks Ollama once the built-in engine is on.
+ * 2. When it failed anyway, the message named the pipe instead of the missing
+ * part. A transport error is not an explanation a user can act on.
+ *
+ * Run: npx vitest run src/api/__tests__/embed-lane-readiness.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+let running = false
+let bundled: { name: string; path: string }[] = []
+
+vi.mock('../backend', () => ({
+ backendCall: async (cmd: string) => {
+ if (cmd === 'bundled_embed_status') return { running, healthy: running }
+ if (cmd === 'list_bundled_models') return { dir: 'C:/models', models: bundled }
+ return null
+ },
+ localFetch: async () => new Response('{}', { status: 200 }),
+ ollamaUrl: (p: string) => `http://localhost:11434/api${p}`,
+ isTauri: () => false,
+}))
+
+import { bundledEmbedLaneReady } from '../engine'
+
+describe('the bundled lane knows whether it can embed', () => {
+ beforeEach(() => {
+ running = false
+ bundled = []
+ })
+
+ it('says no when the only installed GGUF is a chat model', async () => {
+ // The exact box state on 2026-08-15.
+ bundled = [{ name: 'Hermes-3-Llama-3.2-3B-Q4_K_M.gguf', path: 'C:/models/Hermes-3.gguf' }]
+ expect(await bundledEmbedLaneReady()).toBe(false)
+ })
+
+ it('says no when nothing is installed at all', async () => {
+ expect(await bundledEmbedLaneReady()).toBe(false)
+ })
+
+ it('says yes when an embedding GGUF is installed, even with the server down', async () => {
+ // ensureBundledEmbedAlive can start this one, so the lane is serviceable.
+ bundled = [{ name: 'nomic-embed-text-v1.5.Q4_K_M.gguf', path: 'C:/models/nomic.gguf' }]
+ expect(await bundledEmbedLaneReady()).toBe(true)
+ })
+
+ it('says yes when the server is already running, whatever is on disk', async () => {
+ running = true
+ expect(await bundledEmbedLaneReady()).toBe(true)
+ })
+})
diff --git a/src/api/__tests__/rag-embeddings-routing.test.ts b/src/api/__tests__/rag-embeddings-routing.test.ts
index 1b779352..ac9c523a 100644
--- a/src/api/__tests__/rag-embeddings-routing.test.ts
+++ b/src/api/__tests__/rag-embeddings-routing.test.ts
@@ -11,8 +11,10 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
-// Mutable flag the mock reads so each test can flip the active backend.
+// Mutable flags the mock reads so each test can flip the active backend and
+// whether the self-heal left a server behind.
let builtinActive = false
+let embedRunning = true
const ensureEmbed = vi.fn()
vi.mock('../engine', () => ({
@@ -20,7 +22,7 @@ vi.mock('../engine', () => ({
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 }),
+ bundledEmbedStatus: async () => ({ running: embedRunning, healthy: embedRunning }),
}))
const localFetch = vi.fn()
@@ -40,6 +42,7 @@ describe('generateEmbeddings routing', () => {
localFetch.mockReset()
ensureEmbed.mockReset()
builtinActive = false
+ embedRunning = true
})
it('hits the bundled /v1/embeddings when the built-in engine is active', async () => {
@@ -67,6 +70,9 @@ describe('generateEmbeddings routing', () => {
it('falls back to Ollama /api/embed when the built-in engine is NOT active', async () => {
builtinActive = false
+ // A running bundled server would win even here (LM Studio setups embed
+ // through it), so this case only exists with the server down.
+ embedRunning = false
localFetch.mockResolvedValue(jsonResponse({ embeddings: [[0.9, 0.8]] }))
const out = await generateEmbeddings(['x'])
@@ -76,6 +82,20 @@ describe('generateEmbeddings routing', () => {
expect(out).toEqual([[0.9, 0.8]])
})
+ it('names the missing model when the self-heal could not bring a server up', async () => {
+ // The Windows box on 2026-08-15: built-in engine active, no embedding GGUF
+ // installed, so ensureBundledEmbedAlive has nothing to start. Before this
+ // the request went out anyway and came back as
+ // `proxy_localhost: error sending request`, which names the pipe, not the
+ // missing part. No request should leave at all in this state.
+ builtinActive = true
+ embedRunning = false
+
+ await expect(generateEmbeddings(['a'])).rejects.toThrow(/No embedding model is installed/)
+ expect(ensureEmbed).toHaveBeenCalledTimes(1)
+ expect(localFetch).not.toHaveBeenCalled()
+ })
+
it('surfaces a built-in-specific error (not an Ollama hint) when the embed server fails', async () => {
builtinActive = true
localFetch.mockResolvedValue(jsonResponse({ error: { message: 'model still loading' } }, 503))
diff --git a/src/api/embed-install.ts b/src/api/embed-install.ts
new file mode 100644
index 00000000..7327b6e9
--- /dev/null
+++ b/src/api/embed-install.ts
@@ -0,0 +1,54 @@
+/**
+ * Install the embedding GGUF for the bundled embeddings server.
+ *
+ * Onboarding has done this since P5, but Document Chat could not: its only
+ * install path was `ollama pull`, which is the wrong shop when the built-in
+ * engine is the active backend. Someone who onboarded on the built-in engine
+ * and skipped the embeddings step therefore had no way in from the panel.
+ *
+ * Same model, same destination and the same download store the progress UI
+ * renders, so a file started here shows up exactly like an Onboarding one.
+ */
+import { ONBOARDING_EMBED_MODEL } from '../lib/constants'
+import { BUILTIN_BACKEND_ID } from '../lib/onboarding-backend'
+import { detectProviderModelPath, startModelDownloadToPath } from './discover'
+import { startBundledEmbed } from './engine'
+import { useDownloadStore } from '../stores/downloadStore'
+
+export async function installBundledEmbedModel(
+ onProgress?: (completed: number, total: number) => void,
+): Promise<void> {
+ const destDir = await detectProviderModelPath(BUILTIN_BACKEND_ID)
+ if (!destDir) throw new Error('Could not resolve the built-in models directory.')
+
+ const { downloadUrl, filename, sizeGB } = ONBOARDING_EMBED_MODEL
+ useDownloadStore.getState().setMeta(filename, downloadUrl, 'gguf', destDir)
+ await startModelDownloadToPath(
+ downloadUrl,
+ destDir,
+ filename,
+ Math.round(sizeGB * 1_073_741_824),
+ )
+ useDownloadStore.getState().startPolling()
+
+ const unsub = useDownloadStore.subscribe((s) => {
+ const d = s.downloads[filename]
+ if (d) onProgress?.(d.progress || 0, d.total || 0)
+ })
+ try {
+ await new Promise<void>((resolve, reject) => {
+ const poll = setInterval(() => {
+ const d = useDownloadStore.getState().downloads[filename]
+ if (d?.status === 'complete') { clearInterval(poll); resolve() }
+ else if (d?.status === 'error') { clearInterval(poll); reject(new Error(d.error || 'Download failed')) }
+ }, 500)
+ })
+ } finally {
+ unsub()
+ }
+
+ // Boot it right away: the caller is about to embed, and a GGUF on disk with
+ // no server behind it is the exact state this whole fix exists to end.
+ await startBundledEmbed(`${destDir}/${filename}`)
+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))
+}
diff --git a/src/api/engine.ts b/src/api/engine.ts
index d12be627..7ce85b00 100644
--- a/src/api/engine.ts
+++ b/src/api/engine.ts
@@ -159,6 +159,31 @@ export async function ensureBundledEmbedAlive(): Promise<void> {
return embedEnsureInflight
}
+/**
+ * Can the bundled lane actually embed right now.
+ *
+ * "The built-in engine is the active backend" is not the same question, which
+ * is what RAG's pre-flight used to ask. Measured on the Windows box on
+ * 2026-08-15: built-in engine active, the app models dir holding one chat GGUF
+ * and no embedding GGUF, ports 8127 and 8128 both dead. The pre-flight said
+ * yes, the dropped file was accepted, and the embedder then failed with
+ * `proxy_localhost: error sending request`. `ensureBundledEmbedAlive` starts an
+ * embedding GGUF, it cannot conjure one, so an installed embedding model is the
+ * precondition and this is where it gets asked.
+ */
+export async function bundledEmbedLaneReady(): Promise<boolean> {
+ try {
+ if ((await bundledEmbedStatus()).running) return true
+ } catch {
+ /* engine command unavailable — fall through to the model scan */
+ }
+ try {
+ return (await listBundledModels()).some((m) => isEmbeddingGgufName(m.name))
+ } catch {
+ return false
+ }
+}
+
/** 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/rag.ts b/src/api/rag.ts
index dd5dd06b..7162a953 100644
--- a/src/api/rag.ts
+++ b/src/api/rag.ts
@@ -112,6 +112,15 @@ export async function generateEmbeddings(
// A Create/Music render may have offloaded the embed sidecar — revive it
// before the request instead of failing with "cannot reach :8128".
await ensureBundledEmbedAlive()
+ // It revives a server, it cannot create the model one needs. Without this
+ // the next line dies on a bare transport error and the panel shows
+ // `proxy_localhost: error sending request`, which names the pipe instead
+ // of the missing part (measured on the Windows box, 2026-08-15).
+ if (!(await bundledEmbedStatus().then((s) => s.running).catch(() => false))) {
+ throw new Error(
+ "No embedding model is installed for the built-in engine. Open Document Chat and use the install card to download it (84 MB), then drop the file again."
+ )
+ }
return embedViaBuiltin(texts, model)
}
try {
diff --git a/src/hooks/useRAG.ts b/src/hooks/useRAG.ts
index 7be3d398..8748034f 100644
--- a/src/hooks/useRAG.ts
+++ b/src/hooks/useRAG.ts
@@ -2,7 +2,12 @@ import { useCallback, useEffect, useRef } from "react"
import { useShallow } from "zustand/react/shallow"
import { useRAGStore } from "../stores/ragStore"
import { indexDocument, retrieveContext } from "../api/rag"
-import { isManagedBuiltinActive, bundledEmbedStatus } from "../api/engine"
+import {
+ isManagedBuiltinActive,
+ bundledEmbedStatus,
+ bundledEmbedLaneReady,
+} from "../api/engine"
+import { installBundledEmbedModel } from "../api/embed-install"
import { getModelContext, listModels, pullModelTauri, checkConnection } from "../api/ollama"
import { useModelStore } from "../stores/modelStore"
import type { DocumentMeta, RAGContext } from "../types/rag"
@@ -10,15 +15,19 @@ import { log } from "../lib/logger"
const EMPTY_DOCS: DocumentMeta[] = []
-/** True when the bundled embeddings server can serve indexing without Ollama
- * (built-in engine active, or the embed GGUF server is up). */
+/** True when the bundled lane can serve indexing without Ollama: its server is
+ * up, or the built-in engine is active and an embedding GGUF is installed for
+ * it (see `bundledEmbedLaneReady`, which is the same question rag.ts answers
+ * when it routes). */
async function builtinEmbedReady(): Promise<boolean> {
- if (isManagedBuiltinActive()) return true
- try {
- return (await bundledEmbedStatus()).running
- } catch {
- return false
+ if (!isManagedBuiltinActive()) {
+ try {
+ return (await bundledEmbedStatus()).running
+ } catch {
+ return false
+ }
}
+ return bundledEmbedLaneReady()
}
export function useRAG(conversationId: string | null) {
@@ -90,11 +99,21 @@ export function useRAG(conversationId: string | null) {
* from the post-update banner / Install card so the UI can ask once and
* not re-probe per file.
*
- * Returns true when nomic-embed-text (or whatever `embeddingModel` is set
- * to) is in Ollama's model list. False when missing — caller is expected
- * to surface the in-app Install prompt rather than blocking.
+ * Asks about the lane the embedder will ACTUALLY take (rag.ts): the bundled
+ * server whenever it is running or the built-in engine is the backend,
+ * Ollama otherwise. Asking Ollama on a built-in-engine box was the bug that
+ * let RAGPanel open with no install card and swallow a dropped file: Ollama
+ * had nomic-embed-text pulled, the bundled lane had no embedding GGUF at
+ * all, and nobody ever asked the lane that ran.
+ *
+ * False when missing — caller is expected to surface the in-app Install
+ * prompt rather than blocking.
*/
const ensureEmbeddingModel = useCallback(async (): Promise<boolean> => {
+ if (await builtinEmbedReady()) return true
+ // 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 false
const { embeddingModel } = useRAGStore.getState()
const ollamaUp = await checkConnection()
if (!ollamaUp) return false
@@ -132,6 +151,25 @@ export function useRAG(conversationId: string | null) {
setPullingEmbeddingModel(true)
setEmbeddingPullProgress({ completed: 0, total: 0, status: "starting" })
+ // The install has to feed the same lane the embedder reads from. On a
+ // built-in-engine box `ollama pull` fills a shop rag.ts never visits, so
+ // the card would spin, report success and change nothing.
+ if (isManagedBuiltinActive()) {
+ try {
+ await installBundledEmbedModel((completed, total) =>
+ setEmbeddingPullProgress({ completed, total, status: "downloading" }),
+ )
+ setEmbeddingPullProgress({ completed: 1, total: 1, status: "success" })
+ return true
+ } catch (err) {
+ log.error("[EmbeddingPull] bundled install failed", { err })
+ return false
+ } finally {
+ setPullingEmbeddingModel(false)
+ setTimeout(() => setEmbeddingPullProgress(null), 1500)
+ }
+ }
+
try {
const { promise } = pullModelTauri(embeddingModel, (p) => {
const status = (p.status || "").toLowerCase()
@@ -174,6 +212,14 @@ export function useRAG(conversationId: string | null) {
// Ollama — indexDocument → generateEmbeddings already prefers it — so only
// fall back to the Ollama checks when that server isn't running.
if (!(await builtinEmbedReady())) {
+ // Built-in engine but no embedding GGUF: rag.ts routes to the bundled
+ // server regardless of what Ollama has, so offer the install instead
+ // of measuring the wrong lane and accepting a file we cannot index.
+ if (isManagedBuiltinActive()) {
+ queueEmbeddingFile(file)
+ setEmbeddingInstallPrompt(true)
+ return null
+ }
const ollamaUp = await checkConnection()
if (!ollamaUp) {
throw new Error(