The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(agent): Code-Agent verbrennt keine Credits mehr fuer Plan-Runden und Neuanfaenge
purplec88a34d90f37
diff --git a/mobile-client/agent-core.js b/mobile-client/agent-core.jsindex 2842dd85..b412d0c1 100644--- a/mobile-client/agent-core.js+++ b/mobile-client/agent-core.js@@ -8,7 +8,7 @@ import { stripNonCanonicalTags } from './personas.js'// same model behaviour follows us onto mobile. Tests in// src/api/__tests__/tool-description-parity.test.ts pin this parity.var AGENT_TOOLS = [- {name:'todo_write', description:'Write and update the plan for a multi-step task. The list is shown to the user live, so it is how they follow a long run. USE FIRST when a task needs more than about three tool calls, then send it again after each step. Send the COMPLETE list every time: it replaces the previous one, it does not merge.',+ {name:'todo_write', description:'Write and update the plan the user asked for. The list is shown to the user live. NEVER send it as a step of its own: send an update together with your next real tool call. Send the COMPLETE list every time: it replaces the previous one, it does not merge.',parameters:[{name:'todos',type:'array',description:'The complete plan, in order. Replaces the previous list.',required:true}]},{name:'web_search', description:'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. Snippets are teasers, not answers: PREFER web_fetch on the promising URLs for the real content. DO NOT run more than 3 similar queries per turn, refine instead of re-searching.',parameters:[{name:'query',type:'string',description:'The search query string',required:true},diff --git a/mobile-client/personas.js b/mobile-client/personas.jsindex 3bec38c6..f3c4becb 100644--- a/mobile-client/personas.js+++ b/mobile-client/personas.js@@ -4,7 +4,7 @@// with live Thought/Action/Observation cards streamed into the chat.// The old "you can't run tools" text was from v2.3.3 before the mobile// bridge could actually execute them.- var CODEX_PROMPT = 'You are the Coding Agent, an autonomous coding agent inside LU. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. Empty assistant messages are a FAILURE.\n\n2. DO NOT stop after the first tool. Real coding tasks take 3-15 tool calls. Stopping after one file_read or one shell_execute without producing the requested artefact = FAILURE. "I have called one tool, that is enough" is NOT a valid stop reason.\n\n3. NEVER say "Now I will create X" / "Next I\'ll write Y" as plain prose and then stop. Do the next step RIGHT NOW as a concrete tool call.\n\n4. When your plan has N steps, execute ALL N steps in one session — each step as a concrete tool call. Plan in tool-call form, not prose-then-stop.\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk, OR (b) you are stuck and genuinely need user input.\n\n=== WORKFLOW ===\n\n1. Understand the task.\n2. If the task needs more than about three tool calls, call todo_write with the WHOLE plan before you start. The user sees that list live on their phone. It is how they follow a long run on a small screen. Call it again after each step with the complete list, the finished item completed and the next one in_progress. Never mark an item completed before it actually succeeded.\n3. Explore (file_list, file_read, file_search) when you need to know existing layout.\n4. Implement (file_write) — chain ALL writes without stopping.\n5. Verify (shell_execute / file_read).\n6. Only THEN write a short summary of what you did.\n\n=== FILE & DIRECTORY RULES ===\n\n- file_write AUTOMATICALLY creates any missing parent directories. Never call shell_execute with `mkdir`, `New-Item -ItemType Directory`, `md`, or `os.makedirs` to set up a folder before writing — just file_write the target path directly.\n- All relative paths resolve to the current chat workspace folder. Always pass relative paths (e.g. `client/public/index.html`) — do not hard-code absolute drive paths.\n- shell_execute runs inside the workspace folder by default. Do not `cd` into a parent or sibling folder; prefer relative commands.\n- On Windows, the shell is PowerShell. Quote arguments with spaces. Use forward slashes in paths inside commands. Avoid `mkdir -p` (PowerShell mkdir does not accept -p) — again, just use file_write.\n\n=== GENERAL ===\n\n- Always read a file before modifying it.\n- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool.\n- If a command fails, diagnose and retry with corrected arguments — do not introduce yourself again.\n- After 2-3 failures of the same approach, switch strategy (e.g. file_write instead of shell mkdir) instead of repeating.\n- Be concise in text. All real work happens in tool calls.\n- Respond in the same language the user used in their message.';+ var CODEX_PROMPT = 'You are the Coding Agent, an autonomous coding agent inside LU. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. Empty assistant messages are a FAILURE.\n\n2. DO NOT stop after the first tool. Real coding tasks take 3-15 tool calls. Stopping after one file_read or one shell_execute without producing the requested artefact = FAILURE. "I have called one tool, that is enough" is NOT a valid stop reason.\n\n3. NEVER say "Now I will create X" / "Next I\'ll write Y" as plain prose and then stop. Do the next step RIGHT NOW as a concrete tool call.\n\n4. When the task has N steps, execute ALL N steps in one session. Put independent tool calls into ONE response (several reads or writes at once).\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk, OR (b) you are stuck and genuinely need user input.\n\n=== WORKFLOW ===\n\n1. Understand the task.\n2. Only if the user asked for a plan: call todo_write with the whole plan, and send each update together with your next real tool call, never on its own. Every step costs the user money.\n3. Explore (file_list, file_read, file_search) when you need to know existing layout.\n4. Implement (file_write) — chain ALL writes without stopping.\n5. Verify (shell_execute / file_read).\n6. Only THEN write a short summary of what you did.\n\n=== FILE & DIRECTORY RULES ===\n\n- file_write AUTOMATICALLY creates any missing parent directories. Never call shell_execute with `mkdir`, `New-Item -ItemType Directory`, `md`, or `os.makedirs` to set up a folder before writing — just file_write the target path directly.\n- All relative paths resolve to the current chat workspace folder. Always pass relative paths (e.g. `client/public/index.html`) — do not hard-code absolute drive paths.\n- shell_execute runs inside the workspace folder by default. Do not `cd` into a parent or sibling folder; prefer relative commands.\n- On Windows, the shell is PowerShell. Quote arguments with spaces. Use forward slashes in paths inside commands. Avoid `mkdir -p` (PowerShell mkdir does not accept -p) — again, just use file_write.\n\n=== GENERAL ===\n\n- Always read a file before modifying it.\n- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool.\n- If a command fails, diagnose and retry with corrected arguments — do not introduce yourself again.\n- After 2-3 failures of the same approach, switch strategy (e.g. file_write instead of shell mkdir) instead of repeating.\n- Be concise in text. All real work happens in tool calls.\n- Respond in the same language the user used in their message.';// ── Thinking-compatible prefixes (parity with desktop) ──// Keep in sync with THINKING_COMPATIBLE in src/lib/model-compatibility.ts.diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex ae7a0631..6499e7a7 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -160,8 +160,8 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [{name: 'todo_write',description:- 'Write and update the plan for a multi-step task. The list is shown to the user live, so it is how they follow a long run. '- + 'USE FIRST when a task needs more than about three tool calls, then send it again after each step. '+ 'Write and update the plan the user asked for. The list is shown to the user live. '+ + 'NEVER send it as a step of its own: send an update together with your next real tool call. '+ 'Send the COMPLETE list every time: it replaces the previous one, it does not merge.',inputSchema: {type: 'object',diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 7d0d4783..4f0999fd 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -41,6 +41,7 @@ import {import type { ResolvedContextWindow } from '../../lib/context-source'import { contextWindowKey, storedWindow, capIsDerivable } from '../../lib/context-source'import { useSettingsStore } from '../../stores/settingsStore'+import { log } from '../../lib/logger'// Transport routing lives in the `useLocalProxy` getter (below) plus the shared// host helpers in backend.ts. A direct webview fetch only works for hosts the@@ -989,6 +990,9 @@ export class OpenAIProvider implements ProviderClient {// terminal chunk as a clean cut, so the chat layer explains it the same// way instead of throwing a raw error at the user.if (isStreamIdleTimeout(err)) {+ // The only trace a silent cut leaves: the chat shows "disconnected",+ // the support log says which watchdog and after how long.+ log.warn('provider.stream_idle_timeout', { provider: this.config.id, idleMs: err.idleMs })yield doneChunk('disconnect')return}diff --git a/src/components/chat/ExplorerPanel.tsx b/src/components/chat/ExplorerPanel.tsxindex 0af1b954..a6034cd6 100644--- a/src/components/chat/ExplorerPanel.tsx+++ b/src/components/chat/ExplorerPanel.tsx@@ -296,7 +296,7 @@ export function ExplorerPanel({ onApprovePlan }: Props) {title={planWaiting ? 'A plan is waiting for your approval' : 'Show the plan'}data-testid="explorer-plan-waiting"className={`mt-1 p-1 rounded transition-colors hover:bg-gray-100 dark:hover:bg-white/5 ${- planWaiting ? 'text-purple-400' : 'text-blue-400'+ planWaiting ? 'text-lu-accent' : 'text-gray-400 dark:text-gray-500'}`}><ListTodo size={12} />@@ -320,7 +320,7 @@ export function ExplorerPanel({ onApprovePlan }: Props) {onPointerDown={startDrag}title="Drag to resize"data-testid="explorer-resize-handle"- className="absolute left-0 top-0 h-full w-1 -ml-0.5 z-10 cursor-col-resize hover:bg-blue-500/40 active:bg-blue-500/60 transition-colors"+ className="absolute left-0 top-0 h-full w-1 -ml-0.5 z-10 cursor-col-resize hover:bg-white/10 active:bg-white/20 transition-colors"/><div className="flex items-center gap-1 p-1.5 border-b border-gray-200 dark:border-white/[0.04]">@@ -429,7 +429,7 @@ export function ExplorerPanel({ onApprovePlan }: Props) {style={{ paddingLeft: `${row.depth * 8 + 4}px` }}className={`flex items-center gap-1 w-full pr-1 py-[2px] text-[0.5rem] rounded transition-colors text-left ${isSelected- ? 'bg-blue-500/10 text-gray-800 dark:text-gray-100'+ ? 'bg-gray-200/70 dark:bg-white/[0.07] text-gray-800 dark:text-gray-100': row.node.isDirectory? 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5': 'text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-white/5'diff --git a/src/components/chat/PlanApprovalBar.tsx b/src/components/chat/PlanApprovalBar.tsxindex 92ca8841..aa0be461 100644--- a/src/components/chat/PlanApprovalBar.tsx+++ b/src/components/chat/PlanApprovalBar.tsx@@ -56,9 +56,9 @@ export function PlanApprovalBar({ onApprove }: { onApprove: (instruction: stringreturn (<div className="w-full p-1.5" data-testid="plan-approval-panel">- <div className="w-full rounded-md border border-purple-500/25 bg-purple-500/[0.04]">+ <div className="w-full rounded-md border border-gray-200 dark:border-white/[0.06] bg-white dark:bg-white/[0.02]"><div className="flex items-center gap-1.5 px-2 py-1">- <ClipboardCheck size={9} className="text-purple-400 shrink-0" />+ <ClipboardCheck size={9} className="text-lu-accent shrink-0" /><span className="text-[0.55rem] uppercase tracking-wider text-gray-500 shrink-0">plan ready</span><buttononClick={() => setExpanded(!expanded)}@@ -70,7 +70,7 @@ export function PlanApprovalBar({ onApprove }: { onApprove: (instruction: string<buttononClick={approve}title={`Runs the plan in ${CODEX_MODE_SHORT[target]} mode. ${CODEX_MODE_DESCRIPTIONS[target]}`}- className="shrink-0 px-2 py-0.5 rounded text-[0.55rem] font-medium bg-purple-500/15 text-purple-600 dark:text-purple-300 hover:bg-purple-500/25 transition-colors"+ className="shrink-0 px-2 py-0.5 rounded text-[0.55rem] font-medium bg-lu-accent/15 text-lu-accent hover:bg-lu-accent/25 transition-colors">{`Approve and run (${CODEX_MODE_SHORT[target]})`}</button>diff --git a/src/components/chat/PlanBar.tsx b/src/components/chat/PlanBar.tsxindex d356b691..1bfecc36 100644--- a/src/components/chat/PlanBar.tsx+++ b/src/components/chat/PlanBar.tsx@@ -118,7 +118,10 @@ export function PlanBar({ variant = 'header' }: Props) {className={panel ? 'w-full p-1.5' : 'mx-auto w-full max-w-[var(--lu-measure)] px-3 pt-1'}data-testid={panel ? 'plan-panel' : 'plan-header'}>- <div className="w-full rounded-md border border-blue-500/20 bg-blue-500/[0.04]">+ {/* Neutral on purpose (David 30.09.2026: "dunkel LU design, nicht+ abheben"). The plan is a footer of the column, it takes the column's+ own surface and line colour instead of a blue box of its own. */}+ <div className="w-full rounded-md border border-gray-200 dark:border-white/[0.06] bg-white dark:bg-white/[0.02]"><div className="flex items-center gap-1.5 px-2 py-1"><buttononClick={() => setExpanded((v) => !v)}@@ -126,11 +129,11 @@ export function PlanBar({ variant = 'header' }: Props) {className="flex items-center gap-1.5 min-w-0 flex-1 text-left">{expanded ? (- <ChevronDown size={9} className="text-blue-400 shrink-0" />+ <ChevronDown size={9} className="text-gray-400 dark:text-gray-500 shrink-0" />) : (- <ChevronRight size={9} className="text-blue-400 shrink-0" />+ <ChevronRight size={9} className="text-gray-400 dark:text-gray-500 shrink-0" />)}- <ListTodo size={9} className="text-blue-400 shrink-0" />+ <ListTodo size={9} className="text-gray-400 dark:text-gray-500 shrink-0" /><span className="text-[0.55rem] uppercase tracking-wider text-gray-500 shrink-0">plan {done}/{todos.length}</span>@@ -160,7 +163,7 @@ export function PlanBar({ variant = 'header' }: Props) {{todos.map((t, i) => (<li key={`${i}-${t.content}`} className="flex items-start gap-1.5">{t.status === 'completed' ? (- <CheckCircle2 size={10} className="text-emerald-400 shrink-0 mt-[1px]" />+ <CheckCircle2 size={10} className="text-gray-400 dark:text-gray-500 shrink-0 mt-[1px]" />) : t.status === 'in_progress' ? (// Ein Kreisel, der sich dreht, behauptet Arbeit. Nach dem Ende// des Laufs ist das eine Behauptung ueber nichts: gemessen@@ -171,10 +174,10 @@ export function PlanBar({ variant = 'header' }: Props) {// siehe `lib/hinweis.ts`.)<Loader2size={10}- className={`shrink-0 mt-[1px] ${runActive ? 'text-blue-400 animate-spin' : HINWEIS_TEXT.ruhig}`}+ className={`shrink-0 mt-[1px] ${runActive ? 'text-gray-600 dark:text-gray-300 animate-spin' : HINWEIS_TEXT.ruhig}`}/>) : (- <Circle size={10} className="text-gray-600 shrink-0 mt-[1px]" />+ <Circle size={10} className="text-gray-300 dark:text-gray-700 shrink-0 mt-[1px]" />)}<spanclassName={`t-micro leading-snug ${diff --git a/src/components/chat/__tests__/plan-sagt-wann-der-lauf-endete.test.ts b/src/components/chat/__tests__/plan-sagt-wann-der-lauf-endete.test.tsindex 524dde17..b27e879c 100644--- a/src/components/chat/__tests__/plan-sagt-wann-der-lauf-endete.test.ts+++ b/src/components/chat/__tests__/plan-sagt-wann-der-lauf-endete.test.ts@@ -85,7 +85,7 @@ describe('die Leiste fragt beide Laufquellen, nicht nur eine', () => {// nichts mehr laeuft, ist kein halber Fehler, sondern ruhig. Die Aussage// des Tests ist dieselbe geblieben und haengt jetzt an der Bewegung// statt an der Farbe: es dreht sich nur, was wirklich laeuft.- expect(src).toMatch(/runActive \? 'text-blue-400 animate-spin' : HINWEIS_TEXT\.ruhig/)+ expect(src).toMatch(/runActive \? 'text-gray-600 dark:text-gray-300 animate-spin' : HINWEIS_TEXT\.ruhig/)// Und es gibt genau EINE Drehung in der Datei, sonst koennte daneben ein// zweiter Kreisel stehen, den kein Lauf mehr anhaelt.expect(src.match(/animate-spin/g) ?? []).toHaveLength(1)diff --git a/src/hooks/__tests__/codex-create-tool-gate.test.ts b/src/hooks/__tests__/codex-create-tool-gate.test.tsindex 20e4ae51..cbf36ecf 100644--- a/src/hooks/__tests__/codex-create-tool-gate.test.ts+++ b/src/hooks/__tests__/codex-create-tool-gate.test.ts@@ -176,7 +176,7 @@ describe('the prompt and the tool list answer the same question', () => {describe('the wiring in useCodex', () => {it('the gate runs on the routed list, so it covers all three branches', () => {- expect(src).toMatch(/const relevantDefs = gateCreateTools\(routedDefs, lastUserMsg, createGateOpened\)/)+ expect(src).toMatch(/const relevantDefs = gatePlanTool\(\s*gateCreateTools\(routedDefs, lastUserMsg, createGateOpened\),/)})it('the hermes fallback is gated too, it carries the weakest models', () => {diff --git a/src/hooks/codex/__tests__/der-plan-haengt-nicht-bei-schritt-2.test.ts b/src/hooks/codex/__tests__/der-plan-haengt-nicht-bei-schritt-2.test.tsindex 54d56f0c..f22acedc 100644--- a/src/hooks/codex/__tests__/der-plan-haengt-nicht-bei-schritt-2.test.ts+++ b/src/hooks/codex/__tests__/der-plan-haengt-nicht-bei-schritt-2.test.ts@@ -6,16 +6,15 @@* ── WAS HIER ECHT LAEUFT ───────────────────────────────────────────────────* Der wirkliche Ollama Transport (`streamOllamaChatWithTools`) gegen einen* NDJSON Strom, wie Ollama ihn schickt; der wirkliche `todoStore` ueber- * `writeTodos`; die wirkliche `PlanStaleness` und der wirkliche- * `AgentLoopGuard`. Nur `localFetchStream` ist ersetzt, also genau das Kabel.+ * `writeTodos` und der wirkliche `AgentLoopGuard`. Nur `localFetchStream` ist ersetzt, also genau das Kabel.* Das ist die "Schrittmaschine" des Plans: einen Schritt weiterzaehlen kann in* LU ausschliesslich das Modell ueber `todo_write`, der Speicher ersetzt die* Liste jedes Mal ganz.** ── WAS DER LAUF ZEIGT ─────────────────────────────────────────────────────* Ein Plan aus zwei Schritten kommt ueber Schritt 2 hinaus, ohne dass eine der- * Bremsen dazwischenfaehrt: die Schleifenwache haelt nicht an, der- * Frische Waechter mahnt nicht, und die Luecke schliesst sich am Ende. Der+ * Bremsen dazwischenfaehrt: die Schleifenwache haelt nicht an, und die+ * Luecke schliesst sich am Ende. Der* Haenger sitzt also NICHT in dieser Kette.** ── WO ER SITZEN KANN, UND WAS DAFUER FEHLTE ───────────────────────────────@@ -29,7 +28,7 @@* Schleife nicht von einem Modell zu unterscheiden, das fertig ist: keine* Werkzeugaufrufe, also `break-no-toolcalls`, Lauf zu Ende, kein Wort. Der* Plan steht danach genau da, wo er stand, auf seinem offenen Schritt. Und- * der naechste Zug bekommt ueber den Anker und den Frische Waechter die+ * der naechste Zug bekommt ueber den Anker die* Aufforderung, die VOLLSTAENDIGE Liste noch einmal zu schicken; ein Modell,* dem der Verlauf weggeschnitten wurde, schickt sie dann von vorn. Das ist* beides, was der Melder beschreibt.@@ -49,7 +48,6 @@ import { streamOllamaChatWithTools } from '../../../lib/ollama-stream-tools'import { localFetchStream } from '../../../api/backend'import { useTodoStore, writeTodos, type TodoItem } from '../../../stores/todoStore'import { openPlanGap } from '../../../lib/plan-reconcile'-import { PlanStaleness } from '../../../lib/plan-staleness'import { AgentLoopGuard } from '../../../lib/agent-loop-guard'import { codexCutoffNote } from '../turn-cutoff'import type { ToolCall, ToolDefinition } from '../../../api/providers/types'@@ -130,7 +128,6 @@ beforeEach(() => {describe('ein Plan aus zwei Schritten kommt ueber Schritt 2 hinaus', () => {it('zaehlt 0 zu 2, dann 1 zu 2, dann zu', async () => {- const stale = new PlanStaleness()const guard = new AgentLoopGuard()// Zug 1: das Modell schreibt den Plan.@@ -141,13 +138,11 @@ describe('ein Plan aus zwei Schritten kommt ueber Schritt 2 hinaus', () => {done: 0, total: 2, next: 'read the parser',})expect(guard.recordBatch(guardBatch(t1.toolCalls)).action).toBe('ok')- expect(stale.recordBatch(namesOf(t1.toolCalls), true)).toBe(false)// Zug 2: echte Arbeit, kein todo_write. Eine stille Runde ist noch keine.const t2 = await turn(callLine('file_read', { path: 'src/parser.ts' }), doneLine('stop'))expect(namesOf(t2.toolCalls)).toEqual(['file_read'])expect(guard.recordBatch(guardBatch(t2.toolCalls)).action).toBe('ok')- expect(stale.recordBatch(namesOf(t2.toolCalls), true)).toBe(false)// Zug 3: Schritt 1 fertig, Schritt 2 ist dran. DAS ist der Uebergang, an// dem der Melder haengenbleibt.diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex e8df8068..fdb05933 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -38,6 +38,7 @@ import { resolveToolCallingStrategy } from '../lib/agent-strategy'import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from '../lib/ollama-errors'import { stripVisionFeedbackMessages, reportMultimodalRefusal } from '../lib/vision-heal'import { log } from '../lib/logger'+import { gatePlanTool, planToolAllowed } from '../lib/plan-gate'import { buildHermesToolPrompt, buildHermesToolResult, buildHermesToolCall, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, canonicalToolName } from '../lib/loose-tool-parse'import { mediaCallSucceeded } from '../lib/media-result'@@ -95,7 +96,6 @@ import { isOutsideWorkspaceRefusal, OUTSIDE_WORKSPACE_NOTICE } from '../lib/workimport { useChatNoticeStore } from '../stores/chatNoticeStore'import { settleThinking } from '../lib/thinking-stripper'import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/plan-reconcile'-import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'import { planResumeAnchor } from '../lib/plan-resume'import { reasoningOnlyRound, REASONING_CONTINUE_BUDGET, REASONING_CONTINUE_STEER } from '../lib/reasoning-round'import { findUnbackedLinks, unbackedLinksSteer } from '../lib/unbacked-links'@@ -975,13 +975,21 @@ export function useAgentChat() {//// Nur im hermes_xml-Fall berechnet: sonst zahlte jeder native Zug eine// Einbettungsabfrage fuer eine Liste, die er nie benutzt.+ // Planning is opt-in (lib/plan-gate.ts). Decided once per run: the tool+ // list of a run must not change mid-way, and a plan the model cannot open+ // cannot become an open plan inside this run either.+ const planAllowed = planToolAllowed({+ mode: null,+ userText: userContent,+ todos: convId ? useTodoStore.getState().getTodos(convId) : [],+ })const hermesToolDefs = strategy === 'hermes_xml'- ? await selectRelevantToolsAsync(+ ? gatePlanTool(await selectRelevantToolsAsync(userContent,toolRegistry.getAll().filter((t) => toolMatchesCurated(t.name)),permissions,toolSelectionOpts(!!settings.smallModelMode, (texts) => generateEmbeddings(texts)),- )+ ), planAllowed): []// Small-Model Mode (Knob 2): swap the ~3000-char agent prompt for a lean// ~750-char one on the native path. Der Hermes-Zweig behaelt seine eigene@@ -1000,8 +1008,10 @@ export function useAgentChat() {// The roster the prompt shows comes from the same filtered registry the// request draws on, so the prompt can never advertise a tool a permission// blocked or omit one that was added since (audit 2026-08-05).- const offeredTools = toolRegistry.getAvailableTools(permissions)- .filter((t) => toolMatchesCurated(t.name))+ const offeredTools = gatePlanTool(+ toolRegistry.getAvailableTools(permissions).filter((t) => toolMatchesCurated(t.name)),+ planAllowed,+ )let agentSystemPrompt = strategy === 'hermes_xml'? buildHermesToolPrompt(hermesToolDefs) + (systemPrompt ? `\n\n${systemPrompt}` : ''): opts?.chatToolsMode@@ -1278,9 +1288,6 @@ export function useAgentChat() {let planReconcilesRemaining = PLAN_RECONCILE_BUDGET// G17: budget for continuing past reasoning-only rounds mid-run.let reasoningContinuesRemaining = REASONING_CONTINUE_BUDGET- // PlanBar lag: batches of real work without a todo_write while the plan- // has open items earn one bounded mid-run steer to report progress.- const planStaleness = new PlanStaleness()const executedCallKeys = new Set<string>()const callKey = (tc: { function: { name: string; arguments: unknown } }) =>tc.function.name + '|' + JSON.stringify(tc.function.arguments ?? {})@@ -1545,12 +1552,12 @@ export function useAgentChat() {// Als sie hier standen, gab es sie nur an DIESER Stelle — der// hermes_xml-Zweig oben nahm stattdessen den ganzen Katalog, und// niemandem fiel es auf, weil nichts brach.- const relevantDefs = await selectRelevantToolsAsync(+ const relevantDefs = gatePlanTool(await selectRelevantToolsAsync(lastUserMsg,toolRegistry.getAll().filter((t) => toolMatchesCurated(t.name)),permissions,toolSelectionOpts(!!settings.smallModelMode, (texts) => generateEmbeddings(texts)),- )+ ), planAllowed)const tools: ToolDefinition[] = relevantDefs.map(t => ({type: 'function' as const,function: { name: t.name, description: t.description, parameters: t.inputSchema },@@ -2721,14 +2728,6 @@ export function useAgentChat() {if (failVerdict.action === 'steer') {agentMessages.push({ role: 'user', content: failVerdict.message })}- // PlanBar lag: the bar renders only what the model reports, so after- // enough batches of silent progress ask it to bring the list current.- {- const staleGap = openPlanGap(useTodoStore.getState().getTodos(convId!))- if (planStaleness.recordBatch(batch.map((e) => e.ac.toolName), staleGap !== null) && staleGap) {- agentMessages.push({ role: 'user', content: planStalenessSteer(staleGap) })- }- }// Vision feedback (David 2026-06-03): after image_generate, hand the// generated picture to a vision-capable model so it SEES the result and@@ -3237,10 +3236,9 @@ ${roster}That list is what LU can do. Your request carries the subset that fits the task at hand, and on a local model it is a subset. Only ever call a tool that is in your tool list. Calling one that is not there fails as an unknown tool and wastes a step. If you need one that is missing, name it in your answer and carry on with what you have.-PLAN FIRST (todo_write):-- Any task that needs more than about three tool calls starts with todo_write: write the whole plan before the first step. The user sees that list live, it is how they know what you are doing.-- After each step, call todo_write again with the COMPLETE list, flipping the finished item to completed and the next one to in_progress. Exactly one item is in_progress at a time.-- Never mark an item completed before the work actually succeeded. Skip the plan entirely for a single-step request.+WORK IN BATCHES (every step resends the whole conversation and costs the user money):+- Put independent tool calls into ONE response: several reads, searches or edits at once.+- Never spend a step on bookkeeping alone. If a todo_write tool is offered, send the updated list together with your next real tool call.AUTONOMY CONTRACT (read carefully, this is the most important rule):- When the user asks you to BUILD, CREATE, MAKE, or WRITE something (a file, a website, a script, a folder structure), you MUST execute it via tools, typically file_write.@@ -3290,11 +3288,11 @@ ${platformPromptLine()}You always have: ${alwaysThere}. Your request carries the other tools that fit the task. Read their names there, do not guess.Rules:-- For a task of more than about three steps, call todo_write FIRST with the whole plan, then again after each step with the complete list (one item in_progress, finished ones completed). The user watches that list.+- Put independent tool calls into one response (several reads or edits at once). Every step costs the user money.- To build/create/write something, CALL the tool (usually file_write), never paste a code block and say "save this".- To change an existing file use file_edit with a unique old_string, not file_write.- PATHS: use relative paths (e.g. \`package.json\`, \`.\`). Never start with \`/\` or a drive letter, it escapes your workspace and fails.-- Emit the tool call as your FIRST output, no "Okay, let me…" preamble. Valid JSON, one at a time. Never guess file contents, file_read first.+- Emit the tool call as your FIRST output, no "Okay, let me…" preamble. Valid JSON. Never guess file contents, file_read first.- After each tool result, if a step remains, immediately call the next tool. Do not narrate "I will now…" and then stop.- For images/video call image_generate / video_generate as real tool calls.- When everything is done, reply with one short sentence in the user's language.`diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 968326d7..afe98db0 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -63,7 +63,6 @@ import { explainError as explainToolError } from '../api/agents/error-hints'import { budgetFromSettings } from '../api/agents/budget'import { settleThinking } from '../lib/thinking-stripper'import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/plan-reconcile'-import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'import { planResumeAnchor } from '../lib/plan-resume'import { useTodoStore } from '../stores/todoStore'import { httpStatusOf } from '../lib/http-status'@@ -108,13 +107,22 @@ import { codexCutoffNote } from './codex/turn-cutoff'import { codexToolDiff, codexEventKind } from './codex/tool-result-view'import { capHiddenToolHistory } from './codex/hidden-history'import { withHouseConduct } from '../lib/system-prompt'--// 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.-// Release builds must not write to the user's filesystem; if you need-// traces, gate on a build-time env flag or a settings toggle.-function diagLog(_tag: string, _data: unknown): void {- /* release: no-op */+import { gatePlanTool, planToolAllowed } from '../lib/plan-gate'++// Why a run ended, or was pushed on, belongs in the support log. This used to+// be a no-op, and the customer case of 30.09.2026 (936k credits, "never+// finished one task") had nothing to read on the customer's machine: which+// guard ended each run was unknowable. The run-shaping tags go out as warn,+// which logger.ts mirrors into the rolling log file; the per-step trace stays+// on debug (console only). No payload carries message text, only counters,+// reasons and lengths.+const RUN_EVENT_TAGS: ReadonlySet<string> = new Set([+ 'break-no-toolcalls', 'budget-halt', 'context-overflow-retry', 'continue-nudge',+ 'loop-guard-halt', 'loop-guard-steer', 'outer-catch', 'plan-reconcile-steer', 'turn-cut-off',+])+function diagLog(tag: string, data: Record<string, unknown>): void {+ if (RUN_EVENT_TAGS.has(tag)) log.warn(`codex.${tag}`, data)+ else log.debug(`codex.${tag}`, data)}// Review-mode system prompt (B13). In review mode this REPLACES the base@@ -143,13 +151,15 @@ AUTONOMY CONTRACT (read carefully):Workflow per task:1. Understand the task (optional brief sentence)-2. If it needs more than about three tool calls, call todo_write with the whole plan BEFORE step 3. The user sees that list live and it is how they follow a long run.-3. Explore the codebase, file_list / file_read / file_search-4. Implement ALL required changes, file_edit to change existing files, file_write for new ones; as many calls as needed in one go-5. Verify, shell_execute to run tests, lint, or build-6. Only THEN write a short summary of what you did+2. Explore the codebase, file_list / file_read / file_search+3. Implement ALL required changes, file_edit to change existing files, file_write for new ones+4. Verify, shell_execute to run tests, lint, or build+5. Only THEN write a short summary of what you did-Keeping the plan current: after each step call todo_write again with the COMPLETE list, the finished item as completed and the next one as in_progress. Exactly one item is in_progress at a time, and nothing is completed before it actually succeeded. A plan that stops updating is worse than no plan.+Work in batches. Every step resends the whole conversation, so each round trip costs the user real money:+- Put independent tool calls into ONE response: read all the files you need at once, run several searches at once, make several edits at once.+- Never spend a step on bookkeeping alone. If a todo_write tool is offered, send the updated list in the same response as your next real tool call, never on its own.+- Do not re-read a file you already read unless it changed since.Rules:- Always read a file before modifying it@@ -183,11 +193,11 @@ const CODEX_ASSET_LINE = `- Asset generation: when the task needs an image or aconst CODEX_SYSTEM_PROMPT_LEAN = `You are a coding agent in LU. Use tools to do the work, never guess file contents.Rules:-- More than about three steps? Call todo_write first with the plan, and again after each step with the complete list. The user watches it.+- Put independent tool calls into one response (several reads or edits at once). Every step costs the user money.- Read a file before you edit it.- To change an existing file use file_edit (replace a unique old_string with new_string), not file_write. Use file_write only to create a new file.- PATHS: use relative paths (e.g. \`package.json\`, \`.\`). Never start with \`/\` or a drive letter, it escapes the workspace and fails.-- Emit the tool call as your FIRST output, no "Okay, let me…" preamble. One step at a time, as valid JSON.+- Emit the tool call as your FIRST output, no "Okay, let me…" preamble. Valid JSON.- After each tool result, if more steps remain, immediately call the next tool. Do not narrate "I will now…" and then stop.- When the task is done and verified, reply with one short sentence. Never end with only raw JSON or a bare code block.`@@ -817,7 +827,7 @@ export function useCodex() {// started and the next standalone tool call inherits its jail root.if (!conv) { endAgentRun(run); activeCodexRuns.delete(convId); return }- void diagLog('pre-loop', {+ diagLog('pre-loop', {activeModel, providerId, strategy, workDir,systemPromptLen: systemPrompt.length,systemPromptHead: systemPrompt.slice(0, 500),@@ -887,7 +897,7 @@ export function useCodex() {if (convId) {const resume = planResumeAnchor(useTodoStore.getState().getTodos(convId))if (resume) {- void diagLog('plan-resume-anchor', { done: resume.gap.done, total: resume.gap.total })+ diagLog('plan-resume-anchor', { done: resume.gap.done, total: resume.gap.total })messages.push({ role: 'user', content: resume.text })}}@@ -1135,9 +1145,6 @@ export function useCodex() {// from the nudges above, because a nudge fires on an EMPTY turn while// this fires on a turn that claims to be done.let planReconcilesRemaining = PLAN_RECONCILE_BUDGET- // PlanBar lag: batches of real work without a todo_write while the plan- // has open items earn one bounded mid-run steer to report progress.- const planStaleness = new PlanStaleness()// Raised from 20 → 50 (v2.3.7): large refactors across 10+ files// legitimately need >20 tool calls. Budget still caps via// agentMaxToolCalls/agentMaxIterations.@@ -1166,6 +1173,7 @@ export function useCodex() {budget.addIteration()const bx = budget.exceeded()if (bx.kind !== 'none') {+ diagLog('budget-halt', { iter: i, kind: bx.kind })useChatStore.getState().updateMessageContent(convId!,assistantMsg.id,@@ -1409,7 +1417,16 @@ export function useCodex() {: !isLocalModelByName(activeModel)? codexTools: selectRelevantTools(lastUserMsg, codexTools, permissions)- const relevantDefs = gateCreateTools(routedDefs, lastUserMsg, createGateOpened)+ // Planning is opt-in (lib/plan-gate.ts): without Plan mode, a plan+ // request or an open plan, todo_write is not offered at all.+ const relevantDefs = gatePlanTool(+ gateCreateTools(routedDefs, lastUserMsg, createGateOpened),+ planToolAllowed({+ mode: codexMode,+ userText: lastUserMsg,+ todos: convId ? useTodoStore.getState().getTodos(convId) : [],+ }),+ )const tools: ToolDefinition[] = relevantDefs.map(t => ({type: 'function' as const,function: { name: t.name, description: t.description, parameters: t.inputSchema },@@ -1422,7 +1439,7 @@ export function useCodex() {if (convId) {useSendSizeStore.getState().reportTools(convId, stepToolsEstimate)}- void diagLog('iter-start', {+ diagLog('iter-start', {iter: i,activeModel, modelToUse, strategy, providerId,allToolsCount: toolRegistry.getAll().length,@@ -1452,7 +1469,7 @@ export function useCodex() {// count has landed yet, so a real value is never downgraded.seedEstimatedUsage(convId!, assistantMsg.id, sendMessages, tools)try {- void diagLog('streamWithTools-enter', { iter: i, messagesLen: sendMessages.length, toolsCount: tools.length, thinking: chatOptions.thinking })+ diagLog('streamWithTools-enter', { iter: i, messagesLen: sendMessages.length, toolsCount: tools.length, thinking: chatOptions.thinking })turn = await streamWithTools(modelToUse, sendMessages, tools,{ temperature: 0.1, thinking: chatOptions.thinking, maxTokens: chatOptions.maxTokens, contextWindow: numCtx, signal: abort.signal },@@ -1464,9 +1481,9 @@ export function useCodex() {}},)- void diagLog('streamWithTools-ok', { iter: i, contentLen: turn.content?.length || 0, toolCallsCount: turn.toolCalls?.length || 0 })+ diagLog('streamWithTools-ok', { iter: i, contentLen: turn.content?.length || 0, toolCallsCount: turn.toolCalls?.length || 0 })} catch (thinkErr) {- void diagLog('streamWithTools-catch', {+ diagLog('streamWithTools-catch', {iter: i,status: httpStatusOf(thinkErr),messageHead: errorText(thinkErr).slice(0, 400),@@ -1484,7 +1501,7 @@ export function useCodex() {liveContent,() => {},)- void diagLog('streamWithTools-retry-ok', { iter: i, contentLen: turn.content?.length || 0, toolCallsCount: turn.toolCalls?.length || 0 })+ diagLog('streamWithTools-retry-ok', { iter: i, contentLen: turn.content?.length || 0, toolCallsCount: turn.toolCalls?.length || 0 })} else {throw thinkErr}@@ -1494,7 +1511,7 @@ export function useCodex() {turnContent = turn.content || ''turnFinishReason = turn.doneReasonreportTurnUsage(convId!, assistantMsg.id, turn)- void diagLog('streamWithTools-return', {+ diagLog('streamWithTools-return', {iter: i,toolCallsCount: toolCalls.length,toolCalls: toolCalls.map(tc => ({ name: tc.function?.name, args: tc.function?.arguments })),@@ -1701,7 +1718,7 @@ export function useCodex() {overflowRetries++settleLivePaint()learnSendWindow(modelToUse, numCtx, next)- void diagLog('context-overflow-retry', { iter: i, sent, next, window: overflow.window, promptTokens: overflow.promptTokens })+ diagLog('context-overflow-retry', { iter: i, sent, next, window: overflow.window, promptTokens: overflow.promptTokens })addBlock({id: uuid(),phase: 'reflection',@@ -1878,7 +1895,7 @@ export function useCodex() {const { nudgeWorthy } = codexStallVerdict(turnContent, fullContent)if (nudgeWorthy && continueNudgesRemaining > 0) {continueNudgesRemaining--- void diagLog('continue-nudge', { iter: i, remaining: continueNudgesRemaining, turnContentLen: turnContent.length })+ diagLog('continue-nudge', { iter: i, remaining: continueNudgesRemaining, turnContentLen: turnContent.length })messages.push({role: 'user',// A read-only command's deliverable IS the text. Demanding "the@@ -1902,7 +1919,7 @@ export function useCodex() {const gap = openPlanGap(useTodoStore.getState().getTodos(convId))if (gap) {planReconcilesRemaining--- void diagLog('plan-reconcile-steer', { iter: i, done: gap.done, total: gap.total, remaining: planReconcilesRemaining })+ diagLog('plan-reconcile-steer', { iter: i, done: gap.done, total: gap.total, remaining: planReconcilesRemaining })messages.push({ role: 'user', content: planReconcileSteer(gap) })continue}@@ -1920,7 +1937,7 @@ export function useCodex() {convId ? openPlanGap(useTodoStore.getState().getTodos(convId)) : null,)if (cutoff && convId) {- void diagLog('turn-cut-off', { iter: i, reason: turnFinishReason })+ diagLog('turn-cut-off', { iter: i, reason: turnFinishReason })useChatStore.getState().updateMessageContent(convId,assistantMsg.id,@@ -1933,7 +1950,7 @@ export function useCodex() {timestamp: Date.now(),})}- void diagLog('break-no-toolcalls', { iter: i, turnContentLen: turnContent.length, fullContentLen: fullContent.length, finishReason: turnFinishReason })+ diagLog('break-no-toolcalls', { iter: i, turnContentLen: turnContent.length, fullContentLen: fullContent.length, finishReason: turnFinishReason })break}@@ -1964,7 +1981,7 @@ export function useCodex() {{ trimmedReadKeys },)if (batchVerdict.action === 'halt') {- void diagLog('loop-guard-halt', { iter: i, reason: batchVerdict.reason })+ diagLog('loop-guard-halt', { iter: i, reason: batchVerdict.reason })const msg = `\n\n_(halted: ${batchVerdict.reason}. The model is looping. Try a stronger model for multi-step code tasks, or rephrase the instruction.)_`useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)// A halt has to be visible in the thread itself, not only as a@@ -1986,7 +2003,7 @@ export function useCodex() {if (batchVerdict.action === 'steer') {// Let this batch still run (the in-turn cache serves it instantly),// but put the anti-repeat instruction in front of the NEXT turn.- void diagLog('loop-guard-steer', { iter: i })+ diagLog('loop-guard-steer', { iter: i })pendingSteer = batchVerdict.messageaddBlock({id: uuid(),@@ -2228,7 +2245,7 @@ export function useCodex() {abortSignal: abort.signal,})- void diagLog('executeParallel-done', {+ diagLog('executeParallel-done', {iter: i,results: results.map(r => ({ tool: r.toolName, status: r.status, error: r.error?.slice(0,200), hint: r.errorHint?.slice(0,200), resultHead: r.result?.slice(0,200) })),})@@ -2395,16 +2412,6 @@ export function useCodex() {if (failVerdict.action === 'steer') {messages.push({ role: 'user', content: failVerdict.message })}- // PlanBar lag, parity with the Agent loop: the bar renders only what- // the model reports, so after enough batches of silent progress ask it- // to bring the list current.- if (convId) {- const staleGap = openPlanGap(useTodoStore.getState().getTodos(convId))- if (planStaleness.recordBatch(requests.map((r) => r.toolName), staleGap !== null) && staleGap) {- void diagLog('plan-staleness-steer', { iter: i, done: staleGap.done, total: staleGap.total })- messages.push({ role: 'user', content: planStalenessSteer(staleGap) })- }- }}// The bubble carries the MODEL'S answer or nothing. This used to build@@ -2453,7 +2460,7 @@ export function useCodex() {// undefined for a non-object instead.const errName = asString(prop(err, 'name'))const code = asString(prop(err, 'code'))- void diagLog('outer-catch', {+ diagLog('outer-catch', {name: errName,message: errorText(err).slice(0, 400),status: httpStatusOf(err),diff --git a/src/lib/__tests__/keine-deutschen-saetze-in-der-oberflaeche.test.ts b/src/lib/__tests__/keine-deutschen-saetze-in-der-oberflaeche.test.tsindex 1df7f43b..6ed490cc 100644--- a/src/lib/__tests__/keine-deutschen-saetze-in-der-oberflaeche.test.ts+++ b/src/lib/__tests__/keine-deutschen-saetze-in-der-oberflaeche.test.ts@@ -17,7 +17,7 @@* Ein Ausdruck faellt ueber jede zweite Datei: ueber `'https://...'`, dessen* zwei Schraegstriche wie ein Kommentar aussehen, ueber ein `/[;&|`\n]/`, dessen* Backtick wie eine Schablone aussieht, und ueber jedes "don't" im JSX-Text.- * Der Syntaxbaum kennt den Unterschied, und die vier Ausnahmen unten sind+ * Der Syntaxbaum kennt den Unterschied, und die fuenf Ausnahmen unten sind* dadurch wirklich die einzigen.** Run: npx vitest run src/lib/__tests__/keine-deutschen-saetze-in-der-oberflaeche.test.ts@@ -50,8 +50,8 @@ const DEUTSCHE_WOERTER = [const DEUTSCH = new RegExp(`\\b(${DEUTSCHE_WOERTER.join('|')})\\b`)/**- * Die vier Dateien, in denen Deutsch in einem Literal richtig ist, mit dem- * Grund. Keine davon schreibt dem Kunden etwas hin: drei lesen, was er getippt+ * Die fuenf Dateien, in denen Deutsch in einem Literal richtig ist, mit dem+ * Grund. Keine davon schreibt dem Kunden etwas hin: vier lesen, was er getippt* hat, und eine sagt denselben Satz zweimal.** Jeder Eintrag wird unten dagegen gehalten, dass er ueberhaupt noch einen@@ -62,6 +62,7 @@ const DEUTSCH_MIT_GRUND: Record<string, string> = {'lib/tool-selection.ts': 'Deutsche Suchhinweise, gegen die getippte Saetze gelesen werden.','lib/turn-summary.ts': 'Absichtlich zweisprachig, deutscher und englischer Satz in einer Zeile.','lib/release-notes.ts': 'Ein englischer Blattsatz, der eine getippte deutsche Wendung zitiert.',+ 'lib/plan-gate.ts': 'Deutsche Planbitten, gegen die getippte Saetze gelesen werden.',}/** Jede .ts und .tsx unter den Ordnern, ohne die Testbaeume. */@@ -127,7 +128,7 @@ describe('kein deutscher Satz in einem Zeichenkettenliteral', () => {expect(offen, offen.join('\n')).toEqual([])})- it('und jede der vier Ausnahmen traegt noch das Deutsch, fuer das sie dasteht', () => {+ it('und jede der fuenf Ausnahmen traegt noch das Deutsch, fuer das sie dasteht', () => {// Sonst waechst die Liste der Ausnahmen, waehrend der Grund laengst weg ist.const mitTreffer = new Set(treffer().map((t) => t.datei))for (const datei of Object.keys(DEUTSCH_MIT_GRUND)) {diff --git a/src/lib/__tests__/plan-gate.test.ts b/src/lib/__tests__/plan-gate.test.tsnew file mode 100644index 00000000..6dafff70--- /dev/null+++ b/src/lib/__tests__/plan-gate.test.ts@@ -0,0 +1,73 @@+/**+ * Planning is opt-in (customer case 30.09.2026, see lib/plan-gate.ts).+ *+ * Run: npx vitest run src/lib/__tests__/plan-gate.test.ts+ */+import { describe, it, expect } from 'vitest'+import { gatePlanTool, planToolAllowed, userAskedForPlan, PLAN_TOOL } from '../plan-gate'+import type { TodoItem } from '../../stores/todoStore'++const t = (content: string, status: TodoItem['status']): TodoItem => ({ content, status })++describe('userAskedForPlan', () => {+ it.each([+ 'Make a plan for the login refactor',+ 'write me a step-by-step plan',+ 'give me a todo list and then do it',+ 'plan this before you touch anything',+ 'go step by step please',+ 'Mach mir einen Plan für die Migration',+ 'erst einen Plan, dann umsetzen',+ 'schritt für schritt bitte',+ 'erstelle eine Todo-Liste',+ ])('hears a plan request in %j', (text) => {+ expect(userAskedForPlan(text)).toBe(true)+ })++ it.each([+ 'fix the build steps in ci.yml',+ 'add a plan field to the pricing form',+ 'the pricing plan page is broken',+ 'build me a todo app in React',+ 'Baue mir eine Landingpage',+ 'refactor src/app.ts and run the tests',+ ])('stays quiet on %j', (text) => {+ expect(userAskedForPlan(text)).toBe(false)+ })+})++describe('planToolAllowed', () => {+ it('is off for an ordinary coding task', () => {+ expect(planToolAllowed({ mode: 'ask', userText: 'build me a todo app', todos: [] })).toBe(false)+ })++ it('is on in Plan mode', () => {+ expect(planToolAllowed({ mode: 'plan', userText: 'look at the auth code', todos: [] })).toBe(true)+ })++ it('is on when the user asked for a plan', () => {+ expect(planToolAllowed({ mode: 'bypass', userText: 'make a plan first', todos: [] })).toBe(true)+ })++ it('stays on while an open plan has to be kept current', () => {+ const todos = [t('read', 'completed'), t('edit', 'in_progress')]+ expect(planToolAllowed({ mode: 'ask', userText: 'continue', todos })).toBe(true)+ })++ it('goes off again once the plan is finished', () => {+ const todos = [t('read', 'completed'), t('edit', 'completed')]+ expect(planToolAllowed({ mode: 'ask', userText: 'continue', todos })).toBe(false)+ })+})++describe('gatePlanTool', () => {+ const defs = [{ name: 'file_read' }, { name: PLAN_TOOL }, { name: 'shell_execute' }]++ it('removes todo_write when planning is not allowed', () => {+ expect(gatePlanTool(defs, false).map((d) => d.name)).toEqual(['file_read', 'shell_execute'])+ })++ it('keeps the catalog untouched when it is', () => {+ expect(gatePlanTool(defs, true)).toBe(defs)+ })+})diff --git a/src/lib/__tests__/plan-staleness.test.ts b/src/lib/__tests__/plan-staleness.test.tsdeleted file mode 100644index a8ff0dc7..00000000--- a/src/lib/__tests__/plan-staleness.test.ts+++ /dev/null@@ -1,98 +0,0 @@-/**- * PlanBar lag (measured 2026-08-07): PLAN 8/31 on the bar while the model- * narrated step 17. The bar renders only what the model reports through- * todo_write, so when batches of real work keep landing without one, the loop- * asks the model ONCE (budgeted) to bring its own list current. The app never- * invents plan state.- *- * Run: npx vitest run src/lib/__tests__/plan-staleness.test.ts- */-import { describe, it, expect } from 'vitest'-import { readFileSync } from 'node:fs'-import { fileURLToPath } from 'node:url'-import { dirname, resolve } from 'node:path'--import {- PlanStaleness,- planStalenessSteer,- PLAN_STALE_BATCHES,- PLAN_STALE_STEER_BUDGET,-} from '../plan-staleness'--const here = dirname(fileURLToPath(import.meta.url))-const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')--const work = ['file_write', 'shell_execute']--describe('PlanStaleness', () => {- it('fires after enough silent batches, then re-arms only after another stretch', () => {- const s = new PlanStaleness()- expect(s.recordBatch(work, true)).toBe(false)- expect(s.recordBatch(work, true)).toBe(false)- expect(s.recordBatch(work, true)).toBe(true)- // counter reset: the very next batch is not stale again- expect(s.recordBatch(work, true)).toBe(false)- expect(s.recordBatch(work, true)).toBe(false)- expect(s.recordBatch(work, true)).toBe(true)- // budget of 2 is spent: silence forever after- for (let i = 0; i < 10; i++) expect(s.recordBatch(work, true)).toBe(false)- expect(PLAN_STALE_STEER_BUDGET).toBe(2)- expect(PLAN_STALE_BATCHES).toBe(3)- })-- it('NEGATIVE CONTROL: a todo_write in the batch resets the clock', () => {- const s = new PlanStaleness()- s.recordBatch(work, true)- s.recordBatch(work, true)- expect(s.recordBatch([...work, 'todo_write'], true)).toBe(false)- // the two silent batches before the update no longer count- expect(s.recordBatch(work, true)).toBe(false)- expect(s.recordBatch(work, true)).toBe(false)- expect(s.recordBatch(work, true)).toBe(true)- })-- it('NEGATIVE CONTROL: no plan, no nagging, ever', () => {- const s = new PlanStaleness()- for (let i = 0; i < 10; i++) expect(s.recordBatch(work, false)).toBe(false)- // a plan appearing later starts a FRESH count- expect(s.recordBatch(work, true)).toBe(false)- })-- it('NEGATIVE CONTROL: empty batches (no executed tools) do not accumulate', () => {- const s = new PlanStaleness()- for (let i = 0; i < 10; i++) expect(s.recordBatch([], true)).toBe(false)- })-- it('the steer asks the model to report, never claims progress itself', () => {- const msg = planStalenessSteer({ done: 8, total: 31, next: 'run the tests' })- expect(msg).toContain('8 of 31')- expect(msg).toContain('todo_write')- expect(msg).toContain('"run the tests"')- // it must not assert that any step IS done; the model decides that- expect(msg).not.toMatch(/step \d+ is (now )?completed/i)- })-})--describe('wiring in both loops', () => {- it('Agent and Codex each own one tracker per run and steer after the batch', () => {- for (const f of ['../../hooks/useAgentChat.ts', '../../hooks/useCodex.ts']) {- const src = read(f)- expect(src, f).toContain('const planStaleness = new PlanStaleness()')- expect(src, f).toContain('planStaleness.recordBatch(')- expect(src, f).toContain('planStalenessSteer(staleGap)')- }- })-- it('the steer rides the run transcript: agentMessages in Agent, messages in Codex', () => {- expect(read('../../hooks/useAgentChat.ts')).toContain("agentMessages.push({ role: 'user', content: planStalenessSteer(staleGap) })")- expect(read('../../hooks/useCodex.ts')).toContain("messages.push({ role: 'user', content: planStalenessSteer(staleGap) })")- })-- it('NEGATIVE CONTROL: the G16 finish-time reconcile keeps its own budget', () => {- for (const f of ['../../hooks/useAgentChat.ts', '../../hooks/useCodex.ts']) {- const src = read(f)- expect(src, f).toContain('planReconcilesRemaining = PLAN_RECONCILE_BUDGET')- expect(src, f).toContain('planReconcileSteer(gap)')- }- })-})diff --git a/src/lib/__tests__/prompt-tool-roster.test.ts b/src/lib/__tests__/prompt-tool-roster.test.tsindex 253440fa..f68a3b2a 100644--- a/src/lib/__tests__/prompt-tool-roster.test.ts+++ b/src/lib/__tests__/prompt-tool-roster.test.ts@@ -147,9 +147,20 @@ describe('the tools forced into every request are named in the prompts', () => {expect(PROMPTS.codex).toContain('file_edit')})- it('both lean prompts name todo_write, the tool a weak model needs most', () => {- expect(PROMPTS.codexLean).toContain('todo_write')- expect(PROMPTS.agentLean).toContain('todo_write')+ it('no prompt tells the model to open a plan on its own (lib/plan-gate.ts)', () => {+ // Customer case 30.09.2026: "plan first, then again after every step" made+ // every tick a full-context round trip on a plan nobody asked for. The+ // tool is offered only when planning is wanted, and the prompts say to+ // bundle an update with real work, never to start with one.+ for (const key of ['codex', 'codexLean', 'agent', 'agentLean'] as const) {+ expect(PROMPTS[key], key).not.toMatch(/todo_write (?:FIRST|first)|starts with todo_write|after each step,? call todo_write/i)+ }+ })++ it('the prompts ask for batched tool calls', () => {+ for (const key of ['codex', 'codexLean', 'agent', 'agentLean'] as const) {+ expect(PROMPTS[key], key).toMatch(/independent tool calls into (?:ONE|one) response/)+ }})it('the hermes prompt mentions the plan when the tool is offered', () => {diff --git a/src/lib/__tests__/run-ledger.test.ts b/src/lib/__tests__/run-ledger.test.tsnew file mode 100644index 00000000..1b3b0e06--- /dev/null+++ b/src/lib/__tests__/run-ledger.test.ts@@ -0,0 +1,82 @@+/**+ * The run ledger: a trimmed run still knows what it already did (customer+ * case 30.09.2026, "always starting with the beginning", see runLedger).+ *+ * Run: npx vitest run src/lib/__tests__/run-ledger.test.ts+ */+import { describe, it, expect } from 'vitest'+import { runLedger, trimWorkingHistory, LEDGER_MAX_LINES, type DecayMessage } from '../context-decay'++const call = (id: string, name: string, args: Record<string, unknown>): DecayMessage => ({+ role: 'assistant',+ content: '',+ tool_calls: [{ id, function: { name, arguments: args } }],+})+const result = (id: string, chars: number): DecayMessage => ({ role: 'tool', tool_call_id: id, content: 'x'.repeat(chars) })++describe('runLedger', () => {+ it('lists what the dropped part did, oldest first, duplicates folded', () => {+ const ledger = runLedger([+ call('1', 'file_read', { path: 'src/a.ts' }), result('1', 10),+ call('2', 'file_edit', { path: 'src/a.ts', old_string: 'x', new_string: 'y' }), result('2', 10),+ call('3', 'file_read', { path: 'src/a.ts' }), result('3', 10),+ call('4', 'shell_execute', { command: 'npm test' }), result('4', 10),+ ])!+ expect(ledger.split('\n').filter((l) => l.startsWith('- '))).toEqual([+ '- file_read: src/a.ts',+ '- file_edit: src/a.ts',+ '- shell_execute: npm test',+ ])+ })++ it('reads JSON-string arguments too, and skips plan bookkeeping', () => {+ const ledger = runLedger([+ { role: 'assistant', content: '', tool_calls: [{ id: 'a', function: { name: 'file_search', arguments: '{"pattern":"TODO"}' } }] },+ call('b', 'todo_write', { todos: [] }),+ ])!+ expect(ledger).toContain('- file_search: TODO')+ expect(ledger).not.toContain('todo_write')+ })++ it('says nothing when nothing was done', () => {+ expect(runLedger([{ role: 'user', content: 'hi' }])).toBeNull()+ })++ it('keeps the newest lines when there are too many', () => {+ const many = Array.from({ length: LEDGER_MAX_LINES + 5 }, (_, i) => call(String(i), 'file_read', { path: `f${i}.ts` }))+ const lines = runLedger(many)!.split('\n')+ expect(lines).toContain('- (5 older steps)')+ expect(lines).toContain(`- file_read: f${LEDGER_MAX_LINES + 4}.ts`)+ expect(lines).not.toContain('- file_read: f0.ts')+ })+})++describe('trimWorkingHistory carries the ledger on the pinned task', () => {+ const history = (): DecayMessage[] => {+ const out: DecayMessage[] = [{ role: 'system', content: 'sys' }, { role: 'user', content: 'refactor the parser' }]+ for (let i = 0; i < 40; i++) out.push(call(String(i), 'file_read', { path: `src/f${i}.ts` }), result(String(i), 3000))+ return out+ }++ it('the task stays first and names the dropped work', () => {+ const { messages, dropped } = trimWorkingHistory(history(), 8000, { enabled: false })+ expect(dropped).toBeGreaterThan(0)+ expect(messages[1].role).toBe('user')+ const task = messages[1].content as string+ expect(task.startsWith('refactor the parser\n\n[Run ledger]')).toBe(true)+ expect(task).toContain('- file_read: src/f0.ts')+ // No two user messages in a row.+ expect(messages[2].role).not.toBe('user')+ })++ it('is stable between trims: the same drop point yields the same bytes', () => {+ const a = trimWorkingHistory(history(), 8000, { enabled: false })+ const b = trimWorkingHistory(history(), 8000, { enabled: false })+ expect(a.messages[1].content).toBe(b.messages[1].content)+ })++ it('leaves an untrimmed history alone', () => {+ const small = history().slice(0, 4)+ expect(trimWorkingHistory(small, 64000).messages).toBe(small)+ })+})diff --git a/src/lib/__tests__/send-window.test.ts b/src/lib/__tests__/send-window.test.tsindex b99d7780..3da1b69b 100644--- a/src/lib/__tests__/send-window.test.ts+++ b/src/lib/__tests__/send-window.test.ts@@ -78,8 +78,8 @@ describe('A2: the paid-provider send cap', () => {})describe('A2: the shipped defaults', () => {- it('ships the cap at 64k and the decay switch on', () => {- expect(DEFAULT_SETTINGS.codexSendWindowTokens).toBe(64000)+ it('ships the cap at 32k and the decay switch on', () => {+ expect(DEFAULT_SETTINGS.codexSendWindowTokens).toBe(32000)expect(DEFAULT_SETTINGS.contextDecay).toBe(true)})})diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex f0542408..31a8c89b 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -1,4 +1,5 @@import type { Persona, Settings } from '../types/settings'+import { DEFAULT_SEND_WINDOW_TOKENS } from './send-window'// Feature flags — flip to true when ready to shipexport const FEATURE_FLAGS = {@@ -64,7 +65,7 @@ export const DEFAULT_SETTINGS: Settings = {// 2.6.6 plan A1/A2: age decay and the paid-provider send cap. ON by// default; the switch is the support way back without a rollback release.contextDecay: true,- codexSendWindowTokens: 64000,+ codexSendWindowTokens: DEFAULT_SEND_WINDOW_TOKENS,// 2.6.8: auto-compact is OFF until someone sets a threshold. 0 is the// switch, not a tuning value — see the field's comment in types/settings.ts.// No STORE_VERSION bump for this key: settingsStore's migrate mergesdiff --git a/src/lib/context-decay.ts b/src/lib/context-decay.tsindex 7bfd2b86..8a8d62ac 100644--- a/src/lib/context-decay.ts+++ b/src/lib/context-decay.ts@@ -366,6 +366,67 @@ export function pruneSupersededPlans<T extends DecayMessage>(* the contextDecay notaus wants: a support case that flips the switch should* land on the 2.6.5 window, not on a third behaviour nobody has ever seen.*/+/** How many ledger lines the pinned task carries at most. */+export const LEDGER_MAX_LINES = 40++/** The argument that names what a call worked on, in the order tools use them. */+const LEDGER_ARG_KEYS = ['path', 'file_path', 'filePath', 'command', 'query', 'pattern', 'url', 'name'] as const++function ledgerArg(args: unknown): string {+ let obj: unknown = args+ if (typeof args === 'string') {+ try { obj = JSON.parse(args) } catch { return '' }+ }+ if (!obj || typeof obj !== 'object') return ''+ const rec = obj as Record<string, unknown>+ for (const key of LEDGER_ARG_KEYS) {+ const v = rec[key]+ if (typeof v === 'string' && v.trim()) {+ const one = v.replace(/\s+/g, ' ').trim()+ return one.length > 80 ? one.slice(0, 77) + '...' : one+ }+ }+ return ''+}++/**+ * The run ledger (customer case 30.09.2026, "always starting with the+ * beginning"). trimWorkingHistory drops the oldest steps whole once a run+ * outgrows its send window. The task stayed pinned, but nothing said what had+ * already been done, so the model read the same files and redid the same+ * edits, and every repeat paid the full context again.+ *+ * One line per call in the dropped part, oldest first, duplicates folded. It+ * is derived from the dropped messages alone, so it only changes when the+ * drop point moves: between trims every request keeps the same prefix and the+ * upstream cache keeps hitting.+ */+export function runLedger(dropped: DecayMessage[]): string | null {+ const lines: string[] = []+ const seen = new Set<string>()+ for (const m of dropped) {+ if (m.role !== 'assistant') continue+ for (const tc of toolCallsIn(m)) {+ const name = callName(tc)+ if (!name || name === 'todo_write') continue+ const arg = ledgerArg(tc.function?.arguments)+ const line = arg ? `${name}: ${arg}` : name+ if (seen.has(line)) continue+ seen.add(line)+ lines.push(line)+ }+ }+ if (lines.length === 0) return null+ const kept = lines.length > LEDGER_MAX_LINES ? lines.slice(-LEDGER_MAX_LINES) : lines+ const skipped = lines.length - kept.length+ return [+ '[Run ledger] Earlier steps of this run were removed from the context to save cost. They were already done, do not repeat them unless something changed:',+ ...(skipped > 0 ? [`- (${skipped} older steps)`] : []),+ ...kept.map((l) => `- ${l}`),+ 'Continue from where the run stands now.',+ ].join('\n')+}+export function trimWorkingHistory<T extends DecayMessage>(messages: T[],budgetTokens: number,@@ -394,7 +455,14 @@ export function trimWorkingHistory<T extends DecayMessage>(while (tail.length > 0 && isToolResult(tail[0])) tail = tail.slice(1)const out: T[] = []if (systemMsg) out.push(systemMsg)- if (firstUser && !tail.includes(firstUser)) out.push(firstUser)+ if (firstUser && !tail.includes(firstUser)) {+ // The ledger rides on the pinned task instead of being a message of its+ // own: two user messages in a row break strict chat templates.+ const ledger = runLedger(rest.slice(0, drop))+ out.push(ledger && typeof firstUser.content === 'string'+ ? { ...firstUser, content: `${firstUser.content}\n\n${ledger}` }+ : firstUser)+ }out.push(...tail)return out}diff --git a/src/lib/plan-gate.ts b/src/lib/plan-gate.tsnew file mode 100644index 00000000..69d4381d--- /dev/null+++ b/src/lib/plan-gate.ts@@ -0,0 +1,68 @@+/**+ * When the agent is allowed to keep a todo list at all.+ *+ * Customer case 30.09.2026 (swift_maple90, LU Cloud, Code tab): 936k credits+ * in two days, 583 of 909 requests produced at most 300 output tokens. The+ * prompt told the model to open a plan for anything longer than three steps+ * and to resend the complete list after EVERY step. On an open model that is+ * a separate round trip per tick, each one paying the full 30k to 77k token+ * context again, and the user never asked for a plan in the first place+ * (David: "automatisch macht die LLM einen Plan").+ *+ * So planning is opt-in. todo_write is offered when+ * - the conversation runs in Plan mode, or+ * - the user's own message asks for a plan, a todo or checklist, or+ * - the conversation already holds an open plan that has to be kept current.+ * Everywhere else it is not in the tool list, and the model just works.+ */+import { openPlanGap } from './plan-reconcile'+import type { TodoItem } from '../stores/todoStore'++export const PLAN_TOOL = 'todo_write'++/**+ * The user asked for a plan in so many words. Deliberately narrow: "fix the+ * build steps" or "the plan field in the form" must not turn planning on, so+ * the words have to be about THIS task being planned.+ */+const PLAN_REQUEST = new RegExp(+ [+ // English+ String.raw`\b(?:make|write|create|draft|give me|show me|start with|with)\s+(?:me\s+)?(?:a|the|your)\s+(?:short\s+|detailed\s+|step[- ]by[- ]step\s+)?(?:plan|todo(?:\s+list)?|to-do(?:\s+list)?|checklist)\b`,+ String.raw`\bplan\s+(?:it|this|that|the (?:work|task|steps|change|refactor|migration))\b`,+ String.raw`\b(?:todo|to-do)\s+list\b`,+ String.raw`\bstep[- ]by[- ]step\b`,+ String.raw`\bplan (?:first|before)\b`,+ // Deutsch+ String.raw`\b(?:mach|erstell|schreib|zeig|gib)\w*\s+(?:mir\s+)?(?:einen|den|eine|die)\s+(?:kurzen\s+|genauen\s+)?(?:plan|todo-?liste|to-do-liste|checkliste)\b`,+ String.raw`\bplane?\s+(?:das|es|die (?:arbeit|aufgabe|schritte))\b`,+ String.raw`\bschritt f(?:ü|ue)r schritt\b`,+ String.raw`\berst(?:mal)? (?:einen )?plan\b`,+ String.raw`\btodo-?liste\b`,+ ].join('|'),+ 'i',+)++export function userAskedForPlan(text: string): boolean {+ return PLAN_REQUEST.test(text)+}++export interface PlanToolInput {+ /** Coding-agent preset of this run, null on surfaces without one. */+ mode: string | null+ /** The user's own words for this turn. */+ userText: string+ /** The conversation's current todo list. */+ todos: TodoItem[]+}++export function planToolAllowed(input: PlanToolInput): boolean {+ if (input.mode === 'plan') return true+ if (userAskedForPlan(input.userText)) return true+ return openPlanGap(input.todos) !== null+}++/** Drop todo_write from an offered catalog unless planning is allowed. */+export function gatePlanTool<T extends { name: string }>(defs: T[], allowed: boolean): T[] {+ return allowed ? defs : defs.filter((d) => d.name !== PLAN_TOOL)+}diff --git a/src/lib/plan-staleness.ts b/src/lib/plan-staleness.tsdeleted file mode 100644index 5207080d..00000000--- a/src/lib/plan-staleness.ts+++ /dev/null@@ -1,51 +0,0 @@-/**- * PlanBar lag (measured on the 2026-08-07 runs, next to G14-4): the bar read- * PLAN 8/31 while the model was demonstrably narrating step 17. The bar only- * renders what the model reports through todo_write, both system prompts- * already demand an update after every step, and small models ignore it once- * they get going. So the app notices the silence deterministically: batches of- * real work keep landing while the plan has open items and none of them was a- * todo_write. After PLAN_STALE_BATCHES of that, ONE steer asks for the update,- * at most PLAN_STALE_STEER_BUDGET times per run so a model that will not- * comply is not nagged forever.- *- * The steer asks the model to REPORT its own progress. It never invents plan- * state: the store is only ever written by the model's todo_write.- */-import type { PlanGap } from './plan-reconcile'--/** Executed tool batches without a todo_write before the plan counts as stale. */-export const PLAN_STALE_BATCHES = 3--/** Steers per run. Two is enough to recover a forgetful model once and prove- * an unwilling one will not comply. */-export const PLAN_STALE_STEER_BUDGET = 2--/** One instance per run, fed once per executed tool batch. */-export class PlanStaleness {- private quiet = 0- private steersLeft = PLAN_STALE_STEER_BUDGET-- /** Returns true when the steer should fire NOW (and consumes budget). */- recordBatch(toolNames: string[], hasOpenPlan: boolean): boolean {- if (!hasOpenPlan || toolNames.length === 0 || toolNames.includes('todo_write')) {- this.quiet = 0- return false- }- this.quiet++- if (this.quiet >= PLAN_STALE_BATCHES && this.steersLeft > 0) {- this.quiet = 0- this.steersLeft--- return true- }- return false- }-}--export function planStalenessSteer(gap: PlanGap): string {- return (- `Your plan still shows ${gap.done} of ${gap.total} steps completed and has not been updated while you worked. ` +- `Bring it up to date NOW with one todo_write call: send the full list, mark every finished step completed, and mark the step you are actually on as the single in_progress item. ` +- `Then continue with the work. The list currently names "${gap.next}" as the next step.`- )-}diff --git a/src/lib/send-window.ts b/src/lib/send-window.tsindex 96b8c451..e55c49df 100644--- a/src/lib/send-window.ts+++ b/src/lib/send-window.ts@@ -38,8 +38,21 @@*/export const PAID_PROVIDER_IDS: ReadonlySet<string> = new Set(['lu-cloud', 'openai', 'anthropic'])-/** Default ceiling for one sent step, in tokens. Power users may raise it. */-export const DEFAULT_SEND_WINDOW_TOKENS = 64000+/**+ * Default ceiling for one sent step, in tokens. Power users may raise it.+ *+ * 64k until 3.0.4. Customer case 30.09.2026: a Code-tab run on LU Cloud rode+ * that ceiling for two days, 38k tokens per request on average and up to 77k,+ * and 65 % of the credits went to models without an upstream prompt cache,+ * where every one of those tokens is billed again on every step. With the age+ * decay capping old results and the run ledger keeping the dropped steps+ * known, 32k carries a coding run at half the price per step.+ */+export const DEFAULT_SEND_WINDOW_TOKENS = 32000++/** The pre-3.0.4 default. No UI ever wrote this setting, so a stored 64000 is+ * the old default riding along in a profile, not anyone's choice. */+export const RETIRED_SEND_WINDOW_DEFAULT = 64000/** The share of the model window a step was already limited to before 2.6.6. */export const WINDOW_SHARE = 0.8diff --git a/src/stores/__tests__/send-window-retired-default.test.ts b/src/stores/__tests__/send-window-retired-default.test.tsnew file mode 100644index 00000000..037c426e--- /dev/null+++ b/src/stores/__tests__/send-window-retired-default.test.ts@@ -0,0 +1,43 @@+/**+ * @vitest-environment jsdom+ *+ * 3.0.4 halved the paid-provider send window (lib/send-window.ts). No UI ever+ * wrote codexSendWindowTokens, so a stored 64000 is the old default riding+ * along in the profile and must follow the new one on the next start. Any+ * other stored number was put there on purpose and stays.+ *+ * Run: npx vitest run src/stores/__tests__/send-window-retired-default.test.ts+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { useSettingsStore } from '../settingsStore'+import { DEFAULT_SETTINGS } from '../../lib/constants'++const KEY = 'chat-settings'++function seed(codexSendWindowTokens: number) {+ window.localStorage.setItem(KEY, JSON.stringify({+ state: {+ settings: { ...DEFAULT_SETTINGS, codexSendWindowTokens },+ personas: [],+ activePersonaId: 'unrestricted',+ _version: 22,+ },+ version: 22,+ }))+}++beforeEach(() => window.localStorage.removeItem(KEY))++describe('the retired 64k send window', () => {+ it('a stored 64000 follows the new 32k default', async () => {+ seed(64000)+ await useSettingsStore.persist.rehydrate()+ expect(useSettingsStore.getState().settings.codexSendWindowTokens).toBe(32000)+ })++ it('a deliberate other value stays', async () => {+ seed(96000)+ await useSettingsStore.persist.rehydrate()+ expect(useSettingsStore.getState().settings.codexSendWindowTokens).toBe(96000)+ })+})diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 81f1792b..84fb999c 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -5,6 +5,7 @@ import type { Settings, Persona } from '../types/settings'import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'import { isEffortLevel } from '../lib/effort'import { isRecord, asString } from '../types/json-guards'+import { RETIRED_SEND_WINDOW_DEFAULT } from '../lib/send-window'// v5 (Feature EE v2.5.0): added settings.exclusiveVramMode. The migrate below// already merges { ...DEFAULT_SETTINGS, ...persisted.settings }, so bumping the@@ -181,6 +182,13 @@ export const useSettingsStore = create<SettingsState>()(if (!isEffortLevel(String(state.settings.reasoningEffort))) {state.settings.reasoningEffort = DEFAULT_SETTINGS.reasoningEffort}+ // 3.0.4 halved the paid-provider send window. A stored 64000 is the old+ // default (no UI writes this key), so it follows the new one. Here and+ // not in migrate for the same reason as above: no version bump, and a+ // downgrade simply reads the smaller number.+ if (state.settings.codexSendWindowTokens === RETIRED_SEND_WINDOW_DEFAULT) {+ state.settings.codexSendWindowTokens = DEFAULT_SETTINGS.codexSendWindowTokens+ }},migrate: (persisted: unknown, version: number): SettingsState => {// Foreign at read time, an older build wrote this. A read that throws