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): Aufraeumen im finally identitaetsgeprueft, Stop dann sofort neu senden
purple72eb5788fefa
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.tsnew file mode 100644index 00000000..19dbe762--- /dev/null+++ b/src/hooks/__tests__/stop-dann-sofort-neu-senden-macht-lauf-2-unstoppbar.test.ts@@ -0,0 +1,225 @@+/**+ * @vitest-environment jsdom+ *+ * Blocker 2 (review-lanes.md, Runde 3): Stop, dann sofort erneut senden auf+ * DERSELBEN Unterhaltung, macht den neuen Lauf unstoppbar.+ *+ * `activeAgentRuns` selbst war seit `25dd6a72` schon identitaetsgeprueft+ * (`if (activeAgentRuns.get(convId) === runState)`), aber drei Nachbarzeilen+ * im selben `finally` von `useAgentChat.ts` waren es nicht:+ * `useGenerationStore.getState().clearAborter(convId)`,+ * `useGenerationStore.getState().setGenerating(convId, false)` und+ * `drainApprovals(convId)`. Der Ablauf, den dieser Test nachstellt:+ *+ * 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+ * `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).+ * Lauf B registriert SEINEN Abbrecher unter demselben `convId`,+ * ueberschreibt A's Eintrag in `generationStore.aborters`.+ * 4. A's Stream fehlert jetzt erst wirklich (der abgebrochene Fetch+ * schlaegt fehl), A's `finally` laeuft.+ *+ * Ohne Identitaetspruefung wischt A's `finally` in Schritt 4 B's gerade erst+ * registrierten Abbrecher weg (`clearAborter`) und dreht B's `generating`+ * zurueck auf false, obwohl B noch laeuft. Der reale Schaden: der Stop-Knopf+ * (`useChat.ts`'s `stopGeneration`, alle fuenf B1-Ausloeser gehen ueber+ * `generationStore.abortConversation`, das genau diesen Abbrecher aufruft)+ * findet fuer B keinen Abbrecher mehr und tut NICHTS. B laeuft unbezahlbar+ * weiter.+ *+ * Dieser Test faehrt exakt diesen Pfad: nach dem verspaeteten `finally` von A+ * muss B's Abbrecher noch da sein, B's `generating`-Flag muss noch true+ * sein, UND ein echter zweiter Stop (`useGenerationStore.abortConversation`,+ * derselbe Weg wie `stopAllBackgroundWork`/`stopGeneration`) muss B's+ * laufenden Fetch tatsaechlich abbrechen.+ *+ * Run: npx vitest run src/hooks/__tests__/stop-dann-sofort-neu-senden-macht-lauf-2-unstoppbar.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'+import { stopAllBackgroundWork } from '../../lib/background-shutdown'+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'++const MODEL = 'lu-cloud::zai-org/GLM-5.3'++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()+ },+ // 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+ // finally" window Blocker 2 describes, made deterministic.+ error(err: unknown) {+ controller.error(err)+ },+ }+}++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()+ 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('Stop, dann sofort neu senden auf derselben Unterhaltung', () => {+ it('das verspaetete finally von Lauf 1 raeumt Lauf 2s Abbrecher/generating nicht weg, und Stop auf Lauf 2 wirkt wirklich', async () => {+ const convA = seed()++ const streamA = controllableSSE()+ const streamB = controllableSSE()+ let callsA = 0+ let callsB = 0+ let bAbortSeen = false++ 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 ?? '')+ const asStream = (s: ReturnType<typeof controllableSSE>) =>+ new Response(s.readable, { status: 200, headers: { 'content-type': 'text/event-stream' } })+ // 'task-2' FIRST: the resend carries the SAME conversation's history,+ // so its body contains BOTH 'task-1' (the earlier turn, still in the+ // transcript) and 'task-2' (the new one). Checking 'task-1' first+ // would wrongly route the resend into the already-locked streamA.+ if (body.includes('task-2')) {+ callsB+++ init?.signal?.addEventListener('abort', () => { bAbortSeen = true })+ return asStream(streamB)+ }+ if (body.includes('task-1')) {+ callsA+++ return asStream(streamA)+ }+ throw new Error('unexpected request body: ' + body.slice(0, 200))+ })++ const { result } = renderHook(() => useAgentChat())++ // Run 1: send, let it reach the point where it has registered its+ // aborter and is reading the stream.+ let runA!: Promise<void>+ await act(async () => {+ runA = result.current.sendAgentMessage('task-1')+ await tick()+ await tick()+ })+ expect(callsA).toBe(1)+ expect(useGenerationStore.getState().aborters[convA]).toBeDefined()++ // 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).+ let runB!: Promise<void>+ await act(async () => {+ result.current.stopAgent(convA)+ // Immediate resend on the SAME conversation, before run 1's finally+ // has had a chance to run.+ runB = result.current.sendAgentMessage('task-2')+ await tick()+ await tick()+ })+ expect(callsB).toBe(1)+ // Run 2 now owns the aborter slot.+ const aborterAfterResend = useGenerationStore.getState().aborters[convA]+ expect(aborterAfterResend).toBeDefined()+ expect(useGenerationStore.getState().generating[convA]).toBe(true)++ // 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.+ await act(async () => {+ streamA.error(new DOMException('The operation was aborted.', 'AbortError'))+ await runA.catch(() => {})+ await tick()+ await tick()+ })++ // Run 2 must be untouched by run 1's late cleanup.+ expect(useGenerationStore.getState().aborters[convA]).toBe(aborterAfterResend)+ expect(useGenerationStore.getState().generating[convA]).toBe(true)++ // The real-world proof: a Stop now (via stopAllBackgroundWork, the exact+ // path sign-out/window-close/app-quit use, which reaches the run only+ // through generationStore.abortConversation) must actually reach run 2's+ // fetch.+ await act(async () => {+ stopAllBackgroundWork()+ await tick()+ })+ expect(bAbortSeen).toBe(true)+ expect(isRunStopped(convA)).toBe(true)++ // Let run 2 unwind so the test does not leave a dangling promise.+ await act(async () => {+ streamB.error(new DOMException('The operation was aborted.', 'AbortError'))+ await runB.catch(() => {})+ await tick()+ })+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 4f67cefe..e36afeb6 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -2551,13 +2551,18 @@ export function useAgentChat() {}}} finally {- useGenerationStore.getState().clearAborter(convId)- // Identity check (B2): only release the slot if it is still THIS run's.+ // Identity check (B2): only clean up if this run still OWNS the slot.// stopAgent() can already have deleted and even replaced it (Stop, then// an immediate resend on the same conversation) by the time this- // finally runs, and unconditionally deleting would then drop the NEW- // run's re-entry protection out from under it.- if (activeAgentRuns.get(convId) === runState) {+ // finally runs. Blocker 2 (review-lanes.md): the three neighbouring+ // cleanup calls below used to run unconditionally, so run A's delayed+ // finally would clear run B's aborter, flip B's generating flag back+ // to false, and reject B's pending approvals, leaving the NEW run+ // unstoppable through generationStore (Stop button, sign-out, window+ // close, app quit) even though activeAgentRuns still pointed at it.+ const stillOwnsSlot = activeAgentRuns.get(convId) === runState+ if (stillOwnsSlot) {+ useGenerationStore.getState().clearAborter(convId)activeAgentRuns.delete(convId)}// Chat-tools artifact mode: attach any files the model "wrote" (captured@@ -2585,15 +2590,21 @@ export function useAgentChat() {// still-running conversation B does not lose its Stop button just// because conversation A's turn ended first.setIsAgentRunning(activeAgentRuns.size > 0)- useGenerationStore.getState().setGenerating(convId, false)+ if (stillOwnsSlot) {+ useGenerationStore.getState().setGenerating(convId, false)+ }})// Drop the per-run workspace scope so standalone tool calls from// other tabs don't accidentally land in this chat's folder. Only when// this run still owns the shared mirror, so a Coding run that outlives// us keeps its own jail root (plan C1 ERZWINGUNG).endAgentRun(run)- // Reject any pending approvals so their promises don't hang forever- drainApprovals(convId)+ // Reject any pending approvals so their promises don't hang forever,+ // but only THIS run's: a replaced slot means a NEW run's approvals are+ // waiting under the same convId, and they must survive.+ if (stillOwnsSlot) {+ drainApprovals(convId)+ }// Auto-read the finished response when the user opted in (#77). Default// OFF, additionally gated on ttsEnabled; getState() so this callback never@@ -2619,7 +2630,13 @@ export function useAgentChat() {// one: a loop someone asked to keep going keeps going until it says done// or they stop it. The loop bar above the composer is what keeps that// honest rather than invisible.- if (opts?.loop && convId && loopHalt) {+ if (opts?.loop && convId && !stillOwnsSlot) {+ // This run was replaced (Stop, then an immediate resend on the same+ // conversation) before its own finally ran. The NEW run owns convId+ // now; scheduling or clearing the /loop driver on its behalf would+ // be this same finally-runs-late class of bug from Blocker 2, just+ // aimed at the loop timer instead of the generation store.+ } else 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(convId)diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 0d6873f9..48cb25b5 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -355,7 +355,8 @@ export function useChat() {// remember this controller: Stop looks it up there, by conversation, not// through a hook-instance ref that a second overlapping run would// overwrite.- useGenerationStore.getState().registerAborter(convId, () => abort.abort())+ const myAborter = () => abort.abort()+ useGenerationStore.getState().registerAborter(convId, myAborter)setIsGenerating(true)useGenerationStore.getState().setGenerating(convId, true)try {@@ -364,14 +365,23 @@ export function useChat() {await runGroupTurn(convId, model, models, abort)}} finally {- useGenerationStore.getState().clearAborter(convId)+ // Same identity check as the single-model turn below (Blocker 2,+ // review-lanes.md): a Stop followed by an immediate resend on this+ // conversation can register a new aborter before this round's+ // finally runs.+ const stillOwnsSlot = useGenerationStore.getState().aborters[convId] === myAborter+ if (stillOwnsSlot) {+ useGenerationStore.getState().clearAborter(convId)+ }// The round is over, so it goes on disk BEFORE the app says so. Same// contract as the single-model turn below and as the Agent and Coding// runs — see stores/durability.ts for the measurement that made the// order matter.await endTurnDurably(() => {- setIsGenerating(false)- useGenerationStore.getState().setGenerating(convId, false)+ if (stillOwnsSlot) {+ setIsGenerating(false)+ useGenerationStore.getState().setGenerating(convId, false)+ }})}}, [])@@ -793,7 +803,15 @@ export function useChat() {// the chat goes away mid-generation (the _activeHandoffs gate makes it a// no-op when no media gen is in flight). Without it a long video kept// rendering after the chat was deleted.- useGenerationStore.getState().registerAborter(convId, () => { abort.abort(); requestGenerationCancel() })+ //+ // Kept as a named reference (not inlined) so the `finally` below can tell+ // whether THIS run still owns the aborter slot for `convId` before+ // touching anything keyed only by conversation (Blocker 2,+ // review-lanes.md): Stop, then an immediate resend on the same+ // conversation, can register a NEW aborter here before this run's+ // `finally` executes, and the old run's cleanup must not reach past it.+ const myAborter = () => { abort.abort(); requestGenerationCancel() }+ useGenerationStore.getState().registerAborter(convId, myAborter)setIsGenerating(true)// Bind the generating flag to THIS conversation so the typing indicator// only shows in the chat whose turn is in flight — not in every other chat@@ -1172,7 +1190,16 @@ export function useChat() {}}} finally {- useGenerationStore.getState().clearAborter(run.convId)+ // Identity check (B2/Blocker 2): only clean up if this run still owns+ // the aborter slot for run.convId. A replaced slot means a NEW run+ // (Stop, then an immediate resend on the same conversation) is now in+ // flight, and clearing its aborter or flipping its generating flag+ // back to false out from under it would make the new run unstoppable+ // through generationStore, exactly like the useAgentChat.ts case.+ const stillOwnsSlot = useGenerationStore.getState().aborters[run.convId] === myAborter+ if (stillOwnsSlot) {+ useGenerationStore.getState().clearAborter(run.convId)+ }setIsLoadingModel(false)useModelStore.getState().setIsModelLoading(false)@@ -1194,8 +1221,14 @@ export function useChat() {// The answer itself is already painted, so what waits here is the Stop// button turning back into Send, not the text.await endTurnDurably(() => {- setIsGenerating(false)- useGenerationStore.getState().setGenerating(run.convId, false)+ // Review-lanes.md point 1: same asymmetry as Blocker 2. Only THIS+ // run flipping the hook's own flag back to false when it still owns+ // the slot keeps a still-running resend on the same conversation+ // from being reported as idle while it is not.+ if (stillOwnsSlot) {+ setIsGenerating(false)+ useGenerationStore.getState().setGenerating(run.convId, false)+ }})// Auto-read the finished response when the user opted in (#77, ElBiggus).