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(memory): stille Erinnerungs-Extraktion bucht jetzt die lokale Spur

purplee7f9d5f9471c
diff --git a/src/hooks/__tests__/memory-extraktion-bucht-lokale-spur.test.ts b/src/hooks/__tests__/memory-extraktion-bucht-lokale-spur.test.ts
new file mode 100644
index 00000000..d9601c1e
--- /dev/null
+++ b/src/hooks/__tests__/memory-extraktion-bucht-lokale-spur.test.ts
@@ -0,0 +1,169 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Runde 4 (review-lanes.md Blocker 1+6, Schritt 1 "andere Verbraucher der
+ * lokalen Spur"): `extractMemoriesFromPair` (useMemory.ts) fires a genuine
+ * inference call, unawaited, from inside useAgentChat.ts and useCodex.ts,
+ * AFTER the visible turn has landed. Before this fix it ran straight against
+ * `provider.chatStream`, invisible to `lib/run-lanes.ts`. A second local
+ * conversation admitted right after the visible turn released its own lane
+ * could then answer AT THE SAME TIME as this straggling extraction call, on
+ * the same engine: exactly the VRAM-swap race the lane exists to prevent,
+ * just started one level above where run-lanes.ts can see it.
+ *
+ * This file proves the fix directly against the real `lib/run-lanes.ts`
+ * module (nothing about admit/release/queue is mocked): while an extraction
+ * call is mid-stream, a second local conversation that tries to admit must
+ * queue behind it, and is only promoted once the extraction's own call
+ * releases.
+ *
+ * A second question sits right next to it: the booking identity must NOT be
+ * the bare `conversationId`, because `run-slot.ts` treats a second `runInLane`
+ * call under the SAME id, while the first is still active, as a benign
+ * re-entry (the foreground sub-agent case) and lets it through immediately
+ * without ever registering a real queue wait. Since extraction fires while
+ * the visible turn's own `runInLane` body has not returned yet, booking
+ * under the bare id would silently take that fast path and protect nothing.
+ *
+ * NEGATIVE CONTROL (both run by hand on 18.09., exact numbers below, then
+ * reverted and confirmed green again):
+ * 1. Replaced the `runInLane(...)` call with a plain `await (async () => {
+ * ... })()`, i.e. ran the same body without ever booking a lane. Red
+ * with `expected null to be 'conv-a::memory-extraction'` (localLaneHolder
+ * stayed `null` the whole time; nothing ever registered).
+ * 2. Restored the `runInLane` wrap but booked it under the bare
+ * `conversationId` instead of the suffixed one. Red with
+ * `expected 'conv-a' to be 'conv-a::memory-extraction'`: the bare id hit
+ * `run-slot.ts`'s same-conversation re-entry fast path (the visible
+ * turn's own depth counter was still greater than zero) and became the
+ * holder under the WRONG identity, one that the visible turn's own
+ * `finally` releases regardless of whether extraction is still running.
+ *
+ * Run: npx vitest run src/hooks/__tests__/memory-extraktion-bucht-lokale-spur.test.ts
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { useCloudAuthStore } from '../../stores/cloudAuthStore'
+import { admit, localLaneHolder, queuedRunIds, __resetRunLanesForTests } from '../../lib/run-lanes'
+import { __resetRunSlotsForTests } from '../../lib/run-slot'
+
+const chatStream = vi.fn()
+const addMemory = vi.fn(() => 'mem-1')
+
+let activeModel = 'qwen3:8b'
+let resolveStream: (() => void) | null = null
+
+vi.mock('../../stores/modelStore', () => ({
+ useModelStore: { getState: () => ({ activeModel, models: [] }) },
+}))
+// Stable references for `settings` and `entries`: `extractMemoriesFromPair`'s
+// own write guard compares `getState().entries` against the snapshot it took
+// at the start via `!==`, exactly the check that catches a memory edited
+// underneath a running extraction. A mock that hands back a FRESH array or
+// object literal on every call looks changed on every read, exactly like a
+// real edit, and the guard correctly revokes the whole call before it ever
+// reaches `chatStream`.
+const memorySettings = { autoExtractEnabled: true, autoExtractInAllModes: false }
+const memoryEntries: unknown[] = []
+vi.mock('../../stores/memoryStore', () => ({
+ useMemoryStore: {
+ getState: () => ({
+ settings: memorySettings,
+ entries: memoryEntries,
+ addMemory,
+ removeMemory: vi.fn(),
+ applyWriteDecision: vi.fn(),
+ }),
+ },
+}))
+vi.mock('../../stores/providerStore', () => ({
+ useProviderStore: {
+ getState: () => ({
+ providers: { openai: { enabled: true, isLocal: true }, anthropic: { enabled: false } },
+ }),
+ },
+}))
+vi.mock('../../stores/settingsStore', () => ({
+ useSettingsStore: {
+ getState: () => ({ settings: { memoryCloudOptIn: false, contextWindowOverride: 0 } }),
+ },
+}))
+vi.mock('../../api/providers', () => ({
+ getProviderForModel: () => ({ provider: { chatStream }, modelId: 'qwen3:8b' }),
+ getProviderIdFromModel: () => 'ollama',
+}))
+vi.mock('../../lib/agent-num-ctx', () => ({
+ resolveAgentNumCtx: vi.fn(async () => 8192),
+}))
+vi.mock('../../api/rag', () => ({
+ generateEmbeddings: vi.fn(async () => [[]]),
+ cosineSimilarity: vi.fn(() => 0),
+}))
+vi.mock('../../lib/memoryEmbedDB', () => ({
+ loadVectors: vi.fn(async () => new Map()),
+}))
+
+const { extractMemoriesFromPair } = await import('../useMemory')
+
+/** A stream that hangs until the test resolves it by hand, mid-extraction. */
+function haengenderStream() {
+ return (async function* () {
+ yield { content: '', done: false }
+ await new Promise<void>((resolve) => { resolveStream = resolve })
+ yield { content: '{"shouldSave": false, "memories": []}', done: true }
+ })()
+}
+
+beforeEach(() => {
+ __resetRunLanesForTests()
+ __resetRunSlotsForTests()
+ chatStream.mockReset()
+ chatStream.mockImplementation(() => haengenderStream())
+ addMemory.mockClear()
+ useCloudAuthStore.getState().setSignedOut()
+ resolveStream = null
+ activeModel = 'qwen3:8b'
+})
+
+describe('extractMemoriesFromPair bucht die lokale Spur', () => {
+ it('eine zweite lokale Unterhaltung wartet, waehrend die Extraktion mitten im Strom haengt', async () => {
+ // Turns 1 and 2 are rate-limited away (every 3rd turn extracts); the
+ // 3rd actually fires the call and hangs on `haengenderStream`.
+ await extractMemoriesFromPair('frage 1', 'x'.repeat(200), 'conv-a')
+ await extractMemoriesFromPair('frage 2', 'x'.repeat(200), 'conv-a')
+ const dritte = extractMemoriesFromPair('frage 3', 'x'.repeat(200), 'conv-a')
+
+ // Give the extraction's async prologue (guards, resolveSilentCall, the
+ // runInLane admission, the mocked resolveAgentNumCtx await) room to run
+ // and reach the stream.
+ for (let i = 0; i < 10; i++) await Promise.resolve()
+
+ expect(chatStream).toHaveBeenCalledTimes(1)
+ expect(localLaneHolder()).toBe('conv-a::memory-extraction')
+
+ // A second, genuinely different conversation tries the local lane while
+ // the extraction still holds it.
+ const zweiterAdmit = admit('local', 'conv-b', () => {})
+ expect(zweiterAdmit).toBe('queued')
+ expect(queuedRunIds()).toEqual(['conv-b'])
+
+ // Let the extraction finish; it must release the lane and hand it to
+ // the waiting conversation.
+ resolveStream?.()
+ await dritte
+
+ expect(localLaneHolder()).toBe('conv-b')
+ expect(queuedRunIds()).toEqual([])
+ })
+
+ it('GEGENPROBE: eine cloud-Unterhaltung braucht auf eine lokale Extraktion nicht zu warten', async () => {
+ await extractMemoriesFromPair('frage 1', 'x'.repeat(200), 'conv-a')
+ await extractMemoriesFromPair('frage 2', 'x'.repeat(200), 'conv-a')
+ const dritte = extractMemoriesFromPair('frage 3', 'x'.repeat(200), 'conv-a')
+ for (let i = 0; i < 10; i++) await Promise.resolve()
+
+ expect(admit('cloud', 'conv-cloud', () => {})).toBe('started')
+
+ resolveStream?.()
+ await dritte
+ })
+})
diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.ts
index 5a2c5fd6..8b20ed2d 100644
--- a/src/hooks/useMemory.ts
+++ b/src/hooks/useMemory.ts
@@ -25,6 +25,8 @@ import { loadVectors } from '../lib/memoryEmbedDB'
import { silentCallAllowed, pickSilentCallModel } from '../lib/silent-model-calls'
import type { MemoryFile } from '../types/agent-mode'
import { useCloudAuthStore } from '../stores/cloudAuthStore'
+import { runInLane } from '../lib/run-slot'
+import { laneOf, currentLaneFacts } from '../lib/run-lane-of-model'
interface MemoryWriteGuard {
current: () => boolean
@@ -135,71 +137,109 @@ export async function extractMemoriesFromPair(
wrote: () => { expectedEntries = useMemoryStore.getState().entries },
}
- // Same num_ctx as the chat that just ran on this model. Ollama reloads the
- // model whenever num_ctx changes between requests, so an options-less
- // extraction call silently dropped the user's context back to the default
- // and paid a second model load per turn. Resolved for the model this call
- // ACTUALLY runs on — on lu-cloud that is the cheap one, whose window has
- // nothing to do with the active model's.
- const numCtx = await resolveAgentNumCtx(
- modelId,
- getProviderIdFromModel(callModel),
- useSettingsStore.getState().settings.contextWindowOverride,
- callModel,
- )
- if (!guard.current()) return
+ // Runde 4 (review-lanes.md Blocker 1+6): this silent call books into the
+ // local lane too. Before this it ran straight against
+ // `provider.chatStream`, unregistered anywhere run-lanes.ts could see it.
+ // The visible turn that triggers it (`void extractMemoriesFromPair(...)`
+ // in useAgentChat.ts and useCodex.ts) fires this call WHILE ITS OWN
+ // `runInLane` body is still running, unawaited. An unmanaged local call
+ // here could then land on the built-in engine or Ollama at the exact
+ // moment the visible turn finishes and the next queued conversation gets
+ // admitted: the VRAM-swap race this whole module exists to prevent,
+ // started one level up from where run-lanes.ts can see it.
+ //
+ // The booking identity below is deliberately NOT `conversationId` itself.
+ // `run-slot.ts` tracks same-conversation re-entry with a depth counter so
+ // a foreground sub-agent can call back into its own parent's lane without
+ // deadlocking; that counter is still greater than zero right now, because
+ // the visible turn's own `runInLane` body has not returned yet. Booking
+ // under the real id would silently take the fast re-entry path, run this
+ // call immediately, and register nothing that keeps the lane held once
+ // the visible turn's own body finishes and releases behind it: exactly
+ // the unmanaged race this change is meant to close. A distinct suffixed
+ // id is a different identity to `admit`, so it queues for real behind
+ // whichever run currently holds the lane (the visible turn, still
+ // running) and gets its own real `release`. It cannot deadlock the way
+ // the sub-agent case can: extraction never blocks the visible turn on
+ // itself (it is `void`-fired, never awaited by the turn), so there is no
+ // cycle for a real queue wait to close.
+ //
+ // No real abort: this call has nothing running yet to interrupt when it
+ // is still queued, and a fire-and-forget extraction was never stoppable
+ // from the UI to begin with, so `stopAllBackgroundWork` draining it out
+ // of the queue (it just never runs) is the whole contract.
+ await runInLane(
+ { conversationId: `${conversationId}::memory-extraction`, lane: laneOf(callModel, currentLaneFacts()), abort: () => {} },
+ async () => {
+ // Same num_ctx as the chat that just ran on this model. Ollama reloads
+ // the model whenever num_ctx changes between requests, so an
+ // options-less extraction call silently dropped the user's context
+ // back to the default and paid a second model load per turn. Resolved
+ // for the model this call ACTUALLY runs on: on lu-cloud that is the
+ // cheap one, whose window has nothing to do with the active model's.
+ const numCtx = await resolveAgentNumCtx(
+ modelId,
+ getProviderIdFromModel(callModel),
+ useSettingsStore.getState().settings.contextWindowOverride,
+ callModel,
+ )
+ if (!guard.current()) return
- // Re-read immediately before the request; protected or other-project
- // titles must not leak through the extraction deduplication summary.
- const existingSummary = useMemoryStore.getState().entries
- .filter(e => !e.sensitive && !e.stale && e.scope === scope)
- .slice(-20).map(e => `- [${e.type}] ${e.title}`).join('\n')
- const messages = buildExtractionPrompt(userMessage, assistantResponse, existingSummary)
- // Collect full response via streaming
- let fullResponse = ''
- const stream = provider.chatStream(modelId, messages, {
- temperature: 0.1,
- // 800 tokens leaves headroom for models that pad the JSON with prose or a
- // short think block. At 500 the extraction tore off mid-object and the
- // whole turn was lost without a word. Same number as the web.
- maxTokens: 800,
- contextWindow: numCtx,
- })
+ // Re-read immediately before the request; protected or other-project
+ // titles must not leak through the extraction deduplication summary.
+ const existingSummary = useMemoryStore.getState().entries
+ .filter(e => !e.sensitive && !e.stale && e.scope === scope)
+ .slice(-20).map(e => `- [${e.type}] ${e.title}`).join('\n')
+ const messages = buildExtractionPrompt(userMessage, assistantResponse, existingSummary)
+ // Collect full response via streaming
+ let fullResponse = ''
+ const stream = provider.chatStream(modelId, messages, {
+ temperature: 0.1,
+ // 800 tokens leaves headroom for models that pad the JSON with prose
+ // or a short think block. At 500 the extraction tore off mid-object
+ // and the whole turn was lost without a word. Same number as the web.
+ maxTokens: 800,
+ contextWindow: numCtx,
+ })
- for await (const chunk of stream) {
- if (!guard.current()) return
- if (chunk.content) fullResponse += chunk.content
- if (chunk.done) break
- }
-
- // Parse and save — each memory goes through embedding-based write-decision
- // resolution (ADD / UPDATE / NOOP) instead of a blind addMemory.
- const result = parseExtractionResponse(fullResponse)
- if (result.shouldSave) {
- for (const memory of result.memories) {
- if (!guard.current()) return
- // Serial per-memory so the second (resolution) LLM call is bounded and
- // we don't fire N concurrent inferences. Each is wrapped so one bad
- // memory never aborts the rest.
- try {
- await resolveAndSaveMemory(memory, conversationId, scope, sourceKind, guard)
- } catch {
+ for await (const chunk of stream) {
if (!guard.current()) return
- // Per-memory failure → fall back to a plain add so the fact isn't lost.
- memState.addMemory({
- type: memory.type,
- title: memory.title,
- description: memory.description,
- content: memory.content,
- tags: memory.tags,
- source: conversationId,
- scope,
- sourceKind,
- })
- guard.wrote()
+ if (chunk.content) fullResponse += chunk.content
+ if (chunk.done) break
}
- }
- }
+
+ // Parse and save: each memory goes through embedding-based
+ // write-decision resolution (ADD / UPDATE / NOOP) instead of a blind
+ // addMemory.
+ const result = parseExtractionResponse(fullResponse)
+ if (result.shouldSave) {
+ for (const memory of result.memories) {
+ if (!guard.current()) return
+ // Serial per-memory so the second (resolution) LLM call is
+ // bounded and we don't fire N concurrent inferences. Each is
+ // wrapped so one bad memory never aborts the rest.
+ try {
+ await resolveAndSaveMemory(memory, conversationId, scope, sourceKind, guard)
+ } catch {
+ if (!guard.current()) return
+ // Per-memory failure: fall back to a plain add so the fact
+ // isn't lost.
+ memState.addMemory({
+ type: memory.type,
+ title: memory.title,
+ description: memory.description,
+ content: memory.content,
+ tags: memory.tags,
+ source: conversationId,
+ scope,
+ sourceKind,
+ })
+ guard.wrote()
+ }
+ }
+ }
+ },
+ )
} catch {
// Extraction failures are non-critical — silently swallowed
} finally {