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(chat): die Einbettungs-Frage und der Retrieval-Block stehen je an einem Ort

purplecea73a5ee0f1
diff --git a/src/api/__tests__/rag-context-reaches-the-cloud.test.ts b/src/api/__tests__/rag-context-reaches-the-cloud.test.ts
new file mode 100644
index 00000000..d0762dc3
--- /dev/null
+++ b/src/api/__tests__/rag-context-reaches-the-cloud.test.ts
@@ -0,0 +1,133 @@
+/**
+ * The other half of A9: the button is only worth showing in Cloud mode if the
+ * document context actually reaches a cloud model.
+ *
+ * It does, and this file proves it on the wire rather than by reading source.
+ * Retrieval never talks to the chat provider. It builds a block of passages
+ * (lib/rag-prompt.ts), the block is appended to the SYSTEM prompt, and a system
+ * message is the one thing Ollama, the built-in engine, LM Studio and LU Cloud
+ * all accept. Nothing in that path is local-only, which is why hiding the Docs
+ * button on `appMode === 'cloud'` was a guess and not a limit.
+ *
+ * The request below goes out through LuCloudProvider, the real one, against a
+ * spied fetch. What we assert is the JSON body: the passages are in the system
+ * message, and the bearer is the cloud session token, so this is the cloud
+ * lane and not a local one wearing its name.
+ *
+ * Negative controls, because "the text appears somewhere" is not a proof:
+ * - no retrieval hits -> no instruction, no [Source], nothing paid for
+ * - RAG switched off -> the system prompt goes out byte for byte unchanged
+ * - the document text is nowhere in the body when RAG is off, so a passing
+ * positive case cannot be some other part of the payload
+ *
+ * Run: npx vitest run src/api/__tests__/rag-context-reaches-the-cloud.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { buildRagSuffix, RAG_INSTRUCTION } from '../../lib/rag-prompt'
+import { LuCloudProvider } from '../providers/lu-cloud-provider'
+import type { ProviderConfig } from '../providers/types'
+
+vi.mock('../cloud/supabase', () => ({
+ getAccessToken: async () => 'session-token-abc',
+}))
+
+const config: ProviderConfig = {
+ id: 'lu-cloud',
+ name: 'LU Cloud',
+ enabled: true,
+ baseUrl: 'https://lu-labs.ai/api/inference/v1',
+ apiKey: '',
+ isLocal: false,
+}
+
+const okStream = () =>
+ new Response('data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n', { status: 200 })
+
+/** The passage a user's PDF would contribute after chunking and ranking. */
+const SECRET = 'The service level target for the Bergheim site is 99.95 percent.'
+
+async function drain(gen: AsyncGenerator<any>) {
+ for await (const _ of gen) { /* the fetch only happens on the first next() */ }
+}
+
+/** Send one turn through the real cloud provider and hand back the JSON body. */
+async function sendCloudTurn(systemPrompt: string) {
+ const spy = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(okStream())
+ await drain(
+ new LuCloudProvider(config).chatStream(
+ 'zai-org/GLM-5.3',
+ [
+ ...(systemPrompt ? [{ role: 'system' as const, content: systemPrompt }] : []),
+ { role: 'user' as const, content: 'What is the target for Bergheim?' },
+ ],
+ {},
+ ),
+ )
+ const [url, init] = spy.mock.calls[0] as [string, RequestInit]
+ return { url, init, body: JSON.parse(init.body as string) }
+}
+
+afterEach(() => vi.restoreAllMocks())
+
+describe('the retrieval block is built the same way for every provider', () => {
+ it('numbers the passages and wraps them in one instruction', () => {
+ const suffix = buildRagSuffix([{ content: SECRET }, { content: 'Second passage.' }])
+ expect(suffix).toContain(RAG_INSTRUCTION)
+ expect(suffix).toContain('[Source 1]\n' + SECRET)
+ expect(suffix).toContain('[Source 2]\nSecond passage.')
+ })
+
+ it('says nothing at all when retrieval found nothing', () => {
+ // Negative control: an instruction pointing at an empty context is tokens
+ // spent on noise, on every turn, in a mode where tokens are money.
+ expect(buildRagSuffix([])).toBe('')
+ })
+
+ it('rides at the END of the prompt, so the upstream prefix cache still matches', () => {
+ const persona = 'You are a terse assistant.'
+ const full = persona + buildRagSuffix([{ content: SECRET }])
+ expect(full.startsWith(persona)).toBe(true)
+ expect(full.indexOf('[Source 1]')).toBeGreaterThan(full.indexOf(persona))
+ })
+})
+
+describe('a cloud request carries the document context', () => {
+ it('the passages arrive in the system message of the LU Cloud request', async () => {
+ const systemPrompt = 'You are a terse assistant.' + buildRagSuffix([{ content: SECRET }])
+ const { url, init, body } = await sendCloudTurn(systemPrompt)
+
+ // This really is the cloud lane: hosted endpoint, session bearer.
+ expect(String(url)).toContain('/api/inference/v1/chat/completions')
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer session-token-abc')
+
+ const system = body.messages.find((m: any) => m.role === 'system')
+ expect(system).toBeDefined()
+ expect(system.content).toContain(SECRET)
+ expect(system.content).toContain('[Source 1]')
+ expect(system.content).toContain(RAG_INSTRUCTION)
+ // The persona is still in front of the retrieval block on the wire.
+ expect(system.content.indexOf('terse assistant')).toBeLessThan(system.content.indexOf('[Source 1]'))
+ })
+
+ it('with RAG off the same turn goes out clean, so the positive case proved something', async () => {
+ // Negative control on the whole request: no suffix, no document text
+ // anywhere in the payload, and the system prompt byte for byte unchanged.
+ const systemPrompt = 'You are a terse assistant.'
+ const { body, init } = await sendCloudTurn(systemPrompt)
+
+ const system = body.messages.find((m: any) => m.role === 'system')
+ expect(system.content).toBe(systemPrompt)
+ expect(String(init.body)).not.toContain('Bergheim site is 99.95')
+ expect(String(init.body)).not.toContain('[Source 1]')
+ expect(String(init.body)).not.toContain(RAG_INSTRUCTION)
+ })
+
+ it('an empty retrieval leaves the cloud request identical to no RAG at all', async () => {
+ const persona = 'You are a terse assistant.'
+ const withEmptyRag = persona + buildRagSuffix([])
+ const a = await sendCloudTurn(withEmptyRag)
+ vi.restoreAllMocks()
+ const b = await sendCloudTurn(persona)
+ expect(a.init.body).toBe(b.init.body)
+ })
+})
diff --git a/src/api/embed-availability.ts b/src/api/embed-availability.ts
new file mode 100644
index 00000000..6de7832f
--- /dev/null
+++ b/src/api/embed-availability.ts
@@ -0,0 +1,62 @@
+/**
+ * Can this machine embed a document right now.
+ *
+ * One question, one answer, for every surface that needs it: the RAG upload
+ * pre-flight (hooks/useRAG), the RAG panel's install card, and the Docs button
+ * in the composer (hooks/useDocsAvailability). It lived inside useRAG before
+ * A9, which is why the composer could not ask it and hid the button on
+ * `appMode === 'cloud'` instead.
+ *
+ * It asks the lane that will ACTUALLY run (api/rag.ts routes the same way):
+ * the bundled embeddings server whenever it is up or the built-in engine is the
+ * backend, Ollama otherwise. Asking Ollama on a built-in-engine box was the
+ * 2026-08-15 bug. Ollama had nomic-embed-text pulled, the bundled lane had no
+ * embedding GGUF at all, and nobody asked the lane that ran.
+ *
+ * Nothing here reads appMode. The embeddings server is a local sidecar and the
+ * app resumes it in Cloud mode too (useModels.resumeEmbedServer).
+ */
+import {
+ isManagedBuiltinActive,
+ bundledEmbedStatus,
+ bundledEmbedLaneReady,
+} from './engine'
+import { checkConnection, listModels } from './ollama'
+
+/**
+ * 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 (`bundledEmbedLaneReady`, the same question rag.ts answers when it routes).
+ */
+export async function builtinEmbedReady(): Promise<boolean> {
+ if (!isManagedBuiltinActive()) {
+ try {
+ return (await bundledEmbedStatus()).running
+ } catch {
+ return false
+ }
+ }
+ return bundledEmbedLaneReady()
+}
+
+/**
+ * True when SOME embedding backend on this machine can index a document.
+ *
+ * False when missing, and callers then surface the in-app install prompt (RAG panel) or
+ * a tooltip (Docs button) rather than blocking.
+ */
+export async function embeddingBackendReady(embeddingModel: string): 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
+ if (!(await checkConnection())) return false
+ try {
+ const models = await listModels()
+ return models.some(
+ (m) => m.name === embeddingModel || m.name === embeddingModel + ':latest',
+ )
+ } catch {
+ return false
+ }
+}
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 44d9d4a6..c45fbeab 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -24,6 +24,7 @@ import { useModelStore } from '../stores/modelStore'
import { useSettingsStore } from '../stores/settingsStore'
import { useRAGStore } from '../stores/ragStore'
import { retrieveContext } from '../api/rag'
+import { buildRagSuffix } from '../lib/rag-prompt'
import { toolRegistry } from '../api/mcp'
import { usePermissionStore } from '../stores/permissionStore'
import { CODEX_CONFIRM_TOOLS, codexConfirmEnabled } from './codexShellGate'
@@ -432,17 +433,12 @@ export function useAgentChat() {
if (chunks.length > 0) {
try {
const { context: ragContext } = await retrieveContext(userContent, chunks, ragState.embeddingModel)
- if (ragContext.chunks.length > 0) {
- const contextBlock = ragContext.chunks
- .map((c: any, i: number) => `[Source ${i + 1}]\n${c.content}`)
- .join('\n\n')
- // Retrieval is the most volatile thing in the whole prompt:
- // every turn pulls different chunks. In front of the persona it
- // put a fresh byte at offset 0 and made the upstream prefix cache
- // miss the ENTIRE prompt on every RAG turn, so it rides at the end
- // now, behind persona and memory (plan A5).
- ragSuffix = `\n\nUse the following document context to help answer the user's question. If the context is not relevant, ignore it and answer normally.\n\n---\n${contextBlock}\n---`
- }
+ // Same builder plain chat uses (lib/rag-prompt.ts), so the two
+ // surfaces cannot drift apart. It rides at the END of the prompt,
+ // behind persona and memory, because retrieval changes every turn and
+ // at offset 0 it cost the upstream prefix cache the whole prompt
+ // (plan A5).
+ ragSuffix = buildRagSuffix(ragContext.chunks)
} catch (err) {
log.error('RAG retrieval failed', { err })
}
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index c0dbe551..a8152834 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -8,6 +8,7 @@ import { useMemoryStore } from "../stores/memoryStore"
import { useVoiceStore } from "../stores/voiceStore"
import { autoSpeak } from "../lib/ttsBridge"
import { retrieveContext } from "../api/rag"
+import { buildRagSuffix } from "../lib/rag-prompt"
import { getModelMaxTokens, capMessageCount } from "../lib/context-compaction"
import { applyChatSendBudget, chatBudgetApplies } from "../lib/chat-send-budget"
import { isTooManyMessagesError, halveHistory, TOO_MANY_MESSAGES_MAX_HALVINGS } from "../lib/too-many-messages"
@@ -477,18 +478,13 @@ export function useChat() {
// Store scored chunks for display in RAGPanel
ragState.setLastRetrievedChunks(scoredChunks)
- if (ragContext.chunks.length > 0) {
- const contextBlock = ragContext.chunks
- .map((c, i) => `[Source ${i + 1}]\n${c.content}`)
- .join("\n\n")
- // The retrieval block is the most volatile thing in the prompt:
- // every turn pulls different chunks. It used to sit at byte 0,
- // ahead of the persona, so an upstream prefix cache, which
- // matches from the first byte and stops at the first difference,
- // missed the ENTIRE prompt on every RAG turn. It moves to the very
- // end, behind persona and memory, and is appended below (plan A5).
- ragSuffix = `\n\nUse the following document context to help answer the user's question. If the context is not relevant, ignore it and answer normally.\n\n---\n${contextBlock}\n---`
- }
+ // One builder for plain chat, Agent mode and the tests
+ // (lib/rag-prompt.ts). It is a SUFFIX: the retrieval block is the
+ // most volatile thing in the prompt, and at byte 0 it made the
+ // upstream prefix cache miss everything on every RAG turn (plan A5).
+ // The result is appended to the system prompt below, which is what
+ // makes Document Chat work on a cloud model as well as a local one.
+ ragSuffix = buildRagSuffix(ragContext.chunks)
} catch (err) {
log.error("RAG retrieval failed, continuing without context", { err })
}
diff --git a/src/hooks/useRAG.ts b/src/hooks/useRAG.ts
index 8748034f..e93481ae 100644
--- a/src/hooks/useRAG.ts
+++ b/src/hooks/useRAG.ts
@@ -2,34 +2,16 @@ 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,
- bundledEmbedLaneReady,
-} from "../api/engine"
+import { isManagedBuiltinActive } from "../api/engine"
+import { builtinEmbedReady, embeddingBackendReady } from "../api/embed-availability"
import { installBundledEmbedModel } from "../api/embed-install"
-import { getModelContext, listModels, pullModelTauri, checkConnection } from "../api/ollama"
+import { getModelContext, pullModelTauri, checkConnection } from "../api/ollama"
import { useModelStore } from "../stores/modelStore"
import type { DocumentMeta, RAGContext } from "../types/rag"
import { log } from "../lib/logger"
const EMPTY_DOCS: DocumentMeta[] = []
-/** 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()) {
- try {
- return (await bundledEmbedStatus()).running
- } catch {
- return false
- }
- }
- return bundledEmbedLaneReady()
-}
-
export function useRAG(conversationId: string | null) {
const {
documents,
@@ -110,21 +92,7 @@ export function useRAG(conversationId: string | null) {
* 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
- try {
- const models = await listModels()
- return models.some(
- (m) => m.name === embeddingModel || m.name === embeddingModel + ":latest"
- )
- } catch {
- return false
- }
+ return embeddingBackendReady(useRAGStore.getState().embeddingModel)
}, [])
/**
diff --git a/src/lib/rag-prompt.ts b/src/lib/rag-prompt.ts
new file mode 100644
index 00000000..f1bf3dc8
--- /dev/null
+++ b/src/lib/rag-prompt.ts
@@ -0,0 +1,38 @@
+/**
+ * The retrieval block, built in one place.
+ *
+ * Plain chat (hooks/useChat) and Agent mode (hooks/useAgentChat) each carried
+ * their own copy of this string. Two copies of a prompt are two prompts as soon
+ * as one of them is edited, and A9 needed a third caller to prove the block
+ * reaches a CLOUD request, so it moves here.
+ *
+ * It is a suffix, not a prefix, on purpose: the retrieved chunks are the most
+ * volatile thing in the prompt (every turn pulls different ones). At byte 0 they
+ * pushed an upstream prefix cache, which matches from the first byte and stops
+ * at the first difference, off the ENTIRE prompt on every RAG turn. Behind
+ * persona, memory and caveman, everything a cache could match stays
+ * byte-identical from turn to turn (plan A5).
+ *
+ * Provider-independent by construction: the result is appended to the system
+ * message, and a system message is the one thing Ollama, the built-in engine,
+ * LM Studio and LU Cloud all take. That is why Document Chat works in Cloud
+ * mode at all.
+ */
+
+export const RAG_INSTRUCTION =
+ "Use the following document context to help answer the user's question. " +
+ 'If the context is not relevant, ignore it and answer normally.'
+
+/**
+ * @param chunks the retrieved passages, already ranked and cut to the budget
+ * @returns the suffix to append to the system prompt, or '' when there is
+ * nothing to say. Empty in, empty out: a turn without a hit must not spend
+ * tokens on an instruction pointing at no context.
+ */
+export function buildRagSuffix(chunks: { content: string }[]): string {
+ if (!chunks || chunks.length === 0) return ''
+ const contextBlock = chunks
+ .map((c, i) => `[Source ${i + 1}]\n${c.content}`)
+ .join('\n\n')
+ return `\n\n${RAG_INSTRUCTION}\n\n---\n${contextBlock}\n---`
+}