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): loop-Zeitgeber prueft isRunStopped vor dem Feuern

purpledb3d50dbc392
diff --git a/src/hooks/__tests__/loop-pass-ueberlebt-stopAllBackgroundWork-nicht.test.ts b/src/hooks/__tests__/loop-pass-ueberlebt-stopAllBackgroundWork-nicht.test.ts
new file mode 100644
index 00000000..03b49133
--- /dev/null
+++ b/src/hooks/__tests__/loop-pass-ueberlebt-stopAllBackgroundWork-nicht.test.ts
@@ -0,0 +1,148 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Blocker 3 (review-lanes.md, Runde 3): ein wartender /loop-Pass ueberlebt
+ * Abmelden und Fenster schliessen.
+ *
+ * `stopAllBackgroundWork()` (`lib/background-shutdown.ts`) raeumt den
+ * SPEICHER des /loop auf (`useAgentLoopStore.clear`), aber nicht den
+ * Browser-Zeitgeber: die Zeitgeber liegen in `agentLoopTimers`
+ * (`useAgentChat.ts`) und `codexLoopTimers` (`useCodex.ts`), und bisher
+ * loeschten nur `stopAgent`/`stopCodex` sie. Der faellige Rueckruf pruefte
+ * beim Feuern nur, ob DIESE Unterhaltung schon etwas generiert und ob sie die
+ * sichtbare ist — nicht, ob der Nutzer den Lauf per Stop-Merker
+ * (`lib/run-stop.ts`) beendet hat. Nach Abmelden, Fenster schliessen oder App
+ * beenden feuerte der Zeitgeber also trotzdem und schickte eine bezahlte
+ * Cloud-Anfrage in eine Sitzung, die die App dem Nutzer bereits als beendet
+ * gezeigt hatte.
+ *
+ * Fix: `isRunStopped(convForLoop)` als ERSTE Pruefung in beiden
+ * `fireLoopPass`-Rueckrufen, noch vor dem bestehenden
+ * generating/sichtbar-Check.
+ *
+ * Dieser Test faehrt mit Fake-Timern: /loop starten, den Zeitgeber wirklich
+ * REGISTRIEREN lassen (Pass 1 laeuft echt durch), `stopAllBackgroundWork()`
+ * rufen (derselbe Pfad wie Abmelden/Fenster schliessen/App beenden), dann
+ * den Zeitgeber vorspulen. Der Fetch-Zaehler muss bei 1 (dem ersten,
+ * bereits gelaufenen Pass) stehen bleiben statt auf 2 zu steigen.
+ *
+ * Run: npx vitest run src/hooks/__tests__/loop-pass-ueberlebt-stopAllBackgroundWork-nicht.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'
+import { stopAllBackgroundWork } from '../../lib/background-shutdown'
+
+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' },
+ })
+// Never says the /loop magic-done word, so the driver always schedules
+// another pass — that is what gives Blocker 3 something real to prevent.
+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.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+describe('ein wartender /loop-Pass ueberlebt stopAllBackgroundWork() nicht', () => {
+ it('nach Abmelden/Fenster-schliessen/App-beenden (stopAllBackgroundWork) geht keine weitere Anfrage raus, wenn der Zeitgeber vorgespult wird', async () => {
+ let calls = 0
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
+ const url = String(input)
+ if (!url.includes('/chat/completions')) return new Response('{}', { status: 200 })
+ calls++
+ return textZug()
+ })
+
+ vi.useFakeTimers()
+ try {
+ const { result } = renderHook(() => useChat())
+ const convA = seed()
+
+ // Pass 1: runs for real, ends without the done-marker, so the driver
+ // schedules pass 2 on a real setTimeout held in agentLoopTimers.
+ await act(async () => {
+ await result.current.sendMessage('/loop 30s zaehle weiter')
+ })
+ expect(calls).toBe(1)
+ expect(__pendingAgentLoopTimersForTests()).toContain(convA)
+ expect(useAgentLoopStore.getState().loops[convA]).toBeDefined()
+
+ // The trigger this test stands in for: sign-out, window close, app
+ // quit. Clears the loop STORE, but that alone is not what a real
+ // browser setTimeout obeys.
+ act(() => { stopAllBackgroundWork() })
+ expect(useAgentLoopStore.getState().loops[convA]).toBeUndefined()
+
+ // Fast-forward well past pass 2's due time.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(31_000)
+ })
+
+ // The fix: no second request left the process.
+ expect(calls).toBe(1)
+ // And the timer map itself is clean, not just quiet this once.
+ expect(__pendingAgentLoopTimersForTests()).not.toContain(convA)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+})
diff --git a/src/hooks/__tests__/stop-dann-sofort-neu-senden-macht-lauf-2-unstoppbar.test.ts b/src/hooks/__tests__/stop-dann-sofort-neu-senden-macht-lauf-2-unstoppbar.test.ts
index 19dbe762..30f14e07 100644
--- a/src/hooks/__tests__/stop-dann-sofort-neu-senden-macht-lauf-2-unstoppbar.test.ts
+++ b/src/hooks/__tests__/stop-dann-sofort-neu-senden-macht-lauf-2-unstoppbar.test.ts
@@ -14,7 +14,7 @@
* 1. Lauf A startet, registriert seinen Abbrecher unter `convId` in
* `generationStore.aborters` (Zeile 784).
* 2. Nutzer drueckt Stop. `stopAgent` bricht A's `AbortController` ab und
- * loescht A sofort aus `activeAgentRuns` — aber NICHT aus
+ * loescht A sofort aus `activeAgentRuns`, aber NICHT aus
* `generationStore.aborters`, das raeumt erst A's eigenes `finally` auf.
* 3. Nutzer sendet SOFORT neu, bevor A's `finally` gelaufen ist (unter
* Last braucht `endTurnDurably` 323-545 ms, siehe stores/durability.ts).
@@ -89,7 +89,7 @@ function controllableSSE() {
},
// Real fetch rejects a request's stream when its AbortSignal fires; this
// mock does not do that automatically (unlike the browser), so the test
- // controls the moment by hand instead — that IS the "verspaetetes
+ // controls the moment by hand instead; that IS the "verspaetetes
// finally" window Blocker 2 describes, made deterministic.
error(err: unknown) {
controller.error(err)
@@ -171,7 +171,7 @@ describe('Stop, dann sofort neu senden auf derselben Unterhaltung', () => {
expect(callsA).toBe(1)
expect(useGenerationStore.getState().aborters[convA]).toBeDefined()
- // Stop run 1 — deletes it from activeAgentRuns and aborts its
+ // Stop run 1: deletes it from activeAgentRuns and aborts its
// AbortController synchronously, but generationStore.aborters[convA]
// still holds run 1's (now-stale) aborter; only run 1's OWN finally
// clears that, and it has not run yet (the stream has not errored).
@@ -192,7 +192,7 @@ describe('Stop, dann sofort neu senden auf derselben Unterhaltung', () => {
// NOW run 1's stream actually fails (the abort finally reaches the
// fetch/reader), so its `finally` runs LATE, after run 2 is already
- // registered — the exact race Blocker 2 describes.
+ // registered, the exact race Blocker 2 describes.
await act(async () => {
streamA.error(new DOMException('The operation was aborted.', 'AbortError'))
await runA.catch(() => {})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index e36afeb6..a921184a 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -2667,6 +2667,19 @@ export function useAgentChat() {
})
agentLoopTimers.set(convForLoop, setTimeout(() => {
agentLoopTimers.delete(convForLoop)
+ // Blocker 3 (review-lanes.md): stopAllBackgroundWork() (sign-out,
+ // window close, app quit) clears the loop STORE via
+ // useAgentLoopStore.clear, but this timer lives in a module Map
+ // it never touches; clearTimeout only happens inside stopAgent.
+ // Without this check, a pass whose interval elapses AFTER the
+ // user signed out fired a real paid request into a session the
+ // app had already told the user it ended. isRunStopped is the
+ // same sticky per-conversation flag stopAllBackgroundWork sets
+ // via stopRun(), so it is exactly what survives here.
+ if (isRunStopped(convForLoop)) {
+ useAgentLoopStore.getState().clear(convForLoop)
+ return
+ }
// A skipped pass clears the loop store too (audit A3) — leaving
// it standing painted a LoopBar promising a pass that never came.
//
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 7f29dd0d..1894904d 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -2504,6 +2504,19 @@ export function useCodex() {
})
const fireLoopPass = () => {
codexLoopTimers.delete(convForLoop)
+ // Blocker 3 (review-lanes.md): stopAllBackgroundWork() (sign-out,
+ // window close, app quit) clears the loop STORE via
+ // useAgentLoopStore.clear, but this timer lives in a module Map
+ // it never touches, and the 5s self-extension below (Code tab
+ // not visible) can keep re-arming it past that point too.
+ // isRunStopped is the same sticky per-conversation flag
+ // stopAllBackgroundWork sets via stopRun(), checked first so a
+ // due pass never fires a real request into a session the app
+ // already told the user it ended.
+ if (isRunStopped(convForLoop)) {
+ useAgentLoopStore.getState().clear(convForLoop)
+ return
+ }
// Bail if THIS conversation is already generating something else
// meanwhile (a manual send raced the timer). Clear the loop store
// too, leaving it standing painted a LoopBar that promised a pass