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.

perf(codex): a coding step stops paying for the image and video generators

purple055dbbe3bddd
diff --git a/src/hooks/__tests__/codex-create-tool-gate.test.ts b/src/hooks/__tests__/codex-create-tool-gate.test.ts
new file mode 100644
index 00000000..49bfec5d
--- /dev/null
+++ b/src/hooks/__tests__/codex-create-tool-gate.test.ts
@@ -0,0 +1,173 @@
+/**
+ * The create tools ride along on every coding step, and on the cloud path
+ * nothing ever asked whether the turn wanted them.
+ *
+ * CODEX_CATEGORIES has carried this comment since v2.5.3: image and video
+ * "only surface when the keyword router sees a creative intent in the prompt,
+ * so pure coding turns keep the same lean tool list as before". That was true
+ * for a LOCAL model, which goes through selectRelevantTools. A cloud model gets
+ * `codexTools` handed straight to the request, so image_generate,
+ * video_generate and run_workflow shipped on every step of every paid run.
+ *
+ * Measured 2026-08-12 against the model's own tokenizer (DeepSeek V4 Flash
+ * 0731), serialised the way toOpenAITools puts it on the wire:
+ *
+ * coding catalog today 30 tools 6.186 tokens per step
+ * without the three generators 27 tools 4.223 tokens per step
+ *
+ * 1.963 tokens per step, on the surface that bills per token, for three tools
+ * a refactor never calls. Nothing is deleted: the same keyword weiche that has
+ * always guarded them locally now guards them everywhere.
+ *
+ * The second half of this file is the part that makes it safe. A gated tool
+ * list plus a system prompt that still promises asset generation is worse than
+ * no gate at all: the model calls a tool it was told it has, gets "unknown
+ * tool", and burns a step. Prompt and catalog answer the same question here.
+ *
+ * Run: npx vitest run src/hooks/__tests__/codex-create-tool-gate.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 { gateCreateTools, wantsMediaTools, CREATE_TOOLS } from '../../lib/tool-selection'
+import { toolRegistry, DEFAULT_PERMISSIONS } from '../../api/mcp'
+
+const src = readFileSync(
+ resolve(dirname(fileURLToPath(import.meta.url)), '../useCodex.ts'),
+ 'utf8',
+)
+
+// Mirrors CODEX_CATEGORIES in useCodex.ts, same reason as the sibling test:
+// the point is to notice the constant moving without this file moving with it.
+const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web', 'image', 'video', 'workflow']
+const codingCatalog = () =>
+ toolRegistry.getAvailableTools(DEFAULT_PERMISSIONS).filter((t) => CODEX_CATEGORIES.includes(t.category))
+
+const names = <T extends { name: string }>(ts: T[]) => ts.map((t) => t.name)
+
+describe('a plain coding turn does not carry the generators', () => {
+ it('drops all three on a refactor', () => {
+ const out = names(gateCreateTools(codingCatalog(), 'refactor the auth guard and run the tests'))
+ expect(out).not.toContain('image_generate')
+ expect(out).not.toContain('video_generate')
+ expect(out).not.toContain('run_workflow')
+ })
+
+ it('is a filter and not a wipe', () => {
+ const out = names(gateCreateTools(codingCatalog(), 'refactor the auth guard and run the tests'))
+ expect(out).toContain('file_read')
+ expect(out).toContain('shell_execute')
+ expect(out).toContain('git_status')
+ expect(out).toContain('todo_write')
+ })
+
+ it('removes exactly three tools from the real coding catalog and nothing else', () => {
+ const before = names(codingCatalog())
+ const after = names(gateCreateTools(codingCatalog(), 'fix the failing test in parser.ts'))
+ expect(before.length - after.length).toBe(3)
+ expect(before.filter((n) => !after.includes(n)).sort()).toEqual([...CREATE_TOOLS].sort())
+ })
+
+ it('leaves delegate_task alone, which shares the workflow category', () => {
+ // The naive version of this gate filters by category. delegate_task is
+ // category 'workflow' (sub-agent.ts) and joined the Code tab in audit B11
+ // precisely because it was unreachable; a category filter would take the
+ // sub-agent fan-out out again by accident.
+ const out = names(gateCreateTools(codingCatalog(), 'refactor the auth guard'))
+ expect(out).toContain('delegate_task')
+ })
+})
+
+describe('a creative turn keeps exactly what it asked for', () => {
+ const gate = (msg: string) => names(gateCreateTools(codingCatalog(), msg))
+
+ it('an image request keeps both generators, so image can still chain into video', () => {
+ const out = gate('add a hero image to the landing page')
+ expect(out).toContain('image_generate')
+ expect(out).toContain('video_generate')
+ })
+
+ it('a video request keeps them too', () => {
+ expect(gate('turn that into a video')).toContain('video_generate')
+ })
+
+ it('a workflow request keeps run_workflow and not the generators', () => {
+ const out = gate('run the workflow that syncs the docs')
+ expect(out).toContain('run_workflow')
+ expect(out).not.toContain('image_generate')
+ })
+
+ it('an image request does not drag run_workflow in with it', () => {
+ // Parity with TOOL_GROUPS: the two groups are separate there, so they stay
+ // separate here. Otherwise the gate would quietly be more generous than the
+ // router it is supposed to mirror.
+ expect(gate('draw me a logo')).not.toContain('run_workflow')
+ })
+
+ it('German asks work, they are half our users', () => {
+ expect(gate('zeichne mir ein Logo fuer die Startseite')).toContain('image_generate')
+ expect(gate('animiere das Bild')).toContain('video_generate')
+ expect(gate('bau mir eine Grafik dafuer')).toContain('image_generate')
+ })
+
+ it('naming the tool verbatim always wins, even with no other cue', () => {
+ expect(gate('call video_generate with inputImage set')).toContain('video_generate')
+ expect(gate('use run_workflow for this')).toContain('run_workflow')
+ })
+
+ it('the words that arrived with the gate are covered', () => {
+ // These were NOT in TOOL_GROUPS before 2026-08-12. On the local path a miss
+ // only meant a leaner list; with the gate on the cloud path a miss means a
+ // capability the user had yesterday is gone, so they are pinned.
+ for (const ask of ['make a logo', 'design an icon', 'a banner for the top', 'an avatar image', 'a poster', 'a thumbnail for it']) {
+ expect(gate(ask), ask).toContain('image_generate')
+ }
+ })
+})
+
+describe('the prompt and the tool list answer the same question', () => {
+ // The whole risk of this change in one property: the model must never be told
+ // it can generate assets on a turn where the gate removed the tool.
+ const asks = [
+ 'refactor the auth guard',
+ 'add a hero image to the landing page',
+ 'run the tests and commit',
+ 'zeichne mir ein Logo',
+ 'turn the screenshot into a video',
+ 'run the workflow that syncs the docs',
+ ]
+
+ it('the asset line is promised exactly when the generators survive the gate', () => {
+ for (const ask of asks) {
+ const kept = names(gateCreateTools(codingCatalog(), ask)).includes('image_generate')
+ expect(wantsMediaTools(ask), ask).toBe(kept)
+ }
+ })
+})
+
+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\)/)
+ })
+
+ it('the hermes fallback is gated too, it carries the weakest models', () => {
+ expect(src).toMatch(/gateCreateTools\(\s*\n?\s*toolRegistry\.toHermesToolDefs\(permissions\), instruction,/)
+ })
+
+ it('the asset line is conditional and never fires in review mode', () => {
+ expect(src).toMatch(/!reviewMode && !settings\.smallModelMode && wantsMediaTools\(instruction\)/)
+ })
+
+ it('the asset promise left the always-on prompt body', () => {
+ const body = src.slice(src.indexOf('const CODEX_SYSTEM_PROMPT ='), src.indexOf('const CODEX_ASSET_LINE'))
+ expect(body).not.toContain('- Asset generation:')
+ expect(src).toContain('const CODEX_ASSET_LINE')
+ })
+
+ it('the remote branch still hands the routed list through untouched', () => {
+ // The gate is deliberately the LAST step, not a rewrite of the branch: a
+ // hosted model keeps the full coding catalog, minus the three.
+ expect(src).toMatch(/!isLocalModelByName\(activeModel\)\s*\n?\s*\?\s*codexTools/)
+ })
+})
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index e4f2ef8e..38e03a2f 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -52,7 +52,7 @@ 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 } from '../lib/tool-selection'
+import { selectRelevantTools, selectRelevantToolsAsync, SMALL_MODEL_MAX_TOOLS, gateCreateTools, wantsMediaTools } from '../lib/tool-selection'
import { generateEmbeddings } from '../api/rag'
import { truncateToolResult } from '../lib/truncate-tool-result'
import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS, CODE_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'
@@ -115,9 +115,15 @@ Rules:
- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool
- If a command fails, diagnose and retry with a different approach, don't hand back to the user unless truly stuck
- Be concise in text. All the work happens in tool calls.
-- Asset generation: when the task needs an image or a short video (placeholder art, hero image, demo clip), call image_generate / video_generate as a real tool call, they run on-device (Apple MLX on macOS, ComfyUI elsewhere). To animate a generated image, call video_generate with inputImage set to that image's filename.
- FINISH with a short natural-language sentence summarising what you did or found. NEVER end your turn with only a raw JSON object or a bare code block, the user needs a human-readable answer, not a data dump.`
+// Appended only when the run's instruction asks for a picture or a clip
+// (wantsMediaTools), because that is exactly when gateCreateTools leaves the
+// two generators in the catalog. It used to sit inside the prompt above and
+// promised a tool the local keyword router had already removed, which is a
+// wasted step: the model calls it and gets "unknown tool".
+const CODEX_ASSET_LINE = `- Asset generation: when the task needs an image or a short video (placeholder art, hero image, demo clip), call image_generate / video_generate as a real tool call, they run on-device (Apple MLX on macOS, ComfyUI elsewhere). To animate a generated image, call video_generate with inputImage set to that image's filename.`
+
// Small-Model Mode (Knob 2): a lean Codex prompt (~500 chars vs ~1700 above)
// for 3B-8B models. Research (LongFuncEval, arXiv 2505.10570) shows long
// prompts + big tool catalogs degrade small-model tool-calling, and small
@@ -450,6 +456,13 @@ export function useCodex() {
: settings.smallModelMode
? CODEX_SYSTEM_PROMPT_LEAN
: CODEX_SYSTEM_PROMPT
+ // The prompt promises asset generation only while the tool list carries it.
+ // Same question, same helper as the gate on the catalog below, so the two
+ // cannot disagree. Never in review mode, which generates nothing.
+ const assetLine =
+ !reviewMode && !settings.smallModelMode && wantsMediaTools(instruction)
+ ? `\n${CODEX_ASSET_LINE}`
+ : ''
// Ground the model in its cwd. In sandbox mode (workDir '.') say so
// concretely + repeat the relative-path rule, since a bare "." led small
// models to fall back to drive-root absolute paths (e.g. /package.json).
@@ -457,7 +470,7 @@ export function useCodex() {
workDir && workDir !== '.'
? `Working directory: ${workDir}\nUse paths relative to it (e.g. \`package.json\`); do not prefix with \`/\` or a drive letter.`
: 'Working directory: your private sandbox folder. Use relative paths only (e.g. `package.json`, `.`); never a leading `/` or a drive letter like `C:\\`.'
- let systemPrompt = `${baseCodexPrompt}\n\n${workDirLine}`
+ let systemPrompt = `${baseCodexPrompt}${assetLine}\n\n${workDirLine}`
// Standing goal (/goal) — ahead of the rules and the repo map so it frames
// everything that follows instead of reading as an afterthought.
systemPrompt += renderGoalSection(useAgentGoalStore.getState().getGoal(convId))
@@ -881,7 +894,17 @@ export function useCodex() {
// sends), and keyword-guessing its toolbox from message one
// starved 30-minute runs of git_commit/run_tests/background
// shell mid-way.
- const relevantDefs = settings.smallModelMode
+ //
+ // gateCreateTools runs on ALL THREE, last: image_generate,
+ // video_generate and run_workflow are the one group a coding turn
+ // truly never wants, and the CODEX_CATEGORIES comment above has
+ // claimed since v2.5.3 that they "only surface when the keyword
+ // router sees a creative intent". That was true for local models and
+ // false for cloud ones, which got all three on every step: 6.186
+ // tokens instead of 4.223, measured 2026-08-12 against the model's
+ // own tokenizer. Nothing is removed, the keyword weiche just now
+ // decides on both paths.
+ const routedDefs = settings.smallModelMode
? await selectRelevantToolsAsync(lastUserMsg, codexTools, permissions, {
embed: (texts) => generateEmbeddings(texts),
topN: 5,
@@ -891,6 +914,7 @@ export function useCodex() {
: !isLocalModelByName(activeModel)
? codexTools
: selectRelevantTools(lastUserMsg, codexTools, permissions)
+ const relevantDefs = gateCreateTools(routedDefs, lastUserMsg)
const tools: ToolDefinition[] = relevantDefs.map(t => ({
type: 'function' as const,
function: { name: t.name, description: t.description, parameters: t.inputSchema },
@@ -1083,8 +1107,15 @@ export function useCodex() {
} else {
// Hermes-XML fallback — also restrict tools to coding categories
// so the model doesn't see image_generate / screenshot etc.
- // Same review-mode filter as the native path (B13).
- const hermesTools = toolRegistry.toHermesToolDefs(permissions).filter(
+ // Same review-mode filter as the native path (B13), and the same
+ // create-tool gate: this path carries the weakest models in the
+ // fleet and was the one still shipping all three generators in every
+ // prompt, the exact catalog length LongFuncEval says they choke on.
+ // `instruction`, not the newest user-role message: same reason as the
+ // native path above, steers and nudges are pushed as role 'user'.
+ const hermesTools = gateCreateTools(
+ toolRegistry.toHermesToolDefs(permissions), instruction,
+ ).filter(
(t) => {
const def = toolRegistry.getToolByName(t.name)
if (!def) return true
diff --git a/src/lib/tool-selection.ts b/src/lib/tool-selection.ts
index df8ecf37..14c1114a 100644
--- a/src/lib/tool-selection.ts
+++ b/src/lib/tool-selection.ts
@@ -13,6 +13,37 @@ interface ToolGroup {
tools: string[]
}
+// Creative image/video. Surface BOTH generators for any creative request so
+// the model can chain image → video in one conversation (David: "ein Video
+// aus dem Bild soll die LLM auch machen können"). Without video_generate
+// here the keyword path dropped it (it was in no group + not ALWAYS_INCLUDE),
+// so a "now animate it" follow-up had no tool to call.
+//
+// Named constants rather than inline literals because gateCreateTools() below
+// has to ask the SAME question on the cloud path. Two copies of this list would
+// drift, and the failure mode of a drifted copy is a model that is told it can
+// draw and then gets "unknown tool".
+//
+// The nouns beyond image/video (logo, icon, banner…) were added 2026-08-12 with
+// the gate: on the local path a missed keyword only meant a slightly leaner
+// list, on the cloud path it means a capability the user had yesterday is gone.
+// A false positive here costs tokens, a false negative costs the feature, so
+// the list leans generous.
+const MEDIA_KEYWORDS = [
+ 'image', 'picture', 'generate image', 'draw', 'create image', 'bild', 'foto', 'zeichne',
+ 'logo', 'icon', 'thumbnail', 'banner', 'illustration', 'avatar', 'artwork', 'grafik', 'poster',
+ 'video', 'animate', 'animation', 'clip', 'mp4', 'make a video', 'turn into a video', 'movie', 'gif', 'animiere',
+]
+const WORKFLOW_KEYWORDS = ['workflow', 'run workflow', 'automate']
+
+/**
+ * The three tools that draw, film and automate. Everything else in the coding
+ * catalog earns its place on every turn; these three cost 1.963 of the 6.186
+ * tokens a coding step sends (measured 2026-08-12 through the real registry
+ * against the model's own tokenizer) and a coding turn almost never wants them.
+ */
+export const CREATE_TOOLS = ['image_generate', 'video_generate', 'run_workflow']
+
const TOOL_GROUPS: ToolGroup[] = [
{
// Web search intents. Only EXPLICIT web cues route here. Bare 'search',
@@ -94,17 +125,11 @@ const TOOL_GROUPS: ToolGroup[] = [
tools: ['screenshot'],
},
{
- // Creative image/video. Surface BOTH generators for any creative request so
- // the model can chain image → video in one conversation (David: "ein Video
- // aus dem Bild soll die LLM auch machen können"). Without video_generate
- // here the keyword path dropped it (it was in no group + not ALWAYS_INCLUDE),
- // so a "now animate it" follow-up had no tool to call.
- keywords: ['image', 'picture', 'generate image', 'draw', 'create image', 'bild', 'foto', 'zeichne',
- 'video', 'animate', 'animation', 'clip', 'mp4', 'make a video', 'turn into a video', 'movie', 'gif', 'animiere'],
+ keywords: MEDIA_KEYWORDS,
tools: ['image_generate', 'video_generate'],
},
{
- keywords: ['workflow', 'run workflow', 'automate'],
+ keywords: WORKFLOW_KEYWORDS,
tools: ['run_workflow'],
},
{
@@ -220,6 +245,49 @@ export function selectRelevantTools(
return applyMaxTools(selected, maxTools, undefined, mentionedToolNames(userMessage, allTools))
}
+/**
+ * Drop the create tools unless this instruction actually asks for them.
+ *
+ * The keyword router already does this for local models. A CLOUD model gets
+ * the coding catalog untouched (useCodex.ts: a hosted model handles 25+ tools
+ * fine, and guessing its toolbox from message one starved long runs of
+ * git_commit mid-way), so image_generate + video_generate + run_workflow rode
+ * along on every step of every paid coding run: 2.160 tokens per step for
+ * three tools a refactor never calls. This closes exactly that gap and leaves
+ * the rest of the catalog alone.
+ *
+ * Gated per tool, not as a block, so the behaviour matches TOOL_GROUPS above:
+ * a creative intent surfaces the two generators, a workflow intent surfaces
+ * run_workflow, and naming a tool verbatim always wins.
+ *
+ * Honest limit: the decision is made once from the run's instruction. A model
+ * that discovers halfway through that it wants a placeholder image will not
+ * have the tool. That is already how the local path behaves, and the system
+ * prompt only promises asset generation when the gate opened, so the model is
+ * never told it can do something it cannot.
+ */
+export function gateCreateTools<T extends { name: string }>(defs: T[], userMessage: string): T[] {
+ const msg = userMessage.toLowerCase()
+ const wantsMedia = MEDIA_KEYWORDS.some((k) => msg.includes(k))
+ const wantsFlow = WORKFLOW_KEYWORDS.some((k) => msg.includes(k))
+ return defs.filter((t) => {
+ if (!CREATE_TOOLS.includes(t.name)) return true
+ if (msg.includes(t.name)) return true
+ return t.name === 'run_workflow' ? wantsFlow : wantsMedia
+ })
+}
+
+/** True when the instruction asks for a picture or a clip. Drives the asset
+ * line in the Codex system prompt so the prompt and the tool list agree. */
+export function wantsMediaTools(userMessage: string): boolean {
+ const msg = userMessage.toLowerCase()
+ return (
+ MEDIA_KEYWORDS.some((k) => msg.includes(k)) ||
+ msg.includes('image_generate') ||
+ msg.includes('video_generate')
+ )
+}
+
/** Names of tools the message mentions verbatim (case-insensitive). */
function mentionedToolNames(userMessage: string, tools: MCPToolDefinition[]): string[] {
const msg = userMessage.toLowerCase()