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): eine laufende Extraktion laesst sich jetzt wirklich abbrechen

purple3b72882229df
diff --git a/src/hooks/__tests__/memory-extraktion-bucht-lokale-spur.test.ts b/src/hooks/__tests__/memory-extraktion-bucht-lokale-spur.test.ts
index d9601c1e..7b709aa8 100644
--- a/src/hooks/__tests__/memory-extraktion-bucht-lokale-spur.test.ts
+++ b/src/hooks/__tests__/memory-extraktion-bucht-lokale-spur.test.ts
@@ -43,11 +43,17 @@
*/
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { useCloudAuthStore } from '../../stores/cloudAuthStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { useAgentTaskStore } from '../../stores/agentTaskStore'
+import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { stopAllBackgroundWork } from '../../lib/background-shutdown'
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')
+/** The `AbortSignal` the extraction's last `chatStream` call was given, so a
+ * test can check whether `stopAllBackgroundWork` actually reached it. */
+let lastSignal: AbortSignal | undefined
let activeModel = 'qwen3:8b'
let resolveStream: (() => void) | null = null
@@ -104,23 +110,34 @@ vi.mock('../../lib/memoryEmbedDB', () => ({
const { extractMemoriesFromPair } = await import('../useMemory')
-/** A stream that hangs until the test resolves it by hand, mid-extraction. */
-function haengenderStream() {
+/** A stream that hangs until the test resolves it by hand, mid-extraction,
+ * or until its `signal` aborts, mirroring the shape a real provider stream
+ * takes when its underlying fetch is cancelled mid-flight. */
+function haengenderStream(signal?: AbortSignal) {
return (async function* () {
yield { content: '', done: false }
- await new Promise<void>((resolve) => { resolveStream = resolve })
+ await new Promise<void>((resolve, reject) => {
+ resolveStream = resolve
+ signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))
+ })
yield { content: '{"shouldSave": false, "memories": []}', done: true }
})()
}
beforeEach(() => {
__resetRunLanesForTests()
- __resetRunSlotsForTests()
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useAgentTaskStore.setState({ byConv: {} })
+ useAgentLoopStore.setState({ loops: {} })
chatStream.mockReset()
- chatStream.mockImplementation(() => haengenderStream())
+ chatStream.mockImplementation((_model: string, _messages: unknown, options?: { signal?: AbortSignal }) => {
+ lastSignal = options?.signal
+ return haengenderStream(options?.signal)
+ })
addMemory.mockClear()
useCloudAuthStore.getState().setSignedOut()
resolveStream = null
+ lastSignal = undefined
activeModel = 'qwen3:8b'
})
@@ -155,6 +172,32 @@ describe('extractMemoriesFromPair bucht die lokale Spur', () => {
expect(queuedRunIds()).toEqual([])
})
+ // Runde 5 Folgeposten 3 (review-lanes.md Runde 2, Punkt 5 Fund 4): a
+ // RUNNING extraction used to be unstoppable (`abort: () => {}`), so
+ // `stopAllBackgroundWork` (sign-out, window close, app quit) reached a
+ // QUEUED extraction but let a RUNNING one bill to completion after the
+ // user believed they had left.
+ it('stopAllBackgroundWork bricht eine LAUFENDE Extraktion wirklich ab', 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(chatStream).toHaveBeenCalledTimes(1)
+ expect(localLaneHolder()).toBe('conv-a::memory-extraction')
+ expect(lastSignal?.aborted).toBe(false)
+
+ stopAllBackgroundWork()
+
+ expect(lastSignal?.aborted).toBe(true)
+ // The extraction's own outer try/catch swallows the resulting
+ // AbortError by contract (extraction failures are always silent), so the
+ // call still resolves cleanly, it just never saves anything.
+ await dritte
+ expect(addMemory).not.toHaveBeenCalled()
+ expect(localLaneHolder()).toBeNull()
+ })
+
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')
diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.ts
index 8b20ed2d..b1a70918 100644
--- a/src/hooks/useMemory.ts
+++ b/src/hooks/useMemory.ts
@@ -164,12 +164,19 @@ export async function extractMemoriesFromPair(
// 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.
+ // Runde 5 Folgeposten 3 (review-lanes.md Runde 2, Punkt 5 Fund 4): a
+ // RUNNING extraction used to be unstoppable: `abort: () => {}` was a
+ // literal no-op, so `stopAllBackgroundWork` (sign-out, window close, app
+ // quit) reached a QUEUED extraction (pulls it out of the waiting room,
+ // it never runs) but not a running one: the stream kept going to
+ // completion after the user believed they had signed out, on a silent
+ // model call that still bills lu-cloud. A real `AbortController` closes
+ // that: `abort()` cancels the in-flight fetch, the `for await` loop below
+ // sees its `AbortError`, and the outer `catch` already swallows every
+ // extraction failure (silent by contract, always was).
+ const extractionAbort = new AbortController()
await runInLane(
- { conversationId: `${conversationId}::memory-extraction`, lane: laneOf(callModel, currentLaneFacts()), abort: () => {} },
+ { conversationId: `${conversationId}::memory-extraction`, lane: laneOf(callModel, currentLaneFacts()), abort: () => extractionAbort.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
@@ -200,6 +207,7 @@ export async function extractMemoriesFromPair(
// and the whole turn was lost without a word. Same number as the web.
maxTokens: 800,
contextWindow: numCtx,
+ signal: extractionAbort.signal,
})
for await (const chunk of stream) {
@@ -219,7 +227,7 @@ export async function extractMemoriesFromPair(
// 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)
+ await resolveAndSaveMemory(memory, conversationId, scope, sourceKind, guard, extractionAbort.signal)
} catch {
if (!guard.current()) return
// Per-memory failure: fall back to a plain add so the fact
@@ -259,7 +267,7 @@ export async function extractMemoriesFromPair(
* Fire-and-forget contract: any embedding/LLM failure falls back to a plain
* addMemory so a fact is never silently dropped. Never blocks the chat turn.
*/
-async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: string, scope: string | undefined, sourceKind: MemoryFile['sourceKind'], guard: MemoryWriteGuard): Promise<void> {
+async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: string, scope: string | undefined, sourceKind: MemoryFile['sourceKind'], guard: MemoryWriteGuard, abortSignal: AbortSignal): Promise<void> {
const memState = useMemoryStore.getState()
const addPlain = (): string => {
if (!guard.current()) return ''
@@ -361,7 +369,7 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: str
topK,
)
let full = ''
- const stream = provider.chatStream(modelId, messages, { temperature: 0.1, maxTokens: 300 })
+ const stream = provider.chatStream(modelId, messages, { temperature: 0.1, maxTokens: 300, signal: abortSignal })
for await (const chunk of stream) {
if (!guard.current()) return
if (chunk.content) full += chunk.content