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(code): ein abgeschnittener Zug endet nicht mehr wortlos auf dem Plan

David16303a7f51a2
diff --git a/src/hooks/codex/__tests__/der-plan-haengt-nicht-bei-schritt-2.test.ts b/src/hooks/codex/__tests__/der-plan-haengt-nicht-bei-schritt-2.test.ts
new file mode 100644
index 00000000..78fb471a
--- /dev/null
+++ b/src/hooks/codex/__tests__/der-plan-haengt-nicht-bei-schritt-2.test.ts
@@ -0,0 +1,254 @@
+/**
+ * Fehler D, Symptom 2. Discord, aldrich_ironhart, 08.09.2026, Windows 11,
+ * LU 2.6.8, Ollama, Code Reiter: "during code generation the plan hangs at
+ * step 2, sometimes restarts at 0".
+ *
+ * ── WAS HIER ECHT LAEUFT ───────────────────────────────────────────────────
+ * Der wirkliche Ollama Transport (`streamOllamaChatWithTools`) gegen einen
+ * NDJSON Strom, wie Ollama ihn schickt; der wirkliche `todoStore` ueber
+ * `writeTodos`; die wirkliche `PlanStaleness` und der wirkliche
+ * `AgentLoopGuard`. Nur `localFetchStream` ist ersetzt, also genau das Kabel.
+ * Das ist die "Schrittmaschine" des Plans: einen Schritt weiterzaehlen kann in
+ * LU ausschliesslich das Modell ueber `todo_write`, der Speicher ersetzt die
+ * Liste jedes Mal ganz.
+ *
+ * ── WAS DER LAUF ZEIGT ─────────────────────────────────────────────────────
+ * Ein Plan aus zwei Schritten kommt ueber Schritt 2 hinaus, ohne dass eine der
+ * Bremsen dazwischenfaehrt: die Schleifenwache haelt nicht an, der
+ * Frische Waechter mahnt nicht, und die Luecke schliesst sich am Ende. Der
+ * Haenger sitzt also NICHT in dieser Kette.
+ *
+ * ── WO ER SITZEN KANN, UND WAS DAFUER FEHLTE ───────────────────────────────
+ * Ollama meldet einen abgeschnittenen Zug im letzten Stueck des Stroms als
+ * `done_reason: "length"`. `wire.ts` liest das Feld seit jeher aus, der
+ * regulaere Chat gibt es als `finishReason` weiter (ollama-provider.ts:252)
+ * und `useChat.ts` sagt dem Nutzer dann, dass das Token Budget alle war. Der
+ * Transport des CODING AGENTEN warf es weg.
+ *
+ * Damit war ein Zug, den das Modell nie zu Ende schreiben konnte, fuer die
+ * Schleife nicht von einem Modell zu unterscheiden, das fertig ist: keine
+ * Werkzeugaufrufe, also `break-no-toolcalls`, Lauf zu Ende, kein Wort. Der
+ * Plan steht danach genau da, wo er stand, auf seinem offenen Schritt. Und
+ * der naechste Zug bekommt ueber den Anker und den Frische Waechter die
+ * Aufforderung, die VOLLSTAENDIGE Liste noch einmal zu schicken; ein Modell,
+ * dem der Verlauf weggeschnitten wurde, schickt sie dann von vorn. Das ist
+ * beides, was der Melder beschreibt.
+ *
+ * Lauf: npx vitest run src/hooks/codex/__tests__/der-plan-haengt-nicht-bei-schritt-2.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+vi.mock('../../../api/backend', () => ({
+ localFetchStream: vi.fn(),
+ ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,
+}))
+
+import { streamOllamaChatWithTools } from '../../../lib/ollama-stream-tools'
+import { localFetchStream } from '../../../api/backend'
+import { useTodoStore, writeTodos, type TodoItem } from '../../../stores/todoStore'
+import { openPlanGap } from '../../../lib/plan-reconcile'
+import { PlanStaleness } from '../../../lib/plan-staleness'
+import { AgentLoopGuard } from '../../../lib/agent-loop-guard'
+import { codexCutoffNote } from '../turn-cutoff'
+import type { ToolCall, ToolDefinition } from '../../../api/providers/types'
+
+const mockStream = localFetchStream as ReturnType<typeof vi.fn>
+
+const CONV = 'bug-d-plan'
+
+const TOOLS: ToolDefinition[] = [
+ {
+ type: 'function',
+ function: {
+ name: 'todo_write',
+ description: 'write the plan',
+ parameters: { type: 'object', properties: { todos: { type: 'array', description: 'the plan' } }, required: ['todos'] },
+ },
+ },
+ {
+ type: 'function',
+ function: {
+ name: 'file_read',
+ description: 'read a file',
+ parameters: { type: 'object', properties: { path: { type: 'string', description: 'path' } }, required: ['path'] },
+ },
+ },
+]
+
+/** Ein Ollama NDJSON Strom aus fertigen Zeilen. */
+function ndjson(...lines: string[]): Response {
+ return new Response(lines.join('\n') + '\n', { status: 200 })
+}
+
+/** Die Zeile, mit der Ollama einen Werkzeugaufruf schickt. */
+function callLine(name: string, args: unknown): string {
+ return JSON.stringify({ message: { content: '', tool_calls: [{ function: { name, arguments: args } }] }, done: false })
+}
+
+/** Die Schlusszeile eines Zuges. */
+function doneLine(reason: string, content = ''): string {
+ return JSON.stringify({ message: { content }, done: true, done_reason: reason, eval_count: 42, prompt_eval_count: 900 })
+}
+
+/** Ein Zug ueber den echten Transport. */
+function turn(...lines: string[]) {
+ mockStream.mockResolvedValueOnce(ndjson(...lines))
+ return streamOllamaChatWithTools(
+ 'qwen2.5-coder:14b',
+ [{ role: 'user', content: 'refactor the parser' }],
+ TOOLS,
+ { temperature: 0.1 },
+ () => {},
+ () => {},
+ )
+}
+
+const PLAN_START: TodoItem[] = [
+ { content: 'read the parser', status: 'in_progress' },
+ { content: 'rewrite the token loop', status: 'pending' },
+]
+const PLAN_MID: TodoItem[] = [
+ { content: 'read the parser', status: 'completed' },
+ { content: 'rewrite the token loop', status: 'in_progress' },
+]
+const PLAN_DONE: TodoItem[] = [
+ { content: 'read the parser', status: 'completed' },
+ { content: 'rewrite the token loop', status: 'completed' },
+]
+
+/** Die Werkzeugnamen eines Zuges, wie die Schleife sie den Waechtern gibt. */
+const namesOf = (calls: ToolCall[]) => calls.map((c) => c.function.name)
+const guardBatch = (calls: ToolCall[]) =>
+ calls.map((c) => ({ name: c.function.name, args: JSON.stringify(c.function.arguments) }))
+
+beforeEach(() => {
+ mockStream.mockReset()
+ useTodoStore.getState().clearTodos(CONV)
+})
+
+describe('ein Plan aus zwei Schritten kommt ueber Schritt 2 hinaus', () => {
+ it('zaehlt 0 zu 2, dann 1 zu 2, dann zu', async () => {
+ const stale = new PlanStaleness()
+ const guard = new AgentLoopGuard()
+
+ // Zug 1: das Modell schreibt den Plan.
+ const t1 = await turn(callLine('todo_write', { todos: PLAN_START }), doneLine('stop'))
+ expect(namesOf(t1.toolCalls)).toEqual(['todo_write'])
+ writeTodos(CONV, (t1.toolCalls[0].function.arguments as { todos: unknown }).todos)
+ expect(openPlanGap(useTodoStore.getState().getTodos(CONV))).toEqual({
+ done: 0, total: 2, next: 'read the parser',
+ })
+ expect(guard.recordBatch(guardBatch(t1.toolCalls)).action).toBe('ok')
+ expect(stale.recordBatch(namesOf(t1.toolCalls), true)).toBe(false)
+
+ // Zug 2: echte Arbeit, kein todo_write. Eine stille Runde ist noch keine.
+ const t2 = await turn(callLine('file_read', { path: 'src/parser.ts' }), doneLine('stop'))
+ expect(namesOf(t2.toolCalls)).toEqual(['file_read'])
+ expect(guard.recordBatch(guardBatch(t2.toolCalls)).action).toBe('ok')
+ expect(stale.recordBatch(namesOf(t2.toolCalls), true)).toBe(false)
+
+ // Zug 3: Schritt 1 fertig, Schritt 2 ist dran. DAS ist der Uebergang, an
+ // dem der Melder haengenbleibt.
+ const t3 = await turn(callLine('todo_write', { todos: PLAN_MID }), doneLine('stop'))
+ writeTodos(CONV, (t3.toolCalls[0].function.arguments as { todos: unknown }).todos)
+ expect(openPlanGap(useTodoStore.getState().getTodos(CONV))).toEqual({
+ done: 1, total: 2, next: 'rewrite the token loop',
+ })
+ expect(guard.recordBatch(guardBatch(t3.toolCalls)).action).toBe('ok')
+
+ // Zug 4: Schritt 2 wird getan, und zwar an einer anderen Datei, sonst
+ // zaehlt die Schleifenwache zu Recht eine Wiederholung.
+ const t4 = await turn(callLine('file_read', { path: 'src/lexer.ts' }), doneLine('stop'))
+ expect(guard.recordBatch(guardBatch(t4.toolCalls)).action).toBe('ok')
+
+ // Zug 5: der Plan schliesst. Jetzt darf der Lauf enden.
+ const t5 = await turn(callLine('todo_write', { todos: PLAN_DONE }), doneLine('stop'))
+ writeTodos(CONV, (t5.toolCalls[0].function.arguments as { todos: unknown }).todos)
+ expect(openPlanGap(useTodoStore.getState().getTodos(CONV))).toBeNull()
+ })
+
+ it('ein als JSON Zeichenkette geschickter Plan kommt genauso an', async () => {
+ // Kleine lokale Modelle schicken `arguments` als Zeichenkette. Das war
+ // schon einmal der Grund fuer "file_write needs argument", und fuer den
+ // Plan hiesse es: die Liste kommt nie an, der Balken steht still.
+ const t = await turn(
+ callLine('todo_write', JSON.stringify({ todos: PLAN_MID })),
+ doneLine('stop'),
+ )
+ writeTodos(CONV, (t.toolCalls[0].function.arguments as { todos: unknown }).todos)
+ expect(openPlanGap(useTodoStore.getState().getTodos(CONV))?.done).toBe(1)
+ })
+
+ it('dieselbe Liste zweimal im selben Zug ist ein Aufruf, nicht zwei', async () => {
+ // Der Wiederholungsschutz im Transport. Er darf den Plan nicht kosten,
+ // wenn der Server das komplette tool_calls Feld noch einmal schickt.
+ const t = await turn(
+ callLine('todo_write', { todos: PLAN_MID }),
+ callLine('todo_write', { todos: PLAN_MID }),
+ doneLine('stop'),
+ )
+ expect(t.toolCalls).toHaveLength(1)
+ })
+
+ it('eine ganz neue Liste setzt den Balken zurueck, und das ist der Vertrag', async () => {
+ // "sometimes restarts at 0": `todo_write` ERSETZT die Liste ganz, das
+ // steht so in der Werkzeugbeschreibung und im Speicher. Schickt das Modell
+ // seinen Plan von vorn, faellt der Balken auf 0. Der Speicher tut genau,
+ // was ihm gesagt wurde. Hier festgehalten, damit niemand den Rueckfall
+ // spaeter im Reduzierer sucht.
+ writeTodos(CONV, PLAN_MID)
+ expect(openPlanGap(useTodoStore.getState().getTodos(CONV))?.done).toBe(1)
+ writeTodos(CONV, PLAN_START)
+ expect(openPlanGap(useTodoStore.getState().getTodos(CONV))?.done).toBe(0)
+ })
+})
+
+describe('ein Zug, den das Modell nie zu Ende schreiben konnte', () => {
+ it('der Transport meldet den Abschnitt, statt ihn wegzuwerfen', async () => {
+ // Genau die Zeile, die Ollama schickt, wenn num_predict oder num_ctx alle
+ // sind: Text angefangen, Werkzeugaufruf nie geschickt.
+ const t = await turn(
+ JSON.stringify({ message: { content: 'Now I will update the plan and' }, done: false }),
+ doneLine('length'),
+ )
+ expect(t.toolCalls).toHaveLength(0)
+ expect(t.doneReason, 'der abgeschnittene Zug sieht aus wie ein fertiger').toBe('length')
+ })
+
+ it('ein sauberer Schluss bleibt ein sauberer Schluss', async () => {
+ const t = await turn(callLine('file_read', { path: 'a.ts' }), doneLine('stop'))
+ expect(t.doneReason).toBe('stop')
+ expect(codexCutoffNote(t.doneReason, { done: 1, total: 2, next: 'rewrite the token loop' })).toBeNull()
+ })
+
+ it('der Nutzer liest, warum der Lauf auf seinem Schritt stehenblieb', () => {
+ const note = codexCutoffNote('length', { done: 1, total: 2, next: 'rewrite the token loop' })
+ expect(note, 'ein abgeschnittener Zug endet weiter wortlos').not.toBeNull()
+ expect(note).toContain('rewrite the token loop')
+ expect(note).toContain('1 of 2')
+ // Englisch, wie jede Meldung in der Oberflaeche.
+ expect(note).toMatch(/Max Tokens|context/)
+ })
+
+ it('ohne offenen Plan sagt derselbe Satz nichts ueber Schritte', () => {
+ const note = codexCutoffNote('length', null)
+ expect(note).not.toBeNull()
+ expect(note).not.toContain('of 2')
+ })
+
+ it('die Schleife schreibt den Satz hin, bevor sie den Lauf beendet', () => {
+ // Quelltextrechnung: `sendInstruction` steckt in einem `useCallback`, den
+ // kein Test von aussen aufruft. Geprueft wird genau die Reihenfolge, an
+ // der es haengt: der Satz muss VOR dem `break` stehen, sonst endet der
+ // Lauf wieder wortlos.
+ const raw = readFileSync(resolve(__dirname, '..', '..', 'useCodex.ts'), 'utf8')
+ const leer = raw.indexOf('if (toolCalls.length === 0)')
+ expect(leer, 'die Weiche ohne Werkzeugaufruf ist verschwunden').toBeGreaterThan(0)
+ const zweig = raw.slice(leer, raw.indexOf("break-no-toolcalls", leer))
+ expect(zweig, 'der abgeschnittene Zug endet wieder wortlos').toContain('codexCutoffNote')
+ expect(raw, 'Ollama liefert den Grund, die Schleife nimmt ihn nicht').toContain('turn.doneReason')
+ expect(raw, 'die uebrigen Transporte liefern ihn auch').toContain('turn.finishReason')
+ })
+})
diff --git a/src/hooks/codex/turn-cutoff.ts b/src/hooks/codex/turn-cutoff.ts
new file mode 100644
index 00000000..8c91b6a8
--- /dev/null
+++ b/src/hooks/codex/turn-cutoff.ts
@@ -0,0 +1,33 @@
+import type { PlanGap } from '../../lib/plan-reconcile'
+
+/**
+ * Ein Zug, den das Modell nicht selbst beendet hat, und der Satz dafuer.
+ *
+ * Fehler D, Symptom 2 (aldrich_ironhart, Discord 08.09.2026, Ollama, Code
+ * Reiter): "the plan hangs at step 2". Laeuft ein Zug in die Token Grenze,
+ * kommt er OHNE Werkzeugaufruf zurueck, und die Schleife in useCodex.ts kann
+ * ihn von einem Modell, das fertig ist, nicht unterscheiden: sie faellt durch
+ * `break-no-toolcalls` und der Lauf endet wortlos. Der Plan steht danach genau
+ * auf dem Schritt, an dem er stand.
+ *
+ * Der Grund lag die ganze Zeit auf der Leitung. Ollama schickt ihn als
+ * `done_reason: "length"`, `wire.ts` liest ihn aus, der regulaere Chat gibt ihn
+ * als `finishReason` weiter und erklaert ihn dem Nutzer
+ * (lib/answer-notes.ts). Nur der Transport des Coding Agenten warf ihn weg.
+ *
+ * Eigener Satz statt `emptyAnswerExplanation`: dort geht es um eine Antwort,
+ * die nie geschrieben wurde, hier um einen LAUF, der auf einem benannten
+ * Schritt stehenbleibt. Der offene Schritt gehoert in den Satz, denn er ist
+ * das Einzige, was der Nutzer danach wieder aufgreifen kann.
+ *
+ * Reine Funktion, damit der Wortlaut pruefbar ist: der Rest dieser Weiche
+ * steckt in einem `useCallback`, den kein Test von aussen erreicht.
+ */
+export function codexCutoffNote(finishReason: string | undefined, gap: PlanGap | null): string | null {
+ if (finishReason !== 'length') return null
+ const head = 'The model ran out of tokens in the middle of this step, so it never sent the next tool call.'
+ const tail = 'Raise Max Tokens in Settings, or give the model a larger context, then send "continue".'
+ return gap
+ ? `${head} The plan stands at ${gap.done} of ${gap.total}, still open: "${gap.next}". ${tail}`
+ : `${head} ${tail}`
+}
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index e35e5372..746092ef 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -99,6 +99,7 @@ import { shouldDowngradeThinking, engineDeniedThinking } from './codex/thinking-
import { recoverToolCallsFromContent } from './codex/tool-call-recovery'
import { codexStallVerdict } from './codex/stall-verdict'
import { createStagedWriter } from './codex/staged-writes'
+import { codexCutoffNote } from './codex/turn-cutoff'
import { codexToolDiff, codexEventKind } from './codex/tool-result-view'
import { capHiddenToolHistory } from './codex/hidden-history'
import { withHouseConduct } from '../lib/system-prompt'
@@ -1064,6 +1065,10 @@ export function useCodex() {
}
let toolCalls: ToolCall[] = []
let turnContent = ''
+ // Warum DIESER Zug endete. Nur `length` wird ausgewertet, und nur
+ // unten in der Weiche ohne Werkzeugaufruf: ein abgeschnittener Zug
+ // sah dort bis Fehler D genauso aus wie ein fertiges Modell.
+ let turnFinishReason: string | undefined
// Plain-text-planner escape for Gemma 3/4 — see useChat.ts.
const canThinkCx = codexCanThink(activeModel)
@@ -1306,7 +1311,11 @@ export function useCodex() {
// at an empty bubble for 2+ minutes while the model generates.
//
// Echo guard lives in the shared liveContent above.
- let turn: { content: string; toolCalls: ToolCall[]; thinking: string; promptEvalCount?: number; evalCount?: number }
+ // Aus der Quelle abgeleitet statt abgeschrieben: die abgeschriebene
+ // Fassung kannte `doneReason` nicht, und ein Feld, das der
+ // Transport liefert und diese Zeile verschweigt, ist genau die
+ // Sorte Drift, die Fehler D Symptom 2 lange unsichtbar hielt.
+ let turn: Awaited<ReturnType<typeof streamWithTools>>
// Token counter (David 2026-06-12): reflect the REAL prompt size —
// system prompt + tool defs + repo map + history — immediately, not a
// char/4 guess of just the visible messages. Provisional estimate that
@@ -1354,6 +1363,7 @@ export function useCodex() {
settleLivePaint()
toolCalls = turn.toolCalls
turnContent = turn.content || ''
+ turnFinishReason = turn.doneReason
reportTurnUsage(convId!, assistantMsg.id, turn)
void diagLog('streamWithTools-return', {
iter: i,
@@ -1402,6 +1412,7 @@ export function useCodex() {
settleLivePaint()
toolCalls = turn.toolCalls
turnContent = turn.content || ''
+ turnFinishReason = turn.finishReason
reportTurnUsage(convId!, assistantMsg.id, turn)
if (keepThinking && turn.thinking) {
thinkingContent += (thinkingContent ? '\n\n' : '') + turn.thinking
@@ -1736,7 +1747,33 @@ export function useCodex() {
continue
}
}
- void diagLog('break-no-toolcalls', { iter: i, turnContentLen: turnContent.length, fullContentLen: fullContent.length })
+ // Fehler D, Symptom 2: bis hierher war ein Zug, den das Modell nie
+ // zu Ende schreiben konnte, von einem fertigen Modell nicht zu
+ // unterscheiden: derselbe leere Werkzeugsatz, derselbe wortlose
+ // Abbruch, und der Plan blieb auf seinem offenen Schritt stehen.
+ // Der Grund lag die ganze Zeit auf der Leitung (`done_reason` bei
+ // Ollama, `finish_reason` bei den uebrigen). Sichtbar wie der Halt
+ // der Schleifenwache: im Faden UND an der Antwort, sonst kann
+ // niemand die beiden Faelle spaeter auseinanderhalten.
+ const cutoff = codexCutoffNote(
+ turnFinishReason,
+ convId ? openPlanGap(useTodoStore.getState().getTodos(convId)) : null,
+ )
+ if (cutoff && convId) {
+ void diagLog('turn-cut-off', { iter: i, reason: turnFinishReason })
+ useChatStore.getState().updateMessageContent(
+ convId,
+ assistantMsg.id,
+ (fullContent ? fullContent + '\n\n' : '') + `_(${cutoff})_`,
+ )
+ addBlock({
+ id: uuid(),
+ phase: 'reflection',
+ content: `\u26d4 ${cutoff}`,
+ timestamp: Date.now(),
+ })
+ }
+ void diagLog('break-no-toolcalls', { iter: i, turnContentLen: turnContent.length, fullContentLen: fullContent.length, finishReason: turnFinishReason })
break
}
diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.ts
index f5ae171f..5f4b7e22 100644
--- a/src/lib/ollama-stream-tools.ts
+++ b/src/lib/ollama-stream-tools.ts
@@ -58,7 +58,7 @@ export async function streamOllamaChatWithTools(
options: { temperature?: number; thinking?: boolean; maxTokens?: number; contextWindow?: number; signal?: AbortSignal },
onContent: (content: string) => void,
onThinking: (thinking: string) => void,
-): Promise<{ content: string; toolCalls: ToolCall[]; thinking: string; promptEvalCount: number; evalCount: number }> {
+): Promise<{ content: string; toolCalls: ToolCall[]; thinking: string; promptEvalCount: number; evalCount: number; doneReason?: string }> {
// Bug B3: this path talks to /api/chat behind the provider's back, so it
// needs the same contract. It always sends a native `tools` payload (the
// strategy resolution only routes here after Ollama reported the model's
@@ -170,6 +170,14 @@ export async function streamOllamaChatWithTools(
// TokenCounter shows 100% real usage instead of a char/4 estimate.
let promptEvalCount = 0
let evalCount = 0
+ // Why the turn ENDED, straight from Ollama's final chunk. `wire.ts` has
+ // always parsed it and `ollama-provider.ts` has always handed it on as
+ // `finishReason`; this transport dropped it, and the coding loop therefore
+ // could not tell a turn the model never finished from a model that was done
+ // (bug D symptom 2, aldrich_ironhart, Discord 2026-09-08). A `length` cut
+ // arrives with no tool call, so the loop falls through `break-no-toolcalls`
+ // and the run ends without a word while the plan stands on its open step.
+ let doneReason: string | undefined
// No-bytes watchdog (audit A7): a wedged runner behind a live connection
// ends neither with data nor an error, and read() sat forever. Five silent
@@ -240,6 +248,7 @@ export async function streamOllamaChatWithTools(
}
if (j.prompt_eval_count !== undefined) promptEvalCount = j.prompt_eval_count
if (j.eval_count !== undefined) evalCount = j.eval_count
+ if (j.done_reason) doneReason = j.done_reason
}
}
@@ -269,8 +278,9 @@ export async function streamOllamaChatWithTools(
}
if (j.prompt_eval_count !== undefined) promptEvalCount = j.prompt_eval_count
if (j.eval_count !== undefined) evalCount = j.eval_count
+ if (j.done_reason) doneReason = j.done_reason
}
}
- return { content, toolCalls, thinking, promptEvalCount, evalCount }
+ return { content, toolCalls, thinking, promptEvalCount, evalCount, doneReason }
}