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.

refactor(chat): Lauf-Register statt abortRef

purple0a2bf052dd09
diff --git a/src/components/chat/__tests__/senden-und-stop-je-unterhaltung.test.tsx b/src/components/chat/__tests__/senden-und-stop-je-unterhaltung.test.tsx
index 27b13981..ec03aa32 100644
--- a/src/components/chat/__tests__/senden-und-stop-je-unterhaltung.test.tsx
+++ b/src/components/chat/__tests__/senden-und-stop-je-unterhaltung.test.tsx
@@ -10,16 +10,18 @@
* obwohl der generationStore die Wahrheit seit 22f76b04 je Unterhaltung
* fuehrt und die Schreibanzeige sie auch schon las.
*
- * Warum hier nur die halbe Strecke steht: ein vollstaendiges "jede
- * Unterhaltung darf gleichzeitig senden" haengt an den geteilten
- * Stream-Puffern in useChat.ts (contentRef, thinkingRef, abortRef) und
- * useAgentChat.ts, rund 110 Zugriffe, und daran, dass `runInLane` aus
+ * Warum hier zum Zeitpunkt dieses Befunds nur die halbe Strecke stand: ein
+ * vollstaendiges "jede Unterhaltung darf gleichzeitig senden" hing an den
+ * geteilten Stream-Puffern in useChat.ts (contentRef, thinkingRef, abortRef)
+ * und useAgentChat.ts, rund 110 Zugriffe, und daran, dass `runInLane` aus
* lib/run-slot.ts bis heute keinen Aufrufer in der Produktion hat: ohne
* Warteschlange liefen zwei lokale Laeufe gegen einen llama-server mit einem
- * einzigen Slot. Das ist mehr als eine Stunde Arbeit und gehoert in einen
- * eigenen Auftrag. Was hier steht, ist das, was ohne diese Entflechtung
- * richtig wird: der laufende Chat behaelt Stop und bricht nur sich selbst ab,
- * der andere behaelt seinen Sendeknopf und bekommt einen englischen Satz
+ * einzigen Slot. useChat.ts hat seine Haelfte seit B2 Commit 1/2
+ * (ChatRun-Objekt statt Refs, generationStore statt abortRef): siehe
+ * useChat-zwei-laeufe-vermischen-nicht.test.ts. useAgentChat.ts und die
+ * Warteschlange stehen noch aus. Was hier steht, ist das, was schon vorher
+ * richtig wurde: der laufende Chat behaelt Stop und bricht nur sich selbst
+ * ab, der andere behaelt seinen Sendeknopf und bekommt einen englischen Satz
* statt eines stummen Tauschs.
*
* Run: npx vitest run src/components/chat/__tests__/senden-und-stop-je-unterhaltung.test.tsx
@@ -106,19 +108,30 @@ describe('the composer of the chat that IS answering', () => {
})
/**
- * Die zweite Haelfte des Befunds sitzt in zwei Hooks, deren Abbruchgriffe der
- * Hook-INSTANZ gehoeren und nicht der Unterhaltung. Ein echter Lauf mit zwei
- * gleichzeitigen Unterhaltungen ist von hier aus nicht zu fahren, deshalb
- * steht hier der Quelltext-Waechter auf die Bedingung. Nachgemessen werden
- * muss das an der laufenden App (siehe Bericht).
+ * Die zweite Haelfte des Befunds sitzt (noch, Stand vor B2) in zwei Hooks,
+ * deren Abbruchgriffe der Hook-INSTANZ gehoeren und nicht der Unterhaltung.
+ * Ein echter Lauf mit zwei gleichzeitigen Unterhaltungen ist von hier aus
+ * nicht zu fahren, deshalb steht hier der Quelltext-Waechter auf die
+ * Bedingung. Nachgemessen werden muss das an der laufenden App (siehe
+ * Bericht).
+ *
+ * useChat.ts ist seit B2 Commit 2 raus aus dieser Liste: `abortRef` /
+ * `abortConvRef` sind entfernt, weil sie erwiesenermassen redundant waren -
+ * `generationStore.aborters` ist bereits je Konversation gefuehrt und war
+ * schon vorher der Griff, der wirklich abbricht (siehe die
+ * `abortConversation`-Zeile, die hier unveraendert blieb). Ein Quelltext-Pin
+ * auf die entfernten Refs waere jetzt ein Pin auf toten Code. Der Beweis fuer
+ * useChat steht stattdessen als echter Zwei-Unterhaltungen-Lauf in
+ * useChat-zwei-laeufe-vermischen-nicht.test.ts.
*/
describe('Stop bricht nur die eigene Erzeugung ab', () => {
- it('useChat abortet den Controller der Instanz nur fuer die eigene Unterhaltung', () => {
+ it('useChat hat kein Instanz-Ref mehr, das ein zweiter Lauf ueberschreiben koennte', () => {
const chat = src('../../../hooks/useChat.ts')
- expect(chat).toMatch(/const abortConvRef = useRef<string \| null>\(null\)/)
- expect(chat).toMatch(/if \(abortConvRef\.current === convId\) \{\s*\n\s*abortRef\.current\?\.abort\(\)/)
- // Und der Ref wird auch wirklich gesetzt, sonst bricht Stop nie etwas ab.
- expect(chat.match(/abortConvRef\.current = convId/g)?.length).toBe(2)
+ expect(chat).not.toMatch(/abortConvRef/)
+ expect(chat).not.toMatch(/const abortRef = useRef/)
+ // Der EINE Griff, der wirklich abbricht, bleibt: je Konversation, im
+ // generationStore, nicht in einem Hook-Ref.
+ expect(chat).toMatch(/useGenerationStore\.getState\(\)\.abortConversation\(convId\)/)
})
it('useAgentChat beendet den Agentenlauf nur fuer die eigene Unterhaltung', () => {
diff --git a/src/hooks/__tests__/useChat-stop-trifft-nur-die-eigene-unterhaltung.test.ts b/src/hooks/__tests__/useChat-stop-trifft-nur-die-eigene-unterhaltung.test.ts
new file mode 100644
index 00000000..e12adf06
--- /dev/null
+++ b/src/hooks/__tests__/useChat-stop-trifft-nur-die-eigene-unterhaltung.test.ts
@@ -0,0 +1,125 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * B2 Commit 2: Stop must reach the conversation it was pressed for, and
+ * ONLY that one, once `abortRef` / `abortConvRef` are gone.
+ *
+ * Honest note on this commit's own proof: `abortRef` / `abortConvRef` turned
+ * out to be already-dead weight by the time this commit ran, not a live bug.
+ * `stopGeneration` already called `useGenerationStore.getState()
+ * .abortConversation(convId)` — the per-conversation register that
+ * `registerAborter` feeds on every send — BEFORE the `abortRef` check, and
+ * that call alone already aborts the right run regardless of which run last
+ * held the hook-instance ref. Running this exact scenario against the
+ * pre-commit source (both directions: a foreign Stop leaves the other run
+ * running, the named Stop actually flips its AbortSignal) came back green
+ * already, so there is no "red before" to show for this specific commit —
+ * see bau/lanes.md for the measurement. What this commit removes is the
+ * redundant, provably-dead ref pair (Hausregel: alten Code sofort loeschen),
+ * and this file is the permanent behavioural proof that the ONE remaining
+ * mechanism — `generationStore.aborters`, keyed by conversation — carries
+ * the whole guarantee on its own.
+ *
+ * Run: npx vitest run src/hooks/__tests__/useChat-stop-trifft-nur-die-eigene-unterhaltung.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 () => {},
+}))
+
+import { useChat } 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 { 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() {
+ try { controller.enqueue(enc.encode('data: [DONE]\n\n')); controller.close() } catch { /* already closed by the abort path */ }
+ },
+ }
+}
+const tick = () => new Promise((r) => setTimeout(r, 0))
+function seed(): string {
+ const convId = useChatStore.getState().createConversation(MODEL, '')
+ useChatStore.getState().setActiveConversation(convId)
+ return convId
+}
+
+beforeEach(() => {
+ 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 } } }))
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('stop targets the named conversation only', () => {
+ it('B started after A (so it owned the last write to any shared ref): stopping A leaves B running and really aborts A', async () => {
+ const convA = seed()
+ const convB = seed()
+ const streamA = controllableSSE()
+ const streamB = controllableSSE()
+ let sigA: AbortSignal | undefined
+ let sigB: AbortSignal | undefined
+
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ const body = String((init as RequestInit)?.body ?? '')
+ const signal = (init as RequestInit)?.signal as AbortSignal | undefined
+ if (body.includes('msg-A')) { sigA = signal; return new Response(streamA.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } }) }
+ if (body.includes('msg-B')) { sigB = signal; return new Response(streamB.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } }) }
+ throw new Error('unexpected request body: ' + body.slice(0, 200))
+ })
+
+ const { result } = renderHook(() => useChat())
+
+ await act(async () => {
+ useChatStore.getState().setActiveConversation(convA)
+ const runA = result.current.sendMessage('msg-A')
+ useChatStore.getState().setActiveConversation(convB)
+ const runB = result.current.sendMessage('msg-B')
+ await tick()
+
+ // View A and press Stop there. B is the run that most recently touched
+ // any hook-instance state, which is exactly the shape that broke
+ // before generationStore carried the whole guarantee.
+ useChatStore.getState().setActiveConversation(convA)
+ result.current.stopGeneration()
+ await tick()
+
+ streamB.push('still-flowing ')
+ await tick()
+ streamB.done()
+ streamA.done()
+ await Promise.all([runA, runB])
+ })
+
+ expect(sigA?.aborted).toBe(true)
+ expect(sigB?.aborted).toBe(false)
+
+ const finalB = useChatStore.getState().conversations.find((c) => c.id === convB)!
+ const answerB = finalB.messages.find((m) => m.role === 'assistant')!.content
+ expect(answerB).toContain('still-flowing')
+ })
+})
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 22132f2c..31d89058 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -1,4 +1,4 @@
-import { useRef, useState, useCallback } from "react"
+import { useState, useCallback } from "react"
import { markCannotThink } from '../lib/model-compatibility'
import { v4 as uuid } from "uuid"
import { useChatStore } from "../stores/chatStore"
@@ -303,17 +303,6 @@ interface ChatRun {
export function useChat() {
const [isGenerating, setIsGenerating] = useState(false)
const [isLoadingModel, setIsLoadingModel] = useState(false)
- const abortRef = useRef<AbortController | null>(null)
- /**
- * Welche Unterhaltung der Controller oben gehoert.
- *
- * `abortRef` ist EINER je Hook-Instanz, nicht je Unterhaltung. Stop nahm ihn
- * bisher unbesehen und brach damit die Erzeugung der anderen Unterhaltung ab
- * (T1 Punkt 4, auf der Box gemessen). Der Griff je Unterhaltung liegt im
- * generationStore und macht die Arbeit; dieser Ref sagt nur noch, ob der
- * Griff dieser Instanz ueberhaupt zur genannten Unterhaltung gehoert.
- */
- const abortConvRef = useRef<string | null>(null)
// Agent mode composition
const agentChat = useAgentChat()
@@ -361,8 +350,11 @@ export function useChat() {
})
const abort = new AbortController()
- abortRef.current = abort
- abortConvRef.current = convId
+ // The generationStore aborter map IS the run register, keyed by convId —
+ // see the ChatRun doc comment above sendMessage. Nothing else needs to
+ // remember this controller: Stop looks it up there, by conversation, not
+ // through a hook-instance ref that a second overlapping run would
+ // overwrite.
useGenerationStore.getState().registerAborter(convId, () => abort.abort())
setIsGenerating(true)
useGenerationStore.getState().setGenerating(convId, true)
@@ -373,8 +365,6 @@ export function useChat() {
}
} finally {
useGenerationStore.getState().clearAborter(convId)
- abortRef.current = null
- abortConvRef.current = null
// The round is over, so it goes on disk BEFORE the app says so. Same
// contract as the single-model turn below and as the Agent and Coding
// runs — see stores/durability.ts for the measurement that made the
@@ -798,8 +788,6 @@ export function useChat() {
).messages
const abort = new AbortController()
- abortRef.current = abort
- abortConvRef.current = convId
// Register so deleting/closing this chat aborts the in-flight stream (Bug C).
// Also requestGenerationCancel so a running ComfyUI job is interrupted when
// the chat goes away mid-generation (the _activeHandoffs gate makes it a
@@ -1187,8 +1175,6 @@ export function useChat() {
useGenerationStore.getState().clearAborter(run.convId)
setIsLoadingModel(false)
useModelStore.getState().setIsModelLoading(false)
- abortRef.current = null
- abortConvRef.current = null
// The turn is done, so it goes on disk — and only then does the app say
// it is done. Persistence is coalesced while tokens stream (2.6.3 — see
@@ -1262,23 +1248,18 @@ export function useChat() {
* - `stopAgent` Agentenlauf, wartender /loop-Pass, Freigaben, ComfyUI.
* Setzt den Stop-Merker des Gespraechs (lib/run-stop), an
* dem auch der Schleifentreiber und das Aufwecken haengen.
- * - `abortConversation` erreicht einen Lauf, den eine FRUEHERE Instanz
- * gestartet hat: der Abbruchgriff im Speicher ist ein
- * Abschluss ueber dessen eigenen Controller (G29).
- * - `abortRef` der einfache Chat-Stream dieser Instanz.
+ * - `abortConversation` erreicht den einfachen Chat-Stream UND den
+ * Gruppenlauf, gleich welche Hook-Instanz oder welcher
+ * ueberlappende `sendMessage()`-Aufruf ihn gestartet hat:
+ * `generationStore.aborters` ist das Lauf-Register, per
+ * Konversation gefuehrt (B2). Ein Hook-Instanz-Ref, den
+ * der naechste ueberlappende Lauf ueberschreibt, wird
+ * dafuer nicht mehr gebraucht.
*/
const stopGeneration = useCallback(() => {
const convId = useChatStore.getState().activeConversationId
stopAgent()
useGenerationStore.getState().abortConversation(convId)
- // NUR wenn der Controller dieser Instanz auch zu DIESER Unterhaltung
- // gehoert. Ohne die Bedingung brach Stop in Unterhaltung B die Erzeugung
- // in A ab, weil `abortRef` den zuletzt gestarteten Lauf haelt, egal wo
- // (T1 Punkt 4). Gehoert er woanders hin, hat `abortConversation` oben
- // schon den richtigen Griff gezogen.
- if (abortConvRef.current === convId) {
- abortRef.current?.abort()
- }
// Also interrupt an in-flight ComfyUI image/video gen, not just the JS loop —
// otherwise the main Stop button leaves ComfyUI burning (only the in-chat
// tool Stop did this before; now both affordances agree).