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): close the claim-to-try gap in sendMessage (Auflage 1)

purple9fec2819ded8
diff --git a/src/hooks/__tests__/geisterzustand-architektur-parity.test.ts b/src/hooks/__tests__/geisterzustand-architektur-parity.test.ts
index 616744c2..a7584304 100644
--- a/src/hooks/__tests__/geisterzustand-architektur-parity.test.ts
+++ b/src/hooks/__tests__/geisterzustand-architektur-parity.test.ts
@@ -75,7 +75,7 @@ describe('Chat (Einzelmodell + Gruppenrunde): isGenerating haengt jetzt auch an
expect(davor).not.toMatch(/if \(stillOwnsSlot\)\s*{\s*(\/\/[^\n]*\n\s*)*$/)
})
- it('alle vier Fundstellen sind vorhanden: einzelner Chat, Gruppenrunde (zweimal) UND /compact bekamen den Fix, nicht nur einer', () => {
+ it('alle fuenf Fundstellen sind vorhanden: einzelner Chat (zweimal), Gruppenrunde (zweimal) UND /compact bekamen den Fix', () => {
// Auflage 2 (Review composer, 19.09.2026): `/compact` reihte sich in
// dieselbe Invariante ein, seitdem sind es drei statt zwei Fundstellen.
// Auflage 8 (Review composer Runde 2, 19.09.2026): `runGroupRound` bekam
@@ -84,8 +84,13 @@ describe('Chat (Einzelmodell + Gruppenrunde): isGenerating haengt jetzt auch an
// bei einem Wurf VOR `runInLane` dieselbe Neuberechnung noch einmal
// ausfuehrt - im Normalfall ist es ein No-op, weil das innere `finally`
// schon geraeumt hat. Seitdem sind es vier statt drei Fundstellen.
+ // Auflage 1 (Review Teil 13, 19.09.2026): `sendMessage` bekam dasselbe
+ // AEUSSERE `finally` um den ganzen Rumpf (schliesst die Luecke zwischen
+ // dem Claim und dem ersten inneren `try`, u.a. den ungeschuetzten
+ // `ragState.loadChunksFromDB`-Aufruf), ebenfalls ein No-op im Normalfall.
+ // Seitdem sind es fuenf statt vier Fundstellen.
const treffer = useChatSrc.split('setIsGenerating(activeChatRuns.size > 0)').length - 1
- expect(treffer).toBe(4)
+ expect(treffer).toBe(5)
})
it('generationStore.aborters bleibt der Massstab fuer die STORE-eigene Fahne (review-lanes.md Punkt 1) - der Fix aendert daran nichts', () => {
diff --git a/src/hooks/__tests__/send-claim-freigabe-bei-wurf.test.ts b/src/hooks/__tests__/send-claim-freigabe-bei-wurf.test.ts
new file mode 100644
index 00000000..890c6f04
--- /dev/null
+++ b/src/hooks/__tests__/send-claim-freigabe-bei-wurf.test.ts
@@ -0,0 +1,170 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Auflage 1 (Review Teil 13, 19.09.2026, review-teil13.md Punkt 1):
+ * `sendMessage` (useChat.ts) claimt `activeChatRuns` synchron, rund 89
+ * Zeilen weiter unten stand ein UNGESCHUETZTES `await
+ * ragState.loadChunksFromDB(convId)` (IndexedDB, ausserhalb seines eigenen
+ * RAG-`try`), und dazwischen lag kein umschliessendes `try/finally` - nur
+ * der `finally` INNERHALB von `runInLane`, viel weiter unten, tat das, und
+ * der lief nie, wenn der Wurf schon davor passierte. Ein Wurf an dieser
+ * Stelle liess den Eintrag in `activeChatRuns` fuer immer stehen: die
+ * Unterhaltung waere dauerhaft gesperrt gewesen
+ * (`chat.duplicate_send_blocked`), "Stop generation" waere im Composer
+ * stehengeblieben, und kein zweiter Lauf haette je gestartet.
+ *
+ * FIX: derselbe aeussere `try/finally` wie in `runGroupRound` (Auflage 8,
+ * siehe group-runde-claim-freigabe-bei-wurf.test.ts) beginnt jetzt direkt
+ * hinter dem Claim; sein `finally` gibt den Eintrag frei
+ * (Identitaetspruefung, wie ueberall in dieser Datei) und rechnet
+ * `isGenerating` aus der Laufregistry neu.
+ *
+ * Run: npx vitest run src/hooks/__tests__/send-claim-freigabe-bei-wurf.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))
+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))
+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))
+vi.mock('../useMemory', () => ({
+ useMemory: () => ({ extractAndSave: async () => {} }),
+ extractMemoriesFromPair: async () => {},
+}))
+vi.mock('../../lib/run-lane-of-model', () => ({
+ laneOf: () => 'cloud',
+ currentLaneFacts: () => ({ openaiSlotIsLocal: true, ollamaBaseIsLocal: true }),
+}))
+
+import { useChat, __activeChatRunConvIdsForTests } from '../useChat'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useProviderStore } from '../../stores/providerStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { useRAGStore } from '../../stores/ragStore'
+import { __resetRunLanesForTests, localLaneHolder } from '../../lib/run-lanes'
+import { DEFAULT_SETTINGS } from '../../lib/constants'
+
+const MODEL = 'lu-cloud::zai-org/GLM-5.3'
+
+function controllableSSE() {
+ let controller!: ReadableStreamDefaultController<Uint8Array>
+ const readable = new ReadableStream<Uint8Array>({ start(c) { controller = c } })
+ const enc = new TextEncoder()
+ return {
+ readable,
+ push(text: string) {
+ controller.enqueue(enc.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\n`))
+ },
+ done() {
+ controller.enqueue(enc.encode('data: [DONE]\n\n'))
+ controller.close()
+ },
+ }
+}
+const tick = () => new Promise((r) => setTimeout(r, 0))
+
+function seed(): string {
+ const convId = useChatStore.getState().createConversation(MODEL, '')
+ useChatStore.getState().setActiveConversation(convId)
+ return convId
+}
+
+// `loadChunksFromDB` ist der Wurf-Punkt dieses Tests: er sitzt in
+// `sendMessage` SYNCHRON (per `await`) zwischen dem Claim und dem ersten
+// inneren `try`, ausserhalb jedes bestehenden Schutzes - genau die Luecke,
+// die Auflage 1 schliesst.
+let loadChunksShouldThrow = false
+
+beforeEach(() => {
+ loadChunksShouldThrow = false
+ __resetRunLanesForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ models: [], activeModel: MODEL })
+ useSettingsStore.setState({
+ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud', cavemanMode: 'off', chatToolsEnabled: false },
+ })
+ useProviderStore.setState((s) => ({
+ providers: { ...s.providers, 'lu-cloud': { ...s.providers['lu-cloud'], enabled: true } },
+ }))
+ useRAGStore.setState({
+ ragEnabled: {},
+ loadChunksFromDB: async () => {
+ if (loadChunksShouldThrow) {
+ throw new Error('erzwungener Wurf zwischen Claim und dem ersten inneren try (Auflage 1)')
+ }
+ },
+ })
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('Claim und Freigabe in sendMessage: JEDER Ausgang gibt frei (Auflage 1)', () => {
+ it('ein Wurf aus loadChunksFromDB haelt die Sperre nicht dauerhaft, isGenerating wird false, ein erneuter Lauf ist moeglich', async () => {
+ const convId = seed()
+ useRAGStore.setState((s) => ({ ragEnabled: { ...s.ragEnabled, [convId]: true } }))
+ loadChunksShouldThrow = true
+
+ const { result } = renderHook(() => useChat())
+
+ await act(async () => {
+ await expect(result.current.sendMessage('erste Nachricht, wirft')).rejects.toThrow(
+ 'erzwungener Wurf zwischen Claim und dem ersten inneren try (Auflage 1)',
+ )
+ })
+
+ // Der Claim darf den Wurf nicht ueberleben: ohne den Fix bliebe die
+ // Unterhaltung hier fuer immer in `activeChatRuns` stehen, gesperrt.
+ expect(__activeChatRunConvIdsForTests()).toEqual([])
+ expect(result.current.isGenerating).toBe(false)
+ expect(localLaneHolder()).toBeNull()
+
+ // Jetzt ohne den erzwungenen Wurf: ein ECHTER zweiter Lauf auf derselben
+ // Unterhaltung muss wieder moeglich sein - der Wiedereintritts-Riegel
+ // darf nicht dauerhaft blockieren.
+ loadChunksShouldThrow = false
+ const stream = controllableSSE()
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ return new Response(stream.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ })
+
+ await act(async () => {
+ const run2 = result.current.sendMessage('zweite Nachricht, laeuft echt')
+ await tick()
+ stream.push('antwort'); stream.done()
+ await run2
+ })
+
+ const conv = useChatStore.getState().conversations.find((c) => c.id === convId)!
+ const userTurns = conv.messages.filter((m) => m.role === 'user')
+ expect(userTurns.map((m) => m.content)).toEqual(['erste Nachricht, wirft', 'zweite Nachricht, laeuft echt'])
+ expect(__activeChatRunConvIdsForTests()).toEqual([])
+ expect(result.current.isGenerating).toBe(false)
+ })
+
+ it('NEGATIVKONTROLLE: ohne den erzwungenen Wurf laeuft der Sendezug normal durch und raeumt genauso auf', async () => {
+ const convId = seed()
+ useRAGStore.setState((s) => ({ ragEnabled: { ...s.ragEnabled, [convId]: true } }))
+ const stream = controllableSSE()
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ return new Response(stream.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ })
+
+ const { result } = renderHook(() => useChat())
+
+ await act(async () => {
+ const run = result.current.sendMessage('laeuft ohne Wurf')
+ await tick()
+ stream.push('ok'); stream.done()
+ await run
+ })
+
+ expect(__activeChatRunConvIdsForTests()).toEqual([])
+ expect(result.current.isGenerating).toBe(false)
+ })
+})
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 46790bd1..226a6fae 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -737,6 +737,21 @@ export function useChat() {
const myRunToken = Symbol(convId)
activeChatRuns.set(convId, myRunToken)
+ // Auflage 1 (Review Teil 13, 19.09.2026): the claim above and this `try`
+ // must lie back to back, same discipline as the outer `try`/`finally` in
+ // `runGroupRound` and in the `/compact` branch above. Roughly 89 lines
+ // used to sit unprotected between the claim and the body's own inner
+ // `try` (the RAG load at `ragState.loadChunksFromDB(convId)` among them,
+ // plain IndexedDB, outside its own nested `try`): a throw anywhere in
+ // there left the entry in `activeChatRuns` standing forever, and the
+ // conversation was locked (`chat.duplicate_send_blocked`) with "Stop
+ // generation" stuck on screen, no second send ever able to start. This
+ // outer `finally` is a no-op on every path that already cleans up by
+ // identity below (the inner `finally` further down, the early return
+ // right after this comment, and the `cancelled-while-queued` follow-up
+ // at the end all check `activeChatRuns.get(convId) === myRunToken`
+ // first); it only fires on a path the body never reaches.
+ try {
const memoryScope = store.conversations.find(c => c.id === convId)?.memoryScope
const userMessage = {
id: uuid(),
@@ -1484,6 +1499,18 @@ export function useChat() {
// started, so it never registered an aborter or set `generating`.
activeChatRuns.delete(convId)
}
+ } finally {
+ // Same identity check as everywhere else in this file: a no-op when a
+ // path above already released the claim (the normal send, the early
+ // "conversation vanished" return, or the cancelled-while-queued
+ // follow-up just above), and the only thing that actually fires when a
+ // throw between the claim and the first inner `try` skipped all of
+ // them.
+ if (activeChatRuns.get(convId) === myRunToken) {
+ activeChatRuns.delete(convId)
+ setIsGenerating(activeChatRuns.size > 0)
+ }
+ }
// Alle drei Referenzen sind konstant: `extractAndSave` kommt aus dem
// Modul-Singleton MEMORY_API, `runGroupRound` ist ein useCallback mit
// leerer Dep-Liste, `sendAgentMessage` ebenfalls. `sendMessage` behaelt