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): runInLane in useCodex.ts runInstruction als Produktionsweg

purple738bda22b190
diff --git a/src/hooks/__tests__/useCodex-lokale-spur-reiht-zweiten-lauf-ein.test.ts b/src/hooks/__tests__/useCodex-lokale-spur-reiht-zweiten-lauf-ein.test.ts
new file mode 100644
index 00000000..d5b462d6
--- /dev/null
+++ b/src/hooks/__tests__/useCodex-lokale-spur-reiht-zweiten-lauf-ein.test.ts
@@ -0,0 +1,120 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * Runde 4 (review-lanes.md Blocker 1+6): useCodex.ts's runInstruction (over
+ * its sendInstruction wrapper) must run through `runInLane` on the local
+ * lane, same as useChat.ts and useAgentChat.ts. Two Coding-Agent
+ * conversations on the built-in engine (n_parallel=1) may not both reach
+ * their provider call at once — the second must queue.
+ *
+ * `resolveChatWorkspaceSlug` is used as the gate, the same technique as
+ * `useCodex-lauf-gehoert-seiner-unterhaltung.test.ts`: it is the first real
+ * dependency behind the guard, so holding its promise open keeps a run's
+ * body "in flight" (and so still holding the local lane) without having to
+ * fake the entire provider/streaming pipeline underneath it.
+ *
+ * Run: npx vitest run src/hooks/__tests__/useCodex-lokale-spur-reiht-zweiten-lauf-ein.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+type Gate = { resolve: () => void; reject: (e: unknown) => void }
+const gates: Gate[] = []
+const slugCalls: string[] = []
+
+vi.mock('../../api/workspace-slug', () => ({
+ resolveChatWorkspaceSlug: vi.fn(async (convId: string) => {
+ slugCalls.push(convId)
+ await new Promise<void>((resolve, reject) => { gates.push({ resolve, reject }) })
+ // Never actually resolves successfully in this test — rejecting is the
+ // fastest, most deterministic way to end a run via the outer safety-net
+ // catch (Nachbesserung 5, review-lanes.md) once the lane-admission
+ // question has already been observed. What matters here is WHEN the
+ // call happens, not what it returns.
+ throw new Error('workspace slug unavailable (test)')
+ }),
+}))
+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))
+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))
+vi.mock('../../lib/run-lane-of-model', () => ({
+ laneOf: () => 'local',
+ currentLaneFacts: () => ({ openaiSlotIsLocal: true, ollamaBaseIsLocal: true }),
+}))
+
+import { useCodex } from '../useCodex'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useCodexStore } from '../../stores/codexStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { __resetRunLanesForTests, localLaneHolder, queuedRunIds } from '../../lib/run-lanes'
+import { __resetRunSlotsForTests } from '../../lib/run-slot'
+
+const MODEL = 'openai::local-builtin-model'
+
+function silenceUnhandled(p: Promise<unknown>) {
+ p.catch(() => {})
+ return p
+}
+
+const tick = () => new Promise((r) => setTimeout(r, 0))
+
+beforeEach(() => {
+ gates.length = 0
+ slugCalls.length = 0
+ __resetRunLanesForTests()
+ __resetRunSlotsForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useCodexStore.setState({ sendsInFlight: 0, threads: {}, workingDirectory: '' })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ activeModel: MODEL })
+})
+afterEach(() => vi.restoreAllMocks())
+
+describe('runInstruction reiht einen zweiten lokalen Coding-Lauf ein', () => {
+ it('die zweite Unterhaltung erreicht ihre eigene Abhaengigkeit erst nach der ersten', async () => {
+ const { result } = renderHook(() => useCodex())
+ const convA = useChatStore.getState().createConversation(MODEL, '', 'codex')
+ useChatStore.getState().setActiveConversation(convA)
+
+ let pA!: Promise<unknown>
+ act(() => { pA = silenceUnhandled(result.current.sendInstruction('task-A')) })
+ await tick()
+
+ // A holds the local lane and reached its own first real dependency.
+ expect(slugCalls).toEqual([convA])
+ expect(localLaneHolder()).toBe(convA)
+
+ const convB = useChatStore.getState().createConversation(MODEL, '', 'codex')
+ useChatStore.getState().setActiveConversation(convB)
+
+ let pB!: Promise<unknown>
+ act(() => { pB = silenceUnhandled(result.current.sendInstruction('task-B')) })
+ await tick()
+
+ // B queued behind A instead of racing it for the one local slot: its
+ // own body never even started, so its dependency was never called.
+ expect(slugCalls).toEqual([convA])
+ expect(queuedRunIds()).toEqual([convB])
+
+ // Let A's gate fail — A's run ends (through the safety-net catch),
+ // releasing the local lane.
+ await act(async () => {
+ gates[0].reject(new Error('workspace slug unavailable (test)'))
+ await pA.catch(() => {})
+ await tick()
+ })
+
+ // A released the lane; B's body now runs and reaches its own dependency.
+ expect(slugCalls).toEqual([convA, convB])
+ expect(localLaneHolder()).toBe(convB)
+
+ await act(async () => {
+ gates[1].reject(new Error('workspace slug unavailable (test)'))
+ await pB.catch(() => {})
+ await tick()
+ })
+
+ expect(localLaneHolder()).toBeNull()
+ expect(queuedRunIds()).toEqual([])
+ })
+})
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 6f1a673b..bbaaa638 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -43,6 +43,8 @@ import {
loopPassSaysDone,
} from '../lib/agent-commands'
import { useGenerationStore } from '../stores/generationStore'
+import { runInLane } from '../lib/run-slot'
+import { laneOf, currentLaneFacts } from '../lib/run-lane-of-model'
import { isOllamaLocal } from '../api/backend'
import { requestGenerationCancel } from '../api/vram-handoff'
import { planWithArchitect, renderArchitectPlanSection } from '../api/agents/architect'
@@ -406,6 +408,23 @@ export function useCodex() {
// This is the safety net for that whole stretch, not just the happy path.
try {
+ // Lane admission (Runde 4, review-lanes.md Blocker 1+6): everything from
+ // here on (workspace resolution, RAG, memory, the tool loop, the /loop
+ // driver) runs inside runInLane's body, so a local run that has to wait
+ // for the built-in engine's one llama-server slot has not touched the
+ // chat store yet when it is queued. `queueAbort` starts null because the
+ // real AbortController is not created until deep inside the body (after
+ // messages are assembled); it is filled in the moment that happens, so
+ // the rare window between "granted the lane" and "the body registered
+ // its own aborter" still has something to reach if Stop lands there.
+ // 'cancelled-while-queued' (Stop while still waiting) skips the body and
+ // its own finally entirely, so the guard claimed above is freed here.
+ const lane = laneOf(activeModel, currentLaneFacts())
+ let queueAbort: AbortController | null = null
+ const laneOutcome = await runInLane(
+ { conversationId: convId, lane, abort: () => queueAbort?.abort() },
+ async () => {
+
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.
@@ -909,6 +928,7 @@ export function useCodex() {
// Setup
const abort = new AbortController()
+ queueAbort = abort
// 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.
@@ -2623,6 +2643,14 @@ export function useCodex() {
codexLoopTimers.set(convForLoop, setTimeout(fireLoopPass, loopState.intervalMs))
}
}
+ }
+ },
+ )
+ if (laneOutcome === 'cancelled-while-queued' && activeCodexRuns.get(convId) === runToken) {
+ // Stop pulled this run out of the local lane's waiting room before the
+ // body (and its own finally, and even its own AbortController) ever
+ // existed, so the guard claimed above has to be freed here instead.
+ activeCodexRuns.delete(convId)
}
} catch (e) {
// Safety net for the guard claimed above: whatever threw, and from