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): useAgentLoopStore je Unterhaltung

purple994a8af0862b
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index 019380f9..ddd6462a 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -26,7 +26,7 @@ import { LuEngineSwitchBar } from './LuEngineSwitchBar'
import { LoopBar } from './LoopBar'
import { useSettingsStore } from '../../stores/settingsStore'
import { useModelStore } from '../../stores/modelStore'
-import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useAnyAgentLoopActive } from '../../stores/agentLoopStore'
import { useAgentModeStore } from '../../stores/agentModeStore'
import {
CODEX_WORKDIR_LOCK_TITLE,
@@ -127,7 +127,10 @@ export function CodexView() {
// 'running' stehengeblieben ist, sperrt den Ordner nicht mehr allein.
const sendsInFlight = useCodexStore((s) => s.sendsInFlight)
const threads = useCodexStore((s) => s.threads)
- const loop = useAgentLoopStore((s) => s.loop)
+ // The working directory is GLOBAL across every Codex conversation (A8): a
+ // loop in ANY of them must still keep the folder locked, not only the
+ // active one's.
+ const loop = useAnyAgentLoopActive()
const lockReason = codexBusyReason({ sendsInFlight, threads, generating: generatingMap, loop })
// Where the agent goes while no folder is picked: a per-chat workspace or
diff --git a/src/components/chat/ExplorerPanel.tsx b/src/components/chat/ExplorerPanel.tsx
index 4dc1c983..44cc259a 100644
--- a/src/components/chat/ExplorerPanel.tsx
+++ b/src/components/chat/ExplorerPanel.tsx
@@ -39,7 +39,7 @@ import {
FolderX,
} from 'lucide-react'
import { useCodexStore } from '../../stores/codexStore'
-import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useAnyAgentLoopActive } from '../../stores/agentLoopStore'
import { useGenerationStore } from '../../stores/generationStore'
import { useAgentModeStore } from '../../stores/agentModeStore'
import { useSettingsStore } from '../../stores/settingsStore'
@@ -98,14 +98,16 @@ export function ExplorerPanel({ onApprovePlan }: Props) {
const sendsInFlight = useCodexStore((s) => s.sendsInFlight)
const threads = useCodexStore((s) => s.threads)
const generating = useGenerationStore((s) => s.generating)
- const loop = useAgentLoopStore((s) => s.loop)
- const lockReason = codexBusyReason({ sendsInFlight, threads, generating, loop })
- const lockTitle = lockReason ? CODEX_WORKDIR_LOCK_TITLE[lockReason] : null
-
// Read up here because the workspace fallback below needs it too. The plan
// moved into this column, so a collapsed column would hide it, and with it
// the only Approve-and-run button there is. The rail says so instead.
const activeConversationId = useChatStore((s) => s.activeConversationId)
+ // The working directory is GLOBAL across every Codex conversation (A8), so
+ // a loop running in ANY of them still must not have the folder yanked out
+ // from under it — deliberately not scoped to the active conversation.
+ const loop = useAnyAgentLoopActive()
+ const lockReason = codexBusyReason({ sendsInFlight, threads, generating, loop })
+ const lockTitle = lockReason ? CODEX_WORKDIR_LOCK_TITLE[lockReason] : null
const width = useUIStore((s) => s.explorerWidth)
const collapsed = useUIStore((s) => s.explorerCollapsed)
diff --git a/src/components/chat/LoopBar.tsx b/src/components/chat/LoopBar.tsx
index 0320f7fb..81bbbd56 100644
--- a/src/components/chat/LoopBar.tsx
+++ b/src/components/chat/LoopBar.tsx
@@ -6,7 +6,7 @@
import { useEffect, useState } from 'react'
import { RefreshCw, Square } from 'lucide-react'
-import { useAgentLoopStore } from '../../stores/agentLoopStore'
+import { useConversationLoop } from '../../stores/agentLoopStore'
import { useChatStore } from '../../stores/chatStore'
import { COMPOSER_MAX_W } from './composer-width'
@@ -16,8 +16,11 @@ interface Props {
}
export function LoopBar({ onStop }: Props) {
- const loop = useAgentLoopStore((s) => s.loop)
const activeConversationId = useChatStore((s) => s.activeConversationId)
+ // Only the ACTIVE conversation's own loop, never a foreign one (B2): the
+ // store now holds one per conversation, and a loop running elsewhere must
+ // not paint this bar or steal its Stop button.
+ const loop = useConversationLoop(activeConversationId)
// The clock the countdown divides by, read once a second in the interval
// instead of on every render. Reading `Date.now()` down in the render body
// was impure (React 19 `purity`) AND it made the countdown depend on
@@ -29,7 +32,7 @@ export function LoopBar({ onStop }: Props) {
return () => clearInterval(t)
}, [loop])
- if (!loop || loop.conversationId !== activeConversationId) return null
+ if (!loop) return null
const secs = Math.max(0, Math.ceil((loop.nextAt - now) / 1000))
const passLabel = loop.cap > 0 ? `pass ${loop.pass} of ${loop.cap}` : `pass ${loop.pass}`
diff --git a/src/components/chat/__tests__/the-header-can-let-the-folder-go.test.ts b/src/components/chat/__tests__/the-header-can-let-the-folder-go.test.ts
index 13666119..7cd9aed0 100644
--- a/src/components/chat/__tests__/the-header-can-let-the-folder-go.test.ts
+++ b/src/components/chat/__tests__/the-header-can-let-the-folder-go.test.ts
@@ -65,7 +65,7 @@ const removeButton = () => screen.queryByTestId('codex-remove-folder')
beforeEach(() => {
useCodexStore.setState({ workingDirectory: '', threads: {}, sendsInFlight: 0 })
useGenerationStore.setState({ generating: {} })
- useAgentLoopStore.setState({ loop: null })
+ useAgentLoopStore.setState({ loops: {} })
useAgentModeStore.setState({ workspaces: {} })
useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS } })
useChatStore.setState({ conversations: [], activeConversationId: null })
@@ -164,7 +164,7 @@ describe('the header shows the folder, so it also gives it back', () => {
it('is locked between two loop passes as well', async () => {
act(() => useCodexStore.getState().setWorkingDirectory(WINDOWS_PATH))
useAgentLoopStore.setState({
- loop: { conversationId: 'conv-1', pass: 2, cap: 0, task: 'go', intervalMs: 30000, nextAt: 0 },
+ loops: { 'conv-1': { conversationId: 'conv-1', pass: 2, cap: 0, task: 'go', intervalMs: 30000, nextAt: 0 } },
})
await show()
expect((removeButton() as HTMLButtonElement).getAttribute('title')).toContain('loop')
diff --git a/src/components/chat/__tests__/the-working-directory-can-be-removed.test.ts b/src/components/chat/__tests__/the-working-directory-can-be-removed.test.ts
index e7467824..ea82f47f 100644
--- a/src/components/chat/__tests__/the-working-directory-can-be-removed.test.ts
+++ b/src/components/chat/__tests__/the-working-directory-can-be-removed.test.ts
@@ -66,7 +66,7 @@ const A_STANDING_LOOP = {
beforeEach(() => {
useCodexStore.setState({ workingDirectory: '', threads: {}, sendsInFlight: 0 })
useGenerationStore.setState({ generating: {} })
- useAgentLoopStore.setState({ loop: null })
+ useAgentLoopStore.setState({ loops: {} })
useAgentModeStore.setState({ workspaces: {} })
useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS } })
useUIStore.setState({ explorerCollapsed: false })
@@ -272,7 +272,7 @@ describe('a run in flight holds it', () => {
useCodexStore.getState().setWorkingDirectory(WINDOWS_PATH)
useCodexStore.getState().initThread('conv-1', WINDOWS_PATH)
})
- useAgentLoopStore.setState({ loop: A_STANDING_LOOP })
+ useAgentLoopStore.setState({ loops: { 'conv-1': A_STANDING_LOOP } })
show()
const button = removeButton() as HTMLButtonElement
expect(button.disabled).toBe(true)
diff --git a/src/hooks/__tests__/agentLoopStore-zwei-unterhaltungen-teilen-sich-keinen-platz.test.ts b/src/hooks/__tests__/agentLoopStore-zwei-unterhaltungen-teilen-sich-keinen-platz.test.ts
new file mode 100644
index 00000000..a8685514
--- /dev/null
+++ b/src/hooks/__tests__/agentLoopStore-zwei-unterhaltungen-teilen-sich-keinen-platz.test.ts
@@ -0,0 +1,140 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * B2 Commit 3: `/loop` in conversation A must survive a Stop pressed while
+ * viewing conversation B.
+ *
+ * Before this, `useAgentLoopStore` held a single `loop: ActiveLoop | null`
+ * slot for the WHOLE app, and `stopAgent()` called `.clear()` unconditionally
+ * on every press — there was only one slot to clear, so any Stop, anywhere,
+ * wiped whatever loop happened to be standing, including one running in a
+ * completely different, still-live conversation. This did not need two loops
+ * running at once to break: pressing Stop in an idle conversation B while A's
+ * `/loop` was parked between passes already destroyed A's entry.
+ *
+ * Run: npx vitest run src/hooks/__tests__/agentLoopStore-zwei-unterhaltungen-teilen-sich-keinen-platz.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 { useChat } from '../useChat'
+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'
+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'
+
+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' },
+ })
+
+/** A turn that ends the pass (text, no tool call) so the /loop driver gets
+ * to schedule the next one — same shape as stopp-beendet-den-agentenlauf. */
+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
+}
+
+const warte = (ms: number) => new Promise((r) => setTimeout(r, ms))
+
+beforeEach(() => {
+ 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('a loop belongs to its own conversation, not to whichever Stop was last pressed', () => {
+ it('Stop pressed while viewing B leaves a loop standing in A untouched', async () => {
+ const convA = seed()
+ const convB = seed()
+
+ 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(() => useChat())
+
+ // Pass 1 in A: ends in text, so the driver parks a loop for A and
+ // schedules pass 2 on the interval timer.
+ useChatStore.getState().setActiveConversation(convA)
+ await act(async () => { await result.current.sendMessage('/loop 5s zaehle weiter') })
+ expect(useAgentLoopStore.getState().loops[convA]?.conversationId).toBe(convA)
+
+ // The user switches to a second, completely unrelated conversation and
+ // presses Stop there — a conversation with nothing running at all.
+ useChatStore.getState().setActiveConversation(convB)
+ act(() => { result.current.stopGeneration() })
+ await act(async () => { await warte(20) })
+
+ // A's loop is still standing: a Stop for B must not reach it.
+ expect(useAgentLoopStore.getState().loops[convA]?.conversationId).toBe(convA)
+ expect(isRunStopped(convA)).toBe(false)
+ })
+
+ it('COUNTER-CHECK: Stop pressed while VIEWING A does end A\'s loop', async () => {
+ const convA = seed()
+
+ 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(() => useChat())
+
+ useChatStore.getState().setActiveConversation(convA)
+ await act(async () => { await result.current.sendMessage('/loop 5s zaehle weiter') })
+ expect(useAgentLoopStore.getState().loops[convA]).toBeDefined()
+
+ act(() => { result.current.stopGeneration() })
+ await act(async () => { await warte(20) })
+
+ expect(useAgentLoopStore.getState().loops[convA]).toBeUndefined()
+ expect(isRunStopped(convA)).toBe(true)
+ })
+})
diff --git a/src/hooks/__tests__/loop-stops-on-terminal.test.ts b/src/hooks/__tests__/loop-stops-on-terminal.test.ts
index f9fd6215..62440380 100644
--- a/src/hooks/__tests__/loop-stops-on-terminal.test.ts
+++ b/src/hooks/__tests__/loop-stops-on-terminal.test.ts
@@ -53,7 +53,9 @@ describe.each([
it('it clears the loop store, or the bar keeps promising a pass nobody runs', () => {
const block = src.slice(src.indexOf(guard), src.indexOf(guard) + 700)
- expect(block).toContain('useAgentLoopStore.getState().clear()')
+ // B2: clear() takes the conversation id (the store is per conversation
+ // now), so this also pins that the right run's loop is the one cleared.
+ expect(block).toMatch(/useAgentLoopStore\.getState\(\)\.clear\(convId\)/)
})
it('and says once why it stopped', () => {
diff --git a/src/hooks/__tests__/stopp-beendet-den-agentenlauf.test.ts b/src/hooks/__tests__/stopp-beendet-den-agentenlauf.test.ts
index 3e5b1e5a..6d4f1573 100644
--- a/src/hooks/__tests__/stopp-beendet-den-agentenlauf.test.ts
+++ b/src/hooks/__tests__/stopp-beendet-den-agentenlauf.test.ts
@@ -141,7 +141,7 @@ beforeEach(() => {
__resetRunStopsForTests()
useChatStore.setState({ conversations: [], activeConversationId: null })
useAgentTaskStore.setState({ byConv: {} })
- useAgentLoopStore.setState({ loop: null })
+ useAgentLoopStore.setState({ loops: {} })
useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
useAgentModeStore.setState({ agentModeActive: {} })
useTodoStore.setState({ byConversation: {}, updatedAt: {} })
@@ -247,14 +247,14 @@ describe('Stop, gemessen in Anfragen an die Wolke', () => {
await act(async () => { await result.current.sendMessage('/loop 1s zaehle weiter') })
// Pass 1 ist durch, Pass 2 haengt am Zeitgeber, die Leiste steht.
expect(zaehler.n()).toBe(1)
- expect(useAgentLoopStore.getState().loop?.conversationId).toBe(convId)
+ expect(useAgentLoopStore.getState().loops[convId]?.conversationId).toBe(convId)
act(() => { result.current.stopGeneration() })
await act(async () => { await warte(1500) })
// Die Zahl zuerst, denn sie ist die Rechnung.
expect(zaehler.n()).toBe(1)
- expect(useAgentLoopStore.getState().loop).toBeNull()
+ expect(useAgentLoopStore.getState().loops[convId]).toBeUndefined()
expect(isRunStopped(convId)).toBe(true)
})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 45173955..d609df49 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -2547,7 +2547,7 @@ export function useAgentChat() {
if (opts?.loop && convId && loopHalt) {
// Same rule as the coding surface: no retry fixes an empty wallet, so
// the loop ends here instead of refiring into the same refusal.
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convId)
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'assistant', timestamp: Date.now(),
content: `The loop stopped because the run was ${loopHalt}. Start it again once that is sorted.`,
@@ -2559,9 +2559,9 @@ export function useAgentChat() {
const nextPass = loopState.pass + 1
if (saidDone) {
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convId)
} else if (cap > 0 && nextPass > cap) {
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convId)
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'assistant', timestamp: Date.now(),
content: `Stopped after ${cap} passes, which is the limit set in Settings. What is above is where it got to. Raise the limit or set it to unlimited to keep going.`,
@@ -2578,11 +2578,11 @@ export function useAgentChat() {
// A skipped pass clears the loop store too (audit A3) — leaving
// it standing painted a LoopBar promising a pass that never came.
if (runningRef.current) {
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convForLoop)
return
}
if (useChatStore.getState().activeConversationId !== convForLoop) {
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convForLoop)
return
}
void sendRef.current?.(buildLoopRecheck(loopState.task, nextPass), undefined, {
@@ -2622,7 +2622,7 @@ export function useAgentChat() {
clearTimeout(agentLoopTimer)
agentLoopTimer = null
}
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(stoppedConvId ?? '')
// NUR den eigenen Lauf. `runningRef`, `abortRef` und `isAgentRunning`
// gehoeren der Hook-Instanz, nicht der Unterhaltung; ohne diese Bedingung
// beendete Stop in einer zweiten Unterhaltung den Agentenlauf der ersten
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 2f975bd4..c8e000bd 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -2467,7 +2467,7 @@ export function useCodex() {
// Stop the loop where the refusal happened, and say so once. Silently
// dropping it would leave the LoopBar promising a pass nobody is going
// to run (audit A3).
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convId)
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'assistant', timestamp: Date.now(),
content: `The loop stopped because the run was ${loopHalt}. Start it again once that is sorted.`,
@@ -2480,9 +2480,9 @@ export function useCodex() {
if (saidDone) {
// Nothing to do — the marker is stripped from the display by
// cleanCodexText, so the user just sees the answer.
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convId)
} else if (cap > 0 && nextPass > cap) {
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convId)
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'assistant', timestamp: Date.now(),
content: `Stopped after ${cap} passes, which is the limit set in Settings. What is above is where it got to. Raise the limit or set it to unlimited to keep going.`,
@@ -2500,11 +2500,11 @@ export function useCodex() {
// Clear the loop store too — leaving it standing painted a LoopBar
// that promised a pass which was never coming (audit A3).
if (runningRef.current) {
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convForLoop)
return
}
if (useChatStore.getState().activeConversationId !== convForLoop) {
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(convForLoop)
return
}
// The Code view is not on screen (other chat mode, other view):
@@ -2574,7 +2574,7 @@ export function useCodex() {
clearTimeout(codexLoopTimer)
codexLoopTimer = null
}
- useAgentLoopStore.getState().clear()
+ useAgentLoopStore.getState().clear(stoppedConvId ?? '')
// NUR wenn der Controller dieser Instanz auch zu DIESER Unterhaltung
// gehoert. Gehoert er woanders hin, hat `abortConversation` oben schon den
// richtigen Griff gezogen, und der Lauf in der anderen Unterhaltung laeuft
diff --git a/src/lib/__tests__/background-shutdown.test.ts b/src/lib/__tests__/background-shutdown.test.ts
index 1c465672..75e12494 100644
--- a/src/lib/__tests__/background-shutdown.test.ts
+++ b/src/lib/__tests__/background-shutdown.test.ts
@@ -79,7 +79,7 @@ function wartenderLoopPass(convId: string): void {
beforeEach(() => {
useAgentTaskStore.setState({ byConv: {} })
useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
- useAgentLoopStore.setState({ loop: null })
+ useAgentLoopStore.setState({ loops: {} })
useBackgroundShutdownStore.setState({ notice: null })
__resetRunStopsForTests()
__resetBackgroundShutdownForTests()
@@ -138,7 +138,7 @@ describe('stopAllBackgroundWork: reach (Runde 2, Blocker 2)', () => {
stopAllBackgroundWork()
- expect(useAgentLoopStore.getState().loop).toBeNull()
+ expect(useAgentLoopStore.getState().loops).toEqual({})
expect(isRunStopped('conv-loop')).toBe(true)
})
@@ -151,7 +151,7 @@ describe('stopAllBackgroundWork: reach (Runde 2, Blocker 2)', () => {
expect(task.signal.aborted).toBe(true)
expect(strom.aborted()).toBe(true)
- expect(useAgentLoopStore.getState().loop).toBeNull()
+ expect(useAgentLoopStore.getState().loops).toEqual({})
expect(isRunStopped('conv-task')).toBe(true)
expect(isRunStopped('conv-stream')).toBe(true)
expect(isRunStopped('conv-loop')).toBe(true)
diff --git a/src/lib/__tests__/readonly-enforcement.test.ts b/src/lib/__tests__/readonly-enforcement.test.ts
index 9c984589..160262a4 100644
--- a/src/lib/__tests__/readonly-enforcement.test.ts
+++ b/src/lib/__tests__/readonly-enforcement.test.ts
@@ -185,7 +185,10 @@ describe('/loop actually loops', () => {
// Unlimited is only defensible if the user can see it and stop it.
for (const f of ['../../hooks/useCodex.ts', '../../hooks/useAgentChat.ts']) {
expect(read(f)).toContain('useAgentLoopStore.getState().start(')
- expect(read(f)).toContain('useAgentLoopStore.getState().clear()')
+ // B2: clear() takes the conversation id now — a bare `clear()` with no
+ // argument doesn't compile any more (the store is per conversation),
+ // so this also pins that Stop names WHICH conversation's loop it ends.
+ expect(read(f)).toMatch(/useAgentLoopStore\.getState\(\)\.clear\([^)]+\)/)
}
})
diff --git a/src/lib/background-shutdown.ts b/src/lib/background-shutdown.ts
index c46c19f2..cf17d09a 100644
--- a/src/lib/background-shutdown.ts
+++ b/src/lib/background-shutdown.ts
@@ -58,19 +58,17 @@ export function stopAllBackgroundWork(): void {
const ids = new Set<string>()
for (const convId of Object.keys(useAgentTaskStore.getState().byConv)) ids.add(convId)
for (const convId of Object.keys(useGenerationStore.getState().generating)) ids.add(convId)
- const loopConvId = useAgentLoopStore.getState().loop?.conversationId
- if (loopConvId) ids.add(loopConvId)
+ // Per Konversation seit B2 Commit 3 (davor war das ein einziger globaler
+ // Platz): jede Konversation mit einem wartenden /loop-Pass zaehlt, nicht
+ // nur eine.
+ for (const convId of Object.keys(useAgentLoopStore.getState().loops)) ids.add(convId)
for (const convId of ids) {
useAgentTaskStore.getState().cancelAll(convId)
useGenerationStore.getState().abortConversation(convId)
stopRun(convId)
+ useAgentLoopStore.getState().clear(convId)
}
- // Der Zeitgeber eines wartenden /loop-Passes haengt nicht an einer
- // Konversation im Speicher, sondern am globalen Store (bis B2 Commit 3
- // dieser Zweigarbeit ihn je Konversation fuehrt) - darum eigens geraeumt,
- // nicht durch die Schleife oben erfasst.
- if (loopConvId) useAgentLoopStore.getState().clear()
}
/**
diff --git a/src/stores/agentLoopStore.ts b/src/stores/agentLoopStore.ts
index 29ce6e02..e4de4118 100644
--- a/src/stores/agentLoopStore.ts
+++ b/src/stores/agentLoopStore.ts
@@ -1,11 +1,22 @@
/**
- * The currently running `/loop`, so it is never invisible.
+ * The currently running `/loop`s, so none of them is ever invisible.
*
* A loop has no built-in pass ceiling by design: if someone asks it to keep
* going, it keeps going until it says done or they stop it. That is only
* defensible if the user can always SEE that a loop is live, which pass it is
* on, and stop it in one click. Hence this store and the bar it feeds.
*
+ * ── B2: PER CONVERSATION, NOT ONE GLOBAL SLOT ─────────────────────────────
+ *
+ * This used to hold a single `loop: ActiveLoop | null`. `stopAgent` /
+ * `stopCodex` called `clear()` unconditionally, on EVERY Stop press,
+ * regardless of which conversation the press was for — because there was
+ * only ever one slot to clear. A `/loop` in conversation A died the moment
+ * the user pressed Stop in conversation B: not a rare race, a guaranteed
+ * outcome of two conversations ever running a loop "at the same time" (one
+ * of them waiting out its interval counts). See
+ * agentLoopStore.two-loops-do-not-share-a-slot.test.ts.
+ *
* Runtime only — a loop does not survive a restart, and pretending otherwise
* by persisting it would leave a dead loop on screen after a crash.
*/
@@ -25,13 +36,45 @@ export interface ActiveLoop {
}
interface AgentLoopState {
- loop: ActiveLoop | null
+ /** conversationId → its own active loop. Absent = no loop standing there. */
+ loops: Record<string, ActiveLoop>
start: (loop: ActiveLoop) => void
- clear: () => void
+ /** Clears ONLY this conversation's loop. A bare `clear()` with no id would
+ * reintroduce the single-slot bug this store exists to end — there is no
+ * overload for it. */
+ clear: (conversationId: string) => void
}
export const useAgentLoopStore = create<AgentLoopState>((set) => ({
- loop: null,
- start: (loop) => set({ loop }),
- clear: () => set({ loop: null }),
+ loops: {},
+ start: (loop) =>
+ set((state) => ({ loops: { ...state.loops, [loop.conversationId]: loop } })),
+ clear: (conversationId) =>
+ set((state) => {
+ if (!conversationId || !state.loops[conversationId]) return state
+ const next = { ...state.loops }
+ delete next[conversationId]
+ return { loops: next }
+ }),
}))
+
+/** The loop of ONE conversation, or `undefined`. For LoopBar, which shows
+ * only the ACTIVE conversation's own loop — a loop running elsewhere must
+ * not paint this bar or steal its Stop button. */
+export function useConversationLoop(conversationId: string | null | undefined): ActiveLoop | undefined {
+ return useAgentLoopStore((s) => (conversationId ? s.loops[conversationId] : undefined))
+}
+
+/**
+ * Is ANY conversation's loop running right now, anywhere?
+ *
+ * For the Coding Agent's working-directory lock (codexBusyReason): the
+ * folder is a single GLOBAL value shared by every Codex conversation (A8,
+ * 2.6.8 — "moving it mid-run would send the next turn somewhere the user is
+ * not looking"), so a loop in a DIFFERENT conversation still writes through
+ * that same folder and still must not have it yanked out from under it. This
+ * is deliberately NOT scoped to the active conversation, unlike LoopBar.
+ */
+export function useAnyAgentLoopActive(): boolean {
+ return useAgentLoopStore((s) => Object.keys(s.loops).length > 0)
+}