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.

tech(W-T3/KF-14): useCodex.ts zerlegt — und die Obergrenze dabei benannt

Davidf264244b309c
diff --git a/src/hooks/codex/__tests__/ablage-warteschlange.test.ts b/src/hooks/codex/__tests__/ablage-warteschlange.test.ts
new file mode 100644
index 00000000..63e2be19
--- /dev/null
+++ b/src/hooks/codex/__tests__/ablage-warteschlange.test.ts
@@ -0,0 +1,233 @@
+/**
+ * Die Ablage-Warteschlange des Coding-Agenten (Stage-and-Approve).
+ *
+ * ── WARUM ES DIESEN TEST VORHER NICHT GAB ──────────────────────────────────
+ * `stageFileWrite` und `stageFileEdit` waren zwei Closures 1900 Zeilen tief in
+ * einem 2358-Zeilen-`useCallback` eines React-Hooks. Sie schlossen ueber
+ * `convId`, `workDir`, `workspaceSlug` und `backendCall` und waren von aussen
+ * nicht erreichbar — man konnte sie nur pruefen, indem man einen ganzen
+ * Codex-Zug fuhr, also mit Modell, Anbieter und Rust-Backend daran. Genau
+ * deshalb hing an diesen 150 Zeilen kein einziger Test, obwohl in ihnen die
+ * Lies-deine-Schreibungen-Regel steckt, deren Fehlen Morgan am 2026-07-26 eine
+ * fuenfminuetige `file_read`-Schleife eingebracht hat.
+ *
+ * ── WAS HIER ECHT IST ──────────────────────────────────────────────────────
+ * Echt: `useStagedChangesStore` (der wirkliche Zustandsspeicher),
+ * `computeUnifiedDiff`, `applyUniqueEdit`, `findStagedForPath`,
+ * `stagedReadResult`, `stagedListingNote` — die ganze Kette unter Test.
+ *
+ * Der Dateileser ist eine ECHTE Funktion ueber eine echte Zuordnung
+ * Pfad→Inhalt, kein Attrappen-Rahmenwerk: das Modul nimmt ihn als Naht
+ * entgegen, genau wie `dev-server/fs-routes.ts` dem Pfad-Kaefig seinen
+ * `realPath` von aussen gibt. Was in der App dahintersteht, ist
+ * `readWorkspaceFile` → `backendCall('fs_read')`; das ist ein Prozessaufruf ins
+ * Rust-Backend und hat in einem node-Test nichts verloren.
+ *
+ * Run: npx vitest run src/hooks/codex/__tests__/ablage-warteschlange.test.ts
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import { createStagedWriter } from '../staged-writes'
+import { useStagedChangesStore } from '../../../stores/stagedChangesStore'
+import type { CodexFsCtx, CodexFileRead } from '../workspace-fs'
+
+const CONV = 'conv-ablage'
+
+/** Ein echter Leser ueber eine echte Zuordnung. Fehlt der Pfad, wirft er — so
+ * wie `fs_read` es fuer eine nicht vorhandene Datei tut. */
+function readerOver(files: Record<string, CodexFileRead>) {
+ const seen: string[] = []
+ const read = (path: string, _ctx: CodexFsCtx): Promise<CodexFileRead> => {
+ seen.push(path)
+ const hit = files[path]
+ if (!hit) return Promise.reject(new Error(`ENOENT: ${path}`))
+ return Promise.resolve(hit)
+ }
+ return { read, seen }
+}
+
+function writerIn(workDir: string, files: Record<string, CodexFileRead> = {}) {
+ const r = readerOver(files)
+ return {
+ writer: createStagedWriter({
+ convId: CONV,
+ workDir,
+ workspaceSlug: 'slug-1',
+ readFile: r.read,
+ }),
+ seen: r.seen,
+ }
+}
+
+const queue = () => useStagedChangesStore.getState().list(CONV)
+
+beforeEach(() => {
+ useStagedChangesStore.getState().clear(CONV)
+})
+
+describe('Der Pfad, unter dem eine Aenderung spaeter landet', () => {
+ it('haengt einen relativen Pfad an den Arbeitsordner', async () => {
+ const { writer } = writerIn('/home/u/repo')
+ await writer.stageFileWrite({ path: 'src/app.ts', content: 'neu' })
+ expect(queue()[0].resolvedPath).toBe('/home/u/repo/src/app.ts')
+ })
+
+ it('nimmt den Windows-Trenner, wenn der Arbeitsordner einer ist', async () => {
+ const { writer } = writerIn('D:\\Pictures\\foo')
+ await writer.stageFileWrite({ path: 'index.html', content: 'x' })
+ expect(queue()[0].resolvedPath).toBe('D:\\Pictures\\foo\\index.html')
+ })
+
+ it('laesst absolute Pfade in Ruhe — unix, Laufwerksbuchstabe und UNC', async () => {
+ for (const [i, p] of ['/etc/hosts', 'C:/Windows/x.dll', '\\\\server\\share\\x.txt'].entries()) {
+ useStagedChangesStore.getState().clear(CONV)
+ const { writer } = writerIn('/home/u/repo')
+ await writer.stageFileWrite({ path: p, content: `v${i}` })
+ expect(queue()[0].resolvedPath).toBe(p)
+ }
+ })
+
+ it('laesst in der Sandbox alles unveraendert und merkt sich KEINE Wurzel', async () => {
+ const { writer } = writerIn('.')
+ await writer.stageFileWrite({ path: 'a.txt', content: 'x' })
+ expect(queue()[0].resolvedPath).toBe('a.txt')
+ // Ohne echten Ordner ist die Sandbox pro Chat die richtige Wurzel; ein
+ // gemerktes '.' wuerde das Anwenden spaeter in den falschen Ordner lenken.
+ expect(queue()[0].workingDirectory).toBeUndefined()
+ })
+
+ it('merkt sich im Ordner-Betrieb die Wurzel fuer das spaetere Anwenden', async () => {
+ const { writer } = writerIn('/home/u/repo')
+ await writer.stageFileWrite({ path: 'a.txt', content: 'x' })
+ expect(queue()[0].workingDirectory).toBe('/home/u/repo')
+ })
+})
+
+describe('Lies deine eigenen Schreibungen', () => {
+ it('zweites file_write auf dieselbe Datei behaelt die PLATTENfassung als Vergleichsbasis', async () => {
+ const { writer, seen } = writerIn('/repo', { '/repo/a.ts': { content: 'PLATTE' } })
+ await writer.stageFileWrite({ path: 'a.ts', content: 'erste' })
+ await writer.stageFileWrite({ path: 'a.ts', content: 'zweite' })
+ expect(queue()).toHaveLength(1)
+ expect(queue()[0].newContent).toBe('zweite')
+ // Das ist die Zusicherung: der geprueft angezeigte Unterschied bleibt
+ // Platte → Endstand, nicht abgelegt → abgelegt.
+ expect(queue()[0].oldContent).toBe('PLATTE')
+ // Und die Platte wird dafuer kein zweites Mal gelesen.
+ expect(seen).toEqual(['/repo/a.ts'])
+ })
+
+ it('file_edit setzt auf dem ABGELEGTEN Inhalt auf, nicht auf der Platte', async () => {
+ const { writer } = writerIn('/repo', { '/repo/a.ts': { content: 'eins zwei' } })
+ await writer.stageFileEdit({ path: 'a.ts', old_string: 'eins', new_string: 'EINS' })
+ const zweite = await writer.stageFileEdit({ path: 'a.ts', old_string: 'zwei', new_string: 'ZWEI' })
+ expect(zweite).toContain('Staged for review')
+ // Ohne die Regel haette die zweite Bearbeitung die erste still ueberschrieben.
+ expect(queue()[0].newContent).toBe('EINS ZWEI')
+ expect(queue()[0].oldContent).toBe('eins zwei')
+ })
+
+ it('file_edit an einer abgelegten NEUEN Datei gelingt, obwohl die Platte sie nicht kennt', async () => {
+ const { writer } = writerIn('/repo')
+ await writer.stageFileWrite({ path: 'neu.ts', content: 'hallo welt' })
+ const res = await writer.stageFileEdit({ path: 'neu.ts', old_string: 'welt', new_string: 'du' })
+ expect(res).toContain('Staged for review')
+ expect(queue()[0].newContent).toBe('hallo du')
+ expect(queue()[0].oldContent).toBe('')
+ })
+
+ it('file_read wird AUS der Schlange beantwortet, mit Merkzettel', async () => {
+ const { writer } = writerIn('/repo', { '/repo/a.ts': { content: 'PLATTE' } })
+ await writer.stageFileWrite({ path: 'a.ts', content: 'ABGELEGT' })
+ const res = await writer.dispatch('file_read', { path: 'a.ts' }, () =>
+ Promise.resolve('DAS DARF NICHT KOMMEN'))
+ expect(res).toContain('ABGELEGT')
+ expect(res).not.toContain('DAS DARF NICHT KOMMEN')
+ expect(res).toContain('NOT on disk yet')
+ })
+
+ it('file_read auf einen NICHT abgelegten Pfad geht durch', async () => {
+ const { writer } = writerIn('/repo')
+ await writer.stageFileWrite({ path: 'a.ts', content: 'x' })
+ const res = await writer.dispatch('file_read', { path: 'b.ts' }, () => Promise.resolve('VON DER PLATTE'))
+ expect(res).toBe('VON DER PLATTE')
+ })
+
+ it('file_list und file_search bekommen die Anmerkung ANGEHAENGT, nicht ersetzt', async () => {
+ const { writer } = writerIn('/repo')
+ await writer.stageFileWrite({ path: 'a.ts', content: 'x' })
+ for (const name of ['file_list', 'file_search']) {
+ const res = await writer.dispatch(name, {}, () => Promise.resolve('ECHTES LISTING'))
+ expect(res.startsWith('ECHTES LISTING')).toBe(true)
+ expect(res).toContain('a.ts')
+ }
+ })
+
+ it('ohne etwas in der Schlange bleibt jede Antwort unberuehrt', async () => {
+ const { writer } = writerIn('/repo')
+ for (const name of ['file_read', 'file_list', 'file_search', 'shell_execute']) {
+ const res = await writer.dispatch(name, { path: 'a.ts' }, () => Promise.resolve('ROH'))
+ expect(res).toBe('ROH')
+ }
+ })
+})
+
+describe('Was der Nutzer vor der Freigabe zu sehen bekommt', () => {
+ it('eine neue Datei erscheint als reine Einfuegung', async () => {
+ const { writer } = writerIn('/repo')
+ await writer.stageFileWrite({ path: 'neu.ts', content: 'a\nb\n' })
+ const d = queue()[0].diff
+ expect(d).toContain('+a')
+ expect(d).toContain('+b')
+ // Der Kopf `--- a/neu.ts` zaehlt nicht; gemeint sind Loeschzeilen.
+ expect(d.split('\n').filter((l) => l.startsWith('-') && !l.startsWith('---'))).toHaveLength(0)
+ })
+
+ it('eine UEBERSCHRIEBENE Datei zeigt die Loeschungen — das war der Fehler von 2.5.9', async () => {
+ const { writer } = writerIn('/repo', { '/repo/a.ts': { content: 'alt1\nalt2\n' } })
+ await writer.stageFileWrite({ path: 'a.ts', content: 'neu\n' })
+ const d = queue()[0].diff
+ expect(d).toContain('-alt1')
+ expect(d).toContain('-alt2')
+ expect(d).toContain('+neu')
+ })
+})
+
+describe('Was schiefgehen kann, und was dann dasteht', () => {
+ it('ohne Pfad sagt es das und legt nichts ab', async () => {
+ const { writer } = writerIn('/repo')
+ expect(await writer.stageFileWrite({})).toBe('file_write: missing path')
+ expect(await writer.stageFileEdit({})).toBe('file_edit: missing path')
+ expect(queue()).toHaveLength(0)
+ })
+
+ it('eine Binaerdatei wird nicht bearbeitet', async () => {
+ for (const enc of ['binary', 'base64']) {
+ useStagedChangesStore.getState().clear(CONV)
+ const { writer } = writerIn('/repo', { '/repo/bild.png': { content: 'xx', encoding: enc } })
+ const res = await writer.stageFileEdit({ path: 'bild.png', old_string: 'x', new_string: 'y' })
+ expect(res).toBe('file_edit: cannot edit a binary file (bild.png).')
+ expect(queue()).toHaveLength(0)
+ }
+ })
+
+ it('eine unlesbare Datei verweist auf file_write statt still zu scheitern', async () => {
+ const { writer } = writerIn('/repo')
+ const res = await writer.stageFileEdit({ path: 'weg.ts', old_string: 'a', new_string: 'b' })
+ expect(res).toBe('file_edit: could not read weg.ts. To create a new file use file_write.')
+ expect(queue()).toHaveLength(0)
+ })
+
+ it('die vier Absagen des chirurgischen Schnitts kommen woertlich durch', async () => {
+ const { writer } = writerIn('/repo', { '/repo/a.ts': { content: 'x x' } })
+ expect(await writer.stageFileEdit({ path: 'a.ts', old_string: '', new_string: 'b' }))
+ .toBe('file_edit: old_string must be non-empty. Use file_write to create a new file.')
+ expect(await writer.stageFileEdit({ path: 'a.ts', old_string: 'x', new_string: 'x' }))
+ .toBe('file_edit: old_string and new_string are identical, nothing to change.')
+ expect(await writer.stageFileEdit({ path: 'a.ts', old_string: 'zzz', new_string: 'b' }))
+ .toBe('file_edit: old_string not found in a.ts. Read the file and copy the exact text you want to replace.')
+ expect(await writer.stageFileEdit({ path: 'a.ts', old_string: 'x', new_string: 'y' }))
+ .toBe('file_edit: old_string matches 2 places in a.ts. Add surrounding lines so it is unique.')
+ // Keine dieser vier Absagen darf etwas in die Schlange legen.
+ expect(queue()).toHaveLength(0)
+ })
+})
diff --git a/src/hooks/codex/__tests__/ein-lauf.test.ts b/src/hooks/codex/__tests__/ein-lauf.test.ts
new file mode 100644
index 00000000..f839cc4e
--- /dev/null
+++ b/src/hooks/codex/__tests__/ein-lauf.test.ts
@@ -0,0 +1,338 @@
+/**
+ * Was einen Codex-Lauf rahmt: Ordner, Absagen, Bloecke, Ergebnisanzeige und
+ * die versteckte Kette fuer den naechsten Zug.
+ *
+ * ── WARUM ES DIESE TESTS VORHER NICHT GAB ──────────────────────────────────
+ * Fuenf Regeln, fuenf Stellen quer durch `useCodex.ts`, keine davon von aussen
+ * erreichbar. Die teuerste davon steht ganz oben: die Ordner-Rangfolge. Sie
+ * bestimmt ZWEI Dinge gleichzeitig — was dem Modell als Arbeitsverzeichnis
+ * GESAGT wird und worauf die Sperre GESETZT wird —, und genau diese beiden sind
+ * am 2026-07-11 live auseinandergelaufen: die Sperre blieb auf der Sandbox,
+ * waehrend das Modell einen echten Ordner genannt bekam, und jedes
+ * `file_list`/`file_read` scheiterte mit "path escapes the allowed workspace".
+ *
+ * ── WAS HIER ECHT IST ──────────────────────────────────────────────────────
+ * Echt: `useChatStore` fuer die Blockliste, `computeUnifiedDiff` und
+ * `applyUniqueEdit` fuer die Unterschiede, `CODEX_MODE_LABELS` fuer die
+ * Absagen. Nichts auf dem Weg unter Test ist ersetzt.
+ *
+ * Run: npx vitest run src/hooks/codex/__tests__/ein-lauf.test.ts
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import { resolveCodexWorkspace } from '../workspace-precedence'
+import { codexModeRefusal } from '../mode-refusal'
+import { createAgentBlockSink } from '../agent-blocks'
+import { codexToolDiff, codexEventKind } from '../tool-result-view'
+import { capHiddenToolHistory, HIDDEN_HISTORY_MAX } from '../hidden-history'
+import { codexReadCtx } from '../workspace-fs'
+import { useChatStore } from '../../../stores/chatStore'
+import type { AgentWorkspace } from '../../../types/agent-workspace'
+import type { ChatMessage } from '../../../api/providers/types'
+
+// ── Ein Ordner, vier Bewerber ───────────────────────────────────────────────
+
+const FOLDER: AgentWorkspace = { kind: 'folder', path: '/ws/aus-settings' }
+const SANDBOX: AgentWorkspace = { kind: 'sandbox' }
+
+describe('Welcher Ordner der Lauf benutzt', () => {
+ it('die Auswahl im Datei-Baum schlaegt alles andere', () => {
+ const r = resolveCodexWorkspace({
+ threadWorkingDirectory: '/ws/aus-baum',
+ codexWorkspace: FOLDER,
+ storeWorkingDirectory: '/ws/global',
+ })
+ expect(r.workDir).toBe('/ws/aus-baum')
+ })
+
+ it('ein "." im Baum zaehlt NICHT als Auswahl', () => {
+ const r = resolveCodexWorkspace({
+ threadWorkingDirectory: '.',
+ codexWorkspace: FOLDER,
+ storeWorkingDirectory: '/ws/global',
+ })
+ expect(r.workDir).toBe('/ws/aus-settings')
+ })
+
+ it('danach der aufgeloeste Workspace, danach der globale, danach die Sandbox', () => {
+ expect(resolveCodexWorkspace({ threadWorkingDirectory: null, codexWorkspace: FOLDER, storeWorkingDirectory: '/ws/global' }).workDir)
+ .toBe('/ws/aus-settings')
+ expect(resolveCodexWorkspace({ threadWorkingDirectory: null, codexWorkspace: null, storeWorkingDirectory: '/ws/global' }).workDir)
+ .toBe('/ws/global')
+ expect(resolveCodexWorkspace({ threadWorkingDirectory: null, codexWorkspace: null, storeWorkingDirectory: null }).workDir)
+ .toBe('.')
+ })
+
+ it('ein Sandbox-Workspace liefert keinen Pfad und wird uebersprungen', () => {
+ const r = resolveCodexWorkspace({ threadWorkingDirectory: null, codexWorkspace: SANDBOX, storeWorkingDirectory: '/ws/global' })
+ expect(r.workspacePath).toBeNull()
+ expect(r.workDir).toBe('/ws/global')
+ })
+
+ it('DIE ZUSICHERUNG: die Sperre nennt denselben Ordner, den das Modell genannt bekommt', () => {
+ // Das ist der Fund vom 2026-07-11. Der Fall, an dem er auffiel, steht
+ // zuerst: die Auswahl des Code-Reiters, die `resolveWorkspace()` GAR NICHT
+ // SIEHT.
+ const faelle = [
+ { threadWorkingDirectory: null, codexWorkspace: null, storeWorkingDirectory: '/ws/explorer-auswahl' },
+ { threadWorkingDirectory: '/ws/aus-baum', codexWorkspace: null, storeWorkingDirectory: null },
+ { threadWorkingDirectory: '/ws/aus-baum', codexWorkspace: FOLDER, storeWorkingDirectory: '/ws/global' },
+ { threadWorkingDirectory: null, codexWorkspace: SANDBOX, storeWorkingDirectory: '/ws/explorer-auswahl' },
+ { threadWorkingDirectory: null, codexWorkspace: FOLDER, storeWorkingDirectory: null },
+ ]
+ for (const f of faelle) {
+ const r = resolveCodexWorkspace(f)
+ expect(r.workDir).not.toBe('.')
+ expect(r.runWorkspace).not.toBeNull()
+ expect(r.runWorkspace!.kind).toBe('folder')
+ expect(r.runWorkspace!.path).toBe(r.workDir)
+ }
+ })
+
+ it('ohne echten Ordner bleibt die Sperre, was sie war — die Sandbox pro Chat', () => {
+ expect(resolveCodexWorkspace({ threadWorkingDirectory: null, codexWorkspace: null, storeWorkingDirectory: null }).runWorkspace)
+ .toBeNull()
+ expect(resolveCodexWorkspace({ threadWorkingDirectory: null, codexWorkspace: SANDBOX, storeWorkingDirectory: null }).runWorkspace)
+ .toBe(SANDBOX)
+ })
+
+ it('Zusatzpfade eines Mehr-Repo-Laufs ueberleben die Umheftung', () => {
+ const multi: AgentWorkspace = { kind: 'folder', path: '/ws/a', extraPaths: ['/ws/b'] }
+ const r = resolveCodexWorkspace({ threadWorkingDirectory: '/ws/aus-baum', codexWorkspace: multi, storeWorkingDirectory: null })
+ expect(r.runWorkspace!.path).toBe('/ws/aus-baum')
+ expect(r.runWorkspace!.extraPaths).toEqual(['/ws/b'])
+ })
+})
+
+// ── Der Lesekontext ─────────────────────────────────────────────────────────
+
+describe('Der Lesekontext fuer fs_read', () => {
+ it('nennt im Ordner-Betrieb die Wurzel, sonst nicht', () => {
+ expect(codexReadCtx('slug', '/repo')).toEqual({ chatId: 'slug', workingDirectory: '/repo' })
+ expect(codexReadCtx('slug', '.')).toEqual({ chatId: 'slug' })
+ expect(codexReadCtx('slug', '')).toEqual({ chatId: 'slug' })
+ })
+})
+
+// ── Absagen ─────────────────────────────────────────────────────────────────
+
+const schreibbefehl = { command: { name: 'commit' } }
+const lesebefehl = { command: { name: 'review', readOnly: true } }
+
+describe('Ein Befehl, der in diesem Modus nichts ausrichten kann', () => {
+ it('sagt im Review-Modus ab und nennt den Ausweg', () => {
+ const m = codexModeRefusal({ reviewMode: true, codexMode: 'ask', slash: schreibbefehl })
+ expect(m).toContain('Review Mode is on')
+ expect(m).toContain('/commit')
+ expect(m).toContain('/review, /plan, /diff or /explain')
+ })
+
+ it('sagt im Plan-Modus ab und nennt den Modus, auf den man stellen muss', () => {
+ const m = codexModeRefusal({ reviewMode: false, codexMode: 'plan', slash: schreibbefehl })
+ expect(m).toContain('Plan mode is read-only')
+ expect(m).toContain('Ask permissions')
+ expect(m).toContain('/review, /plan, /diff or /explain')
+ })
+
+ it('DIE RANGFOLGE: Review gewinnt vor Plan', () => {
+ // Bisher ergab sich das nur daraus, dass ein `if` vor dem anderen stand.
+ const m = codexModeRefusal({ reviewMode: true, codexMode: 'plan', slash: schreibbefehl })
+ expect(m).toContain('Review Mode is on')
+ expect(m).not.toContain('Plan mode is read-only')
+ })
+
+ it('laesst einen schreibfreien Befehl in beiden Modi durch', () => {
+ expect(codexModeRefusal({ reviewMode: true, codexMode: 'plan', slash: lesebefehl })).toBeNull()
+ })
+
+ it('laesst eine normale Anweisung ohne Befehl immer durch', () => {
+ expect(codexModeRefusal({ reviewMode: true, codexMode: 'plan', slash: null })).toBeNull()
+ })
+
+ it('behandelt ein fehlendes Review-Flag wie "aus"', () => {
+ expect(codexModeRefusal({ reviewMode: undefined, codexMode: 'ask', slash: schreibbefehl })).toBeNull()
+ })
+})
+
+// ── Die Blockliste ──────────────────────────────────────────────────────────
+
+describe('Die Blockliste und ihr Spiegel im Speicher', () => {
+ let convId = ''
+ const MSG = 'msg-blocks'
+ const gespiegelt = () =>
+ useChatStore.getState().conversations.find((c) => c.id === convId)
+ ?.messages.find((m) => m.id === MSG)?.agentBlocks
+
+ beforeEach(() => {
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ convId = useChatStore.getState().createConversation('m', '', 'codex')
+ useChatStore.getState().addMessage(convId, { id: MSG, role: 'assistant', content: '', timestamp: Date.now() })
+ })
+
+ it('jeder Zugang landet sofort im Speicher', () => {
+ const sink = createAgentBlockSink(convId, MSG)
+ sink.add({ id: 'b1', phase: 'answer', content: 'eins', timestamp: 1 })
+ sink.add({ id: 'b2', phase: 'answer', content: 'zwei', timestamp: 2 })
+ expect(gespiegelt()?.map((b) => b.id)).toEqual(['b1', 'b2'])
+ })
+
+ it('DIE ZUSICHERUNG: jeder Schreibvorgang reicht eine FRISCHE Liste weiter', () => {
+ // React vergleicht flach. Zweimal dieselbe Liste hiesse: neue Bloecke sind
+ // da, aber unsichtbar.
+ const sink = createAgentBlockSink(convId, MSG)
+ sink.add({ id: 'b1', phase: 'answer', content: 'eins', timestamp: 1 })
+ const ersteListe = gespiegelt()
+ sink.add({ id: 'b2', phase: 'answer', content: 'zwei', timestamp: 2 })
+ expect(gespiegelt()).not.toBe(ersteListe)
+ expect(gespiegelt()).not.toBe(sink.list())
+ })
+
+ it('update aendert genau einen Block und laesst den Rest stehen', () => {
+ const sink = createAgentBlockSink(convId, MSG)
+ sink.add({ id: 'b1', phase: 'tool_call', content: 'Running: file_read', timestamp: 1 })
+ sink.add({ id: 'b2', phase: 'tool_call', content: 'Running: file_write', timestamp: 2 })
+ sink.update('b1', { content: 'Completed: file_read' })
+ expect(gespiegelt()?.map((b) => b.content)).toEqual(['Completed: file_read', 'Running: file_write'])
+ })
+
+ it('update auf eine unbekannte Kennung tut NICHTS — kein Nachschieben, kein Anlegen', () => {
+ const sink = createAgentBlockSink(convId, MSG)
+ sink.add({ id: 'b1', phase: 'answer', content: 'eins', timestamp: 1 })
+ const vorher = gespiegelt()
+ sink.update('gibtesnicht', { content: 'kaputt' })
+ expect(gespiegelt()).toBe(vorher)
+ expect(gespiegelt()).toHaveLength(1)
+ })
+})
+
+// ── Was der Nutzer vom Ergebnis sieht ───────────────────────────────────────
+
+describe('Der nachgebaute Unterschied eines fertigen Aufrufs', () => {
+ it('file_write: Vorlese-Runde gegen den geschriebenen Inhalt', () => {
+ const d = codexToolDiff({ toolName: 'file_write', path: 'a.ts', oldText: 'alt\n', args: { content: 'neu\n' } })
+ expect(d).toContain('-alt')
+ expect(d).toContain('+neu')
+ })
+
+ it('file_edit: der neue Inhalt wird aus Vorgelesenem plus Ersetzung rekonstruiert', () => {
+ const d = codexToolDiff({
+ toolName: 'file_edit', path: 'a.ts', oldText: 'eins\nzwei\ndrei\n',
+ args: { old_string: 'zwei', new_string: 'ZWEI' },
+ })
+ expect(d).toContain('-zwei')
+ expect(d).toContain('+ZWEI')
+ // Die unberuehrten Zeilen bleiben Kontext, keine Loeschung.
+ expect(d).not.toContain('-eins')
+ })
+
+ it('eine nicht eindeutige Bearbeitung zeigt GAR KEINEN Unterschied statt einen falschen', () => {
+ const d = codexToolDiff({
+ toolName: 'file_edit', path: 'a.ts', oldText: 'x\nx\n',
+ args: { old_string: 'x', new_string: 'y' },
+ })
+ expect(d).toBeUndefined()
+ })
+
+ it('ein Aufruf, der nichts geaendert hat, bekommt keinen leeren Rahmen', () => {
+ expect(codexToolDiff({ toolName: 'file_write', path: 'a.ts', oldText: 'gleich\n', args: { content: 'gleich\n' } }))
+ .toBeUndefined()
+ })
+
+ it('Argumente, die das Modell nicht als Text geschickt hat, werden nicht geraten', () => {
+ // `content` ist Modell-Ausgabe. Eine Zahl darf nicht als "123" gezeichnet
+ // werden, sondern zaehlt als leer.
+ const d = codexToolDiff({ toolName: 'file_write', path: 'a.ts', oldText: 'alt\n', args: { content: 123 } })
+ expect(d).toContain('-alt')
+ expect(d).not.toContain('123')
+ })
+
+ it('jedes andere Werkzeug bekommt keinen Unterschied', () => {
+ expect(codexToolDiff({ toolName: 'shell_execute', path: undefined, oldText: '', args: { command: 'ls' } }))
+ .toBeUndefined()
+ })
+})
+
+describe('In welchen Eintrag des Ereignisprotokolls ein Aufruf faellt', () => {
+ it('die beiden Ausfuehrer werden Terminalausgabe', () => {
+ expect(codexEventKind('shell_execute', false)).toBe('terminal_output')
+ expect(codexEventKind('code_execute', false)).toBe('terminal_output')
+ })
+
+ it('DIE REIHENFOLGE: ein FEHLGESCHLAGENES file_write bleibt eine Dateiaenderung', () => {
+ // Der Zweig fuer die Schreibwerkzeuge steht vor dem Fehlerzweig. Wer das
+ // umdreht, verliert die Aenderungsansicht genau dann, wenn man sie braucht.
+ expect(codexEventKind('file_write', true)).toBe('file_change')
+ expect(codexEventKind('file_edit', true)).toBe('file_change')
+ expect(codexEventKind('shell_execute', true)).toBe('terminal_output')
+ })
+
+ it('ein gescheitertes Lesewerkzeug wird ein Fehler', () => {
+ expect(codexEventKind('file_read', true)).toBe('error')
+ })
+
+ it('ein gelungenes Lesewerkzeug bekommt gar keinen Eintrag', () => {
+ expect(codexEventKind('file_read', false)).toBeNull()
+ expect(codexEventKind('web_search', false)).toBeNull()
+ })
+})
+
+// ── Die versteckte Werkzeugkette ────────────────────────────────────────────
+
+const paar = (i: number): ChatMessage[] => ([
+ { role: 'assistant', content: '', tool_calls: [{ id: `c${i}`, function: { name: 'file_read', arguments: {} } }] },
+ { role: 'tool', content: `ergebnis ${i}`, tool_call_id: `c${i}` },
+])
+
+describe('Was der naechste Zug an versteckter Kette wiederbekommt', () => {
+ it('kurze Ketten bleiben unangetastet', () => {
+ const all = [...paar(1), ...paar(2)]
+ expect(capHiddenToolHistory(all)).toEqual(all)
+ })
+
+ it('lange Ketten werden gedeckelt', () => {
+ const all = Array.from({ length: 100 }, (_, i) => paar(i)).flat()
+ expect(capHiddenToolHistory(all).length).toBeLessThanOrEqual(HIDDEN_HISTORY_MAX)
+ })
+
+ it('DIE ZUSICHERUNG: die behaltene Kette beginnt NIE mit einem Waisen-Ergebnis', () => {
+ // Ein Ergebnis, dessen Aufruf aus dem Fenster fiel, laesst einen strengen
+ // Anbieter den ganzen Folgezug mit 422 abweisen.
+ //
+ // DIE PAARIGE KETTE ALLEIN ZEIGT DAS NICHT: bei lauter Aufruf/Ergebnis-Paaren
+ // faellt die Fenstergrenze immer auf einen geraden Index, also auf einen
+ // Aufruf. Der Waisenfall entsteht erst, wenn die Kette UNGERADE lang ist —
+ // und genau so endet ein echter Lauf, dessen letzter Zug nur noch geredet
+ // hat. Beide Formen stehen deshalb hier, sonst waere die Zusicherung leer.
+ const schluss: ChatMessage = { role: 'assistant', content: 'fertig' }
+ for (const n of [30, 31, 60, 61, 120, 121]) {
+ const paare = Array.from({ length: n }, (_, i) => paar(i)).flat()
+ for (const all of [paare, [...paare, schluss]]) {
+ const kept = capHiddenToolHistory(all)
+ if (kept.length > 0) expect(kept[0].role).not.toBe('tool')
+ }
+ // Und derselbe Grenzfall ueber eine ungerade Fensterbreite.
+ const eng = capHiddenToolHistory(paare, 59)
+ if (eng.length > 0) expect(eng[0].role).not.toBe('tool')
+ }
+ })
+
+ it('der Waisenschnitt kostet genau die eine Waise, nicht mehr', () => {
+ const paare = Array.from({ length: 50 }, (_, i) => paar(i)).flat()
+ const eng = capHiddenToolHistory(paare, 59)
+ // 59 gedeckelt, die fuehrende Waise weg: 58 bleiben, und der Rest steht
+ // vollstaendig da.
+ expect(eng).toHaveLength(58)
+ expect(eng[0].role).toBe('assistant')
+ expect(eng[eng.length - 1].role).toBe('tool')
+ })
+
+ it('ein Fenster aus lauter Ergebnissen bleibt leer statt kaputt', () => {
+ const nurErgebnisse: ChatMessage[] = Array.from({ length: 5 }, (_, i) => ({
+ role: 'tool', content: `e${i}`, tool_call_id: `c${i}`,
+ }))
+ expect(capHiddenToolHistory(nurErgebnisse)).toEqual([])
+ })
+
+ it('eine leere Kette bleibt leer', () => {
+ expect(capHiddenToolHistory([])).toEqual([])
+ })
+})
diff --git a/src/hooks/codex/__tests__/ein-modellzug.test.ts b/src/hooks/codex/__tests__/ein-modellzug.test.ts
new file mode 100644
index 00000000..7f934193
--- /dev/null
+++ b/src/hooks/codex/__tests__/ein-modellzug.test.ts
@@ -0,0 +1,273 @@
+/**
+ * Was ein einzelner Modellzug im Coding-Agenten ergibt.
+ *
+ * ── WARUM ES DIESE TESTS VORHER NICHT GAB ──────────────────────────────────
+ * Alle vier Regeln hier standen inline in der Schleife von `useCodex.ts`, in
+ * einem `useCallback` von 2358 Zeilen. Erreichbar waren sie nur ueber einen
+ * kompletten Zug — also mit Modell, Anbieter und Netz daran. Drei von ihnen
+ * hatten dabei eine dokumentierte Fehlergeschichte, und keine davon einen Test:
+ *
+ * • der Live-Anstrich (Pruefung D1: ein wartendes Bild malte alten Inhalt
+ * ueber den fertigen Text);
+ * • die Bergung von Werkzeugaufrufen aus dem Fliesstext (qwen2.5-coder:3b);
+ * • das Urteil "steckengeblieben oder fertig" (David 2026-06-02: der Agent
+ * "antwortet in loops" auf eine simple Frage);
+ * • der Denk-Abstieg, der in DREI Transporten in drei Schreibweisen stand.
+ *
+ * ── WAS HIER ECHT IST ──────────────────────────────────────────────────────
+ * Echt: `useChatStore` (der wirkliche Speicher), `extractToolCallsWithRanges`,
+ * `stripRanges`, `httpStatusOf`, `errorText`, `estimateTokens`. Die Muster und
+ * die Zahlen sind die echten.
+ *
+ * Der Bildplaner des Live-Anstrichs kommt von aussen. Nicht als Attrappe: die
+ * node-Umgebung dieser Testreihe HAT kein `requestAnimationFrame`, und die
+ * Regel, um die es geht ("settle loescht ein noch nicht gefeuertes Bild"),
+ * laesst sich nur zeigen, wenn man das Feuern in der Hand hat.
+ *
+ * Run: npx vitest run src/hooks/codex/__tests__/ein-modellzug.test.ts
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import { createLivePaint } from '../live-paint'
+import { recoverToolCallsFromContent } from '../tool-call-recovery'
+import { codexStallVerdict } from '../stall-verdict'
+import { isThinkingUnsupportedError } from '../thinking-downgrade'
+import { seedEstimatedUsage, reportTurnUsage } from '../turn-usage'
+import { useChatStore } from '../../../stores/chatStore'
+
+// ── Der Live-Anstrich ───────────────────────────────────────────────────────
+
+/** Ein echter Planer, dessen Bilder man von Hand feuert. */
+function manualFrames() {
+ const queued: Array<() => void> = []
+ return {
+ schedule: (cb: () => void) => { queued.push(cb) },
+ fire: () => { const q = queued.splice(0); for (const cb of q) cb() },
+ pending: () => queued.length,
+ }
+}
+
+function paintRig(opts: { prefix?: string; suppress?: (c: string) => boolean } = {}) {
+ const painted: string[] = []
+ const frames = manualFrames()
+ const lp = createLivePaint({
+ suppress: opts.suppress ?? (() => false),
+ prefix: () => opts.prefix ?? '',
+ paint: (t) => painted.push(t),
+ schedule: frames.schedule,
+ })
+ return { lp, painted, frames }
+}
+
+describe('Der Live-Anstrich: ein Puffer, ein Bild pro Runde', () => {
+ it('malt gar nichts, solange das Bild nicht gefeuert hat', () => {
+ const { lp, painted } = paintRig()
+ lp.feed('abc')
+ expect(painted).toEqual([])
+ })
+
+ it('fasst mehrere Einspeisungen zu EINEM Schreibvorgang zusammen, mit dem LETZTEN Text', () => {
+ const { lp, painted, frames } = paintRig()
+ lp.feed('a'); lp.feed('ab'); lp.feed('abc')
+ expect(frames.pending()).toBe(1)
+ frames.fire()
+ expect(painted).toEqual(['abc'])
+ })
+
+ it('settle() verhindert das Nachmalen — das ist Pruefung D1', () => {
+ const { lp, painted, frames } = paintRig()
+ lp.feed('alter zwischenstand')
+ lp.settle()
+ frames.fire()
+ // Ohne settle stuende hier der alte Zwischenstand, GESCHRIEBEN NACH dem
+ // fertigen Text, den der Transport direkt gesetzt hat.
+ expect(painted).toEqual([])
+ })
+
+ it('setzt den Vorspann dieses Zuges davor, mit Leerzeile', () => {
+ const { lp, painted, frames } = paintRig({ prefix: 'FRUEHER' })
+ lp.feed('jetzt')
+ frames.fire()
+ expect(painted).toEqual(['FRUEHER\n\njetzt'])
+ })
+
+ it('unterdrueckter Text landet nicht einmal im Puffer', () => {
+ const { lp, painted, frames } = paintRig({ suppress: (c) => c.startsWith('Hello, I am the Coding Agent') })
+ lp.feed('Hello, I am the Coding Agent, an autonomous coding agent')
+ expect(frames.pending()).toBe(0)
+ frames.fire()
+ expect(painted).toEqual([])
+ })
+
+ it('nach einem gefeuerten Bild wird das naechste wieder geplant', () => {
+ const { lp, painted, frames } = paintRig()
+ lp.feed('eins'); frames.fire()
+ lp.feed('zwei'); frames.fire()
+ expect(painted).toEqual(['eins', 'zwei'])
+ })
+})
+
+// ── Aufrufe im Fliesstext ───────────────────────────────────────────────────
+
+describe('Werkzeugaufrufe, die das Modell in seinen Text geschrieben hat', () => {
+ const fenced = '```json\n{"name": "file_read", "arguments": {"path": "a.ts"}}\n```'
+
+ it('holt den Aufruf aus dem Text, wenn die native Liste leer ist', () => {
+ const r = recoverToolCallsFromContent([], fenced)
+ expect(r.toolCalls).toHaveLength(1)
+ expect(r.toolCalls[0].function.name).toBe('file_read')
+ expect(r.toolCalls[0].function.arguments).toEqual({ path: 'a.ts' })
+ expect(r.extractedFromContent).toBe(true)
+ })
+
+ it('BEHAELT die Prosa um den Aufruf herum — das ist die Regel, die man kaputtmacht', () => {
+ const r = recoverToolCallsFromContent([], `Ich schaue mir die Datei an.\n${fenced}\nDanach geht es weiter.`)
+ expect(r.content).toContain('Ich schaue mir die Datei an.')
+ expect(r.content).toContain('Danach geht es weiter.')
+ expect(r.content).not.toContain('file_read')
+ })
+
+ it('leert den Text nur, wenn nach dem Schnitt nichts als Satzzeichen bleibt', () => {
+ const r = recoverToolCallsFromContent([], `${fenced}\n.\n`)
+ expect(r.content).toBe('')
+ })
+
+ it('schneidet das JSON auch dann heraus, wenn die native Liste schon voll ist', () => {
+ const nativ = [{ function: { name: 'file_read', arguments: { path: 'a.ts' } } }]
+ const r = recoverToolCallsFromContent(nativ, `Lese jetzt.\n${fenced}`)
+ // Die nativen Aufrufe bleiben unangetastet, nur die Blase wird lesbar.
+ expect(r.toolCalls).toBe(nativ)
+ expect(r.content).toContain('Lese jetzt.')
+ expect(r.content).not.toContain('"file_read"')
+ })
+
+ it('laesst einen Zug ohne JSON voellig unveraendert', () => {
+ const calls = [{ function: { name: 'x', arguments: {} } }]
+ const r = recoverToolCallsFromContent(calls, 'Fertig, alle Tests laufen.')
+ expect(r.content).toBe('Fertig, alle Tests laufen.')
+ expect(r.toolCalls).toBe(calls)
+ expect(r.extractedFromContent).toBe(false)
+ })
+})
+
+// ── Steckengeblieben oder fertig ────────────────────────────────────────────
+
+describe('Ein Zug ohne Werkzeugaufruf', () => {
+ const nudge = (t: string, full = '') => codexStallVerdict(t, full).nudgeWorthy
+
+ it('stupst, wenn das Modell den naechsten Schritt ERZAEHLT', () => {
+ expect(nudge("I'm about to read the source file.")).toBe(true)
+ expect(nudge('Let me check the config first.')).toBe(true)
+ expect(nudge("Next, I will open package.json.")).toBe(true)
+ expect(nudge('I need to read the test file.')).toBe(true)
+ })
+
+ it('stupst, wenn das Modell nach etwas fragt, das es selbst finden koennte', () => {
+ // Der Live-Fund vom 2026-06-02 mit qwen2.5-coder:7b, woertlich.
+ expect(nudge('it seems there is an issue with the file path … could you please verify the correct path to sum.js?')).toBe(true)
+ expect(nudge('please provide the path')).toBe(true)
+ expect(nudge('Which file should I look at?')).toBe(true)
+ })
+
+ it('stupst NICHT bei einer echten Antwort — das war die Schleife von David', () => {
+ expect(nudge('2+2 is 4.')).toBe(false)
+ expect(nudge('Task completed. The answer is 4.')).toBe(false)
+ expect(nudge('The bug was a missing await in loadUser(); I added it and the suite passes.')).toBe(false)
+ })
+
+ it('stupst NICHT bei "please verify the changes" — nur Pfad/Datei zaehlt', () => {
+ expect(nudge('I fixed it, please verify the changes.')).toBe(false)
+ expect(nudge('Please verify the correct path to the config.')).toBe(true)
+ })
+
+ it('ein leerer Zug stupst nur, wenn noch NICHTS geliefert wurde', () => {
+ expect(nudge('', '')).toBe(true)
+ // Leer NACH einer echten Antwort heisst fertig, sonst bleiben die
+ // Schreibpunkte stehen (David 2026-06-12).
+ expect(nudge('', 'Die Antwort steht oben.')).toBe(false)
+ expect(nudge(' \n ', 'Die Antwort steht oben.')).toBe(false)
+ })
+})
+
+// ── Der Denk-Abstieg ────────────────────────────────────────────────────────
+
+describe('"Dieses Modell kann nicht denken"', () => {
+ it('erkennt die 400 auf BEIDEN Feldern, die die Transporte benutzen', () => {
+ expect(isThinkingUnsupportedError(Object.assign(new Error('bad request'), { status: 400 }))).toBe(true)
+ expect(isThinkingUnsupportedError(Object.assign(new Error('bad request'), { statusCode: 400 }))).toBe(true)
+ })
+
+ it('erkennt den Satz auch ohne Statusfeld', () => {
+ expect(isThinkingUnsupportedError(new Error('model xyz does not support thinking'))).toBe(true)
+ })
+
+ it('steigt bei einem anderen Fehler NICHT ab', () => {
+ expect(isThinkingUnsupportedError(Object.assign(new Error('nope'), { status: 500 }))).toBe(false)
+ expect(isThinkingUnsupportedError(new Error('Failed to fetch'))).toBe(false)
+ })
+
+ it('ueberlebt einen geworfenen Nicht-Fehler statt selbst zu werfen', () => {
+ // Das ist der Grund, warum die Frage ueber die Grenzwaechter laeuft und
+ // nicht ueber `(e as Error).message`.
+ expect(() => isThinkingUnsupportedError(null)).not.toThrow()
+ expect(isThinkingUnsupportedError(null)).toBe(false)
+ expect(isThinkingUnsupportedError('does not support thinking')).toBe(true)
+ })
+})
+
+// ── Die Verbrauchsanzeige ───────────────────────────────────────────────────
+
+describe('Das Feld usage: eine Schaetzung ueberschreibt nie eine echte Zahl', () => {
+ let convId = ''
+ const MSG = 'msg-usage'
+ const usage = () =>
+ useChatStore.getState().conversations.find((c) => c.id === convId)
+ ?.messages.find((m) => m.id === MSG)?.usage
+
+ beforeEach(() => {
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ convId = useChatStore.getState().createConversation('m', '', 'codex')
+ useChatStore.getState().addMessage(convId, {
+ id: MSG, role: 'assistant', content: '', timestamp: Date.now(),
+ })
+ })
+
+ it('setzt die Schaetzung, solange nichts dasteht', () => {
+ seedEstimatedUsage(convId, MSG, [{ role: 'user', content: 'hallo welt' }], [])
+ expect(usage()?.estimated).toBe(true)
+ expect(usage()?.promptTokens).toBeGreaterThan(0)
+ })
+
+ it('die echte Zahl des Modells setzt estimated auf false', () => {
+ seedEstimatedUsage(convId, MSG, [{ role: 'user', content: 'hallo' }], [])
+ reportTurnUsage(convId, MSG, { promptEvalCount: 1234, evalCount: 56 })
+ expect(usage()).toMatchObject({ promptTokens: 1234, completionTokens: 56, totalTokens: 1290, estimated: false })
+ })
+
+ it('eine spaetere Schaetzung ruehrt die echte Zahl NICHT an', () => {
+ reportTurnUsage(convId, MSG, { promptEvalCount: 1234, evalCount: 56 })
+ seedEstimatedUsage(convId, MSG, [{ role: 'user', content: 'x'.repeat(10000) }], [])
+ expect(usage()?.promptTokens).toBe(1234)
+ expect(usage()?.estimated).toBe(false)
+ })
+
+ it('ein Zug ohne Zahlen schreibt gar nichts', () => {
+ seedEstimatedUsage(convId, MSG, [{ role: 'user', content: 'hallo' }], [])
+ const before = usage()
+ reportTurnUsage(convId, MSG, {})
+ expect(usage()).toEqual(before)
+ })
+
+ it('der Werkzeugkatalog zaehlt mit — er steht mit auf der Rechnung des Anbieters', () => {
+ const nurNachrichten = (() => {
+ seedEstimatedUsage(convId, MSG, [{ role: 'user', content: 'hallo' }], [])
+ return usage()!.promptTokens
+ })()
+ useChatStore.getState().updateMessageUsage(convId, MSG, {
+ promptTokens: 0, completionTokens: 0, totalTokens: 0, estimated: true,
+ })
+ seedEstimatedUsage(convId, MSG, [{ role: 'user', content: 'hallo' }], [
+ { type: 'function', function: { name: 'file_read', description: 'Read a file from disk', parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] } } },
+ ])
+ expect(usage()!.promptTokens).toBeGreaterThan(nurNachrichten)
+ })
+})
diff --git a/src/hooks/codex/agent-blocks.ts b/src/hooks/codex/agent-blocks.ts
new file mode 100644
index 00000000..a867421f
--- /dev/null
+++ b/src/hooks/codex/agent-blocks.ts
@@ -0,0 +1,47 @@
+import { useChatStore } from '../../stores/chatStore'
+import type { AgentBlock } from '../../types/agent-mode'
+
+/**
+ * Die Blockliste eines Zuges und ihr Spiegel im Chat-Speicher.
+ *
+ * Geteilter veraenderlicher Zustand: das Feld `blocks`. In useCodex.ts wurde es
+ * von ACHT Stellen quer durch 1500 Zeilen angefasst — Architekt, Repo-Karte,
+ * Gedanke, Antwort, zwei Schleifenwaechter-Meldungen, jeder Werkzeugaufruf und
+ * jedes Werkzeugergebnis. Drei dieser Stellen (Architekt, Architekt-Absage,
+ * Repo-Karte) schrieben `blocks.push(...)` und den Spiegelaufruf HAENDISCH
+ * hin, statt `addBlock` zu benutzen; das ist dieselbe Doppelung, die den
+ * Zustand irgendwann auseinanderlaufen laesst.
+ *
+ * DIE ZUSICHERUNG, die daran haengt und die kein Test bisher erreichen konnte:
+ * jeder Schreibvorgang gibt eine FRISCHE Liste weiter (`[...blocks]`). React
+ * vergleicht flach; wuerde dieselbe Liste zweimal gereicht, blieben neue
+ * Bloecke unsichtbar, obwohl sie da sind. Und `update` auf eine unbekannte
+ * Kennung tut NICHTS — sie schiebt keinen Block nach und legt keinen an.
+ */
+
+export interface AgentBlockSink {
+ add(block: AgentBlock): void
+ update(blockId: string, updates: Partial<AgentBlock>): void
+ /** Die laufende Liste, fuer Leser die nicht schreiben. */
+ list(): AgentBlock[]
+}
+
+export function createAgentBlockSink(convId: string, messageId: string): AgentBlockSink {
+ const blocks: AgentBlock[] = []
+ const mirror = () => {
+ useChatStore.getState().updateMessageAgentBlocks(convId, messageId, [...blocks])
+ }
+ return {
+ add(block: AgentBlock) {
+ blocks.push(block)
+ mirror()
+ },
+ update(blockId: string, updates: Partial<AgentBlock>) {
+ const idx = blocks.findIndex((b) => b.id === blockId)
+ if (idx < 0) return
+ blocks[idx] = { ...blocks[idx], ...updates }
+ mirror()
+ },
+ list: () => blocks,
+ }
+}
diff --git a/src/hooks/codex/hidden-history.ts b/src/hooks/codex/hidden-history.ts
new file mode 100644
index 00000000..e62fad08
--- /dev/null
+++ b/src/hooks/codex/hidden-history.ts
@@ -0,0 +1,40 @@
+import type { ChatMessage } from '../../api/providers/types'
+
+/**
+ * Die versteckte Werkzeugkette, die der naechste Zug wiederbekommt.
+ *
+ * Der Schnitt trennt die REGEL vom Schreibvorgang. Was in useCodex.ts
+ * uebrigbleibt, ist das Einfuegen in den Chat-Speicher; was hier steht, ist die
+ * Auswahl — und die hat zwei Gruende, die einander bedingen:
+ *
+ * 1. DIE DECKELUNG (Pruefung E2). Ungedeckelt legte ein Lauf mit 200
+ * Durchlaeufen hunderte versteckte Nachrichten zu je bis zu 60k Zeichen an
+ * — zweistellige Megabytes in EINEM Gespraech, die jede spaetere
+ * Speicherung neu durchschreiben musste. Die juengste Kette ist das, was
+ * der naechste Zug wirklich braucht; aeltere Schritte stehen ohnehin im
+ * sichtbaren Verlauf.
+ *
+ * 2. DER WAISENSCHNITT. Die Deckelung allein WAERE EIN FEHLER: schneidet das
+ * Fenster mitten in ein Aufruf/Ergebnis-Paar, beginnt die behaltene Kette
+ * mit einem Ergebnis, dessen Aufruf draussen liegt. Ein strenger Anbieter
+ * (lu-cloud/DeepInfra) antwortet darauf mit 422 und der ganze
+ * Folgezug faellt aus. Deshalb gehoeren die beiden Schritte zusammen und
+ * nicht in zwei Zeilen quer durch einen `finally`-Block.
+ *
+ * Rein und damit pruefbar — inklusive des Grenzfalls, den man sonst nie sieht:
+ * ein Fenster, das AUSSCHLIESSLICH aus Ergebnissen besteht, bleibt leer.
+ */
+
+/** Was der naechste Zug hoechstens an versteckter Kette wiederbekommt. */
+export const HIDDEN_HISTORY_MAX = 60
+
+export function capHiddenToolHistory(
+ all: ChatMessage[],
+ max: number = HIDDEN_HISTORY_MAX,
+): ChatMessage[] {
+ let toolHistory = all.slice(-max)
+ // Never start the kept slice on an orphan tool result — strict
+ // providers 422 a result whose call fell outside the window.
+ while (toolHistory.length > 0 && toolHistory[0].role === 'tool') toolHistory = toolHistory.slice(1)
+ return toolHistory
+}
diff --git a/src/hooks/codex/live-paint.ts b/src/hooks/codex/live-paint.ts
new file mode 100644
index 00000000..12b3efbc
--- /dev/null
+++ b/src/hooks/codex/live-paint.ts
@@ -0,0 +1,73 @@
+/**
+ * Der EINE Zwischenspeicher, in den drei Transporte malen.
+ *
+ * Der geteilte veraenderliche Zustand sind die zwei Zeilen `livePaintPending`
+ * und `livePaintFrame`. In useCodex.ts standen sie in der Schleife, und
+ * angefasst wurden sie von DREI Transportzweigen (Ollama, OpenAI-kompatibel,
+ * Hermes-XML) plus drei `settleLivePaint()`-Aufrufen, die bis zu 400 Zeilen
+ * weiter unten liegen. Wer den Puffer fuellt und wer ihn abraeumt, gehoert
+ * zusammen — das ist derselbe Schnitt, mit dem `dev-server/comfy.ts` seinen
+ * Kindprozess samt Logpuffer bekommen hat.
+ *
+ * ZWEI REGELN HAENGEN DARAN, und beide waren in der grossen Datei nicht
+ * pruefbar:
+ *
+ * 1. ZUSAMMENFASSEN PRO BILD (Pruefung D1). Codex schrieb frueher bei JEDEM
+ * Token in den Speicher und zeichnete damit das ganze Gespraech neu.
+ * Mehrere `feed()` in einem Bild ergeben genau EINEN Schreibvorgang, und
+ * zwar mit dem ZULETZT eingespeisten Text.
+ *
+ * 2. `settle()` LOESCHT EIN NOCH NICHT GEFEUERTES BILD. Ohne das konnte ein
+ * wartendes Bild NACH dem letzten direkten Schreiben feuern und alten
+ * Inhalt ueber den fertigen Text malen. Deshalb raeumt jeder Transport
+ * sofort ab, wenn der Stream-Aufruf zurueckkehrt.
+ *
+ * `schedule` ist ein Parameter und kein fest verdrahtetes
+ * `requestAnimationFrame`: die App reicht das echte durch, und ein Test kann
+ * die Bilder von Hand ausloesen. Ohne diese Naht waere die Regel "settle
+ * verhindert das Nachmalen" ueberhaupt nicht zu zeigen — `requestAnimationFrame`
+ * gibt es in der node-Umgebung der Tests gar nicht.
+ */
+
+export interface LivePaintDeps {
+ /** Wird `true`, solange der Text nicht in den Chat darf (Echo-Wache). */
+ suppress: (content: string) => boolean
+ /** Was diesem Zug schon vorausging; leer heisst "nichts davor". */
+ prefix: () => string
+ /** Der tatsaechliche Schreibvorgang in den Chat-Speicher. */
+ paint: (text: string) => void
+ /** Voreinstellung: das echte Bild des Browsers. */
+ schedule?: (cb: () => void) => void
+}
+
+export interface LivePaint {
+ feed: (content: string) => void
+ settle: () => void
+}
+
+export function createLivePaint(deps: LivePaintDeps): LivePaint {
+ const schedule = deps.schedule ?? ((cb: () => void) => { requestAnimationFrame(cb) })
+ let livePaintPending: string | null = null
+ let livePaintFrame = false
+
+ const settle = () => {
+ livePaintPending = null
+ }
+
+ const feed = (c: string) => {
+ if (deps.suppress(c)) return
+ const before = deps.prefix()
+ livePaintPending = before ? before + '\n\n' + c : c
+ if (livePaintFrame) return
+ livePaintFrame = true
+ schedule(() => {
+ livePaintFrame = false
+ if (livePaintPending !== null) {
+ deps.paint(livePaintPending)
+ livePaintPending = null
+ }
+ })
+ }
+
+ return { feed, settle }
+}
diff --git a/src/hooks/codex/mode-refusal.ts b/src/hooks/codex/mode-refusal.ts
new file mode 100644
index 00000000..014a766c
--- /dev/null
+++ b/src/hooks/codex/mode-refusal.ts
@@ -0,0 +1,50 @@
+import { CODEX_MODE_LABELS, type CodexMode } from '../../lib/codex-mode'
+
+/**
+ * Ein Schraegstrich-Befehl, der in diesem Modus nichts ausrichten kann.
+ *
+ * Der Schnitt folgt dem, WAS ZWEI UNABHAENGIGE BRAUCHEN. In useCodex.ts standen
+ * zwei fast gleiche Bloecke 14 Zeilen auseinander — einer fuer den
+ * Code-Review-Modus, einer fuer den Plan-Modus —, und beide nannten dieselbe
+ * Ausweichliste WOERTLICH:
+ *
+ * "use a read-only command such as /review, /plan, /diff or /explain"
+ *
+ * Zwei Kopien einer Liste, die nur gemeinsam stimmen kann: waechst ein
+ * schreibfreier Befehl dazu, muss er in BEIDEN Saetzen stehen. Das ist genau
+ * der Fall, den ZB-7 nach nebenan legt, statt ihn in einem der beiden zu
+ * lassen.
+ *
+ * DIE RANGFOLGE IST DIE ZWEITE ZUSICHERUNG. Der Review-Modus gewinnt vor dem
+ * Plan-Modus, weil er die staerkere Sperre ist: er tauscht den ganzen
+ * Systemprompt gegen den schreibfreien Vertrag. Bisher ergab sich diese
+ * Rangfolge nur daraus, dass das eine `if` VOR dem anderen stand — sie hing an
+ * der Reihenfolge zweier Bloecke in einer 2642-Zeilen-Datei und war nirgends
+ * pruefbar.
+ *
+ * WOZU DIE SAETZE UEBERHAUPT DA SIND: ein Befehl, dessen ganze Aufgabe das
+ * Aendern ist, liefe sonst bis zum Ende durch und ERZAEHLTE Arbeit, die er
+ * nicht tun konnte — ohne dass auf dem Bildschirm stuende, warum. Also sagen
+ * und aufhoeren.
+ */
+
+export interface ModeRefusalInput {
+ /** `settings.codexReviewMode` — unveraendert, auch `undefined`. */
+ reviewMode: boolean | undefined
+ codexMode: CodexMode
+ /** Der erkannte Befehl, oder `null` bei einer normalen Anweisung. */
+ slash: { command: { name: string; readOnly?: boolean } } | null
+}
+
+/**
+ * Der Satz fuer den Nutzer, oder `null`, wenn der Zug laufen darf.
+ */
+export function codexModeRefusal({ reviewMode, codexMode, slash }: ModeRefusalInput): string | null {
+ if (reviewMode && slash && !slash.command.readOnly) {
+ return `Review Mode is on, so I cannot write files or run commands, and /${slash.command.name} needs both. Turn Review Mode off in Settings, or use a read-only command such as /review, /plan, /diff or /explain.`
+ }
+ if (codexMode === 'plan' && slash && !slash.command.readOnly) {
+ return `Plan mode is read-only, and /${slash.command.name} needs to write files or run commands. Switch the mode dropdown to "${CODEX_MODE_LABELS.ask}" first, or use a read-only command such as /review, /plan, /diff or /explain.`
+ }
+ return null
+}
diff --git a/src/hooks/codex/staged-writes.ts b/src/hooks/codex/staged-writes.ts
new file mode 100644
index 00000000..b24e51b5
--- /dev/null
+++ b/src/hooks/codex/staged-writes.ts
@@ -0,0 +1,218 @@
+import { useStagedChangesStore } from '../../stores/stagedChangesStore'
+import { computeUnifiedDiff } from '../../lib/diff'
+import { applyUniqueEdit } from '../../lib/surgical-edit'
+import { findStagedForPath, stagedReadResult, stagedListingNote } from '../../lib/staged-overlay'
+import { codexReadCtx, type CodexFsCtx, type CodexFileRead } from './workspace-fs'
+import type { ToolArgs } from '../../api/mcp/types'
+
+/**
+ * Die Warteschlange der noch nicht geschriebenen Aenderungen — und ALLES, was
+ * sie anfasst.
+ *
+ * Das ist der Schnitt nach GETEILTEM ZUSTAND, wie ihn ZB-7 fuer `dev-server/`
+ * gezogen hat. Der veraenderliche Zustand ist `stagedChangesStore`, und in
+ * useCodex.ts lagen VIER Zugriffe darauf ueber 60 Zeilen verstreut, die nur
+ * zusammen richtig sind:
+ *
+ * 1. `stageFileWrite` legt eine ganze Datei in die Schlange,
+ * 2. `stageFileEdit` loest old_string→new_string JETZT auf und legt das
+ * Ergebnis in die Schlange,
+ * 3. `file_read` muss AUS der Schlange beantwortet werden,
+ * 4. `file_list`/`file_search` muessen die Schlange ANMERKEN.
+ *
+ * Warum 3 und 4 hier stehen und nicht beim Werkzeug-Versand: eine abgelegte
+ * Schreibung ist auf der Platte UNSICHTBAR. Liest das Modell danach die alten
+ * Bytes (oder ein "nicht gefunden"), schliesst es, sein Schreiben sei
+ * gescheitert, und legt dieselbe Datei wieder und wieder ab — Morgans
+ * `file_read`-Schleife vom 2026-07-26. Wer die Schlange fuellt und wer sie
+ * liest, gehoert deshalb in EIN Modul; getrennt koennen sie auseinanderlaufen,
+ * und genau das ist zweimal passiert.
+ *
+ * DIE ZWEITE GEMEINSAMKEIT, die den Schnitt traegt: 2 und 3 lasen den
+ * Grundtext frueher jeweils von der PLATTE. Bei einer zweiten Bearbeitung
+ * derselben Datei ueberschrieb das still die erste, und eine Bearbeitung an
+ * einer abgelegten NEUEN Datei scheiterte mit "could not read". Die
+ * Lies-deine-Schreibungen-Regel (`findStagedForPath` vor dem Plattenzugriff)
+ * ist in 1 und 2 dieselbe Regel und steht jetzt zweimal nebeneinander statt
+ * zweimal quer durch die Datei.
+ *
+ * WAS BEWUSST VERSCHIEDEN BLEIBT, weil es Verhalten ist und keine Doppelung:
+ * `stageFileWrite` nimmt bei einem Vorgaenger dessen `oldContent` (die
+ * Plattenfassung), `stageFileEdit` nimmt dessen `newContent` als GRUNDLAGE und
+ * dessen `oldContent` als Vergleichsbasis. Der geprueft angezeigte Unterschied
+ * ist in beiden Faellen Platte → Endstand, nie abgelegt → abgelegt.
+ *
+ * `readFile` kommt von aussen (dieselbe Naht wie `RulesReader` in
+ * `workspace-fs.ts` und wie `realPath` im Pfad-Kaefig des Dev-Servers): der
+ * echte Leser spricht mit dem Rust-Backend, im Test steht ein echter
+ * Dateiinhalt dahinter. Ohne diese Naht waere von den vier Regeln oben keine
+ * einzige pruefbar.
+ */
+
+export interface StagedWriterDeps {
+ convId: string
+ /** Der Ordner, den auch der Systemprompt nennt. `'.'` = Sandbox pro Chat. */
+ workDir: string
+ workspaceSlug: string
+ readFile: (path: string, ctx: CodexFsCtx) => Promise<CodexFileRead>
+}
+
+export interface StagedWriter {
+ stageFileWrite(args: ToolArgs): Promise<string>
+ stageFileEdit(args: ToolArgs): Promise<string>
+ /**
+ * Der Versand einer Runde mit eingeschalteter Ablage. `passthrough` ist der
+ * echte Weg zum Werkzeug (mit Zeitgrenze und Abbruchsignal); er bleibt beim
+ * Aufrufer, weil nur der den Lauf kennt.
+ */
+ dispatch(name: string, args: ToolArgs, passthrough: () => Promise<string>): Promise<string>
+}
+
+/**
+ * Der Pfad, unter dem eine abgelegte Aenderung SPAETER landet.
+ *
+ * JETZT aufgeloest, nicht beim Anwenden: das Anwenden laeuft, nachdem das
+ * `finally` dieses Zuges den aktiven Chat- und Workspace-Kontext geraeumt hat,
+ * und ein relativer Pfad zeigte dann nach `agent-workspace/default/` statt in
+ * den echten Projektordner.
+ */
+function resolveStagedPath(path: string, workDir: string): string {
+ const isAbs = /^([a-zA-Z]:[\\/]|[\\/]|\\\\)/.test(path)
+ return isAbs || !workDir || workDir === '.'
+ ? path
+ : `${workDir.replace(/[\\/]+$/, '')}${workDir.includes('\\') ? '\\' : '/'}${path.replace(/^[\\/]+/, '')}`
+}
+
+export function createStagedWriter(deps: StagedWriterDeps): StagedWriter {
+ const { convId, workDir, workspaceSlug, readFile } = deps
+
+ // Multi-File Stage-and-Approve (B10). When the user has codex
+ // stage mode on, file_write calls don't hit the disk — they
+ // queue in stagedChangesStore as "pending changes" the user
+ // reviews and applies (or rejects) per-file. The model still
+ // sees a synthetic success message so the loop progresses; the
+ // user is the gatekeeper for the actual disk write.
+ const stageFileWrite = async (args: ToolArgs): Promise<string> => {
+ const path = String(args.path ?? '')
+ if (!path) return 'file_write: missing path'
+ const newContent = String(args.content ?? '')
+ // Resolve against the run's workspace NOW (at stage time). The bridge
+ // jails absolute paths to the workspace root, so the pre-read MUST pass
+ // the run's workingDirectory (as its root) — otherwise the absolute
+ // project path is rejected and the staged diff shows a 100% insert,
+ // hiding what will be overwritten. (v2.5.0 + 2.5.9 audit fix.)
+ const resolvedPath = resolveStagedPath(path, workDir)
+ const stageReadCtx = codexReadCtx(workspaceSlug, workDir)
+ // A prior staged entry for this path already knows the DISK state —
+ // reuse it so the reviewed diff stays disk → latest even when the
+ // model writes the same file twice in one run.
+ const priorWrite = findStagedForPath(useStagedChangesStore.getState().list(convId), path)
+ let oldContent = ''
+ if (priorWrite) {
+ oldContent = priorWrite.oldContent
+ } else {
+ try {
+ const r = await readFile(resolvedPath, stageReadCtx)
+ oldContent = r?.content ?? ''
+ } catch {
+ // New file — leave oldContent empty so the diff renders an
+ // all-add hunk and the apply path creates the file.
+ }
+ }
+ const diff = computeUnifiedDiff(path, oldContent, newContent)
+ useStagedChangesStore.getState().stage(convId, {
+ path,
+ resolvedPath,
+ // Capture the workspace root so Apply (which runs after the loop's
+ // finally clears the active context) can jail the write to the real
+ // project folder instead of agent-workspace/default. Undefined in
+ // sandbox mode — the per-chat sandbox is the right root there.
+ workingDirectory: workDir && workDir !== '.' ? workDir : undefined,
+ oldContent,
+ newContent,
+ diff,
+ })
+ return `Staged for review: ${path}. The user will apply or reject the change before it lands on disk.`
+ }
+
+ // Stage-mode counterpart for surgical edits: resolve old_string ->
+ // new_string against the current file NOW and stage the resulting full
+ // content, so the staged diff and the applied write are the real change
+ // (and a bad edit is reported the same way whether staged or not).
+ const stageFileEdit = async (args: ToolArgs): Promise<string> => {
+ const path = String(args.path ?? '')
+ if (!path) return 'file_edit: missing path'
+ const oldString = typeof args.old_string === 'string' ? args.old_string : ''
+ const newString = typeof args.new_string === 'string' ? args.new_string : ''
+ const resolvedPath = resolveStagedPath(path, workDir)
+ const stageReadCtx = codexReadCtx(workspaceSlug, workDir)
+ // Read-your-writes: chain onto the STAGED content when this path is
+ // already pending. Without this the base was re-read from DISK —
+ // which never saw the staged write — so a second edit to the same
+ // file silently clobbered the first, and an edit to a staged NEW
+ // file failed with "could not read".
+ const priorEdit = findStagedForPath(useStagedChangesStore.getState().list(convId), path)
+ let baseContent = ''
+ let diskContent = ''
+ if (priorEdit) {
+ baseContent = priorEdit.newContent
+ diskContent = priorEdit.oldContent
+ } else {
+ try {
+ const r = await readFile(resolvedPath, stageReadCtx)
+ if (r?.encoding === 'binary' || r?.encoding === 'base64') return `file_edit: cannot edit a binary file (${path}).`
+ baseContent = diskContent = r?.content ?? ''
+ } catch {
+ return `file_edit: could not read ${path}. To create a new file use file_write.`
+ }
+ }
+ const applied = applyUniqueEdit(baseContent, oldString, newString)
+ if (!applied.ok) {
+ switch (applied.reason) {
+ case 'empty_old': return 'file_edit: old_string must be non-empty. Use file_write to create a new file.'
+ case 'noop': return 'file_edit: old_string and new_string are identical, nothing to change.'
+ case 'not_found': return `file_edit: old_string not found in ${path}. Read the file and copy the exact text you want to replace.`
+ case 'not_unique': return `file_edit: old_string matches ${applied.matches} places in ${path}. Add surrounding lines so it is unique.`
+ default: return 'file_edit: failed.'
+ }
+ }
+ const newContent = applied.content ?? ''
+ // Diff and oldContent stay anchored on the DISK state, so the user
+ // reviews (and apply writes) disk → final, not staged → staged.
+ const diff = computeUnifiedDiff(path, diskContent, newContent)
+ useStagedChangesStore.getState().stage(convId, {
+ path,
+ resolvedPath,
+ workingDirectory: workDir && workDir !== '.' ? workDir : undefined,
+ oldContent: diskContent,
+ newContent,
+ diff,
+ })
+ return `Staged for review: ${path} (surgical edit). The user will apply or reject the change before it lands on disk.`
+ }
+
+ const dispatch = (name: string, args: ToolArgs, passthrough: () => Promise<string>): Promise<string> => {
+ if (name === 'file_write') return stageFileWrite(args)
+ if (name === 'file_edit') return stageFileEdit(args)
+ // Read-your-writes: staged content is invisible on disk, so reads
+ // MUST be answered from the queue — otherwise the model reads the
+ // old bytes (or a not-found), concludes its write failed, and
+ // stages the same file forever (Morgan's file_read loop,
+ // 2026-07-26). The in-turn cache composes correctly: every staged
+ // write is audited as a file_write mutation, which invalidates
+ // cached reads, so a pre-stage result is never replayed.
+ const staged = convId ? useStagedChangesStore.getState().list(convId) : []
+ if (staged.length > 0) {
+ if (name === 'file_read') {
+ const hit = findStagedForPath(staged, String(args.path ?? ''))
+ if (hit) return Promise.resolve(stagedReadResult(hit))
+ }
+ if (name === 'file_list' || name === 'file_search') {
+ return passthrough().then((r) => r + stagedListingNote(staged))
+ }
+ }
+ return passthrough()
+ }
+
+ return { stageFileWrite, stageFileEdit, dispatch }
+}
diff --git a/src/hooks/codex/stall-verdict.ts b/src/hooks/codex/stall-verdict.ts
new file mode 100644
index 00000000..b0c27b41
--- /dev/null
+++ b/src/hooks/codex/stall-verdict.ts
@@ -0,0 +1,62 @@
+/**
+ * Ein Zug ohne Werkzeugaufruf: fertig oder steckengeblieben?
+ *
+ * Der Schnitt folgt nicht der Zeilenzahl, sondern der ENTSCHEIDUNG: drei
+ * unabhaengige Muster ueber DENSELBEN Text (`turnContent`) ergeben zusammen
+ * genau eine Weiche — Schleife weiter oder abbrechen. In useCodex.ts standen
+ * die drei Regexe inline in einem `if`-Zweig eines 2358-Zeilen-`useCallback`,
+ * und damit war keine von ihnen einzeln erreichbar, obwohl jede eine
+ * dokumentierte Geschichte von FEHLALARMEN hat:
+ *
+ * • Die frueher umgekehrte Fassung ("anstupsen, ausser ein Abschlusswort
+ * kommt vor") drehte bei bereits beantworteten Fragen durch — David
+ * 2026-06-02: der Coding-Agent "antwortet in loops" auf eine simple Frage,
+ * weil "completed" nie auf den Abschluss-Regex passte.
+ *
+ * • `asksForInfo` muss "could you please verify the correct path to sum.js?"
+ * fangen (qwen2.5-coder:7b, 2026-06-02) und "I fixed it, please verify the
+ * changes" IN RUHE LASSEN. Deshalb haengt der verify/confirm/clarify-Zweig
+ * an einem Pfad- oder Datei-HAUPTWORT und nicht am Verb allein.
+ *
+ * • Ein LEERER Zug stupst nur, wenn noch NICHTS geliefert wurde. Leer NACH
+ * einer echten Antwort heisst fertig; anders blieben die Schreibpunkte
+ * stehen, lange nachdem die Antwort da war (David 2026-06-12: "die punkte
+ * bleiben so lange obwohl keine antwort mehr kam").
+ *
+ * Die Muster sind woertlich uebernommen. Das Urteil ist eine reine Funktion
+ * von (Zugtext, bisherige Antwort).
+ */
+
+export interface StallVerdict {
+ /** Das Modell hat den naechsten Schritt ERZAEHLT statt ihn zu tun. */
+ stalledNarration: boolean
+ /** Das Modell fragt nach etwas, das es selbst finden koennte. */
+ asksForInfo: boolean
+ /** Gar kein Text. */
+ emptyTurn: boolean
+ /** Das Urteil: anstupsen statt abbrechen. */
+ nudgeWorthy: boolean
+}
+
+export function codexStallVerdict(turnContent: string, fullContent: string): StallVerdict {
+ // Nudge ONLY when the model clearly STALLED mid-task — it narrated the
+ // next step ("I'm about to…", "let me…", "next I'll…", "I need to read…")
+ // or asked for info it could find itself ("please provide the path",
+ // "which file?"), or returned no text at all. A substantive ANSWER
+ // matches none of these, so simple Q&A ("2+2 is 4" / "Task completed.
+ // The answer is 4.") stops cleanly.
+ const stalledNarration = /\b(i(?:'?m| am) about to|i will(?: now)?|i'?ll\b|let me\b|next,?\s*i\b|now i'?ll|going to|first,?\s*i\b|then i'?ll|i (?:need|have|am going) to (?:read|open|check|look|run|see|find))\b/i.test(turnContent)
+ // "asksForInfo" also catches the model giving up by asking the user to
+ // VERIFY/CONFIRM a path it can discover itself. The verify/confirm/clarify
+ // branch is anchored on a path/file NOUN so a genuine completion
+ // ("I fixed it, please verify the changes") does NOT match — only
+ // "verify the (correct) path/file/location" does.
+ const asksForInfo = /\b(please provide|could you (?:please )?(?:provide|share|tell|give|specify|verify|confirm|clarify)|what(?:'s| is) the (?:path|file|name|location)|which file|can you (?:provide|share|specify|tell)|provide (?:the|me) (?:the )?(?:path|file|details|more)|(?:verify|confirm|clarify) (?:the )?(?:correct |right |exact |full )?(?:path|file ?path|location|directory|filename|file name)|need (?:the|more) (?:path|info|details|context))\b/i.test(turnContent)
+ const emptyTurn = turnContent.trim().length === 0
+ // Only nudge an empty turn when NOTHING has been produced yet (a true
+ // early stall). An empty turn AFTER a real answer means the model is
+ // finished. Read-only report commands (/review, /explain …) legitimately
+ // end on a text answer + an empty follow-up turn.
+ const nudgeWorthy = stalledNarration || asksForInfo || (emptyTurn && !fullContent.trim())
+ return { stalledNarration, asksForInfo, emptyTurn, nudgeWorthy }
+}
diff --git a/src/hooks/codex/thinking-downgrade.ts b/src/hooks/codex/thinking-downgrade.ts
new file mode 100644
index 00000000..20c33202
--- /dev/null
+++ b/src/hooks/codex/thinking-downgrade.ts
@@ -0,0 +1,36 @@
+import { httpStatusOf } from '../../lib/http-status'
+import { errorText } from '../../types/json-guards'
+
+/**
+ * "Dieses Modell kann nicht denken" — die eine Frage, DREIMAL gestellt.
+ *
+ * Der Schnitt folgt dem, WAS DREI UNABHAENGIGE BRAUCHEN. In useCodex.ts stand
+ * derselbe Test in allen drei Transportzweigen, und in drei verschiedenen
+ * Schreibweisen:
+ *
+ * Ollama: httpStatusOf(e) === 400 || errorText(e).includes('does not support thinking')
+ * OpenAI: errorText(e).includes('does not support thinking') || httpStatusOf(e) === 400
+ * Hermes: opts.thinking !== undefined && (errorText(e).includes(…) || httpStatusOf(e) === 400)
+ *
+ * Die ersten beiden unterscheiden sich NUR in der Reihenfolge der beiden
+ * Operanden. Beide Operanden sind rein (`httpStatusOf` und `errorText` lesen
+ * nur), also ist das Ergebnis identisch — es sind zwei Kopien einer Regel, von
+ * denen jede fuer sich weiterentwickelt werden konnte.
+ *
+ * DIE DRITTE IST NICHT DIESELBE, und das bleibt hier sichtbar statt still
+ * eingeebnet zu werden: der Hermes-Zweig steigt nur ab, wenn ueberhaupt ein
+ * Denk-Schalter gesetzt war. Diese Zusatzbedingung bleibt an ihrer Aufrufstelle
+ * stehen; sie ist Verhalten, keine Doppelung, und eine Umstrukturierung raeumt
+ * kein Verhalten weg.
+ *
+ * WOZU DER ABSTIEG DA IST: ein aelterer Ollama-Bau oder ein Endpunkt, der den
+ * Schalter nicht kennt, antwortet mit 400. Der Lauf muss das ueberleben statt
+ * daran zu enden.
+ *
+ * `errorText` und `httpStatusOf` sind Grenzwaechter, also ueberlebt diese
+ * Frage auch ein `throw null` — das ist der Grund, warum sie hier so und nicht
+ * ueber `(e as Error).message` gestellt wird.
+ */
+export function isThinkingUnsupportedError(err: unknown): boolean {
+ return httpStatusOf(err) === 400 || errorText(err).includes('does not support thinking')
+}
diff --git a/src/hooks/codex/tool-call-recovery.ts b/src/hooks/codex/tool-call-recovery.ts
new file mode 100644
index 00000000..c17ea185
--- /dev/null
+++ b/src/hooks/codex/tool-call-recovery.ts
@@ -0,0 +1,87 @@
+import { extractToolCallsWithRanges, stripRanges } from '../../lib/tool-call-repair'
+import type { ToolCall } from '../../api/providers/types'
+
+/**
+ * Werkzeugaufrufe, die das Modell in seinen Fliesstext geschrieben hat.
+ *
+ * Der Schnitt folgt dem geteilten Zustand `turnContent`/`toolCalls`: DREI
+ * Regeln lasen und schrieben in useCodex.ts dieselben zwei Variablen
+ * hintereinander, und nur zusammen ergeben sie den Vertrag "was ist Aufruf,
+ * was ist Antwort". Auseinandergenommen kippt der Rest sofort — deshalb liegen
+ * sie hier zu dritt und nicht als drei Helferlein.
+ *
+ * 1. NATIVE LISTE LEER, aber der Text sieht aus wie ein Aufruf: qwen2.5-coder:3b
+ * schickt einen ```json-Block in `content` statt in `message.tool_calls`.
+ * Herausziehen und den Block aus dem Text schneiden, damit der Nutzer kein
+ * rohes JSON sieht.
+ *
+ * 2. NATIVE LISTE VOLL, und dasselbe JSON steht TROTZDEM noch im Text.
+ * Ebenfalls herausschneiden — die Aufrufe sind schon geparst.
+ *
+ * 3. WAS UEBRIG BLEIBT, IST ANTWORT. Das ist die Regel, die man am leichtesten
+ * falsch macht: die Prosa um das JSON herum wird BEHALTEN, damit die
+ * Zwischenantworten in der Zeitleiste stehen bleiben (David 2026-06-02 r2:
+ * "antworten zwischen drin verschwinden immer, darf nicht sein"). Geleert
+ * wird nur, wenn nach dem Schnitt nichts als Satzzeichen und Leerraum
+ * dasteht.
+ *
+ * Reine Funktion von (Aufrufe, Text) auf (Aufrufe, Text) — in einem
+ * 2358-Zeilen-`useCallback` war keine dieser drei Regeln einzeln erreichbar.
+ */
+
+export interface RecoveredTurn {
+ toolCalls: ToolCall[]
+ content: string
+ /** Ob ueberhaupt etwas aus dem Text geschnitten wurde. */
+ extractedFromContent: boolean
+}
+
+export function recoverToolCallsFromContent(toolCalls: ToolCall[], content: string): RecoveredTurn {
+ let calls = toolCalls
+ let turnContent = content
+ // v2.5.0 fix (post-merge bug hunt): some Ollama models
+ // (qwen2.5-coder:3b confirmed) emit tool calls as a fenced
+ // ```json { "name":..., "arguments":... } ``` block inside
+ // message.content INSTEAD of the native message.tool_calls
+ // array. When the native list is empty but content looks like
+ // a tool call, extract it and strip the fence so the user
+ // doesn't see raw JSON.
+ // Track whether this iteration's content held tool-call JSON.
+ // qwen2.5-coder:3b emits the JSON in content rather than native
+ // tool_calls, and every iteration wraps the JSON with the same
+ // narrative ("I'm about to verify…" + code blocks). Those lines
+ // are not the FINAL answer — they're filler between tool calls
+ // and would duplicate across iterations if accumulated.
+ let extractedFromContent = false
+ if (calls.length === 0 && turnContent) {
+ const { calls: extracted, ranges } = extractToolCallsWithRanges(turnContent)
+ if (extracted.length > 0) {
+ calls = extracted.map(tc => ({ function: { name: tc.name, arguments: tc.arguments } }))
+ turnContent = stripRanges(turnContent, ranges)
+ extractedFromContent = true
+ }
+ }
+ // Safety net for qwen2.5-coder: sometimes the model emits the
+ // tool-call JSON alongside native tool_calls — native was parsed
+ // already, but the same JSON still sits in the content. Strip
+ // those too so the chat bubble stays readable.
+ if (calls.length > 0 && turnContent && /\{\s*"(?:name|tool|function)"\s*:/.test(turnContent)) {
+ const { ranges } = extractToolCallsWithRanges(turnContent)
+ if (ranges.length > 0) {
+ turnContent = stripRanges(turnContent, ranges)
+ extractedFromContent = true
+ }
+ }
+ // When the model bundles its tool-call JSON INSIDE the text
+ // (qwen2.5-coder & co.), KEEP the surrounding prose as this
+ // iteration's commentary — the JSON itself was already removed by
+ // stripRanges above. Keeping it (instead of clearing) is what makes
+ // every between-tool answer survive so the renderer can interleave
+ // them chronologically: tool → answer → tool → tool → answer …
+ // (David 2026-06-02 r2: "antworten zwischen drin verschwinden immer,
+ // darf nicht sein"). Older answers auto-collapse in the UI, so the
+ // old "stack of duplicated I'm-about-to paragraphs" problem is gone.
+ // Only drop it when nothing but punctuation/whitespace remains.
+ if (extractedFromContent && !/[A-Za-z0-9]/.test(turnContent)) turnContent = ''
+ return { toolCalls: calls, content: turnContent, extractedFromContent }
+}
diff --git a/src/hooks/codex/tool-result-view.ts b/src/hooks/codex/tool-result-view.ts
new file mode 100644
index 00000000..c6838f3f
--- /dev/null
+++ b/src/hooks/codex/tool-result-view.ts
@@ -0,0 +1,85 @@
+import { computeUnifiedDiff } from '../../lib/diff'
+import { applyUniqueEdit } from '../../lib/surgical-edit'
+import type { ToolArgs } from '../../api/mcp/types'
+
+/**
+ * Was der Nutzer von einem fertigen Werkzeugaufruf zu sehen bekommt.
+ *
+ * Der Schnitt folgt dem geteilten Zustand `acDiff`/`acPath`: in useCodex.ts
+ * berechnete ein Block beide, und ZWEI Verbraucher lasen sie danach — der
+ * Werkzeug-Block in der Chat-Blase und der `file_change`-Eintrag im
+ * Codex-Ereignisprotokoll. Beide muessen denselben Unterschied zeigen; die
+ * Rechnung gehoert deshalb an EINE Stelle und nicht in einen der beiden.
+ *
+ * WARUM DAS HEIKEL IST: der angezeigte Unterschied ist NACHGEBAUT, nicht
+ * beobachtet. Das Werkzeug schreibt auf die Platte und meldet Text zurueck; was
+ * hier gezeichnet wird, entsteht aus der Vorlese-Runde plus dem, was das Modell
+ * in den Aufruf geschrieben hat. Bei `file_edit` bekam das Werkzeug ueberhaupt
+ * nur old_string/new_string — der neue Inhalt wird aus dem Vorgelesenen und der
+ * eindeutigen Ersetzung REKONSTRUIERT. Diese Stelle ist damit die eine, an der
+ * die Anzeige ueber die Aenderung luegen kann, und sie hatte bis hierher keinen
+ * eigenen Test, weil sie mitten in der Ergebnisschleife stand.
+ *
+ * Beide Funktionen sind rein.
+ */
+
+export interface ToolDiffInput {
+ toolName: string
+ /** Der geprueft gelesene Pfad aus dem Aufruf (`asString`), sonst undefined. */
+ path: string | undefined
+ /** Was die Vorlese-Runde auf der Platte fand; fehlende Datei = ''. */
+ oldText: string
+ /** Die Argumente, die tatsaechlich an das Werkzeug gingen. */
+ args: ToolArgs
+}
+
+/**
+ * Der Unterschied fuer die beiden Schreibwerkzeuge. `undefined` heisst
+ * "nichts anzeigen": kein Schreibwerkzeug, ein leerer Unterschied, oder eine
+ * Bearbeitung, die nicht eindeutig angewandt werden konnte (dann hat der
+ * Ausfuehrer bereits einen Fehler gemeldet).
+ */
+export function codexToolDiff({ toolName, path, oldText, args }: ToolDiffInput): string | undefined {
+ if (toolName === 'file_write') {
+ // Pre-read above captured the on-disk version; a missing file
+ // yields an all-add hunk. Empty diff → omit.
+ const newText =
+ typeof args.content === 'string'
+ ? args.content
+ : ''
+ return computeUnifiedDiff(path ?? '', oldText, newText) || undefined
+ }
+ if (toolName === 'file_edit') {
+ // Surgical edit — the tool only received old_string/new_string, so
+ // reconstruct the new content from the pre-read + the unique
+ // replacement to attach a real diff. If the edit did not apply
+ // uniquely the executor already returned an error; skip the diff.
+ const applied = applyUniqueEdit(
+ oldText,
+ typeof args.old_string === 'string' ? args.old_string : '',
+ typeof args.new_string === 'string' ? args.new_string : '',
+ )
+ return applied.ok
+ ? computeUnifiedDiff(path ?? '', oldText, applied.content ?? '') || undefined
+ : undefined
+ }
+ return undefined
+}
+
+/**
+ * In welchen Eintrag des Codex-Ereignisprotokolls ein fertiger Aufruf faellt.
+ * `null` heisst: kein Eintrag.
+ *
+ * Die Reihenfolge ist Teil der Regel — ein FEHLGESCHLAGENES `file_write`
+ * bleibt ein `file_change` und wird NICHT zum `error`, weil der Zweig fuer die
+ * Schreibwerkzeuge vor dem Fehlerzweig steht.
+ */
+export function codexEventKind(
+ toolName: string,
+ isError: boolean,
+): 'terminal_output' | 'file_change' | 'error' | null {
+ if (toolName === 'shell_execute' || toolName === 'code_execute') return 'terminal_output'
+ if (toolName === 'file_write' || toolName === 'file_edit') return 'file_change'
+ if (isError) return 'error'
+ return null
+}
diff --git a/src/hooks/codex/turn-usage.ts b/src/hooks/codex/turn-usage.ts
new file mode 100644
index 00000000..eb6109b1
--- /dev/null
+++ b/src/hooks/codex/turn-usage.ts
@@ -0,0 +1,75 @@
+import { useChatStore } from '../../stores/chatStore'
+import { estimateTokens } from '../../lib/context-compaction'
+import type { ChatMessage, ToolDefinition } from '../../api/providers/types'
+
+/**
+ * Das Feld `usage` einer Antwort — die eine Zahl, die der Nutzer als
+ * Verbrauchsanzeige sieht.
+ *
+ * Der Schnitt folgt dem geteilten Zustand `message.usage`: in useCodex.ts
+ * schrieben DREI Stellen hinein — ein Schaetzblock im Ollama-Zweig und zwei
+ * WOERTLICH IDENTISCHE Bloecke, einer im Ollama-Zweig und einer im
+ * OpenAI-kompatiblen Zweig:
+ *
+ * if (turn.promptEvalCount || turn.evalCount) {
+ * useChatStore.getState().updateMessageUsage(convId!, assistantMsg.id, {
+ * promptTokens: turn.promptEvalCount || 0, …, estimated: false,
+ * })
+ * }
+ *
+ * Zwei Kopien derselben Regel in zwei Transporten, die dasselbe Feld fuellen,
+ * gehoeren nach nebenan — sonst bekommt der eine Transport eine Korrektur, die
+ * der andere nicht sieht.
+ *
+ * DIE REGEL, DIE DABEI ZU PRUEFEN IST: eine SCHAETZUNG darf eine ECHTE Zahl
+ * NIE ueberschreiben. Der Schaetzblock traegt seinen Wert nur ein, solange
+ * `usage` fehlt oder selbst geschaetzt ist; die echte Zahl des Modells (letzte
+ * gewinnt, weil der spaeteste Aufruf den vollsten Prompt hatte) setzt
+ * `estimated: false` und ist damit endgueltig. In der grossen Datei stand
+ * diese Rangfolge nur als Kommentar; hier ist sie pruefbar, und zwar am
+ * ECHTEN Chat-Speicher.
+ */
+
+/** Was ein Transportzug an Zahlen zurueckmeldet. */
+export interface TurnCounts {
+ promptEvalCount?: number
+ evalCount?: number
+}
+
+/**
+ * Die vorlaeufige Schaetzung: echte Promptgroesse (Systemprompt + Werkzeuge +
+ * Repo-Karte + Verlauf), nicht ein Zeichen/4-Rateschluss ueber die sichtbaren
+ * Nachrichten allein. Wird nur gesetzt, solange keine echte Zahl vorliegt.
+ */
+export function seedEstimatedUsage(
+ convId: string,
+ messageId: string,
+ sendMessages: ChatMessage[],
+ tools: ToolDefinition[],
+): void {
+ const existingUsage = useChatStore.getState().conversations
+ .find((c) => c.id === convId)?.messages.find((m) => m.id === messageId)?.usage
+ if (!existingUsage || existingUsage.estimated) {
+ const estPrompt =
+ estimateTokens(sendMessages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n')) +
+ estimateTokens(JSON.stringify(tools))
+ useChatStore.getState().updateMessageUsage(convId, messageId, {
+ promptTokens: estPrompt, completionTokens: 0, totalTokens: estPrompt, estimated: true,
+ })
+ }
+}
+
+/**
+ * Die echte Zahl dieses Modellaufrufs. Mehrere Aufrufe laufen pro Aufgabe; der
+ * letzte hat den vollsten Prompt, also gewinnt der letzte.
+ */
+export function reportTurnUsage(convId: string, messageId: string, turn: TurnCounts): void {
+ if (turn.promptEvalCount || turn.evalCount) {
+ useChatStore.getState().updateMessageUsage(convId, messageId, {
+ promptTokens: turn.promptEvalCount || 0,
+ completionTokens: turn.evalCount || 0,
+ totalTokens: (turn.promptEvalCount || 0) + (turn.evalCount || 0),
+ estimated: false,
+ })
+ }
+}
diff --git a/src/hooks/codex/workspace-fs.ts b/src/hooks/codex/workspace-fs.ts
new file mode 100644
index 00000000..b9f9d548
--- /dev/null
+++ b/src/hooks/codex/workspace-fs.ts
@@ -0,0 +1,89 @@
+import { backendCall } from '../../api/backend'
+import type { RulesReader } from '../../lib/lurules'
+
+/**
+ * Der EINE Dateizugriff des Coding-Agenten, der den echten Projektordner sieht.
+ *
+ * Der Schnitt folgt keiner Zeilenzahl: VIER Stellen in useCodex.ts brauchten
+ * dieselbe Regel, und drei davon trugen den identischen Ausdruck woertlich noch
+ * einmal —
+ *
+ * workDir && workDir !== '.'
+ * ? { chatId: workspaceSlug, workingDirectory: workDir }
+ * : { chatId: workspaceSlug }
+ *
+ * einmal fuer die Vorlese-Runde vor `file_write` (`readCtx`), einmal in
+ * `stageFileWrite` und einmal in `stageFileEdit` (`stageReadCtx`). Drei Kopien
+ * einer Regel, die in allen drei Faellen dasselbe entscheiden muss, sind genau
+ * der Fall, den ZB-7 nach nebenan legt statt in eines der drei.
+ *
+ * WAS DIE REGEL ENTSCHEIDET, steht in den Kommentaren der drei alten Kopien und
+ * gilt hier einmal: es MUSS `fs_read` sein, der werkstattbewusste Befehl, nicht
+ * das aeltere `file_read`. `file_read` sperrt jeden Pfad in die Sandbox pro Chat
+ * (`agent-workspace/<id>`) und WEIST damit den absoluten Projektpfad ZURUECK.
+ * Diese stille Ablehnung hat zweimal etwas gekostet:
+ *
+ * • `.lurules` wurde in einem echten Ordner-Workspace nie geladen, weil der
+ * absolute Regelpfad an der Sperre haengenblieb;
+ * • jede Vorlese-Runde lieferte '' zurueck, und jeder Unterschied, den der
+ * Nutzer VOR dem Freigeben sehen sollte, wurde als 100 % Einfuegung
+ * gezeichnet — die Loeschungen und Ueberschreibungen waren unsichtbar.
+ *
+ * `workingDirectory` setzt die Wurzel der Sperre auf den wirklichen
+ * Projektordner, und deshalb loest sich der absolute Pfad dort auf.
+ *
+ * DER UNTERSCHIED ZWISCHEN DEN BEIDEN FORMEN IST ABSICHT, nicht Nachlaessigkeit:
+ * `makeLurulesReader` reicht `workingDirectory` IMMER durch, auch als '.',
+ * waehrend `codexReadCtx` das Feld im Sandbox-Fall weglaesst. Beide Formen sind
+ * hier unveraendert uebernommen; eine Vereinheitlichung waere eine
+ * Verhaltensaenderung und gehoert nicht in eine Umstrukturierung.
+ */
+
+/** Der Kontext, den `fs_read` braucht, um im echten Ordner zu lesen. */
+export interface CodexFsCtx {
+ chatId?: string
+ workingDirectory?: string
+}
+
+/** Was `fs_read` zurueckgibt, soweit der Coding-Agent es liest. */
+export interface CodexFileRead {
+ content?: string
+ encoding?: string
+}
+
+/**
+ * Der Lesekontext fuer einen Lauf: im Ordner-Workspace mit Wurzel, in der
+ * Sandbox ohne. Frueher dreimal woertlich in useCodex.ts.
+ */
+export function codexReadCtx(workspaceSlug: string, workDir: string): CodexFsCtx {
+ return workDir && workDir !== '.'
+ ? { chatId: workspaceSlug, workingDirectory: workDir }
+ : { chatId: workspaceSlug }
+}
+
+/** Ein Lesevorgang ueber den werkstattbewussten Befehl. */
+export function readWorkspaceFile(path: string, ctx: CodexFsCtx): Promise<CodexFileRead> {
+ return backendCall<CodexFileRead>('fs_read', { path, ...ctx })
+}
+
+/**
+ * Der Leser, den `loadLurules` erwartet. Fehler fallen weiterhin auf `null`
+ * zurueck, damit `loadLurules()` "Datei fehlt" und "Lesefehler" gleich
+ * behandelt und die Codex-Schleife trotzdem startet.
+ */
+export function makeLurulesReader(chatId: string, workDir: string): RulesReader {
+ return {
+ async read(path: string): Promise<string | null> {
+ try {
+ const r = await backendCall<{ content?: string }>('fs_read', {
+ path,
+ chatId,
+ workingDirectory: workDir,
+ })
+ return r?.content ?? null
+ } catch {
+ return null
+ }
+ },
+ }
+}
diff --git a/src/hooks/codex/workspace-precedence.ts b/src/hooks/codex/workspace-precedence.ts
new file mode 100644
index 00000000..e865406a
--- /dev/null
+++ b/src/hooks/codex/workspace-precedence.ts
@@ -0,0 +1,86 @@
+import type { AgentWorkspace } from '../../types/agent-workspace'
+
+/**
+ * EIN Ordner, vier Bewerber — und die Sperre muss denselben nennen wie der
+ * Systemprompt.
+ *
+ * Der Schnitt folgt dem GETEILTEN ZUSTAND "welcher Ordner", nicht der
+ * Zeilenzahl. In useCodex.ts standen drei Rechnungen (`workspacePath`,
+ * `workDir`, `runWorkspace`) untereinander, die alle dieselbe Frage
+ * beantworten, und ZWEI VERBRAUCHER haengen daran, die auseinanderlaufen
+ * koennen:
+ *
+ * • `workDir` ist, was dem Modell im Systemprompt als Arbeitsverzeichnis
+ * GESAGT wird (und was in jeden `file_*`-Pfad und in `shell_execute.cwd`
+ * injiziert wird);
+ * • `runWorkspace` ist, was `beginAgentRun` als SPERRE setzt.
+ *
+ * Genau diese beiden sind am 2026-07-11 live auseinandergelaufen:
+ * `resolveWorkspace()` sieht nur den Agent-Modus-Speicher pro Chat und
+ * `settings.defaultWorkspace` — es SIEHT DEN ORDNER NICHT, den die
+ * Explorer-Auswahl des Code-Reiters in `codexStore.workingDirectory` legt, und
+ * das ist der Hauptweg, ein Repo im Code-Reiter zu waehlen. Die Sperre blieb
+ * dann auf der Sandbox pro Chat stehen, waehrend dem Modell ein echter Ordner
+ * genannt wurde, und jedes `file_list`/`file_read` des Arbeitsverzeichnisses
+ * scheiterte mit "path escapes the allowed workspace".
+ *
+ * Die Zusicherung, die deshalb hier steht und nirgends sonst: fuer jede
+ * Eingabe, bei der `workDir` einen echten Ordner nennt, nennt `runWorkspace`
+ * DENSELBEN Pfad. Das war in der 2642-Zeilen-Datei nicht pruefbar, weil die
+ * Rechnung mitten in einem 2358-Zeilen-`useCallback` stand.
+ */
+
+export interface WorkspacePrecedenceInput {
+ /** `thread.workingDirectory` — die Ordnerauswahl im Datei-Baum des Reiters. */
+ threadWorkingDirectory: string | null | undefined
+ /** Das Ergebnis von `resolveWorkspace({ perChat, defaultWorkspace })`. */
+ codexWorkspace: AgentWorkspace | null
+ /** `codexStore.workingDirectory` — die globale Auswahl des Code-Reiters. */
+ storeWorkingDirectory: string | null | undefined
+}
+
+export interface WorkspacePrecedence {
+ /** Der Ordner-Pfad des aufgeloesten Workspace, sonst `null`. */
+ workspacePath: string | null
+ /** Was dem Modell gesagt wird. `'.'` bedeutet Sandbox pro Chat. */
+ workDir: string
+ /** Was die Sperre bekommt — im Ordnerfall derselbe Pfad wie `workDir`. */
+ runWorkspace: AgentWorkspace | null
+}
+
+/**
+ * Reihenfolge, unveraendert aus useCodex.ts uebernommen:
+ * 1. Ausdrueckliches `thread.workingDirectory` (Datei-Baum-Auswahl)
+ * 2. Der aufgeloeste Agent-Workspace-Pfad (wenn Ordner-Art)
+ * 3. Globales `codexStore.workingDirectory`
+ * 4. `'.'` (Sandbox pro Chat der Bruecke)
+ */
+export function resolveCodexWorkspace({
+ threadWorkingDirectory,
+ codexWorkspace,
+ storeWorkingDirectory,
+}: WorkspacePrecedenceInput): WorkspacePrecedence {
+ const workspacePath =
+ codexWorkspace && codexWorkspace.kind === 'folder' && codexWorkspace.path
+ ? codexWorkspace.path
+ : null
+ const workDir =
+ (threadWorkingDirectory && threadWorkingDirectory !== '.' ? threadWorkingDirectory : null) ||
+ workspacePath ||
+ storeWorkingDirectory ||
+ '.'
+
+ // Die Sperre auf DENSELBEN Ordner heften, der dem Modell genannt wird.
+ // `extraPaths` ueberlebt aus dem aufgeloesten Workspace, damit ein
+ // Mehr-Repo-Lauf seine Zusatzpfade behaelt.
+ const runWorkspace =
+ workDir && workDir !== '.'
+ ? {
+ kind: 'folder' as const,
+ path: workDir,
+ extraPaths: codexWorkspace && codexWorkspace.kind === 'folder' ? codexWorkspace.extraPaths : undefined,
+ }
+ : codexWorkspace
+
+ return { workspacePath, workDir, runWorkspace }
+}
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index b39341c3..50505a56 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -21,26 +21,24 @@ import { streamProviderTurn, type StreamedProviderTurn } from '../lib/provider-s
import { createHermesDisplayFilter, createThinkStreamSplitter, createTurnThinkingSink } from '../lib/hermes-stream'
import { beginAgentRun, endAgentRun, setActiveAgentModel, type AgentRunContext } from '../api/agent-context'
import { resolveChatWorkspaceSlug } from '../api/workspace-slug'
-import { codexModeKnobs, CODEX_MODE_LABELS, type CodexMode } from '../lib/codex-mode'
+import { codexModeKnobs, type CodexMode } from '../lib/codex-mode'
import { CODEX_PLAN_SYSTEM_PROMPT } from '../lib/codex-plan-prompt'
import { resolveWorkspace } from '../api/agents/workspace-resolve'
import { useAgentModeStore } from '../stores/agentModeStore'
-import { loadLurules, renderRulesSection, type RulesReader } from '../lib/lurules'
+import { loadLurules, renderRulesSection } from '../lib/lurules'
import {
parseAgentCommand, parseLoopSpec, buildLoopRecheck,
loopPassSaysDone,
} from '../lib/agent-commands'
import { useGenerationStore } from '../stores/generationStore'
-import { backendCall, isOllamaLocal } from '../api/backend'
+import { isOllamaLocal } from '../api/backend'
import { requestGenerationCancel } from '../api/vram-handoff'
import { planWithArchitect, renderArchitectPlanSection } from '../api/agents/architect'
import { fetchRepoMap, renderRepoMapSection } from '../api/agents/repo-map'
import { isLocalModelByName } from '../api/agents/model-locality'
import { useStagedChangesStore, flushStagedPersist } from '../stores/stagedChangesStore'
-import { computeUnifiedDiff } from '../lib/diff'
-import { applyUniqueEdit } from '../lib/surgical-edit'
import { log } from '../lib/logger'
-import type { AgentBlock, AgentToolCall } from '../types/agent-mode'
+import type { AgentToolCall } from '../types/agent-mode'
import { isThinkingCompatible, isPlainTextPlanner } from '../lib/model-compatibility'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
import { executeParallel, applyResultToToolCall, APPROVE_ALL, type ExecutionRequest } from '../api/agents/tool-executor'
@@ -58,7 +56,6 @@ import { asString, errorText, prop } from '../types/json-guards'
import type { ToolArgs } from '../api/mcp/types'
import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'
import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'
-import { extractToolCallsWithRanges, stripRanges } from '../lib/tool-call-repair'
import { canonicalToolName } from '../lib/loose-tool-parse'
import { selectRelevantTools, selectRelevantToolsAsync, SMALL_MODEL_MAX_TOOLS, gateCreateTools, wantsMediaTools, isGatedTool } from '../lib/tool-selection'
import { generateEmbeddings } from '../api/rag'
@@ -72,11 +69,26 @@ import { resolveAgentNumCtx } from '../lib/agent-num-ctx'
import { platformPromptLine, hostClockLine } from '../lib/host-platform'
import { ensureBuiltinAgentCtx } from '../api/builtin-ensure'
import { AgentLoopGuard } from '../lib/agent-loop-guard'
-import { findStagedForPath, stagedReadResult, stagedListingNote } from '../lib/staged-overlay'
import { applyAllStagedChanges } from '../lib/staged-apply'
import { useMemoryStore } from '../stores/memoryStore'
import { extractMemoriesFromPair } from './useMemory'
import { useCodexConfirmStore } from '../stores/codexConfirmStore'
+// ── Die Teile, die dieser Haken nicht mehr selbst traegt ────────────────────
+// Jedes dieser Module haelt EINEN geteilten Zustand oder EINE Regel, die
+// mehrere Stellen hier gemeinsam brauchen; der Dateikopf dort sagt jeweils,
+// welchen. Was hier bleibt, ist die Reihenfolge des Zuges.
+import { codexReadCtx, readWorkspaceFile, makeLurulesReader } from './codex/workspace-fs'
+import { resolveCodexWorkspace } from './codex/workspace-precedence'
+import { codexModeRefusal } from './codex/mode-refusal'
+import { createAgentBlockSink } from './codex/agent-blocks'
+import { createLivePaint } from './codex/live-paint'
+import { seedEstimatedUsage, reportTurnUsage } from './codex/turn-usage'
+import { isThinkingUnsupportedError } from './codex/thinking-downgrade'
+import { recoverToolCallsFromContent } from './codex/tool-call-recovery'
+import { codexStallVerdict } from './codex/stall-verdict'
+import { createStagedWriter } from './codex/staged-writes'
+import { codexToolDiff, codexEventKind } from './codex/tool-result-view'
+import { capHiddenToolHistory } from './codex/hidden-history'
// No-op diagnostic hook. Kept as a call site so future debugging can swap
// this for a file logger without re-editing every iter-point in the loop.
@@ -177,31 +189,6 @@ const streamWithTools = streamOllamaChatWithTools
const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web', 'image', 'video', 'workflow'] as const
-// `.lurules` reader. MUST go through `fs_read` (the workspace-aware command)
-// with the run's chatId + workingDirectory — NOT the older `file_read`, which
-// jails every path to the per-chat sandbox (agent-workspace/<id>) and so
-// REJECTS the absolute `<workDir>/.lurules` path with "escapes the allowed
-// workspace". That silent rejection meant per-repo rules never loaded in a real
-// folder workspace. Threading workingDirectory sets the jail root to the actual
-// project folder, so the absolute rules path resolves. Errors still swallow to
-// null so loadLurules() treats "missing file" and "fs error" identically.
-function makeLurulesReader(chatId: string, workDir: string): RulesReader {
- return {
- async read(path: string): Promise<string | null> {
- try {
- const r = await backendCall<{ content?: string }>('fs_read', {
- path,
- chatId,
- workingDirectory: workDir,
- })
- return r?.content ?? null
- } catch {
- return null
- }
- },
- }
-}
-
// Detect when the model emits a re-introduction of itself ("Hello, I am
// the Coding Agent, an autonomous coding agent…") instead of the actual
// answer. Gemma 4 + smaller models do this after a tool error — they
@@ -360,37 +347,13 @@ export function useCodex() {
}
const thread = codexStore.getThread(convId)!
- // Resolve working directory with this precedence:
- // 1. Explicit codex thread.workingDirectory (file-tree picker)
- // 2. Resolved agent workspace path (when folder-kind)
- // 3. Global codexStore.workingDirectory
- // 4. '.' (bridge's per-chat sandbox)
- const workspacePath =
- codexWorkspace && codexWorkspace.kind === 'folder' && codexWorkspace.path
- ? codexWorkspace.path
- : null
- const workDir =
- (thread.workingDirectory && thread.workingDirectory !== '.' ? thread.workingDirectory : null) ||
- workspacePath ||
- codexStore.workingDirectory ||
- '.'
-
- // Pin the tool-containment workspace to the SAME folder the model is told
- // to use (workDir). resolveWorkspace() above only sees the agent-mode
- // per-chat store + settings.defaultWorkspace — it MISSES the folder the
- // Code tab's explorer picker sets (codexStore.workingDirectory), which is
- // the primary way to pick a repo in the Code tab. Without this, containment
- // stayed pinned to the per-chat sandbox while the model was told to work in
- // a real folder, so every file_list/file_read of the working dir failed
- // with "path escapes the allowed workspace" (live cloud find, 2026-07-11).
- const runWorkspace =
- workDir && workDir !== '.'
- ? {
- kind: 'folder' as const,
- path: workDir,
- extraPaths: codexWorkspace && codexWorkspace.kind === 'folder' ? codexWorkspace.extraPaths : undefined,
- }
- : codexWorkspace
+ // Welcher Ordner: Rangfolge, Sperre und die Zusicherung, dass beide
+ // denselben Pfad nennen — hooks/codex/workspace-precedence.ts.
+ const { workDir, runWorkspace } = resolveCodexWorkspace({
+ threadWorkingDirectory: thread.workingDirectory,
+ codexWorkspace,
+ storeWorkingDirectory: codexStore.workingDirectory,
+ })
// `/goal` is bookkeeping, not a prompt. Handle it here and show the result;
// every LATER turn picks the goal up from the system prompt below.
@@ -405,30 +368,20 @@ export function useCodex() {
return
}
- // Review Mode strips every mutating tool. A command whose whole job is to
- // change something would then run to completion narrating work it could not
- // do, with nothing on screen explaining why. Say it and stop.
- if (settings.codexReviewMode && slash && !slash.command.readOnly) {
- useChatStore.getState().addMessage(convId, {
- id: uuid(), role: 'user', content: rawInstruction, timestamp: Date.now(),
- })
- useChatStore.getState().addMessage(convId, {
- id: uuid(), role: 'assistant', timestamp: Date.now(),
- content: `Review Mode is on, so I cannot write files or run commands, and /${slash.command.name} needs both. Turn Review Mode off in Settings, or use a read-only command such as /review, /plan, /diff or /explain.`,
- })
- return
- }
-
- // Same for Plan mode: it is read-only for the whole conversation, so a
- // command whose job is to change something has nowhere to land. Saying so
- // beats narrating work that silently could not happen.
- if (codexMode === 'plan' && slash && !slash.command.readOnly) {
+ // Ein Befehl, der in diesem Modus nichts ausrichten kann, wird gesagt und
+ // nicht erzaehlt. Rangfolge und Wortlaut: hooks/codex/mode-refusal.ts.
+ const modeRefusal = codexModeRefusal({
+ reviewMode: settings.codexReviewMode,
+ codexMode,
+ slash,
+ })
+ if (modeRefusal) {
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'user', content: rawInstruction, timestamp: Date.now(),
})
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'assistant', timestamp: Date.now(),
- content: `Plan mode is read-only, and /${slash.command.name} needs to write files or run commands. Switch the mode dropdown to "${CODEX_MODE_LABELS.ask}" first, or use a read-only command such as /review, /plan, /diff or /explain.`,
+ content: modeRefusal,
})
return
}
@@ -481,17 +434,10 @@ export function useCodex() {
// classic top-of-bubble field (plain answer turns keep the old look).
let anyToolExecuted = false
- const blocks: AgentBlock[] = []
- function addBlock(block: AgentBlock) {
- blocks.push(block)
- useChatStore.getState().updateMessageAgentBlocks(convId!, assistantMsg.id, [...blocks])
- }
- function updateBlockById(blockId: string, updates: Partial<AgentBlock>) {
- const idx = blocks.findIndex((b) => b.id === blockId)
- if (idx < 0) return
- blocks[idx] = { ...blocks[idx], ...updates }
- useChatStore.getState().updateMessageAgentBlocks(convId!, assistantMsg.id, [...blocks])
- }
+ // Die Blockliste und ihr Spiegel im Speicher — hooks/codex/agent-blocks.ts.
+ const blockSink = createAgentBlockSink(convId!, assistantMsg.id)
+ const addBlock = blockSink.add
+ const updateBlockById = blockSink.update
// Resolve provider
const { provider, modelId } = getProviderForModel(activeModel)
@@ -779,14 +725,13 @@ export function useCodex() {
// Cloud model picked without explicit opt-in → fall back to
// editor-only. Surface a one-line reflection so the user knows
// why the plan didn't appear.
- blocks.push({
+ addBlock({
id: uuid(),
phase: 'reflection',
content:
`🏗️ Architect skipped, \`${archModel}\` is a cloud model and "Allow cloud architect" is off. Enable it in Settings → Coding Agent, or pick a local model.`,
timestamp: Date.now(),
})
- useChatStore.getState().updateMessageAgentBlocks(convId, assistantMsg.id, [...blocks])
} else {
try {
const planResult = await planWithArchitect({
@@ -801,13 +746,12 @@ export function useCodex() {
if (planResult.plan) {
systemPrompt += renderArchitectPlanSection(planResult.plan)
messages[0] = { role: 'system', content: systemPrompt }
- blocks.push({
+ addBlock({
id: uuid(),
phase: 'reflection',
content: `🏗️ **Architect plan** (\`${planResult.modelUsed}\`, ${planResult.tookMs}ms)\n\n${planResult.plan}`,
timestamp: Date.now(),
})
- useChatStore.getState().updateMessageAgentBlocks(convId, assistantMsg.id, [...blocks])
}
} catch (e) {
// Architect is advisory — never blocks the editor loop. Use
@@ -834,13 +778,12 @@ export function useCodex() {
if (repoMap.files.length > 0) {
systemPrompt += renderRepoMapSection(repoMap)
messages[0] = { role: 'system', content: systemPrompt }
- blocks.push({
+ addBlock({
id: uuid(),
phase: 'reflection',
content: `🗺️ Repo map: top ${repoMap.files.length} files (of ${repoMap.count}), ${repoMap.files.slice(0, 5).map((f) => f.path).join(', ')}${repoMap.files.length > 5 ? '…' : ''}`,
timestamp: Date.now(),
})
- useChatStore.getState().updateMessageAgentBlocks(convId, assistantMsg.id, [...blocks])
}
} catch (e) {
log.warn('codex.repo_map_fetch_failed', { err: e })
@@ -1096,24 +1039,15 @@ export function useCodex() {
// cancels the queued frame the moment the stream call returns, so a
// stale frame can never fire AFTER a final direct write and repaint
// old content over it.
- let livePaintPending: string | null = null
- let livePaintFrame = false
- const settleLivePaint = () => {
- livePaintPending = null
- }
- const liveContent = (c: string) => {
- if (echoRetriesRemaining > 0 && isSystemPromptEcho(c)) return
- livePaintPending = fullContent ? fullContent + '\n\n' + c : c
- if (livePaintFrame) return
- livePaintFrame = true
- requestAnimationFrame(() => {
- livePaintFrame = false
- if (livePaintPending !== null) {
- useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, livePaintPending)
- livePaintPending = null
- }
- })
- }
+ // Ein Puffer, drei Transporte, ein Bild pro Zeichenrunde — und ein
+ // settle(), das ein wartendes Bild loescht: hooks/codex/live-paint.ts.
+ const livePaint = createLivePaint({
+ suppress: (c) => echoRetriesRemaining > 0 && isSystemPromptEcho(c),
+ prefix: () => fullContent,
+ paint: (text) => useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, text),
+ })
+ const settleLivePaint = livePaint.settle
+ const liveContent = livePaint.feed
if (strategy === 'native') {
// Route on the USER's instruction, never on the newest user-role
@@ -1220,18 +1154,7 @@ export function useCodex() {
// char/4 guess of just the visible messages. Provisional estimate that
// the model's exact count overwrites below; only (re)set while no real
// count has landed yet, so a real value is never downgraded.
- {
- const existingUsage = useChatStore.getState().conversations
- .find((c) => c.id === convId)?.messages.find((m) => m.id === assistantMsg.id)?.usage
- if (!existingUsage || existingUsage.estimated) {
- const estPrompt =
- estimateTokens(sendMessages.map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))).join('\n')) +
- estimateTokens(JSON.stringify(tools))
- useChatStore.getState().updateMessageUsage(convId!, assistantMsg.id, {
- promptTokens: estPrompt, completionTokens: 0, totalTokens: estPrompt, estimated: true,
- })
- }
- }
+ seedEstimatedUsage(convId!, assistantMsg.id, sendMessages, tools)
try {
void diagLog('streamWithTools-enter', { iter: i, messagesLen: sendMessages.length, toolsCount: tools.length, thinking: chatOptions.thinking })
turn = await streamWithTools(
@@ -1253,7 +1176,7 @@ export function useCodex() {
messageHead: errorText(thinkErr).slice(0, 400),
name: asString(prop(thinkErr, 'name')),
})
- if (httpStatusOf(thinkErr) === 400 || errorText(thinkErr).includes('does not support thinking')) {
+ if (isThinkingUnsupportedError(thinkErr)) {
turn = await streamWithTools(
modelToUse, sendMessages, tools,
{ temperature: 0.1, thinking: undefined, maxTokens: chatOptions.maxTokens, contextWindow: numCtx, signal: abort.signal },
@@ -1268,18 +1191,7 @@ export function useCodex() {
settleLivePaint()
toolCalls = turn.toolCalls
turnContent = turn.content || ''
- // Real consumed-context usage for THIS coding turn (system + tools +
- // RAG + file context + history). Multiple model calls run per task;
- // the latest has the fullest prompt, so store each (last wins) to
- // keep the TokenCounter on the true fill, not a char/4 estimate.
- if (turn.promptEvalCount || turn.evalCount) {
- useChatStore.getState().updateMessageUsage(convId!, assistantMsg.id, {
- promptTokens: turn.promptEvalCount || 0,
- completionTokens: turn.evalCount || 0,
- totalTokens: (turn.promptEvalCount || 0) + (turn.evalCount || 0),
- estimated: false,
- })
- }
+ reportTurnUsage(convId!, assistantMsg.id, turn)
void diagLog('streamWithTools-return', {
iter: i,
toolCallsCount: toolCalls.length,
@@ -1293,50 +1205,13 @@ export function useCodex() {
useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
}
- // v2.5.0 fix (post-merge bug hunt): some Ollama models
- // (qwen2.5-coder:3b confirmed) emit tool calls as a fenced
- // ```json { "name":..., "arguments":... } ``` block inside
- // message.content INSTEAD of the native message.tool_calls
- // array. When the native list is empty but content looks like
- // a tool call, extract it and strip the fence so the user
- // doesn't see raw JSON.
- // Track whether this iteration's content held tool-call JSON.
- // qwen2.5-coder:3b emits the JSON in content rather than native
- // tool_calls, and every iteration wraps the JSON with the same
- // narrative ("I'm about to verify…" + code blocks). Those lines
- // are not the FINAL answer — they're filler between tool calls
- // and would duplicate across iterations if accumulated.
- let extractedFromContent = false
- if (toolCalls.length === 0 && turnContent) {
- const { calls: extracted, ranges } = extractToolCallsWithRanges(turnContent)
- if (extracted.length > 0) {
- toolCalls = extracted.map(tc => ({ function: { name: tc.name, arguments: tc.arguments } }))
- turnContent = stripRanges(turnContent, ranges)
- extractedFromContent = true
- }
- }
- // Safety net for qwen2.5-coder: sometimes the model emits the
- // tool-call JSON alongside native tool_calls — native was parsed
- // already, but the same JSON still sits in the content. Strip
- // those too so the chat bubble stays readable.
- if (toolCalls.length > 0 && turnContent && /\{\s*"(?:name|tool|function)"\s*:/.test(turnContent)) {
- const { ranges } = extractToolCallsWithRanges(turnContent)
- if (ranges.length > 0) {
- turnContent = stripRanges(turnContent, ranges)
- extractedFromContent = true
- }
+ // Werkzeugaufrufe, die im Fliesstext stehen — und die Prosa, die dabei
+ // stehen bleiben MUSS: hooks/codex/tool-call-recovery.ts.
+ {
+ const recovered = recoverToolCallsFromContent(toolCalls, turnContent)
+ toolCalls = recovered.toolCalls
+ turnContent = recovered.content
}
- // When the model bundles its tool-call JSON INSIDE the text
- // (qwen2.5-coder & co.), KEEP the surrounding prose as this
- // iteration's commentary — the JSON itself was already removed by
- // stripRanges above. Keeping it (instead of clearing) is what makes
- // every between-tool answer survive so the renderer can interleave
- // them chronologically: tool → answer → tool → tool → answer …
- // (David 2026-06-02 r2: "antworten zwischen drin verschwinden immer,
- // darf nicht sein"). Older answers auto-collapse in the UI, so the
- // old "stack of duplicated I'm-about-to paragraphs" problem is gone.
- // Only drop it when nothing but punctuation/whitespace remains.
- if (extractedFromContent && !/[A-Za-z0-9]/.test(turnContent)) turnContent = ''
} else {
// ── Streaming path for OpenAI-compat / Anthropic / LU Cloud ──
// chatStream carries the tool defs (ChatOptions.tools) and the
@@ -1355,7 +1230,7 @@ export function useCodex() {
try {
turn = await streamProviderTurn(provider, modelToUse, sendMessages, streamOpts, liveContent, liveThinking)
} catch (thinkErr) {
- if (errorText(thinkErr).includes('does not support thinking') || httpStatusOf(thinkErr) === 400) {
+ if (isThinkingUnsupportedError(thinkErr)) {
turn = await streamProviderTurn(provider, modelToUse, sendMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, liveContent, () => {})
} else {
throw thinkErr
@@ -1364,14 +1239,7 @@ export function useCodex() {
settleLivePaint()
toolCalls = turn.toolCalls
turnContent = turn.content || ''
- if (turn.promptEvalCount || turn.evalCount) {
- useChatStore.getState().updateMessageUsage(convId!, assistantMsg.id, {
- promptTokens: turn.promptEvalCount || 0,
- completionTokens: turn.evalCount || 0,
- totalTokens: (turn.promptEvalCount || 0) + (turn.evalCount || 0),
- estimated: false,
- })
- }
+ reportTurnUsage(convId!, assistantMsg.id, turn)
if (keepThinking && turn.thinking) {
thinkingContent += (thinkingContent ? '\n\n' : '') + turn.thinking
useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
@@ -1480,8 +1348,9 @@ export function useCodex() {
// Same downgrade the native branch carries: an old Ollama build or
// an endpoint that predates the knob answers 400, and the run must
// survive that instead of ending on it.
- if (hermesOpts.thinking !== undefined
- && (errorText(thinkErr).includes('does not support thinking') || httpStatusOf(thinkErr) === 400)) {
+ // Die Zusatzbedingung bleibt HIER: nur absteigen, wenn ueberhaupt ein
+ // Denk-Schalter gesetzt war. Das ist Verhalten, keine Doppelung.
+ if (hermesOpts.thinking !== undefined && isThinkingUnsupportedError(thinkErr)) {
hermesTurn = await runHermes({ ...hermesOpts, thinking: undefined as unknown as boolean })
} else {
throw thinkErr
@@ -1669,34 +1538,9 @@ export function useCodex() {
// (only strong "is complete / all tests pass / committed" phrases, not
// forward-looking "to complete the fix") so we err toward nudging.
if (toolCalls.length === 0) {
- // Nudge ONLY when the model clearly STALLED mid-task — it narrated the
- // next step ("I'm about to…", "let me…", "next I'll…", "I need to read…")
- // or asked for info it could find itself ("please provide the path",
- // "which file?"), or returned no text at all. A substantive ANSWER
- // matches none of these, so simple Q&A ("2+2 is 4" / "Task completed.
- // The answer is 4.") stops cleanly. The previous "nudge unless a
- // completion keyword is present" version looped on already-answered
- // questions (David 2026-06-02: coding agent "antwortet in loops" on a
- // simple question — it called shell_execute 3× + repeated "Task
- // completed" because "completed" never matched the completion regex).
- const stalledNarration = /\b(i(?:'?m| am) about to|i will(?: now)?|i'?ll\b|let me\b|next,?\s*i\b|now i'?ll|going to|first,?\s*i\b|then i'?ll|i (?:need|have|am going) to (?:read|open|check|look|run|see|find))\b/i.test(turnContent)
- // "asksForInfo" also catches the model giving up by asking the user to
- // VERIFY/CONFIRM a path it can discover itself ("it seems there is an
- // issue with the file path … could you please verify the correct path
- // to sum.js?" — David 2026-06-02 live coding run with qwen2.5-coder:7b).
- // The verify/confirm/clarify branch is anchored on a path/file NOUN so
- // a genuine completion ("I fixed it, please verify the changes") does
- // NOT match — only "verify the (correct) path/file/location" does.
- const asksForInfo = /\b(please provide|could you (?:please )?(?:provide|share|tell|give|specify|verify|confirm|clarify)|what(?:'s| is) the (?:path|file|name|location)|which file|can you (?:provide|share|specify|tell)|provide (?:the|me) (?:the )?(?:path|file|details|more)|(?:verify|confirm|clarify) (?:the )?(?:correct |right |exact |full )?(?:path|file ?path|location|directory|filename|file name)|need (?:the|more) (?:path|info|details|context))\b/i.test(turnContent)
- const emptyTurn = turnContent.trim().length === 0
- // Only nudge an empty turn when NOTHING has been produced yet (a true
- // early stall). An empty turn AFTER a real answer means the model is
- // finished, break immediately instead of spinning slow no-op nudge
- // iterations that keep the typing dots up long after the answer is
- // done (David 2026-06-12: "die punkte bleiben so lange obwohl keine
- // antwort mehr kam"). Read-only report commands (/review, /explain …)
- // legitimately end on a text answer + an empty follow-up turn.
- const nudgeWorthy = stalledNarration || asksForInfo || (emptyTurn && !fullContent.trim())
+ // Steckengeblieben oder fertig — drei Muster ueber denselben Text und
+ // ihre Fehlalarm-Geschichte: hooks/codex/stall-verdict.ts.
+ const { nudgeWorthy } = codexStallVerdict(turnContent, fullContent)
if (nudgeWorthy && continueNudgesRemaining > 0) {
continueNudgesRemaining--
void diagLog('continue-nudge', { iter: i, remaining: continueNudgesRemaining, turnContentLen: turnContent.length })
@@ -1875,15 +1719,14 @@ export function useCodex() {
// absolute project path, so every pre-read returned '' and every diff
// rendered as a 100% insert — hiding exactly the deletions/overwrites
// the user needs to see before approving a staged change.
- const readCtx: { chatId?: string; workingDirectory?: string } =
- workDir && workDir !== '.' ? { chatId: workspaceSlug, workingDirectory: workDir } : { chatId: workspaceSlug }
+ const readCtx = codexReadCtx(workspaceSlug, workDir)
const oldContents = new Map<string, string>()
await Promise.all(
batch
.filter((e) => (e.ac.toolName === 'file_write' || e.ac.toolName === 'file_edit') && typeof e.injectedArgs.path === 'string')
.map(async (e) => {
try {
- const r = await backendCall<{ content?: string }>('fs_read', { path: e.injectedArgs.path, ...readCtx })
+ const r = await readWorkspaceFile(e.injectedArgs.path as string, readCtx)
oldContents.set(e.ac.id, r?.content ?? '')
} catch {
oldContents.set(e.ac.id, '')
@@ -1907,146 +1750,21 @@ export function useCodex() {
toolCallCapMs(name, args, settings),
)
- // Multi-File Stage-and-Approve (B10). When the user has codex
- // stage mode on, file_write calls don't hit the disk — they
- // queue in stagedChangesStore as "pending changes" the user
- // reviews and applies (or rejects) per-file. The model still
- // sees a synthetic success message so the loop progresses; the
- // user is the gatekeeper for the actual disk write.
- const stageFileWrite = async (args: ToolArgs): Promise<string> => {
- const path = String(args.path ?? '')
- if (!path) return 'file_write: missing path'
- const newContent = String(args.content ?? '')
- // Resolve against the run's workspace NOW (at stage time). Apply
- // happens later, after this turn's finally clears the active
- // chat/workspace context, so a relative path would otherwise route to
- // agent-workspace/default/ instead of the real project folder. The
- // bridge jails absolute paths to the workspace root, so the pre-read
- // MUST pass the run's workingDirectory (as its root) — otherwise the
- // absolute project path is rejected and the staged diff shows a 100%
- // insert, hiding what will be overwritten. (v2.5.0 + 2.5.9 audit fix.)
- const isAbs = /^([a-zA-Z]:[\\/]|[\\/]|\\\\)/.test(path)
- const resolvedPath = isAbs || !workDir || workDir === '.'
- ? path
- : `${workDir.replace(/[\\/]+$/, '')}${workDir.includes('\\') ? '\\' : '/'}${path.replace(/^[\\/]+/, '')}`
- const stageReadCtx: { chatId?: string; workingDirectory?: string } =
- workDir && workDir !== '.' ? { chatId: workspaceSlug, workingDirectory: workDir } : { chatId: workspaceSlug }
- // A prior staged entry for this path already knows the DISK state —
- // reuse it so the reviewed diff stays disk → latest even when the
- // model writes the same file twice in one run.
- const priorWrite = findStagedForPath(useStagedChangesStore.getState().list(convId!), path)
- let oldContent = ''
- if (priorWrite) {
- oldContent = priorWrite.oldContent
- } else {
- try {
- const r = await backendCall<{ content?: string }>('fs_read', { path: resolvedPath, ...stageReadCtx })
- oldContent = r?.content ?? ''
- } catch {
- // New file — leave oldContent empty so the diff renders an
- // all-add hunk and the apply path creates the file.
- }
- }
- const diff = computeUnifiedDiff(path, oldContent, newContent)
- useStagedChangesStore.getState().stage(convId!, {
- path,
- resolvedPath,
- // Capture the workspace root so Apply (which runs after the loop's
- // finally clears the active context) can jail the write to the real
- // project folder instead of agent-workspace/default. Undefined in
- // sandbox mode — the per-chat sandbox is the right root there.
- workingDirectory: workDir && workDir !== '.' ? workDir : undefined,
- oldContent,
- newContent,
- diff,
- })
- return `Staged for review: ${path}. The user will apply or reject the change before it lands on disk.`
- }
-
- // Stage-mode counterpart for surgical edits: resolve old_string ->
- // new_string against the current file NOW and stage the resulting full
- // content, so the staged diff and the applied write are the real change
- // (and a bad edit is reported the same way whether staged or not).
- const stageFileEdit = async (args: ToolArgs): Promise<string> => {
- const path = String(args.path ?? '')
- if (!path) return 'file_edit: missing path'
- const oldString = typeof args.old_string === 'string' ? args.old_string : ''
- const newString = typeof args.new_string === 'string' ? args.new_string : ''
- const isAbs = /^([a-zA-Z]:[\\/]|[\\/]|\\\\)/.test(path)
- const resolvedPath = isAbs || !workDir || workDir === '.'
- ? path
- : `${workDir.replace(/[\\/]+$/, '')}${workDir.includes('\\') ? '\\' : '/'}${path.replace(/^[\\/]+/, '')}`
- const stageReadCtx: { chatId?: string; workingDirectory?: string } =
- workDir && workDir !== '.' ? { chatId: workspaceSlug, workingDirectory: workDir } : { chatId: workspaceSlug }
- // Read-your-writes: chain onto the STAGED content when this path is
- // already pending. Without this the base was re-read from DISK —
- // which never saw the staged write — so a second edit to the same
- // file silently clobbered the first, and an edit to a staged NEW
- // file failed with "could not read".
- const priorEdit = findStagedForPath(useStagedChangesStore.getState().list(convId!), path)
- let baseContent = ''
- let diskContent = ''
- if (priorEdit) {
- baseContent = priorEdit.newContent
- diskContent = priorEdit.oldContent
- } else {
- try {
- const r = await backendCall<{ content?: string; encoding?: string }>('fs_read', { path: resolvedPath, ...stageReadCtx })
- if (r?.encoding === 'binary' || r?.encoding === 'base64') return `file_edit: cannot edit a binary file (${path}).`
- baseContent = diskContent = r?.content ?? ''
- } catch {
- return `file_edit: could not read ${path}. To create a new file use file_write.`
- }
- }
- const applied = applyUniqueEdit(baseContent, oldString, newString)
- if (!applied.ok) {
- switch (applied.reason) {
- case 'empty_old': return 'file_edit: old_string must be non-empty. Use file_write to create a new file.'
- case 'noop': return 'file_edit: old_string and new_string are identical, nothing to change.'
- case 'not_found': return `file_edit: old_string not found in ${path}. Read the file and copy the exact text you want to replace.`
- case 'not_unique': return `file_edit: old_string matches ${applied.matches} places in ${path}. Add surrounding lines so it is unique.`
- default: return 'file_edit: failed.'
- }
- }
- const newContent = applied.content ?? ''
- // Diff and oldContent stay anchored on the DISK state, so the user
- // reviews (and apply writes) disk → final, not staged → staged.
- const diff = computeUnifiedDiff(path, diskContent, newContent)
- useStagedChangesStore.getState().stage(convId!, {
- path,
- resolvedPath,
- workingDirectory: workDir && workDir !== '.' ? workDir : undefined,
- oldContent: diskContent,
- newContent,
- diff,
- })
- return `Staged for review: ${path} (surgical edit). The user will apply or reject the change before it lands on disk.`
- }
+ // Die Ablage-Warteschlange und ALLES, was sie anfasst — die vier
+ // Zugriffe, die nur zusammen richtig sind: hooks/codex/staged-writes.ts.
+ const stagedWriter = createStagedWriter({
+ convId: convId!,
+ workDir,
+ workspaceSlug,
+ readFile: readWorkspaceFile,
+ })
const dispatchTool = (name: string, args: ToolArgs, signal?: AbortSignal): Promise<string> => {
// Stage-and-Approve follows the MODE preset, not the raw setting:
// Ask stages every write for review, Bypass writes straight through,
// Plan never gets here because the write tools are stripped.
if (knobs.stageWrites) {
- if (name === 'file_write') return stageFileWrite(args)
- if (name === 'file_edit') return stageFileEdit(args)
- // Read-your-writes: staged content is invisible on disk, so reads
- // MUST be answered from the queue — otherwise the model reads the
- // old bytes (or a not-found), concludes its write failed, and
- // stages the same file forever (Morgan's file_read loop,
- // 2026-07-26). The in-turn cache composes correctly: every staged
- // write is audited as a file_write mutation, which invalidates
- // cached reads, so a pre-stage result is never replayed.
- const staged = convId ? useStagedChangesStore.getState().list(convId) : []
- if (staged.length > 0) {
- if (name === 'file_read') {
- const hit = findStagedForPath(staged, String(args.path ?? ''))
- if (hit) return Promise.resolve(stagedReadResult(hit))
- }
- if (name === 'file_list' || name === 'file_search') {
- return withTimeout(name, args, signal).then((r) => r + stagedListingNote(staged))
- }
- }
+ return stagedWriter.dispatch(name, args, () => withTimeout(name, args, signal))
}
return withTimeout(name, args, signal)
}
@@ -2163,31 +1881,15 @@ export function useCodex() {
// itself re-checks. The display path checks it too instead of handing
// whatever arrived to the differ.
const acPath = asString(entry.injectedArgs.path)
- let acDiff: string | undefined
- if (entry.ac.toolName === 'file_write') {
- // Pre-read above captured the on-disk version; a missing file
- // yields an all-add hunk. Empty diff → omit.
- const oldText = oldContents.get(entry.ac.id) ?? ''
- const newText =
- typeof entry.injectedArgs.content === 'string'
- ? entry.injectedArgs.content
- : ''
- acDiff = computeUnifiedDiff(acPath ?? '', oldText, newText) || undefined
- } else if (entry.ac.toolName === 'file_edit') {
- // Surgical edit — the tool only received old_string/new_string, so
- // reconstruct the new content from the pre-read + the unique
- // replacement to attach a real diff. If the edit did not apply
- // uniquely the executor already returned an error; skip the diff.
- const oldText = oldContents.get(entry.ac.id) ?? ''
- const applied = applyUniqueEdit(
- oldText,
- typeof entry.injectedArgs.old_string === 'string' ? entry.injectedArgs.old_string : '',
- typeof entry.injectedArgs.new_string === 'string' ? entry.injectedArgs.new_string : '',
- )
- acDiff = applied.ok
- ? computeUnifiedDiff(acPath ?? '', oldText, applied.content ?? '') || undefined
- : undefined
- }
+ // Der angezeigte Unterschied ist NACHGEBAUT, nicht beobachtet — die
+ // eine Stelle, die ueber eine Aenderung luegen kann:
+ // hooks/codex/tool-result-view.ts.
+ const acDiff = codexToolDiff({
+ toolName: entry.ac.toolName,
+ path: acPath,
+ oldText: oldContents.get(entry.ac.id) ?? '',
+ args: entry.injectedArgs,
+ })
if (acDiff) entry.ac.diff = acDiff
updateBlockById(entry.blockId, {
@@ -2201,23 +1903,17 @@ export function useCodex() {
: `Failed: ${entry.ac.toolName}`,
})
- // Codex event log parity with the old path.
+ // Codex event log parity with the old path. Welcher Eintrag —
+ // und warum ein FEHLGESCHLAGENES file_write trotzdem ein
+ // file_change bleibt: hooks/codex/tool-result-view.ts.
const resultStr = entry.ac.result ?? entry.ac.error ?? ''
- if (entry.ac.toolName === 'shell_execute' || entry.ac.toolName === 'code_execute') {
+ const eventKind = codexEventKind(entry.ac.toolName, isError)
+ if (eventKind) {
codexStore.addEvent(convId, {
- id: uuid(), type: 'terminal_output', content: resultStr, timestamp: Date.now(),
- })
- } else if (entry.ac.toolName === 'file_write' || entry.ac.toolName === 'file_edit') {
- codexStore.addEvent(convId, {
- id: uuid(), type: 'file_change', content: resultStr,
- filePath: acPath,
- diff: acDiff,
+ id: uuid(), type: eventKind, content: resultStr,
+ ...(eventKind === 'file_change' ? { filePath: acPath, diff: acDiff } : {}),
timestamp: Date.now(),
})
- } else if (isError) {
- codexStore.addEvent(convId, {
- id: uuid(), type: 'error', content: resultStr, timestamp: Date.now(),
- })
}
}
@@ -2447,11 +2143,8 @@ export function useCodex() {
// The most recent chain is what the next turn actually needs; older
// steps are summarised by the visible transcript anyway.
const toolHistoryAll = messages.slice(messagesStartLen)
- const HIDDEN_HISTORY_MAX = 60
- let toolHistory = toolHistoryAll.slice(-HIDDEN_HISTORY_MAX)
- // Never start the kept slice on an orphan tool result — strict
- // providers 422 a result whose call fell outside the window.
- while (toolHistory.length > 0 && toolHistory[0].role === 'tool') toolHistory = toolHistory.slice(1)
+ // Deckelung UND Waisenschnitt gehoeren zusammen: hooks/codex/hidden-history.ts.
+ const toolHistory = capHiddenToolHistory(toolHistoryAll)
if (toolHistory.length > 0 && convId) {
const store = useChatStore.getState()
// Find the assistant message we just filled so we can insert BEFORE it