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): stopAgent/stopCodex stoppen die benannte Unterhaltung

purple87ca46a7bd87
diff --git a/src/hooks/__tests__/stopAgent-nimmt-die-benannte-unterhaltung.test.ts b/src/hooks/__tests__/stopAgent-nimmt-die-benannte-unterhaltung.test.ts
new file mode 100644
index 00000000..54e1cb41
--- /dev/null
+++ b/src/hooks/__tests__/stopAgent-nimmt-die-benannte-unterhaltung.test.ts
@@ -0,0 +1,131 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * B2 Commit 5: stopAgent (and stopCodex) stop the CONVERSATION THE CALLER
+ * NAMES, not whichever one happens to be active right now.
+ *
+ * Before this commit `stopAgent()` took no argument at all and always
+ * re-read `useChatStore.getState().activeConversationId` itself. The one
+ * caller in the app (`useChat.ts`'s `stopGeneration`) always meant the
+ * active conversation anyway, so this was never observably wrong today —
+ * but it made "which conversation gets stopped" an assumption baked into
+ * `stopAgent`, not a fact its caller stated. This test proves the new,
+ * explicit contract: passing a DIFFERENT conversation id than the active one
+ * stops THAT one.
+ *
+ * Run: npx vitest run src/hooks/__tests__/stopAgent-nimmt-die-benannte-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('../../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 () => {},
+}))
+
+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, isRunStopped } from '../../lib/run-stop'
+
+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: 'weiter beim naechsten Mal' } }] })
+
+function seed(): string {
+ const convId = useChatStore.getState().createConversation(MODEL, '')
+ useChatStore.getState().setActiveConversation(convId)
+ useAgentModeStore.getState().setAgentModeActive(convId, true)
+ return convId
+}
+
+beforeEach(async () => {
+ const { registerBuiltinTools, toolRegistry } = await import('../../api/mcp')
+ registerBuiltinTools(toolRegistry)
+ __resetRunStopsForTests()
+ 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: 'cloud', cavemanMode: 'off' },
+ })
+ useProviderStore.setState((s) => ({
+ providers: { ...s.providers, 'lu-cloud': { ...s.providers['lu-cloud'], enabled: true } },
+ }))
+ useModelStore.setState({ models: [], activeModel: MODEL })
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('stopAgent(conversationId) stops the named run', () => {
+ it('stops A by id while B is the active/visible conversation', async () => {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ return textZug()
+ })
+
+ const { result } = renderHook(() => useAgentChat())
+ const convA = seed()
+ // useAgentChat has no slash parser of its own — that lives in
+ // useChat.ts's sendMessage, which seeds `opts.loop` for pass 1. Passed
+ // directly here, the same way that call site does.
+ await act(async () => {
+ await result.current.sendAgentMessage('zaehle weiter', undefined, {
+ loop: { pass: 1, intervalMs: 1000, task: 'zaehle weiter', startedAt: Date.now() },
+ })
+ })
+ expect(useAgentLoopStore.getState().loops[convA]).toBeDefined()
+
+ const convB = seed() // switches the active conversation to B
+
+ // Explicitly name A, even though B is the one currently visible.
+ act(() => { result.current.stopAgent(convA) })
+
+ expect(isRunStopped(convA)).toBe(true)
+ expect(useAgentLoopStore.getState().loops[convA]).toBeUndefined()
+ // B was never touched.
+ expect(isRunStopped(convB)).toBe(false)
+ })
+
+ it('COUNTER-CHECK: omitting the id falls back to the active conversation, unchanged from before', async () => {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ return textZug()
+ })
+
+ const { result } = renderHook(() => useAgentChat())
+ const convA = seed()
+ await act(async () => { await result.current.sendAgentMessage('/loop 1s zaehle weiter') })
+
+ act(() => { result.current.stopAgent() })
+
+ expect(isRunStopped(convA)).toBe(true)
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 2f086b6b..0ea70c5c 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -2614,14 +2614,23 @@ export function useAgentChat() {
// ── Stop the agent ────────────────────────────────────────────
- const stopAgent = useCallback(() => {
+ const stopAgent = useCallback((conversationId?: string | null) => {
// Stop means stop: also cancel a /loop pass waiting out its interval,
// otherwise the run the user just killed comes back by itself. Recorded per
// CONVERSATION so the finally of a pass started by a previous hook instance
// (the chat view unmounts on a view switch) sees it too, and so the flag is
// cleared again by the next real instruction instead of standing for the
// rest of the session.
- const stoppedConvId = useChatStore.getState().activeConversationId
+ //
+ // B2 Commit 5: the caller NAMES the run it means to stop instead of this
+ // function re-reading "whichever conversation happens to be visible
+ // right now" — the visible one is only ever correct because today's one
+ // caller (useChat.ts's stopGeneration) already resolved it that way. A
+ // future caller that stops a run the user is NOT looking at (a per-item
+ // Stop in a task list, say) would otherwise silently stop the wrong one.
+ const stoppedConvId = conversationId !== undefined
+ ? conversationId
+ : useChatStore.getState().activeConversationId
stopRun(stoppedConvId)
// B1 (3.0.1, Orchestrator-Entscheid): "Stop means stop" gilt auch fuer
// Hintergrundauftraege dieser Unterhaltung, die per delegate_task
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 31d89058..992d5a26 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -1258,7 +1258,9 @@ export function useChat() {
*/
const stopGeneration = useCallback(() => {
const convId = useChatStore.getState().activeConversationId
- stopAgent()
+ // B2 Commit 5: name the run explicitly instead of letting stopAgent
+ // re-read "the active conversation" itself.
+ stopAgent(convId)
useGenerationStore.getState().abortConversation(convId)
// 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
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 4ea97acf..62f5ae56 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -2570,10 +2570,15 @@ export function useCodex() {
const sendRef = useRef<typeof sendInstruction | null>(null)
sendRef.current = sendInstruction
- const stopCodex = useCallback(() => {
+ const stopCodex = useCallback((conversationId?: string | null) => {
// Stop means stop: also cancel a /loop pass that is waiting out its
// interval, otherwise the run the user just killed comes back by itself.
- const stoppedConvId = useChatStore.getState().activeConversationId
+ // B2 Commit 5: the caller names the run, see useAgentChat.ts's stopAgent
+ // for why (today's one caller already resolves it this way, but the
+ // function itself should not have to assume that).
+ const stoppedConvId = conversationId !== undefined
+ ? conversationId
+ : useChatStore.getState().activeConversationId
// Both of these reach a run a PREVIOUS hook instance started (the Code view
// remounts on every tab switch): the store holds that run's real aborter,
// and the module-scoped stop is readable from its loop driver's finally,