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(agent): runInLane in useAgentChat.ts sendAgentMessage als Produktionsweg

purple0b9dfce31370
diff --git a/src/hooks/__tests__/useAgentChat-lokale-spur-reiht-zweiten-agentenlauf-ein.test.ts b/src/hooks/__tests__/useAgentChat-lokale-spur-reiht-zweiten-agentenlauf-ein.test.ts
new file mode 100644
index 00000000..7b45a86a
--- /dev/null
+++ b/src/hooks/__tests__/useAgentChat-lokale-spur-reiht-zweiten-agentenlauf-ein.test.ts
@@ -0,0 +1,167 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Runde 4 (review-lanes.md Blocker 1+6): useAgentChat.ts's sendAgentMessage
+ * must run through `runInLane` on the local lane, same as plain chat. Two
+ * conversations on the built-in engine (n_parallel=1) may not both fire a
+ * request at once — the second must queue, show up in `queuedRunIds()`, and
+ * only start once the first agent run is done.
+ *
+ * `laneOf`/`currentLaneFacts` are mocked to force the 'local' lane
+ * regardless of model name, same technique as the useChat.ts sibling test.
+ *
+ * Run: npx vitest run src/hooks/__tests__/useAgentChat-lokale-spur-reiht-zweiten-agentenlauf-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('../../api/rag', () => ({
+ retrieveContext: async () => ({ context: { chunks: [], query: '', documentIds: [] }, scoredChunks: [] }),
+ generateEmbeddings: async () => [[0.1, 0.2]],
+}))
+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 { useAgentChat } from '../useAgentChat'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useProviderStore } from '../../stores/providerStore'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { useAgentTaskStore } from '../../stores/agentTaskStore'
+import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { useTodoStore } from '../../stores/todoStore'
+import { useToolAuditStore } from '../../stores/toolAuditStore'
+import { DEFAULT_SETTINGS } from '../../lib/constants'
+import { __resetRunStopsForTests } from '../../lib/run-stop'
+import { __resetRunLanesForTests, localLaneHolder, queuedRunIds } from '../../lib/run-lanes'
+import { __resetRunSlotsForTests } from '../../lib/run-slot'
+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'
+
+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,
+ pushContent(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)
+ useAgentModeStore.getState().setAgentModeActive(convId, true)
+ return convId
+}
+
+beforeEach(() => {
+ registerBuiltinTools(toolRegistry)
+ __resetRunStopsForTests()
+ __resetRunLanesForTests()
+ __resetRunSlotsForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useAgentTaskStore.setState({ byConv: {} })
+ useAgentLoopStore.setState({ loops: {} })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useAgentModeStore.setState({ agentModeActive: {} })
+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })
+ useToolAuditStore.setState({ entries: {} })
+ useSettingsStore.setState({
+ settings: { ...DEFAULT_SETTINGS, appMode: 'local', cavemanMode: 'off' },
+ })
+ useProviderStore.setState((s) => ({
+ providers: { ...s.providers, openai: { ...s.providers.openai, enabled: true } },
+ }))
+ useModelStore.setState({ models: [], activeModel: MODEL })
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('sendAgentMessage reiht einen zweiten lokalen Agentenlauf ein', () => {
+ it('die zweite Unterhaltung wartet sichtbar und startet erst nach der ersten', async () => {
+ const convA = seed()
+ const convB = seed()
+
+ const streamA = controllableSSE()
+ const streamB = controllableSSE()
+ let callsA = 0
+ let callsB = 0
+
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ const body = String(init?.body ?? '')
+ if (body.includes('task-A')) {
+ callsA++
+ return new Response(streamA.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ }
+ if (body.includes('task-B')) {
+ callsB++
+ 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(() => useAgentChat())
+
+ let runB!: Promise<void>
+ await act(async () => {
+ useChatStore.getState().setActiveConversation(convA)
+ const runA = result.current.sendAgentMessage('task-A')
+ await tick()
+
+ expect(callsA).toBe(1)
+ expect(localLaneHolder()).toBe(convA)
+
+ useChatStore.getState().setActiveConversation(convB)
+ runB = result.current.sendAgentMessage('task-B')
+ await tick()
+
+ // B queued instead of racing A for the built-in engine's one slot.
+ expect(callsB).toBe(0)
+ expect(queuedRunIds()).toEqual([convB])
+
+ streamA.pushContent('final-answer-A')
+ streamA.done()
+ await runA
+ await tick()
+
+ // A released the lane; B's request goes out now.
+ expect(callsB).toBe(1)
+ expect(localLaneHolder()).toBe(convB)
+
+ streamB.pushContent('final-answer-B')
+ 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('final-answer-A')
+ expect(finalB.messages.find((m) => m.role === 'assistant')!.content).toContain('final-answer-B')
+ expect(localLaneHolder()).toBeNull()
+ expect(queuedRunIds()).toEqual([])
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 2cad9828..6c31667f 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -22,6 +22,8 @@ import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'
import { useChatStore } from '../stores/chatStore'
import { endTurnDurably } from '../stores/durability'
import { useGenerationStore } from '../stores/generationStore'
+import { runInLane } from '../lib/run-slot'
+import { laneOf, currentLaneFacts } from '../lib/run-lane-of-model'
import { useModelStore } from '../stores/modelStore'
import { useSettingsStore } from '../stores/settingsStore'
import { useRAGStore } from '../stores/ragStore'
@@ -412,6 +414,24 @@ export function useAgentChat() {
// once. The only early return before the try (no conv) undoes both.
setIsAgentRunning(true)
+ // Lane admission (Runde 4, review-lanes.md Blocker 1+6): everything from
+ // here to the end of this call (RAG, memory, the tool loop, the /loop
+ // driver) runs inside runInLane's body, so a local turn that has to wait
+ // for the built-in engine's one llama-server slot has not yet touched the
+ // chat store when it is queued — nothing has been added that a cancelled
+ // wait would need to unwind. The re-entry guard above already claimed
+ // activeAgentRuns/isAgentRunning synchronously, before any await, so a
+ // second send on the SAME conversation is refused before it ever reaches
+ // the lane; a wait here is always a DIFFERENT conversation's turn.
+ //
+ // 'cancelled-while-queued' means Stop was pressed while this run was
+ // still in the waiting room: the body (and its own finally below) never
+ // ran, so the guard this call claimed above has to be freed here instead.
+ const lane = laneOf(activeModel, currentLaneFacts())
+ const laneOutcome = await runInLane(
+ { conversationId: convId, lane, abort: () => abort.abort() },
+ async () => {
+
// Z36 finding 2: an agent turn carries the tool catalogue and outgrows
// the built-in engine's 8192 start default, and llama-server's ctx is a
// start-time flag no per-request option can raise. Lift the engine to
@@ -2709,6 +2729,18 @@ export function useAgentChat() {
}
}
}
+ },
+ )
+ if (laneOutcome === 'cancelled-while-queued' && activeAgentRuns.get(convId) === runState) {
+ // Stop pulled this run out of the local lane's waiting room before its
+ // own finally ever ran (that finally lives inside the body above), so
+ // the guard this call claimed synchronously at the top has to be freed
+ // here instead. Nothing else needs undoing: the body never started, so
+ // it never added a message, registered its own aborter, or booked a
+ // loop timer.
+ activeAgentRuns.delete(convId)
+ setIsAgentRunning(activeAgentRuns.size > 0)
+ }
}, [])
// Self-reference so the /loop driver can start the next pass.