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(agent): Schleifenzeitgeber je Lauf statt modulweit
purplebeb90d45ed99
diff --git a/src/hooks/__tests__/loop-stops-on-terminal.test.ts b/src/hooks/__tests__/loop-stops-on-terminal.test.tsindex 62440380..340f3b38 100644--- a/src/hooks/__tests__/loop-stops-on-terminal.test.ts+++ b/src/hooks/__tests__/loop-stops-on-terminal.test.ts@@ -26,8 +26,8 @@ const codex = readFileSync(resolve(here, '../useCodex.ts'), 'utf8')const agent = readFileSync(resolve(here, '../useAgentChat.ts'), 'utf8')describe.each([- ['the coding surface', codex, 'loopState && convId && loopHalt', 'codexLoopTimer = setTimeout('],- ['the agent surface', agent, 'opts?.loop && convId && loopHalt', 'agentLoopTimer = setTimeout('],+ ['the coding surface', codex, 'loopState && convId && loopHalt', 'codexLoopTimers.set(convForLoop, setTimeout('],+ ['the agent surface', agent, 'opts?.loop && convId && loopHalt', 'agentLoopTimers.set(convForLoop, setTimeout('],])('%s', (_name, src, guard, scheduler) => {it('declares the halt per run, so one refusal cannot poison the next loop', () => {expect(src).toContain('let loopHalt: string | null = null')diff --git a/src/hooks/__tests__/loop-timer-je-unterhaltung.test.ts b/src/hooks/__tests__/loop-timer-je-unterhaltung.test.tsnew file mode 100644index 00000000..9f2b6782--- /dev/null+++ b/src/hooks/__tests__/loop-timer-je-unterhaltung.test.ts@@ -0,0 +1,146 @@+/**+ * @vitest-environment jsdom+ *+ * B2 Commit 4: the pending `/loop` timer belongs to its OWN conversation, not+ * to whichever conversation last scheduled one.+ *+ * Before this, `agentLoopTimer` (useAgentChat.ts) and `codexLoopTimer`+ * (useCodex.ts) were each a single module VARIABLE. Conversation A schedules+ * its next pass and gets a handle; conversation B schedules ITS next pass+ * and OVERWRITES the same variable with its own handle. Two consequences,+ * both real:+ *+ * - The two timers cannot coexist as far as the app can see: asking "is a+ * pass still pending for A" after B scheduled one always answered with+ * B's handle, never A's — there was only ever one answer for the whole+ * app, not one per conversation.+ * - Stop pressed for A, while B's handle is the one currently held, clears+ * B's real browser timer by mistake and leaves A's own timer orphaned —+ * unreachable, but still counting down on its own, because a JS timer+ * fires independently of whether anything still references its id.+ *+ * A real fetch-count race is fought over by a SEPARATE, pre-existing rule+ * (a pass whose conversation is not the visible one is deferred/dropped, see+ * useAgentChat.ts and useCodex.ts), so counting `/chat/completions` calls+ * here would prove that rule instead of this one. This file asks the+ * question directly instead, through a test-only peek at the timer map's+ * own keys — the same shape of proof `run-lanes.ts`'s and `run-stop.ts`'s+ * own tests use for module-private state.+ *+ * Run: npx vitest run src/hooks/__tests__/loop-timer-je-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 { useChat } from '../useChat'+import { __pendingAgentLoopTimersForTests } 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'++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('a pending loop timer belongs to its own conversation', () => {+ it('two conversations each hold their own pending timer at once', 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(() => useChat())+ const convA = seed()+ await act(async () => { await result.current.sendMessage('/loop 1s zaehle weiter') })+ const convB = seed()+ await act(async () => { await result.current.sendMessage('/loop 1s zaehle weiter') })++ // Both pending at once — a single shared variable could only ever have+ // shown the LATER of the two.+ const pending = __pendingAgentLoopTimersForTests()+ expect(pending).toContain(convA)+ expect(pending).toContain(convB)+ })++ it("stopping A cancels only A's timer; B's stays pending, untouched", 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(() => useChat())+ const convA = seed()+ await act(async () => { await result.current.sendMessage('/loop 1s zaehle weiter') })+ const convB = seed()+ await act(async () => { await result.current.sendMessage('/loop 1s zaehle weiter') })+ expect(__pendingAgentLoopTimersForTests()).toContain(convA)+ expect(__pendingAgentLoopTimersForTests()).toContain(convB)++ // View is on B right now (seed() switched it there); go back to A and+ // press Stop there. B was the LAST conversation to schedule a timer —+ // exactly the shape that clobbered a shared module variable before.+ useChatStore.getState().setActiveConversation(convA)+ act(() => { result.current.stopGeneration() })++ const pending = __pendingAgentLoopTimersForTests()+ expect(pending).not.toContain(convA)+ expect(pending).toContain(convB)+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex d609df49..2f086b6b 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -111,12 +111,25 @@ import { buildChatSystemPrompt } from '../lib/system-prompt'// ── Hook ──────────────────────────────────────────────────────/**- * The pending next /loop pass. MODULE scope, not a hook ref (audit A3): the- * chat view unmounts on a view switch, and a timer parked in an unmounted- * instance's ref was unreachable for the remounted hook — stopAgent cleared- * its own (empty) ref while the old timer kept firing new passes.+ * The pending next /loop pass, PER CONVERSATION. MODULE scope, not a hook+ * ref (audit A3): the chat view unmounts on a view switch, and a timer+ * parked in an unmounted instance's ref was unreachable for the remounted+ * hook — stopAgent cleared its own (empty) ref while the old timer kept+ * firing new passes.+ *+ * B2: was a single module VARIABLE, not a map, until this commit. Two+ * conversations each waiting out a /loop interval shared the one handle —+ * the second conversation's `setTimeout` result overwrote the first's, and+ * `clearTimeout` on that overwritten handle canceled the WRONG conversation's+ * pending pass, while the one it meant to cancel kept its real timer running+ * untouched. Keyed by conversation now, the same shape as `agentLoopStore`.*/-let agentLoopTimer: ReturnType<typeof setTimeout> | null = null+const agentLoopTimers = new Map<string, ReturnType<typeof setTimeout>>()++/** Test-only: which conversations currently have a pending /loop timer. */+export function __pendingAgentLoopTimersForTests(): string[] {+ return [...agentLoopTimers.keys()]+}export function useAgentChat() {const [isAgentRunning, setIsAgentRunning] = useState(false)@@ -2573,8 +2586,8 @@ export function useAgentChat() {task: loopState.task, intervalMs: loopState.intervalMs,nextAt: Date.now() + loopState.intervalMs,})- agentLoopTimer = setTimeout(() => {- agentLoopTimer = null+ agentLoopTimers.set(convForLoop, setTimeout(() => {+ agentLoopTimers.delete(convForLoop)// 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) {@@ -2589,7 +2602,7 @@ export function useAgentChat() {displayContent: cap > 0 ? `pass ${nextPass} of ${cap}` : `pass ${nextPass}`,loop: { ...loopState, pass: nextPass },})- }, loopState.intervalMs)+ }, loopState.intervalMs))}}}@@ -2618,9 +2631,14 @@ export function useAgentChat() {// Unterhaltung ab (siehe agentTaskStore.ts), derselbe Griff wie der// "Stop all"-Knopf im Aufgabenpanel.useAgentTaskStore.getState().cancelAll(stoppedConvId ?? '')- if (agentLoopTimer) {- clearTimeout(agentLoopTimer)- agentLoopTimer = null+ // Nur DIESER Unterhaltung Zeitgeber - ein Stop in B darf den wartenden+ // Pass von A nicht treffen (B2 Commit 4, derselbe Fehler wie beim+ // vorherigen einzelnen `agentLoopTimer`, nur beim Zeitgeber statt beim+ // Store).+ const pendingLoopTimer = agentLoopTimers.get(stoppedConvId ?? '')+ if (pendingLoopTimer) {+ clearTimeout(pendingLoopTimer)+ agentLoopTimers.delete(stoppedConvId ?? '')}useAgentLoopStore.getState().clear(stoppedConvId ?? '')// NUR den eigenen Lauf. `runningRef`, `abortRef` und `isAgentRunning`diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex c8e000bd..4ea97acf 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -247,13 +247,25 @@ function codexEffort(model: string): { levels?: string[]; fallback?: string } {}/**- * The pending next /loop pass. MODULE scope, not a hook ref (audit A3): the- * Code view unmounts on every tab switch, and a timer parked in an unmounted- * instance's ref was unreachable for the remounted hook — stopCodex cleared- * its own (empty) ref while the old timer kept firing new passes. One shared- * handle means whichever instance is alive can cancel the pending pass.+ * The pending next /loop pass, PER CONVERSATION. MODULE scope, not a hook+ * ref (audit A3): the Code view unmounts on every tab switch, and a timer+ * parked in an unmounted instance's ref was unreachable for the remounted+ * hook — stopCodex cleared its own (empty) ref while the old timer kept+ * firing new passes.+ *+ * B2: was a single module variable until this commit, so two Code+ * conversations each waiting out a /loop interval shared one handle — the+ * second overwrote the first, and stopping either one cleared the wrong+ * conversation's timer while the intended one kept running. Keyed by+ * conversation now, same shape as `agentLoopStore` and the Chat-side+ * `agentLoopTimers` (useAgentChat.ts).*/-let codexLoopTimer: ReturnType<typeof setTimeout> | null = null+const codexLoopTimers = new Map<string, ReturnType<typeof setTimeout>>()++/** Test-only: which conversations currently have a pending /loop timer. */+export function __pendingCodexLoopTimersForTests(): string[] {+ return [...codexLoopTimers.keys()]+}export function useCodex() {const [isRunning, setIsRunning] = useState(false)@@ -2495,7 +2507,7 @@ export function useCodex() {nextAt: Date.now() + loopState.intervalMs,})const fireLoopPass = () => {- codexLoopTimer = null+ codexLoopTimers.delete(convForLoop)// Bail if the user moved on or started something else meanwhile.// Clear the loop store too — leaving it standing painted a LoopBar// that promised a pass which was never coming (audit A3).@@ -2513,7 +2525,7 @@ export function useCodex() {// cancel, so peeking at Create doesn't kill a standing loop; the// pass fires within 5 s of the view coming back.if (useCodexStore.getState().chatMode !== 'codex') {- codexLoopTimer = setTimeout(fireLoopPass, 5000)+ codexLoopTimers.set(convForLoop, setTimeout(fireLoopPass, 5000))return}void sendRef.current?.(buildLoopRecheck(loopState.task, nextPass), {@@ -2521,7 +2533,7 @@ export function useCodex() {loop: { ...loopState, pass: nextPass },})}- codexLoopTimer = setTimeout(fireLoopPass, loopState.intervalMs)+ codexLoopTimers.set(convForLoop, setTimeout(fireLoopPass, loopState.intervalMs))}}}@@ -2570,9 +2582,13 @@ export function useCodex() {// B1: cancels a delegate_task background agent too, see useAgentChat.ts.useAgentTaskStore.getState().cancelAll(stoppedConvId ?? '')useGenerationStore.getState().abortConversation(stoppedConvId)- if (codexLoopTimer) {- clearTimeout(codexLoopTimer)- codexLoopTimer = null+ // Nur DIESER Unterhaltung Zeitgeber (B2 Commit 4): sonst trifft ein Stop+ // in B den wartenden Pass von A, waehrend A's eigener Zeitgeber ungeruehrt+ // weiterlaeuft.+ const pendingLoopTimer = codexLoopTimers.get(stoppedConvId ?? '')+ if (pendingLoopTimer) {+ clearTimeout(pendingLoopTimer)+ codexLoopTimers.delete(stoppedConvId ?? '')}useAgentLoopStore.getState().clear(stoppedConvId ?? '')// NUR wenn der Controller dieser Instanz auch zu DIESER Unterhaltungdiff --git a/src/lib/__tests__/readonly-enforcement.test.ts b/src/lib/__tests__/readonly-enforcement.test.tsindex 160262a4..f3dfc8cc 100644--- a/src/lib/__tests__/readonly-enforcement.test.ts+++ b/src/lib/__tests__/readonly-enforcement.test.ts@@ -155,9 +155,11 @@ describe('/loop actually loops', () => {it('starts the NEXT pass after the interval instead of killing the run', () => {const src = read('../../hooks/useCodex.ts')// The handle is module-scoped since audit A3 — a hook ref died with the- // unmounted Code view, so stopCodex could not reach a pending pass.- expect(src).toContain('let codexLoopTimer:')- expect(src).toContain('codexLoopTimer = setTimeout(fireLoopPass, loopState.intervalMs)')+ // unmounted Code view, so stopCodex could not reach a pending pass. Per+ // conversation since B2 Commit 4 — a single shared handle let one+ // conversation's Stop cancel a DIFFERENT conversation's pending pass.+ expect(src).toContain('const codexLoopTimers = new Map<string, ReturnType<typeof setTimeout>>()')+ expect(src).toContain('codexLoopTimers.set(convForLoop, setTimeout(fireLoopPass, loopState.intervalMs))')expect(src).toContain('buildLoopRecheck(loopState.task, nextPass)')})@@ -202,7 +204,11 @@ describe('/loop actually loops', () => {// the callback's actual end survives any reflow inside the body.const src = read('../../hooks/useCodex.ts')const stopBody = extractUseCallbackBody(src, 'const stopCodex = useCallback(')- expect(stopBody).toContain('clearTimeout(codexLoopTimer)')+ // B2 Commit 4: the timer is per conversation, looked up by the id being+ // stopped, not a bare module variable — this proves Stop cancels the+ // handle that belongs to THIS conversation.+ expect(stopBody).toContain('codexLoopTimers.get(stoppedConvId')+ expect(stopBody).toMatch(/clearTimeout\(pendingLoopTimer\)/)// The stop is recorded MODULE-side, keyed by conversation (audit M1): a// hook-instance ref was invisible to the finally of a pass a previous// instance had started, so that finally re-armed the loop the user killed.