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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): runInLane in useChat.ts sendMessage als Produktionsweg
purple5dfeddbe2d4b
diff --git a/src/hooks/__tests__/useChat-lokale-spur-reiht-zweite-sendung-ein.test.ts b/src/hooks/__tests__/useChat-lokale-spur-reiht-zweite-sendung-ein.test.tsnew file mode 100644index 00000000..ba312b2a--- /dev/null+++ b/src/hooks/__tests__/useChat-lokale-spur-reiht-zweite-sendung-ein.test.ts@@ -0,0 +1,147 @@+/**+ * @vitest-environment jsdom+ *+ * Runde 4 (review-lanes.md Blocker 1+6): useChat.ts's plain sendMessage+ * must run through `runInLane` on the local lane. Two conversations on the+ * built-in engine (n_parallel=1) may not both fire a request at once — the+ * second must queue and only start once the first is done.+ *+ * `laneOf`/`currentLaneFacts` are mocked to force BOTH conversations onto+ * the 'local' lane regardless of which model name they carry, so the test+ * does not have to fake the built-in-engine detection plumbing.+ *+ * Run: npx vitest run src/hooks/__tests__/useChat-lokale-spur-reiht-zweite-sendung-ein.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 }),+}))++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 { __resetRunSlotsForTests } from '../../lib/run-slot'+import { DEFAULT_SETTINGS } from '../../lib/constants'++const MODEL = 'openai::local-builtin-model'++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+}++beforeEach(() => {+ __resetRunLanesForTests()+ __resetRunSlotsForTests()+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ useModelStore.setState({ models: [], activeModel: 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('sendMessage reiht eine zweite lokale Sendung ein', () => {+ it('die zweite Sendung fragt keinen zweiten Server an, bis die erste fertig ist', async () => {+ const convA = seed()+ const convB = seed()++ const streamA = controllableSSE()+ const streamB = 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('first-A-message')) {+ return new Response(streamA.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })+ }+ if (body.includes('first-B-message')) {+ 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())++ let runB: Promise<void> = Promise.resolve()+ await act(async () => {+ useChatStore.getState().setActiveConversation(convA)+ const runA = result.current.sendMessage('first-A-message')+ await tick()++ // A holds the local lane; B must not have called fetch yet.+ expect(fetchCalls).toBe(1)+ expect(localLaneHolder()).toBe(convA)++ useChatStore.getState().setActiveConversation(convB)+ runB = result.current.sendMessage('first-B-message')+ await tick()++ // B queued behind A instead of racing it for the one local slot.+ expect(fetchCalls).toBe(1)+ expect(queuedRunIds()).toEqual([convB])++ streamA.push('Alpha-answer')+ streamA.done()+ await runA+ await tick()++ // A released the lane, so B's request goes out now.+ expect(fetchCalls).toBe(2)+ expect(localLaneHolder()).toBe(convB)++ streamB.push('Bravo-answer')+ streamB.done()+ await runB+ })++ const finalA = useChatStore.getState().conversations.find((c) => c.id === convA)!+ const finalB = useChatStore.getState().conversations.find((c) => c.id === convB)!+ expect(finalA.messages.find((m) => m.role === 'assistant')!.content).toContain('Alpha-answer')+ expect(finalB.messages.find((m) => m.role === 'assistant')!.content).toContain('Bravo-answer')+ expect(localLaneHolder()).toBeNull()+ expect(queuedRunIds()).toEqual([])+ })+})diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 65dcc3ab..be6d95c8 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -29,6 +29,8 @@ import { applyGoalCommand } from '../lib/goal-command'import { useMemory } from "./useMemory"import { useAgentModeStore } from "../stores/agentModeStore"import { useGenerationStore } from "../stores/generationStore"+import { runInLane } from "../lib/run-slot"+import { laneOf, currentLaneFacts } from "../lib/run-lane-of-model"import { resolveChatToolRoute, CHAT_TOOLS, type ChatToolRouteMsg } from "../lib/chat-tool-intent"import { getProviderForModel, getProviderIdFromModel } from "../api/providers"import { modelOutOfMode } from "../lib/modeGate"@@ -797,7 +799,15 @@ export function useChat() {},).messages+ // Lane admission (Runde 4, review-lanes.md Blocker 1+6): the built-in+ // engine runs llama-server with n_parallel=1, so two local sends racing+ // it at once queue instead of both landing on the one slot. Cloud lanes+ // start right away, same as before this round. Nothing has touched the+ // store yet (no message added below this point), so a send that Stop+ // 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 () => {// 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@@ -1252,6 +1262,7 @@ export function useChat() {extractAndSave(content, run.content, run.convId, { scope: memoryScope }).catch(() => {})}}+ })// 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