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(codex): Wiedereintritts-Riegel je Unterhaltung, abortRef/abortConvRef geloescht

purplea1b270be582b
diff --git a/src/hooks/__tests__/useCodex-lauf-gehoert-seiner-unterhaltung.test.ts b/src/hooks/__tests__/useCodex-lauf-gehoert-seiner-unterhaltung.test.ts
index 362ef839..d321364c 100644
--- a/src/hooks/__tests__/useCodex-lauf-gehoert-seiner-unterhaltung.test.ts
+++ b/src/hooks/__tests__/useCodex-lauf-gehoert-seiner-unterhaltung.test.ts
@@ -1,68 +1,137 @@
/**
- * B2 Commit 6: mirror the useChat.ts fix into useCodex.ts, the second copy
- * of the same logic.
+ * @vitest-environment jsdom
*
- * `runningRef` in useCodex.ts is a single boolean per HOOK INSTANCE, not per
- * run, and CodexView is not remounted on a conversation switch, so one
- * `useCodex()` instance really does serve every Code conversation for the
- * whole window (same premise as the useChat.ts bug, see
- * useChat-zwei-laeufe-vermischen-nicht.test.ts).
+ * Nachbesserung 8 (review-lanes.md, Runde 3): dieser Test war ein reiner
+ * Quelltextpin (Regex auf eine vollstaendige `for`-Schleifen-Zeile), der
+ * Implementierungsdetails prueft statt Verhalten, und bei jedem harmlosen
+ * Umbau der Schleifenbedingung rot wuerde, ohne dass etwas kaputt ist. Der
+ * Bericht der vorigen Runde begruendete das mit "die Nachbardateien machen
+ * es auch so", was der Pruefer zu Recht als keine Begruendung zurueckwies.
*
- * Three places read or write that shared flag as if it belonged to the ONE
- * run currently in flight:
+ * Ersetzt durch einen echten Verhaltensbeweis fuer den Wiedereintritts-
+ * Riegel, den Nachbesserung 5 dieser Runde in useCodex.ts nachgezogen hat
+ * (`activeCodexRuns`, dieselbe Form wie `activeAgentRuns` in
+ * useAgentChat.ts): ein Prompt, zweimal schnell hintereinander gesendet auf
+ * DERSELBEN Unterhaltung, darf nur EINMAL tatsaechlich lossenden, und ein
+ * Doppelklick OHNE bestehende Unterhaltung darf nur EINE Unterhaltung
+ * erzeugen statt zwei.
*
- * - The ReAct loop's own iteration guard (`... && runningRef.current && ...`
- * and `if (!runningRef.current || abort.signal.aborted) break`): if
- * conversation A finishes (its `finally` sets `runningRef.current = false`)
- * while conversation B is still mid-loop on the SAME hook instance, B's
- * very next iteration check reads `false` and B's loop exits early, not
- * because B was stopped, but because A happened to finish first.
- * - The `/loop` pass driver's re-entry gate (`if (runningRef.current) {
- * clear the loop; return }`): meant to defer a pass while ITS OWN
- * conversation is still busy, it actually fires whenever ANY conversation
- * on this hook instance is running, so a manual send in conversation A
- * silently cancels conversation B's scheduled loop pass.
- *
- * Fix: the ReAct loop already carries a per-call `abort` (its own
- * AbortController) and every conversation already has a canonical,
- * per-conversation stop flag (`lib/run-stop.ts`'s `isRunStopped`), both are
- * genuinely scoped to the right run. The `/loop` gate is rewritten to ask
- * the STORE whether THIS conversation is generating, not the shared ref.
- * `runningRef` itself is retired; nothing correctness-critical should still
- * read it once these three spots stop.
- *
- * This reads the source directly (the same shape as
- * loop-detection.test.ts / useCodex-streaming.test.ts in this same
- * directory): a genuine behavioral repro needs two full ReAct runs
- * interleaved through real tool-call rounds, which the existing behavioral
- * useCodex tests do not attempt either, the wiring pin is what this file's
- * neighbours already rely on for logic this deep in the hook.
+ * `resolveChatWorkspaceSlug` ist die erste echte Abhaengigkeit hinter dem
+ * Riegel (Zeile ~428 in useCodex.ts, vor jedem Provider-/Speicher-Zugriff),
+ * also der fruehestmoegliche Beobachtungspunkt: haelt der Riegel, wird sie
+ * fuer den zweiten Aufruf nie erreicht.
*
* Run: npx vitest run src/hooks/__tests__/useCodex-lauf-gehoert-seiner-unterhaltung.test.ts
*/
-import { describe, it, expect } from 'vitest'
-import { readFileSync } from 'fs'
-import { fileURLToPath } from 'url'
-import { dirname, join } from 'path'
-
-const __filename = fileURLToPath(import.meta.url)
-const __dirname = dirname(__filename)
-const src = readFileSync(join(__dirname, '../useCodex.ts'), 'utf8')
-
-describe('a codex run in useCodex.ts is gated by its OWN state, not a shared hook-instance flag', () => {
- it('runningRef is gone: no other conversation\'s finally can flip this run\'s own loop guard', () => {
- expect(src).not.toMatch(/runningRef/)
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+const slugCalls = { count: 0 }
+vi.mock('../../api/workspace-slug', () => ({
+ // Throws after counting: the guard is what this test proves, not the rest
+ // of the send pipeline. A fast, deterministic failure here also exercises
+ // the wrapping try/catch Nachbesserung 5 added around the whole body (the
+ // safety net that keeps a thrown error from leaving the conversation
+ // permanently locked out of sending).
+ resolveChatWorkspaceSlug: async () => {
+ slugCalls.count++
+ throw new Error('workspace slug unavailable (test)')
+ },
+}))
+
+import { useCodex } from '../useCodex'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useCodexStore } from '../../stores/codexStore'
+
+function silenceUnhandled(p: Promise<unknown>) {
+ p.catch(() => {})
+ return p
+}
+
+beforeEach(() => {
+ slugCalls.count = 0
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useCodexStore.setState({ sendsInFlight: 0, threads: {}, workingDirectory: '' })
+ useModelStore.setState({ models: [], activeModel: 'ollama::qwen3:14b' })
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('a Codex run in useCodex.ts is gated by its OWN conversation, not a shared hook-instance flag', () => {
+ it('two fast sends on the SAME existing conversation only let the first one through', async () => {
+ const { result } = renderHook(() => useCodex())
+ const convId = useChatStore.getState().createConversation('ollama::qwen3:14b', '', 'codex')
+ useChatStore.getState().setActiveConversation(convId)
+
+ let p1!: Promise<unknown>
+ let p2!: Promise<unknown>
+ act(() => {
+ p1 = silenceUnhandled(result.current.sendInstruction('first'))
+ // Immediate second send, no await in between: the exact double-submit
+ // shape (two Enters before React re-renders Send into Stop).
+ p2 = silenceUnhandled(result.current.sendInstruction('second'))
+ })
+ await act(async () => { await Promise.allSettled([p1, p2]) })
+
+ // Only the FIRST call ever reached past the guard.
+ expect(slugCalls.count).toBe(1)
+ // Still exactly one conversation: the second call did not create its own.
+ expect(useChatStore.getState().conversations.length).toBe(1)
})
- it('the ReAct loop bound checks this run\'s own abort signal and its own conversation\'s stop flag', () => {
- expect(src).toMatch(/for \(let i = 0; i < MAX_CODEX_ITERATIONS && !abort\.signal\.aborted && !isRunStopped\(convId\); i\+\+\)/)
+ it('a double-click with NO existing conversation creates exactly ONE, not two', async () => {
+ const { result } = renderHook(() => useCodex())
+ expect(useChatStore.getState().activeConversationId).toBeNull()
+
+ let p1!: Promise<unknown>
+ let p2!: Promise<unknown>
+ act(() => {
+ p1 = silenceUnhandled(result.current.sendInstruction('first'))
+ p2 = silenceUnhandled(result.current.sendInstruction('second'))
+ })
+ await act(async () => { await Promise.allSettled([p1, p2]) })
+
+ expect(useChatStore.getState().conversations.length).toBe(1)
+ expect(slugCalls.count).toBe(1)
})
- it('the mid-loop break also reads only this run\'s own signal', () => {
- expect(src).toMatch(/if \(abort\.signal\.aborted \|\| isRunStopped\(convId\)\) break/)
+ it('COUNTER-CHECK: a run in a DIFFERENT conversation is not blocked by this one', async () => {
+ const { result } = renderHook(() => useCodex())
+ const convA = useChatStore.getState().createConversation('ollama::qwen3:14b', '', 'codex')
+ useChatStore.getState().setActiveConversation(convA)
+
+ let pA!: Promise<unknown>
+ act(() => { pA = silenceUnhandled(result.current.sendInstruction('task-A')) })
+
+ // Switch to a brand-new conversation B before A's send has settled.
+ const convB = useChatStore.getState().createConversation('ollama::qwen3:14b', '', 'codex')
+ useChatStore.getState().setActiveConversation(convB)
+
+ let pB!: Promise<unknown>
+ act(() => { pB = silenceUnhandled(result.current.sendInstruction('task-B')) })
+
+ await act(async () => { await Promise.allSettled([pA, pB]) })
+
+ // Both reached the same dependency: A's run in flight did not block B's.
+ expect(slugCalls.count).toBe(2)
})
- it('the /loop pass driver defers on ITS OWN conversation generating, not on any conversation running', () => {
- expect(src).toContain("if (useGenerationStore.getState().generating[convForLoop])")
+ it('the guard does not leak: a failed send frees the conversation for the next one', async () => {
+ const { result } = renderHook(() => useCodex())
+ const convId = useChatStore.getState().createConversation('ollama::qwen3:14b', '', 'codex')
+ useChatStore.getState().setActiveConversation(convId)
+
+ await act(async () => {
+ await result.current.sendInstruction('first').catch(() => {})
+ })
+ expect(slugCalls.count).toBe(1)
+
+ // A second, later send on the SAME conversation must go through, the
+ // wrapping try/catch Nachbesserung 5 added is exactly what keeps the
+ // thrown error above from locking this conversation out forever.
+ await act(async () => {
+ await result.current.sendInstruction('second').catch(() => {})
+ })
+ expect(slugCalls.count).toBe(2)
})
})
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 45f77c90..6f1a673b 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -267,19 +267,45 @@ export function __pendingCodexLoopTimersForTests(): string[] {
return [...codexLoopTimers.keys()]
}
+/**
+ * Nachbesserung 5 (review-lanes.md, 3.0.1 lanes Runde 3): the same
+ * re-entry guard `useAgentChat.ts`'s `activeAgentRuns` gives the Agent
+ * surface, now on the Code surface too. Before this, useCodex was the ONE
+ * of the three send paths with no guard of its own: two fast sends on the
+ * SAME conversation both ran, the second `registerAborter` overwrote the
+ * first, and the first turn was then stoppable only through a signal
+ * nobody held any more. Keyed to `conversationId`, not the hook instance,
+ * so a run in an UNRELATED conversation never blocks this one (the same
+ * B2 fix `activeAgentRuns` needed).
+ *
+ * The value is a per-run token, not the AbortController itself, because
+ * `stopCodex`/the finally below only need to answer "is this still MY
+ * run", the same identity question `activeAgentRuns.get(convId) ===
+ * runState` answers on the Agent surface; a plain token is enough and
+ * keeps this file from growing a second run-state shape next to the
+ * plain local variables `949cd0d6` already made instance-safe.
+ */
+const activeCodexRuns = new Map<string, symbol>()
+
+/** Test-only: which conversations currently have a run claimed. */
+export function __activeCodexRunsForTests(): string[] {
+ return [...activeCodexRuns.keys()]
+}
+
export function useCodex() {
const [isRunning, setIsRunning] = useState(false)
- const abortRef = useRef<AbortController | null>(null)
- /**
- * Zu WELCHER Unterhaltung der Controller oben gehoert.
- *
- * R2-19: `stopCodex` brach ihn bedingungslos ab. Der Griff gehoert der
- * Hook-INSTANZ und haelt den zuletzt gestarteten Lauf, egal wo, und
- * `CodexView` wird beim Unterhaltungswechsel nicht neu montiert
- * (`ChatView.tsx` gibt ihm kein `key`). Stop in B toetete damit den Lauf in
- * A. Dieselbe Klammer wie in useChat und useAgentChat.
- */
- const abortConvRef = useRef<string | null>(null)
+ // Nachbesserung 5 (review-lanes.md): abortRef/abortConvRef used to live
+ // here, a hook-instance ref pair duplicating exactly what
+ // generationStore.aborters + activeCodexRuns now cover. stopCodex read
+ // them only as a SECOND, redundant abort() call on the same
+ // AbortController generationStore's abortConversation already aborts
+ // (AbortController.abort() is idempotent), and their unconditional
+ // `= null` reset in the finally below cleared conversation A's ref out
+ // from under conversation B (the Code view is not remounted on a tab
+ // switch), the same class of bug Blocker 2 fixed for the Agent surface.
+ // Deleted rather than kept "harmless": Hausregel, dead duplication is
+ // not a safe place to leave a second copy of a Stop mechanism.
+ //
// "The user pressed stop" lives in lib/run-stop, keyed by conversation, NOT
// in a ref of this hook instance. The Code view unmounts on every tab switch,
// and the /loop driver's finally runs in the closure of the instance that
@@ -354,6 +380,32 @@ export function useCodex() {
convId = store.createConversation(activeModel, persona?.systemPrompt || '', 'codex')
}
+ // ── Re-entry guard (double-submit), PER CONVERSATION ─────────────────
+ // Nachbesserung 5 (review-lanes.md): same shape as useAgentChat.ts's
+ // `activeAgentRuns` guard, claimed synchronously HERE, with no `await`
+ // between the `has()` check and the `set()` below, so a racing second
+ // call for the SAME conversation bails before duplicating anything. A
+ // run in a DIFFERENT conversation is untouched: this was the one send
+ // path of the three without any re-entry protection at all, so two
+ // fast sends on the same Code conversation started two loops that
+ // shared nothing and left the first one stoppable only through a
+ // signal `registerAborter` had already overwritten.
+ if (activeCodexRuns.has(convId)) {
+ log.info('codex.duplicate_send_blocked', { activeModel, convId })
+ return
+ }
+ const runToken = Symbol('codex-run')
+ activeCodexRuns.set(convId, runToken)
+ // A wrapping try/catch, not just the identity-checked cleanup deep in the
+ // body's own finally (below): the body has many awaited calls BEFORE that
+ // inner try (resolveChatWorkspaceSlug, runCompactForConversation,
+ // getModelMaxTokens, memory retrieval, .lurules, ...), and an unhandled
+ // throw from any of them used to leave `convId` claimed FOREVER: every
+ // later send on that conversation would silently hit the guard above and
+ // do nothing, with no error and no way out short of reloading the app.
+ // This is the safety net for that whole stretch, not just the happy path.
+ try {
+
const memoryScope = store.conversations.find(c => c.id === convId)?.memoryScope
// A brand-new instruction clears a previous stop; a /loop pass inherits it,
// which is what makes Stop end the LOOP and not just the pass in flight.
@@ -452,6 +504,7 @@ export function useCodex() {
focus: slash.args || undefined,
})
useChatStore.getState().updateMessageContent(convId, noticeId, compactOutcomeMessage(outcome))
+ activeCodexRuns.delete(convId)
return
}
@@ -463,6 +516,7 @@ export function useCodex() {
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'assistant', content: res.message, timestamp: Date.now(),
})
+ activeCodexRuns.delete(convId)
return
}
@@ -481,6 +535,7 @@ export function useCodex() {
id: uuid(), role: 'assistant', timestamp: Date.now(),
content: modeRefusal,
})
+ activeCodexRuns.delete(convId)
return
}
@@ -740,7 +795,7 @@ export function useCodex() {
// The only bail-out between opening the run and the try/finally that closes
// it. Close it here too, or the run context outlives a turn that never
// started and the next standalone tool call inherits its jail root.
- if (!conv) { endAgentRun(run); return }
+ if (!conv) { endAgentRun(run); activeCodexRuns.delete(convId); return }
void diagLog('pre-loop', {
activeModel, providerId, strategy, workDir,
@@ -854,8 +909,6 @@ export function useCodex() {
// Setup
const abort = new AbortController()
- abortRef.current = abort
- abortConvRef.current = convId
// Hand Stop to everything this run starts, including the nested ReAct loop
// a delegate_task sub-agent runs (audit AGT-1). Assigned here rather than
// in beginAgentRun because the controller does not exist that early.
@@ -2415,9 +2468,19 @@ export function useCodex() {
})
}
- useGenerationStore.getState().clearAborter(convId)
- abortRef.current = null
- abortConvRef.current = null
+ // Identity check (Blocker 2, review-lanes.md, this file's own copy of
+ // the useAgentChat.ts/useChat.ts finally fix): a Stop followed by an
+ // immediate resend on the SAME conversation can claim `activeCodexRuns`
+ // and `generationStore.aborters` for a NEW run before THIS run's
+ // finally executes. Unconditionally clearing either here would then
+ // wipe the new run's aborter and reject its generating flag out from
+ // under it, leaving it unstoppable through generationStore exactly
+ // like the Agent-surface bug.
+ const stillOwnsSlot = activeCodexRuns.get(convId) === runToken
+ if (stillOwnsSlot) {
+ useGenerationStore.getState().clearAborter(convId)
+ activeCodexRuns.delete(convId)
+ }
// Close THIS run. The process-wide mirror is only cleared when this run
// still owns it, so a run that outlives us keeps its workspace and its
// read-only flag (plan C1 ERZWINGUNG, blocker S3).
@@ -2438,9 +2501,11 @@ export function useCodex() {
// moving to the bottom of the block.
await endTurnDurably(
() => {
- setIsRunning(false)
- useGenerationStore.getState().setGenerating(convId, false)
- codexStore.setThreadStatus(convId, 'idle')
+ if (stillOwnsSlot) {
+ setIsRunning(false)
+ useGenerationStore.getState().setGenerating(convId, false)
+ codexStore.setThreadStatus(convId, 'idle')
+ }
},
[flushChatPersist, flushStagedPersist],
)
@@ -2559,6 +2624,16 @@ export function useCodex() {
}
}
}
+ } catch (e) {
+ // Safety net for the guard claimed above: whatever threw, and from
+ // wherever in the body, this conversation must not stay locked out of
+ // sending forever. Identity-checked the same way the body's own
+ // finally is (Blocker 2 shape): a replaced slot (Stop, then an
+ // immediate resend) means a NEWER run owns `convId` now, and this
+ // must not delete that one out from under it.
+ if (activeCodexRuns.get(convId) === runToken) activeCodexRuns.delete(convId)
+ throw e
+ }
}, [])
/**
@@ -2618,14 +2693,17 @@ export function useCodex() {
codexLoopTimers.delete(stoppedConvId ?? '')
}
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
- // weiter.
- if (abortConvRef.current === stoppedConvId) {
- abortRef.current?.abort()
- abortRef.current = null
- setIsRunning(false)
+ // Nachbesserung 5 (review-lanes.md): NUR den eigenen Lauf aus
+ // activeCodexRuns nehmen, dieselbe Klammer wie useAgentChat.ts's
+ // stopAgent um activeAgentRuns. `abortConversation` oben hat den echten
+ // Abbrecher schon gerufen (Aborter-Identitaet lebt in generationStore,
+ // nicht mehr in einem Hook-Ref); dies raeumt nur den Wiedereintritts-
+ // Riegel, damit ein sofortiges erneutes Senden auf DERSELBEN
+ // Unterhaltung nicht am eigenen, gerade gestoppten Lauf abprallt.
+ const stoppedRunToken = stoppedConvId ? activeCodexRuns.get(stoppedConvId) : undefined
+ if (stoppedRunToken) {
+ activeCodexRuns.delete(stoppedConvId!)
+ setIsRunning(activeCodexRuns.size > 0)
}
}, [])