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.

feat(engine): P5 — Ollama-free embeddings via a bundled --embeddings server

purple87c1313d0f4d
diff --git a/e2e/document-chat-builtin.spec.ts b/e2e/document-chat-builtin.spec.ts
new file mode 100644
index 00000000..eca2696c
--- /dev/null
+++ b/e2e/document-chat-builtin.spec.ts
@@ -0,0 +1,80 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+
+/**
+ * P5 acceptance test — Document-Chat / RAG embeddings without Ollama.
+ *
+ * The whole point of P5 is that the RAG path embeds against the bundled
+ * `llama-server --embeddings` (OpenAI `/v1/embeddings` on 8128), not Ollama.
+ * With the Tauri mock reporting every external backend unreachable, this test:
+ *
+ * 1. Onboards on the built-in engine and installs the embedding model on the
+ * built-in path (GGUF download → start_bundled_embed), proving the
+ * onboarding embeddings step is Ollama-free.
+ * 2. Drives the REAL RAG code (indexDocument → retrieveContext) in-page and
+ * asserts the vectors came back from the bundled server on :8128 — and
+ * that Ollama's :11434 /embed endpoint was never touched.
+ */
+
+async function installMock(page: Page) {
+ await page.addInitScript(tauriMockInit, {
+ assistantReply: DEFAULT_ASSISTANT_REPLY,
+ modelName: DEFAULT_MODEL_NAME,
+ })
+}
+
+test('document chat embeds via the bundled server, never Ollama', async ({ page }) => {
+ await installMock(page)
+ await page.goto('/')
+
+ // welcome → backends (built-in preselected) → comfyui skip
+ await page.getByRole('button', { name: /Get Started/i }).click()
+ await page.getByRole('button', { name: /Continue/i }).click()
+ await page.getByRole('button', { name: /Skip for now/i }).click()
+
+ // models — install the starter GGUF, auto-advances to embeddings
+ await expect(page.getByRole('heading', { name: /Pick a starter model/i })).toBeVisible()
+ await page.getByRole('button', { name: /Qwen 2\.5 0\.5B/i }).click()
+ await page.getByRole('button', { name: /Install \d+ model/i }).click()
+
+ // embeddings — install on the built-in path (84 MB GGUF, not the 274 MB
+ // Ollama pull). Success text proves the embed server booted with no Ollama.
+ const embedInstall = page.getByRole('button', { name: /Install nomic-embed-text \(84 MB\)/i })
+ await expect(embedInstall).toBeVisible({ timeout: 30_000 })
+ await embedInstall.click()
+ await expect(page.getByText(/Installed\. Document Chat is ready\./i)).toBeVisible({ timeout: 30_000 })
+
+ // finish onboarding
+ await page.getByRole('button', { name: /Continue/i }).click()
+ await page.getByRole('button', { name: /Get Started/i }).click()
+
+ // ── Drive the real RAG pipeline in-page against the mocked bundled embed ──
+ const result = await page.evaluate(async () => {
+ const rag = await import('/src/api/rag.ts')
+ const file = new File(
+ ['The mitochondria is the powerhouse of the cell. It produces ATP through respiration. ' +
+ 'Ribosomes synthesize proteins from messenger RNA in the cytoplasm of the cell.'],
+ 'bio.txt',
+ { type: 'text/plain' },
+ )
+ const { chunks } = await rag.indexDocument(file)
+ const retrieved = await rag.retrieveContext('what makes ATP in the cell', chunks, undefined, 2)
+ return {
+ chunkCount: chunks.length,
+ embeddingDims: chunks.map((c: any) => (Array.isArray(c.embedding) ? c.embedding.length : 0)),
+ retrievedChunks: retrieved.context.chunks.length,
+ proxyUrls: (window as any).__E2E_PROXY_URLS__ || [],
+ }
+ })
+
+ // The document was chunked and every chunk carries a real embedding vector.
+ expect(result.chunkCount).toBeGreaterThan(0)
+ expect(result.embeddingDims.every((d: number) => d > 0)).toBe(true)
+ expect(result.retrievedChunks).toBeGreaterThan(0)
+
+ // Embeddings hit the bundled server on 8128 …
+ const urls: string[] = result.proxyUrls
+ expect(urls.some((u) => u.includes(':8128') && u.includes('/v1/embeddings'))).toBe(true)
+ // … and NEVER Ollama's /api/embed on 11434.
+ expect(urls.some((u) => u.includes('11434') && u.includes('/embed'))).toBe(false)
+})
diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.ts
index c9760fb5..d2c81650 100644
--- a/e2e/support/tauri-mock.ts
+++ b/e2e/support/tauri-mock.ts
@@ -102,6 +102,14 @@ export function tauriMockInit(opts: TauriMockOptions) {
models: [{ name: opts.modelName, path: modelPath, size: 400 * 1024 * 1024, loaded: true }],
})
+ // ── built-in EMBEDDINGS server lifecycle (P5) ─────────────────
+ case 'start_bundled_embed':
+ return Promise.resolve({ status: 'started', port: 8128, model_path: args?.modelPath })
+ case 'stop_bundled_embed':
+ return Promise.resolve(null)
+ case 'bundled_embed_status':
+ return Promise.resolve({ running: true, healthy: true, port: 8128, model_path: `${MODELS_DIR}/nomic.gguf` })
+
// ── detection: nothing external is running ────────────────────
case 'get_ollama_host':
return Promise.resolve('http://localhost:11434')
@@ -147,6 +155,26 @@ export function tauriMockInit(opts: TauriMockOptions) {
// ever detected as live.
case 'proxy_localhost': {
const url: string = args?.url || ''
+ // Record every proxied URL so tests can assert routing (e.g. embeddings
+ // hit the bundled server on 8128, never Ollama on 11434).
+ ;(w.__E2E_PROXY_URLS__ = w.__E2E_PROXY_URLS__ || []).push(url)
+
+ // P5: bundled embeddings server on 8128 speaks OpenAI /v1/embeddings.
+ // Echo one deterministic (content-varying) vector per input so the real
+ // RAG code (indexDocument / retrieveContext) runs end to end, no Ollama.
+ if (url.includes(':8128') || url.includes('/v1/embeddings')) {
+ let inputs: string[] = []
+ try {
+ const parsed = JSON.parse(args?.body || '{}').input
+ inputs = Array.isArray(parsed) ? parsed : [parsed]
+ } catch { /* empty */ }
+ const data = inputs.map((s: string, index: number) => ({
+ index,
+ embedding: [(s?.length ?? 0) % 7, (s?.charCodeAt(0) || 0) % 13, 1],
+ }))
+ return Promise.resolve(JSON.stringify({ object: 'list', data, model: 'nomic-embed-text-v1.5' }))
+ }
+
if (url.includes('11434') || /\/tags(\?|$)/.test(url)) {
return Promise.resolve(JSON.stringify({ models: [] }))
}
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index eadab459..c88611fd 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -29,6 +29,12 @@ const CREATE_NO_WINDOW: u32 = 0x08000000;
/// preset base URL on the frontend (`http://127.0.0.1:8127/v1`).
pub const DEFAULT_ENGINE_PORT: u16 = 8127;
+/// Default loopback port for the managed EMBEDDINGS server (P5). Separate
+/// process/port from the chat engine so Document-Chat/RAG can embed while a
+/// chat model stays loaded. Matches `embedBaseUrl()` on the frontend
+/// (`http://127.0.0.1:8128/v1`).
+pub const DEFAULT_EMBED_PORT: u16 = 8128;
+
/// How long to wait for `/health` to flip to 200 after spawn. A cold GGUF
/// load (mmap + Metal warm-up) on a big model can take a while on a slow disk;
/// 60 s is comfortably above a normal 1-3 s load without hanging forever on a
@@ -77,6 +83,27 @@ pub(crate) fn build_server_args(model_path: &str, ctx: u32, port: u16) -> Vec<St
]
}
+/// Build the `llama-server` argv for the EMBEDDINGS server (P5). `--embeddings`
+/// switches llama-server into pooled-embedding mode so `/v1/embeddings`
+/// returns vectors instead of chat completions. `--pooling mean` matches how
+/// nomic/bge embedding GGUFs are meant to be pooled. `-ngl 999` offloads all
+/// layers (Metal on mac); embedding models are tiny so this is cheap.
+pub(crate) fn build_embed_args(model_path: &str, port: u16) -> Vec<String> {
+ vec![
+ "-m".into(),
+ model_path.into(),
+ "--host".into(),
+ "127.0.0.1".into(),
+ "--port".into(),
+ port.to_string(),
+ "--embeddings".into(),
+ "--pooling".into(),
+ "mean".into(),
+ "-ngl".into(),
+ "999".into(),
+ ]
+}
+
#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct BundledModel {
/// File name without the `.gguf` extension — the id the frontend shows and
@@ -392,6 +419,131 @@ fn stop_engine_locked(state: &State<'_, AppState>) -> bool {
}
}
+// ── Embeddings server (P5) ────────────────────────────────────────────────────
+//
+// A second `llama-server` in `--embeddings` mode on its own port. Same
+// lifecycle shape as the chat engine (spawn → health-wait → stop), reusing
+// `resolve_engine_binary` / `wait_for_health` / `engine_healthy` (all
+// port-generic). Document-Chat / RAG POST to `/v1/embeddings` on this port
+// instead of Ollama's `/api/embed`, so the RAG path is Ollama-free.
+
+/// Start (or reuse) the managed embeddings server for `model_path`. Idempotent
+/// for the same model + healthy. A different embed model in flight is stopped
+/// first (single-process server).
+#[tauri::command]
+pub fn start_bundled_embed(
+ app: AppHandle,
+ state: State<'_, AppState>,
+ model_path: String,
+ port: Option<u16>,
+) -> Result<serde_json::Value, String> {
+ let port = port.unwrap_or(DEFAULT_EMBED_PORT);
+
+ if !Path::new(&model_path).exists() {
+ return Err(format!("Embedding model file not found: {model_path}"));
+ }
+
+ // Already serving this exact model and healthy → no-op.
+ {
+ let guard = state.bundled_embed.lock().unwrap();
+ if let Some(embed) = guard.as_ref() {
+ if embed.model_path == model_path && engine_healthy(embed.port) {
+ return Ok(serde_json::json!({
+ "status": "already_running",
+ "port": embed.port,
+ "model_path": embed.model_path,
+ }));
+ }
+ }
+ }
+
+ stop_embed_locked(&state);
+
+ let binary = resolve_engine_binary(&app).ok_or_else(|| {
+ format!(
+ "Bundled engine binary not found ({}). Run scripts/build-llama.sh to produce the sidecar.",
+ sidecar_binary_name()
+ )
+ })?;
+
+ println!("[Engine] Starting built-in embeddings server on port {port} — {model_path}");
+ let mut cmd = Command::new(&binary);
+ cmd.args(build_embed_args(&model_path, port))
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ if let Ok(sel) = state.gpu_selection.lock() {
+ crate::commands::gpu::apply_gpu_env(&mut cmd, &sel);
+ }
+ #[cfg(target_os = "windows")]
+ cmd.creation_flags(CREATE_NO_WINDOW);
+
+ let child = cmd
+ .spawn()
+ .map_err(|e| format!("Failed to spawn embeddings server: {e}"))?;
+
+ *state.bundled_embed.lock().unwrap() = Some(BundledEngine {
+ child,
+ model_path: model_path.clone(),
+ port,
+ });
+
+ if let Err(e) = wait_for_health(port) {
+ stop_embed_locked(&state);
+ return Err(e);
+ }
+
+ println!("[Engine] Built-in embeddings server healthy on port {port}");
+ Ok(serde_json::json!({
+ "status": "started",
+ "port": port,
+ "model_path": model_path,
+ }))
+}
+
+/// Stop the managed embeddings server, killing the child. Idempotent.
+#[tauri::command]
+pub fn stop_bundled_embed(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
+ let was_running = stop_embed_locked(&state);
+ Ok(serde_json::json!({ "status": if was_running { "stopped" } else { "idle" } }))
+}
+
+/// Report whether the embeddings server is up, which model, on which port.
+#[tauri::command]
+pub fn bundled_embed_status(
+ state: State<'_, AppState>,
+) -> Result<serde_json::Value, String> {
+ let guard = state.bundled_embed.lock().unwrap();
+ match guard.as_ref() {
+ Some(embed) => Ok(serde_json::json!({
+ "running": true,
+ "healthy": engine_healthy(embed.port),
+ "port": embed.port,
+ "model_path": embed.model_path,
+ })),
+ None => Ok(serde_json::json!({
+ "running": false,
+ "healthy": false,
+ "port": DEFAULT_EMBED_PORT,
+ "model_path": null,
+ })),
+ }
+}
+
+/// Kill the managed embeddings child if present. Returns whether one was
+/// running. Takes the state lock internally; callers must not already hold it.
+fn stop_embed_locked(state: &State<'_, AppState>) -> bool {
+ let mut guard = state.bundled_embed.lock().unwrap();
+ if let Some(mut embed) = guard.take() {
+ let _ = embed.child.kill();
+ let _ = embed.child.wait();
+ println!("[Engine] Built-in embeddings server stopped (port {})", embed.port);
+ true
+ } else {
+ false
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -411,6 +563,26 @@ mod tests {
);
}
+ #[test]
+ fn embed_args_enable_embeddings_and_mean_pooling() {
+ let args = build_embed_args("/models/nomic-embed.gguf", 8128);
+ assert_eq!(
+ args,
+ vec![
+ "-m", "/models/nomic-embed.gguf",
+ "--host", "127.0.0.1",
+ "--port", "8128",
+ "--embeddings",
+ "--pooling", "mean",
+ "-ngl", "999",
+ ]
+ );
+ // The whole point of P5: the embed server must NOT carry --ctx-size
+ // (chat-only) and MUST carry --embeddings so /v1/embeddings works.
+ assert!(args.iter().any(|a| a == "--embeddings"));
+ assert!(!args.iter().any(|a| a == "--ctx-size"));
+ }
+
#[test]
fn host_triple_is_platform_shaped() {
let t = host_target_triple();
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 93bec9be..d0502bf8 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -179,6 +179,10 @@ fn main() {
commands::engine::bundled_engine_status,
commands::engine::swap_bundled_model,
commands::engine::list_bundled_models,
+ // Built-in embeddings server (bundled llama-server --embeddings, P5)
+ commands::engine::start_bundled_embed,
+ commands::engine::stop_bundled_embed,
+ commands::engine::bundled_embed_status,
// Provider API-key keychain (H5)
commands::secret::secret_set,
commands::secret::secret_get,
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 983b1ba1..45edc06a 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -21,10 +21,14 @@ pub struct DownloadProgress {
pub error: Option<String>,
}
-/// Handle to a running bundled `llama-server` (built-in engine, P1). One
-/// model per process, so `model_path` identifies what's loaded and `port` is
-/// the loopback port the OpenAI-compatible API is served on. Killed in
-/// `shutdown_subprocesses` like the other spawned children.
+/// Handle to a running bundled `llama-server`. One model per process, so
+/// `model_path` identifies what's loaded and `port` is the loopback port the
+/// OpenAI-compatible API is served on. Killed in `shutdown_subprocesses` like
+/// the other spawned children.
+///
+/// Used for BOTH the chat engine (`bundled_engine`) and — P5 — the separate
+/// `--embeddings` server (`bundled_embed`): same lifecycle shape, different
+/// port + model + serve mode. Keeping one struct avoids duplicating the handle.
pub struct BundledEngine {
pub child: Child,
pub model_path: String,
@@ -144,6 +148,11 @@ pub struct AppState {
/// managed lifecycle (start/stop/swap) lives in `commands::engine`; this
/// is just the handle so shutdown can reap it.
pub bundled_engine: Mutex<Option<BundledEngine>>,
+ /// Built-in EMBEDDINGS server (P5) — a second bundled `llama-server` run in
+ /// `--embeddings` mode on its own port, serving OpenAI `/v1/embeddings` for
+ /// Document-Chat / RAG so embeddings no longer require Ollama. `None` until
+ /// started via `start_bundled_embed`; reaped in `shutdown_subprocesses`.
+ pub bundled_embed: Mutex<Option<BundledEngine>>,
pub comfy_path: Mutex<Option<String>>,
pub comfy_port: Mutex<u16>,
/// Configurable ComfyUI host. Default "localhost". Setting this to a
@@ -256,6 +265,7 @@ impl AppState {
comfy_process: Mutex::new(None),
ollama_process: Mutex::new(None),
bundled_engine: Mutex::new(None),
+ bundled_embed: Mutex::new(None),
comfy_path: Mutex::new(None),
comfy_port: Mutex::new(initial_port),
comfy_host: Mutex::new(initial_host),
@@ -340,6 +350,15 @@ impl AppState {
*engine = None;
}
+ // Built-in embeddings server (P5) — same plain-kill treatment.
+ if let Ok(mut embed) = self.bundled_embed.lock() {
+ if let Some(ref mut e) = *embed {
+ let _ = e.child.kill();
+ println!("[Engine] Built-in embeddings server stopped (explicit shutdown)");
+ }
+ *embed = None;
+ }
+
if let Ok(mut proc) = self.comfy_process.lock() {
if let Some(ref mut child) = *proc {
let pid = child.id();
diff --git a/src/api/__tests__/rag-embeddings-routing.test.ts b/src/api/__tests__/rag-embeddings-routing.test.ts
new file mode 100644
index 00000000..13bf921c
--- /dev/null
+++ b/src/api/__tests__/rag-embeddings-routing.test.ts
@@ -0,0 +1,77 @@
+/**
+ * P5 — Embeddings routing: Document-Chat/RAG must embed against the bundled
+ * `llama-server --embeddings` (OpenAI `/v1/embeddings`) when the app-managed
+ * built-in engine is active, and only fall back to Ollama's `/api/embed`
+ * otherwise. This is the frontend half of "onboarding is Ollama-free".
+ *
+ * We mock the backend transport + the engine active-check so the pure routing
+ * decision (which URL, which response shape) is testable without a real server.
+ *
+ * Run: npx vitest run src/api/__tests__/rag-embeddings-routing.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// Mutable flag the mock reads so each test can flip the active backend.
+let builtinActive = false
+
+vi.mock('../engine', () => ({
+ isManagedBuiltinActive: () => builtinActive,
+ embedBaseUrl: () => 'http://127.0.0.1:8128/v1',
+}))
+
+const localFetch = vi.fn()
+vi.mock('../backend', () => ({
+ localFetch: (...args: any[]) => localFetch(...args),
+ ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,
+}))
+
+import { generateEmbeddings } from '../rag'
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
+}
+
+describe('generateEmbeddings routing', () => {
+ beforeEach(() => {
+ localFetch.mockReset()
+ builtinActive = false
+ })
+
+ it('hits the bundled /v1/embeddings when the built-in engine is active', async () => {
+ builtinActive = true
+ // OpenAI shape, deliberately returned out of order to prove we sort by index.
+ localFetch.mockResolvedValue(jsonResponse({
+ data: [
+ { index: 1, embedding: [0.3, 0.4] },
+ { index: 0, embedding: [0.1, 0.2] },
+ ],
+ }))
+
+ const out = await generateEmbeddings(['a', 'b'])
+
+ const [url, opts] = localFetch.mock.calls[0]
+ expect(url).toBe('http://127.0.0.1:8128/v1/embeddings')
+ expect(opts.method).toBe('POST')
+ 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]])
+ })
+
+ it('falls back to Ollama /api/embed when the built-in engine is NOT active', async () => {
+ builtinActive = false
+ localFetch.mockResolvedValue(jsonResponse({ embeddings: [[0.9, 0.8]] }))
+
+ const out = await generateEmbeddings(['x'])
+
+ const [url] = localFetch.mock.calls[0]
+ expect(url).toBe('http://localhost:11434/api/embed')
+ expect(out).toEqual([[0.9, 0.8]])
+ })
+
+ 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))
+
+ await expect(generateEmbeddings(['a'])).rejects.toThrow(/model still loading/)
+ })
+})
diff --git a/src/api/engine.ts b/src/api/engine.ts
index dfd04e3c..4dab416e 100644
--- a/src/api/engine.ts
+++ b/src/api/engine.ts
@@ -34,6 +34,14 @@ export interface EngineStatus {
model_path: string | null
}
+/** 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`. */
+export const EMBED_PORT = 8128
+export function embedBaseUrl(): string {
+ return `http://127.0.0.1:${EMBED_PORT}/v1`
+}
+
// name → absolute GGUF path, populated by listBundledModels(). Lets callers
// activate a model by its picker id (which is what the model store carries)
// without threading the path through AIModel, which has no path field.
@@ -69,6 +77,22 @@ export function swapBundledModel(modelPath: string, ctx?: number) {
return backendCall('swap_bundled_model', { modelPath, ctx })
}
+/** Start the built-in embeddings server (P5) with a specific embedding GGUF.
+ * Idempotent for the same model. Runs on EMBED_PORT, separate from chat. */
+export function startBundledEmbed(modelPath: string) {
+ return backendCall('start_bundled_embed', { modelPath })
+}
+
+/** Stop the managed embeddings server if one is running. */
+export function stopBundledEmbed() {
+ return backendCall('stop_bundled_embed')
+}
+
+/** Embeddings-server health + which model is loaded on which port. */
+export function bundledEmbedStatus() {
+ return backendCall<EngineStatus>('bundled_embed_status')
+}
+
/** 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 bbf1af89..15631c80 100644
--- a/src/api/rag.ts
+++ b/src/api/rag.ts
@@ -1,6 +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 } from "./engine"
export async function extractText(file: File): Promise<string> {
const ext = file.name.split(".").pop()?.toLowerCase()
@@ -64,6 +65,54 @@ export async function generateEmbeddings(
texts: string[],
model = "nomic-embed-text"
): Promise<number[][]> {
+ // P5: when the app-managed built-in engine is the active backend, embed
+ // against the bundled `llama-server --embeddings` (OpenAI `/v1/embeddings`)
+ // so Document-Chat/RAG works with zero Ollama. Otherwise fall back to the
+ // Ollama `/api/embed` path (still supported as an "Advanced" backend).
+ if (isManagedBuiltinActive()) {
+ return embedViaBuiltin(texts, model)
+ }
+ return embedViaOllama(texts, model)
+}
+
+/** OpenAI `/v1/embeddings` against the bundled embeddings server (P5). */
+async function embedViaBuiltin(texts: string[], model: string): Promise<number[][]> {
+ let res: Response
+ try {
+ res = await localFetch(`${embedBaseUrl()}/embeddings`, {
+ method: "POST",
+ body: JSON.stringify({ model, input: texts }),
+ })
+ } catch (err) {
+ throw new Error(
+ `Cannot reach the built-in embeddings server. (${err instanceof Error ? err.message : String(err)})`
+ )
+ }
+
+ if (!res.ok) {
+ let detail = ""
+ try {
+ const body = await res.json()
+ detail = body?.error?.message || body?.error || ""
+ } catch { /* ignore parse errors */ }
+ throw new Error(
+ `Embedding failed (HTTP ${res.status}): ${detail || "the built-in embeddings server may still be loading"}`
+ )
+ }
+
+ const data = await res.json()
+ // OpenAI shape: { data: [{ embedding: number[], index }] }. Sort by index so
+ // the vectors line up with the input order even if the server reorders them.
+ if (!data?.data || !Array.isArray(data.data)) {
+ throw new Error("Unexpected response from the built-in /v1/embeddings endpoint")
+ }
+ return [...data.data]
+ .sort((a: any, b: any) => (a.index ?? 0) - (b.index ?? 0))
+ .map((d: any) => d.embedding as number[])
+}
+
+/** Ollama `/api/embed` — the legacy/Advanced path (unchanged). */
+async function embedViaOllama(texts: string[], model: string): Promise<number[][]> {
let res: Response
try {
res = await localFetch(ollamaUrl("/embed"), {
diff --git a/src/components/onboarding/Onboarding.tsx b/src/components/onboarding/Onboarding.tsx
index 2d47a005..c085f99b 100644
--- a/src/components/onboarding/Onboarding.tsx
+++ b/src/components/onboarding/Onboarding.tsx
@@ -3,7 +3,7 @@ import { motion, AnimatePresence } from 'framer-motion'
import { Minus, Square, X as XIcon, ArrowRight, Download, Check, ChevronRight, Loader2, RefreshCw, ExternalLink, FolderOpen, Cpu } from 'lucide-react'
import { useSettingsStore } from '../../stores/settingsStore'
import { useProviderStore } from '../../stores/providerStore'
-import { ONBOARDING_MODELS } from '../../lib/constants'
+import { ONBOARDING_MODELS, ONBOARDING_EMBED_MODEL } from '../../lib/constants'
import { PROVIDER_PRESETS } from '../../api/providers/types'
import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'
import { detectProviderModelPath, startModelDownloadToPath } from '../../api/discover'
@@ -15,7 +15,7 @@ import { backendCall } from '../../api/backend'
import { getSystemVRAM } from '../../api/comfyui'
import { pullModelTauri, checkConnection as checkOllama } from '../../api/ollama'
import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir } from '../../lib/hf-to-provider'
-import { startBundledEngine } from '../../api/engine'
+import { startBundledEngine, startBundledEmbed, isManagedBuiltinActive } from '../../api/engine'
import { BUILTIN_BACKEND_ID, classifyOnboardingBackend, resolveOnboardingBackend } from '../../lib/onboarding-backend'
// Bug (h): the dedicated 'theme' onboarding step was removed because users
@@ -459,24 +459,25 @@ export function Onboarding() {
const [embeddingsProgress, setEmbeddingsProgress] = useState<{ completed: number; total: number }>({ completed: 0, total: 0 })
const [embeddingsAlreadyHave, setEmbeddingsAlreadyHave] = useState<boolean | null>(null)
- // Probe whether an embedding model is already present on the box. Ollama
- // lists pulled models; we look for anything with `embed`/`bge`/`nomic` in
- // the name (the same heuristic used elsewhere for chat-capability filtering).
+ // Probe whether an embedding model is already present. For the built-in
+ // engine (P5) we scan the app models dir via list_bundled_models; otherwise
+ // Ollama lists pulled models. Either way we match anything with
+ // `embed`/`bge`/`nomic` in the name (same heuristic used elsewhere).
useEffect(() => {
if (step !== 'embeddings') return
let cancelled = false
- import('../../api/ollama').then(({ listModels }) =>
- listModels()
- .then(models => {
- if (cancelled) return
- const hasEmbedding = models.some(m => {
- const lower = (m.name || '').toLowerCase()
- return lower.includes('embed') || lower.includes('bge-') || lower.includes('nomic')
- })
- setEmbeddingsAlreadyHave(hasEmbedding)
- })
- .catch(() => { if (!cancelled) setEmbeddingsAlreadyHave(false) })
- )
+ const isEmbed = (name: string) => {
+ const lower = (name || '').toLowerCase()
+ return lower.includes('embed') || lower.includes('bge-') || lower.includes('nomic')
+ }
+ const probe = isManagedBuiltinActive()
+ ? import('../../api/engine').then(({ listBundledModels }) =>
+ listBundledModels().then(models => models.some(m => isEmbed(m.name))))
+ : import('../../api/ollama').then(({ listModels }) =>
+ listModels().then(models => models.some(m => isEmbed(m.name))))
+ probe
+ .then(hasEmbedding => { if (!cancelled) setEmbeddingsAlreadyHave(hasEmbedding) })
+ .catch(() => { if (!cancelled) setEmbeddingsAlreadyHave(false) })
return () => { cancelled = true }
}, [step])
@@ -488,6 +489,40 @@ export function Onboarding() {
setEmbeddingsPulling(true)
setEmbeddingsError(null)
setEmbeddingsProgress({ completed: 0, total: 0 })
+
+ // P5: built-in engine path — download the embedding GGUF flat into the app
+ // models dir and boot the embeddings server on it. No Ollama involved, so
+ // Document-Chat/RAG works on a fresh install with zero external provider.
+ if (isManagedBuiltinActive()) {
+ try {
+ 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
+ dlStore.getState().setMeta(filename, downloadUrl, 'gguf', destDir)
+ const expectedBytes = sizeGB ? Math.round(sizeGB * 1_073_741_824) : undefined
+ await startModelDownloadToPath(downloadUrl, destDir, filename, expectedBytes)
+ dlStore.getState().startPolling()
+ // Mirror the store's completed/total into the step's progress UI.
+ const unsub = useDownloadStore.subscribe(s => {
+ const d = s.downloads[filename]
+ if (d) setEmbeddingsProgress({ completed: d.progress || 0, total: d.total || 0 })
+ })
+ try {
+ await awaitDownloadComplete(filename)
+ } finally {
+ unsub()
+ }
+ await startBundledEmbed(`${destDir}/${filename}`)
+ setEmbeddingsPulled(true)
+ window.dispatchEvent(new CustomEvent('lu-models-refresh'))
+ } catch (e) {
+ setEmbeddingsError(`Embedding setup failed: ${e instanceof Error ? e.message : String(e)}`)
+ } finally {
+ setEmbeddingsPulling(false)
+ }
+ return
+ }
+
try {
// Make sure ollama is reachable before kicking off the pull.
let ok = await checkOllama()
@@ -1662,7 +1697,7 @@ export function Onboarding() {
Standard embedding model from Nomic AI. Used purely on-device to chunk and retrieve your documents — never sent anywhere.
</p>
<p className={`text-[0.55rem] mt-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
- 274 MB · runs on any CPU
+ {isManagedBuiltinActive() ? '84 MB · bundled engine, runs on any CPU' : '274 MB · runs on any CPU'}
</p>
</div>
</div>
@@ -1693,7 +1728,7 @@ export function Onboarding() {
<div className="flex items-center gap-2 pt-1">
{embeddingsAlreadyHave !== true && !embeddingsPulled && !embeddingsPulling && (
<button onClick={handlePullEmbeddings} className={primaryBtn} style={{ flex: 1 }}>
- <Download size={14} /> Install nomic-embed-text (274 MB)
+ <Download size={14} /> Install nomic-embed-text ({isManagedBuiltinActive() ? '84 MB' : '274 MB'})
</button>
)}
<button
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 640be649..c9f39b1c 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -281,6 +281,16 @@ export interface OnboardingModel {
const HF_OB = (repo: string, file: string) => `https://huggingface.co/${repo}/resolve/main/${file}`
+// P5: the embedding GGUF for the built-in embeddings server (Document-Chat/RAG
+// without Ollama). nomic-embed-text v1.5, Q4_K_M — ~84 MB, 768-dim, broadly
+// compatible with llama-server's `--embeddings` mode. Downloaded flat into the
+// same app models dir as chat models, then served on EMBED_PORT.
+export const ONBOARDING_EMBED_MODEL = {
+ downloadUrl: HF_OB('nomic-ai/nomic-embed-text-v1.5-GGUF', 'nomic-embed-text-v1.5.Q4_K_M.gguf'),
+ filename: 'nomic-embed-text-v1.5.Q4_K_M.gguf',
+ sizeGB: 0.084,
+}
+
export const ONBOARDING_MODELS: OnboardingModel[] = [
// P4 / LU-Aufgaben: ONBOARDING shows exactly ONE model — the tiny ~400 MB
// Qwen 2.5 0.5B starter. The previous list of 22 entries (5–42 GB) was