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): Gruppenchat haelt die Spur, Wiedereintritts-Riegel je Unterhaltung

purple3c2dcfe31dfb
diff --git a/src/hooks/__tests__/chat-doppelklick-auf-derselben-unterhaltung.test.ts b/src/hooks/__tests__/chat-doppelklick-auf-derselben-unterhaltung.test.ts
new file mode 100644
index 00000000..eac6a4bb
--- /dev/null
+++ b/src/hooks/__tests__/chat-doppelklick-auf-derselben-unterhaltung.test.ts
@@ -0,0 +1,127 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Runde 5 Folgeposten 2 (review-lanes.md, Runde 2 Punkt 4): useChat.ts's
+ * plain `sendMessage` had NO re-entry guard, unlike its two sister hooks
+ * (`useAgentChat.ts`'s `activeAgentRuns`, `useCodex.ts`'s `activeCodexRuns`).
+ *
+ * Blocker A's fix (this round, `run-slot.ts`) gives every `runInLane` call
+ * its own booking identity, so a LOCAL double-send now queues behind itself
+ * instead of racing. But `admit()` returns `'started'` immediately for the
+ * `'cloud'` lane, unconditionally (`run-lanes.ts`): there is no queue for
+ * cloud sends, so nothing about Blocker A stops two `sendMessage()` calls on
+ * the SAME cloud conversation from both firing a real request at once, each
+ * into its OWN fresh assistant message. That is exactly the live money bug
+ * this house already paid for once with the sister hooks' guard (one prompt,
+ * two Enters, `video_generate` four times, David 2026-06-16), just never
+ * closed for plain chat.
+ *
+ * Run: npx vitest run src/hooks/__tests__/chat-doppelklick-auf-derselben-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'
+
+const sse = (payload: object) =>
+ new Response(`data: ${JSON.stringify(payload)}\n\ndata: [DONE]\n\n`, {
+ status: 200, headers: { 'content-type': 'text/event-stream' },
+ })
+const textZug = () => sse({ choices: [{ delta: { content: 'a video of a cat' } }] })
+
+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: {} })
+ 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 } },
+ }))
+ useModelStore.setState({ models: [], activeModel: MODEL })
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('sendMessage: der Wiedereintritts-Riegel blockt einen Doppelklick auf DERSELBEN Unterhaltung', () => {
+ it('ein Prompt, zweimal in derselben Zehntelsekunde gesendet: genau EINE Modellanfrage', async () => {
+ let calls = 0
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ calls++
+ return textZug()
+ })
+
+ const { result } = renderHook(() => useChat())
+ seed()
+
+ let run1!: Promise<void>
+ let run2!: Promise<void>
+ await act(async () => {
+ // No await between the two calls: the double-submit shape (two Enters
+ // before React repaints Send into Stop).
+ run1 = result.current.sendMessage('mach mir ein video von einer katze')
+ run2 = result.current.sendMessage('mach mir ein video von einer katze')
+ await Promise.all([run1, run2])
+ })
+
+ expect(calls).toBe(1)
+ // Exactly one user/assistant pair, not two: the second call was refused
+ // before it ever added its own message pair.
+ const conv = useChatStore.getState().conversations[0]
+ expect(conv.messages.filter((m) => m.role === 'user')).toHaveLength(1)
+ expect(conv.messages.filter((m) => m.role === 'assistant')).toHaveLength(1)
+ })
+
+ it('COUNTER-CHECK: derselbe Doppel-Sendevorgang auf ZWEI VERSCHIEDENEN Unterhaltungen wird NICHT geblockt', async () => {
+ let calls = 0
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ calls++
+ return textZug()
+ })
+
+ const { result } = renderHook(() => useChat())
+ const convA = seed()
+ const convB = seed()
+
+ await act(async () => {
+ useChatStore.getState().setActiveConversation(convA)
+ const runA = result.current.sendMessage('task-A')
+ useChatStore.getState().setActiveConversation(convB)
+ const runB = result.current.sendMessage('task-B')
+ await Promise.all([runA, runB])
+ })
+
+ // Negative control on the test itself: if this ever reads 1, the guard
+ // has regressed to hook-instance-wide and is blocking an unrelated
+ // conversation, the defect the sister hooks' guard was keyed by convId
+ // to avoid.
+ expect(calls).toBe(2)
+ })
+})
diff --git a/src/hooks/__tests__/group-chat-bucht-lokale-spur.test.ts b/src/hooks/__tests__/group-chat-bucht-lokale-spur.test.ts
new file mode 100644
index 00000000..565d15be
--- /dev/null
+++ b/src/hooks/__tests__/group-chat-bucht-lokale-spur.test.ts
@@ -0,0 +1,248 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Runde 5 (review-lanes.md Blocker B): a group round must hold the local
+ * lane for its whole span, exactly like the other two send paths. Before
+ * this fix, `fbfe15c3` (Runde 4) had removed the app-wide composer lock that
+ * used to cover a group round as a side effect, without ever wiring
+ * `runGroupRound` into `runInLane`: a local group chat and a second local
+ * conversation could stream from the built-in engine at the same time,
+ * silently, because `localLaneHolder()` never heard about the group round.
+ *
+ * Two directions, both required by the task: a group round already running
+ * blocks a second local send, AND a local conversation already running
+ * blocks a group round from starting.
+ *
+ * `laneOf`/`currentLaneFacts` are mocked to force everything onto the
+ * 'local' lane, the same technique as
+ * useChat-lokale-spur-reiht-zweite-sendung-ein.test.ts. `builtin-ensure` is
+ * mocked so a group turn does not try to reach the real (Tauri-backed)
+ * engine control path in this environment.
+ *
+ * Run: npx vitest run src/hooks/__tests__/group-chat-bucht-lokale-spur.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: () => 'local',
+ currentLaneFacts: () => ({ openaiSlotIsLocal: true, ollamaBaseIsLocal: true }),
+}))
+vi.mock('../../api/builtin-ensure', () => ({
+ builtinReloadNeeded: async () => null,
+ ensureBuiltinEngineAlive: async () => {},
+ isManagedBuiltinSlot: () => true,
+}))
+
+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 { __resetRunLanesForTests, localLaneHolder, queuedRunIds } from '../../lib/run-lanes'
+import { DEFAULT_SETTINGS } from '../../lib/constants'
+
+const SOLO_MODEL = 'openai::local-solo-model'
+const GROUP_MODEL_1 = 'openai::local-group-speaker-1'
+const GROUP_MODEL_2 = 'openai::local-group-speaker-2'
+
+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 seedSolo(): string {
+ const convId = useChatStore.getState().createConversation(SOLO_MODEL, '')
+ useChatStore.getState().setActiveConversation(convId)
+ return convId
+}
+
+function seedGroup(): string {
+ const convId = useChatStore.getState().createConversation(GROUP_MODEL_1, '')
+ useChatStore.getState().setGroupModels(convId, [GROUP_MODEL_1, GROUP_MODEL_2])
+ useChatStore.getState().setActiveConversation(convId)
+ return convId
+}
+
+beforeEach(() => {
+ __resetRunLanesForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ models: [], activeModel: SOLO_MODEL })
+ useSettingsStore.setState({
+ settings: { ...DEFAULT_SETTINGS, appMode: 'local', cavemanMode: 'off', chatToolsEnabled: false },
+ })
+ useProviderStore.setState((s) => ({
+ providers: { ...s.providers, openai: { ...s.providers.openai, enabled: true } },
+ }))
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('ein laufender Gruppenchat haelt die lokale Spur', () => {
+ it('eine zweite lokale Unterhaltung wartet, bis die letzte Gruppenantwort fertig ist', async () => {
+ const convGroup = seedGroup()
+ const convSolo = seedSolo()
+
+ const stream1 = controllableSSE()
+ const stream2 = controllableSSE()
+ const streamSolo = controllableSSE()
+ let fetchCalls = 0
+
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ fetchCalls++
+ const body = String((init as RequestInit)?.body ?? '')
+ if (body.includes(`"model":"${GROUP_MODEL_1.split('::')[1]}"`)) {
+ return new Response(stream1.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ }
+ if (body.includes(`"model":"${GROUP_MODEL_2.split('::')[1]}"`)) {
+ return new Response(stream2.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ }
+ if (body.includes('solo-message')) {
+ return new Response(streamSolo.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ }
+ throw new Error('unexpected request body: ' + body.slice(0, 200))
+ })
+
+ const { result } = renderHook(() => useChat())
+
+ let runSolo: Promise<void> = Promise.resolve()
+ await act(async () => {
+ useChatStore.getState().setActiveConversation(convGroup)
+ const runGroup = result.current.sendMessage('group-round-message')
+ await tick()
+
+ // Speaker 1 has fired; the group round holds the local lane.
+ expect(fetchCalls).toBe(1)
+ expect(localLaneHolder()).toBe(convGroup)
+
+ // A second, unrelated local conversation must NOT fire while the
+ // group round (any of its speakers) is still going.
+ useChatStore.getState().setActiveConversation(convSolo)
+ runSolo = result.current.sendMessage('solo-message')
+ await tick()
+ expect(fetchCalls).toBe(1)
+ expect(queuedRunIds()).toEqual([convSolo])
+
+ // Speaker 1 finishes, speaker 2 takes its turn. The round is not over
+ // yet, so the lane must still belong to the group.
+ stream1.push('speaker-1-answer')
+ stream1.done()
+ await tick()
+ expect(fetchCalls).toBe(2)
+ expect(localLaneHolder()).toBe(convGroup)
+ expect(queuedRunIds()).toEqual([convSolo])
+
+ // Speaker 2 finishes: the round is over, the solo send goes out now.
+ stream2.push('speaker-2-answer')
+ stream2.done()
+ await runGroup
+ await tick()
+
+ expect(fetchCalls).toBe(3)
+ expect(localLaneHolder()).toBe(convSolo)
+
+ streamSolo.push('solo-answer')
+ streamSolo.done()
+ await runSolo
+ })
+
+ const group = useChatStore.getState().conversations.find((c) => c.id === convGroup)!
+ const solo = useChatStore.getState().conversations.find((c) => c.id === convSolo)!
+ const groupAnswers = group.messages.filter((m) => m.role === 'assistant').map((m) => m.content)
+ expect(groupAnswers).toEqual(['speaker-1-answer', 'speaker-2-answer'])
+ expect(solo.messages.find((m) => m.role === 'assistant')!.content).toContain('solo-answer')
+ expect(localLaneHolder()).toBeNull()
+ expect(queuedRunIds()).toEqual([])
+ })
+
+ it('umgekehrt: eine laufende lokale Unterhaltung haelt die Spur, der Gruppenchat wartet', async () => {
+ const convSolo = seedSolo()
+ const convGroup = seedGroup()
+
+ const streamSolo = controllableSSE()
+ const stream1 = controllableSSE()
+ const stream2 = controllableSSE()
+ let fetchCalls = 0
+
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ fetchCalls++
+ const body = String((init as RequestInit)?.body ?? '')
+ if (body.includes('solo-message')) {
+ return new Response(streamSolo.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ }
+ if (body.includes(`"model":"${GROUP_MODEL_1.split('::')[1]}"`)) {
+ return new Response(stream1.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ }
+ if (body.includes(`"model":"${GROUP_MODEL_2.split('::')[1]}"`)) {
+ return new Response(stream2.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ }
+ throw new Error('unexpected request body: ' + body.slice(0, 200))
+ })
+
+ const { result } = renderHook(() => useChat())
+
+ let runGroup: Promise<void> = Promise.resolve()
+ await act(async () => {
+ useChatStore.getState().setActiveConversation(convSolo)
+ const runSolo = result.current.sendMessage('solo-message')
+ await tick()
+ expect(fetchCalls).toBe(1)
+ expect(localLaneHolder()).toBe(convSolo)
+
+ // The group round must not fire a single speaker while the solo
+ // conversation still holds the lane.
+ useChatStore.getState().setActiveConversation(convGroup)
+ runGroup = result.current.sendMessage('group-round-message')
+ await tick()
+ expect(fetchCalls).toBe(1)
+ expect(queuedRunIds()).toEqual([convGroup])
+
+ streamSolo.push('solo-answer')
+ streamSolo.done()
+ await runSolo
+ await tick()
+
+ expect(fetchCalls).toBe(2)
+ expect(localLaneHolder()).toBe(convGroup)
+
+ stream1.push('speaker-1-answer')
+ stream1.done()
+ await tick()
+ expect(fetchCalls).toBe(3)
+
+ stream2.push('speaker-2-answer')
+ stream2.done()
+ await runGroup
+ })
+
+ expect(localLaneHolder()).toBeNull()
+ expect(queuedRunIds()).toEqual([])
+ })
+})
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index be6d95c8..e0b0e165 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -302,6 +302,37 @@ interface ChatRun {
discardedThinkBuf: string
}
+/**
+ * Runs currently in flight in PLAIN chat's `sendMessage`, keyed by
+ * conversation. The re-entry guard `useAgentChat.ts` (`activeAgentRuns`) and
+ * `useCodex.ts` (`activeCodexRuns`) already have; `sendMessage` had none
+ * (Runde 5 Folgeposten 2, review-lanes.md Runde 2 Punkt 4).
+ *
+ * Blocker A's fix (`run-slot.ts`, this round) gives every `runInLane` call
+ * its own booking identity, so two sends on the same conversation can no
+ * longer both hold the LOCAL lane at once, but that only serializes the
+ * lane a local model uses. A CLOUD model's lane always returns `'started'`
+ * immediately (`admit`, `run-lanes.ts`): nothing there stops a double-click
+ * on a cloud conversation from firing two real, simultaneous requests, each
+ * writing into its OWN fresh assistant message. That is the exact live money
+ * bug this house has already paid for once (one prompt, two Enters,
+ * `video_generate` four times, David 2026-06-16). Blocker A closed the
+ * local half of it and left the cloud half open, because a cloud send was
+ * never anyone's re-entry guard's job before.
+ *
+ * Same shape and same placement as the sister hooks: claimed synchronously
+ * right after `convId` is resolved, no `await` in between, freed in the
+ * `finally` only if this run still owns the entry (a Stop-then-resend on the
+ * same conversation must not have the OLD run's cleanup evict the NEW run's
+ * claim).
+ */
+const activeChatRuns = new Map<string, symbol>()
+
+/** Test-only: which conversations currently have a live plain-chat send. */
+export function __activeChatRunConvIdsForTests(): string[] {
+ return [...activeChatRuns.keys()]
+}
+
export function useChat() {
const [isGenerating, setIsGenerating] = useState(false)
const [isLoadingModel, setIsLoadingModel] = useState(false)
@@ -341,7 +372,16 @@ export function useChat() {
/** One group round: the user's line goes in once, then every group model
* answers in turn on the shared, attribution-tagged history. One abort
* controller spans the whole round, so Stop ends the round, not just the
- * model that happened to be talking. */
+ * model that happened to be talking.
+ *
+ * Runde 5 (review-lanes.md Blocker B): the round now books the local lane
+ * for its ENTIRE span, all speakers included, exactly like the other two
+ * send paths. Before this, `fbfe15c3` (Runde 4) removed the app-wide
+ * composer lock that used to cover a group round as a side effect, without
+ * putting the round on the lane that replaced it: a local group chat and
+ * a second local conversation could stream from the built-in engine at the
+ * same time, silently, because `localLaneHolder()` never heard about the
+ * group round at all. */
const runGroupRound = useCallback(async (convId: string, content: string, images: ImageAttachment[] | undefined, models: string[]) => {
useChatStore.getState().addMessage(convId, {
id: uuid(),
@@ -351,41 +391,53 @@ export function useChat() {
timestamp: Date.now(),
})
+ // The round holds the lane its SPEAKERS need. Mixed local+cloud speakers
+ // hold the local lane: a single local speaker anywhere in the round still
+ // ties up the one engine slot for the whole round's duration, and the
+ // safe reading is "this round touches the local card", not "every
+ // speaker does". Getting this wrong the other way (treating a mixed
+ // round as cloud) would let a local speaker in the round run alongside
+ // an unrelated local conversation, the exact VRAM swap this module
+ // exists to prevent.
+ const facts = currentLaneFacts()
+ const lane = models.some((model) => laneOf(model, facts) === 'local') ? 'local' : 'cloud'
const abort = new AbortController()
- // 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.
- const myAborter = () => abort.abort()
- useGenerationStore.getState().registerAborter(convId, myAborter)
- setIsGenerating(true)
- useGenerationStore.getState().setGenerating(convId, true)
- try {
- for (const model of models) {
- if (abort.signal.aborted) break
- await runGroupTurn(convId, model, models, abort)
- }
- } finally {
- // Same identity check as the single-model turn below (Blocker 2,
- // review-lanes.md): a Stop followed by an immediate resend on this
- // conversation can register a new aborter before this round's
- // finally runs.
- const stillOwnsSlot = useGenerationStore.getState().aborters[convId] === myAborter
- if (stillOwnsSlot) {
- useGenerationStore.getState().clearAborter(convId)
- }
- // 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
- // order matter.
- await endTurnDurably(() => {
+ await runInLane({ conversationId: convId, lane, abort: () => abort.abort() }, async () => {
+ // 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.
+ const myAborter = () => abort.abort()
+ useGenerationStore.getState().registerAborter(convId, myAborter)
+ setIsGenerating(true)
+ useGenerationStore.getState().setGenerating(convId, true)
+ try {
+ for (const model of models) {
+ if (abort.signal.aborted) break
+ await runGroupTurn(convId, model, models, abort)
+ }
+ } finally {
+ // Same identity check as the single-model turn below (Blocker 2,
+ // review-lanes.md): a Stop followed by an immediate resend on this
+ // conversation can register a new aborter before this round's
+ // finally runs.
+ const stillOwnsSlot = useGenerationStore.getState().aborters[convId] === myAborter
if (stillOwnsSlot) {
- setIsGenerating(false)
- useGenerationStore.getState().setGenerating(convId, false)
+ useGenerationStore.getState().clearAborter(convId)
}
- })
- }
+ // 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
+ // order matter.
+ await endTurnDurably(() => {
+ if (stillOwnsSlot) {
+ setIsGenerating(false)
+ useGenerationStore.getState().setGenerating(convId, false)
+ }
+ })
+ }
+ })
}, [])
const sendMessage = useCallback(async (content: string, images?: ImageAttachment[]) => {
@@ -549,6 +601,18 @@ export function useChat() {
convId = store.createConversation(activeModel, persona?.systemPrompt || "")
}
+ // Re-entry guard (Runde 5 Folgeposten 2): claimed synchronously, no
+ // `await` since `convId` was resolved above, same discipline as
+ // `activeAgentRuns`/`activeCodexRuns`. A second `sendMessage` for the
+ // SAME conversation while the first is still in flight is refused here,
+ // before it can add its own message pair or fire its own request.
+ if (activeChatRuns.has(convId)) {
+ log.info('chat.duplicate_send_blocked', { activeModel, convId })
+ return
+ }
+ const myRunToken = Symbol(convId)
+ activeChatRuns.set(convId, myRunToken)
+
const memoryScope = store.conversations.find(c => c.id === convId)?.memoryScope
const userMessage = {
id: uuid(),
@@ -575,7 +639,13 @@ export function useChat() {
useChatStore.getState().addMessage(convId, assistantMessage)
const conv = useChatStore.getState().conversations.find((c) => c.id === convId)
- if (!conv) return
+ if (!conv) {
+ // Practically unreachable (nothing awaited since the message pair was
+ // just added to this exact conversation), but the guard claimed above
+ // must not survive an early return regardless.
+ if (activeChatRuns.get(convId) === myRunToken) activeChatRuns.delete(convId)
+ return
+ }
// RAG context injection
// Per-chat persona toggle (mobile-parity, mirrors mobile's
@@ -807,7 +877,7 @@ export function useChat() {
// pulls out of the queue before its turn leaves nothing to unwind.
const lane = laneOf(activeModel, currentLaneFacts())
const abort = new AbortController()
- await runInLane({ conversationId: convId, lane, abort: () => abort.abort() }, async () => {
+ const laneOutcome = await runInLane({ conversationId: convId, lane, abort: () => abort.abort() }, async () => {
// 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
@@ -1214,6 +1284,13 @@ export function useChat() {
if (stillOwnsSlot) {
useGenerationStore.getState().clearAborter(run.convId)
}
+ // Re-entry guard release (Runde 5 Folgeposten 2): its own identity
+ // check, same reasoning as `stillOwnsSlot` above but a SEPARATE map.
+ // A Stop-then-resend on the same conversation must free only the run
+ // that actually still holds the claim, never a newer one's.
+ if (activeChatRuns.get(run.convId) === myRunToken) {
+ activeChatRuns.delete(run.convId)
+ }
setIsLoadingModel(false)
useModelStore.getState().setIsModelLoading(false)
@@ -1263,6 +1340,14 @@ export function useChat() {
}
}
})
+ if (laneOutcome === 'cancelled-while-queued' && activeChatRuns.get(convId) === myRunToken) {
+ // Stop pulled this send out of the local lane's waiting room before its
+ // own `finally` ever ran (that `finally` lives inside the body above),
+ // so the guard claimed synchronously at the top has to be freed here
+ // instead. Nothing else needs undoing beyond that: the body never
+ // started, so it never registered an aborter or set `generating`.
+ activeChatRuns.delete(convId)
+ }
// 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