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.

feat(code): ask, bypass and plan become one dropdown, and a gate reads its own run

Davidf849f488c521
diff --git a/src/api/__tests__/codex-run-isolation.test.ts b/src/api/__tests__/codex-run-isolation.test.ts
new file mode 100644
index 00000000..c4129cfd
--- /dev/null
+++ b/src/api/__tests__/codex-run-isolation.test.ts
@@ -0,0 +1,268 @@
+/**
+ * Two interleaving agent runs cannot reach into each other (plan 2.6.6, C1
+ * ERZWINGUNG / blocker S3).
+ *
+ * Two runs at once are reachable from the UI today: a Coding run survives the
+ * tab switch, a second Coding conversation frees the send, and the Chat/Agent
+ * send is not locked. While the whole run context was ONE globalThis object,
+ * that meant a Bypass run B flipped the read-only flag of a Plan run A mid-run,
+ * B's cleanup nulled A's workspace so later writes went to
+ * agent-workspace/default, A's todo_write landed in B's conversation, and a
+ * chat-artifact run captured the coding run's writes.
+ *
+ * These tests run A and B genuinely interleaved and pin all four. Each one has
+ * its negative control right next to it: the SAME call with the run not
+ * threaded reads the module global and shows the old, broken answer.
+ *
+ * Run: npx vitest run src/api/__tests__/codex-run-isolation.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+// The vitest env is 'node', so todoStore's zustand persist has no storage and
+// logs one warning per write. Irrelevant here: every assertion reads the live
+// store, and the state is reset in beforeEach.
+
+const backendCalls: { cmd: string; body: any }[] = []
+
+vi.mock('../backend', () => ({
+ backendCall: vi.fn(async (cmd: string, body: any) => {
+ backendCalls.push({ cmd, body })
+ if (cmd === 'shell_execute') return { stdout: 'ok', stderr: '', exitCode: 0 }
+ if (cmd === 'fs_write') return { status: 'saved', path: `${body.workingDirectory ?? 'default'}/${body.path}` }
+ if (cmd === 'fs_read') return { content: 'file bytes' }
+ if (cmd === 'fs_list') return { entries: [], count: 0 }
+ return { ok: true }
+ }),
+ fetchExternal: vi.fn(async () => ({ ok: true, status: 200, text: async () => '' })),
+ isOllamaLocal: () => true,
+}))
+// The delegate/workflow imports drag in the provider stack, which nothing here
+// touches. Stub them so the module graph loads in a node test.
+vi.mock('../agents/sub-agent', () => ({
+ DELEGATE_TASK_TOOL_DEF: { name: 'delegate_task', description: '', category: 'system', inputSchema: {} },
+ buildDelegateExecutor: () => async () => 'stub',
+}))
+vi.mock('../../lib/workflow-engine', () => ({ WorkflowEngine: class {} }))
+
+import { registerBuiltinTools } from '../mcp/builtin-tools'
+import { ToolRegistry } from '../mcp/tool-registry'
+import { beginAgentRun, endAgentRun, clearActiveChatId, type AgentRunContext } from '../agent-context'
+import { useTodoStore } from '../../stores/todoStore'
+
+const registry = new ToolRegistry()
+registerBuiltinTools(registry)
+
+const ws = (path: string) => ({ kind: 'folder' as const, path })
+
+const startPlanRunA = (): AgentRunContext =>
+ beginAgentRun({
+ chatId: 'plan-a',
+ conversationId: 'conv-A',
+ workspace: ws('/repo-a'),
+ readOnlyShellTurn: true,
+ mode: 'plan',
+ })
+
+const startBypassRunB = (): AgentRunContext =>
+ beginAgentRun({
+ chatId: 'bypass-b',
+ conversationId: 'conv-B',
+ workspace: ws('/repo-b'),
+ readOnlyShellTurn: false,
+ // B is a plain-chat artifact run as well, so the capture gate is exercised
+ // in the same interleave.
+ artifactMode: true,
+ mode: 'bypass',
+ })
+
+const MUTATING = 'rm -rf build'
+
+beforeEach(() => {
+ backendCalls.length = 0
+ clearActiveChatId()
+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })
+})
+afterEach(() => clearActiveChatId())
+
+describe('run A stays read-only before, during and after run B', () => {
+ it('refuses A mutating shell before B, while B runs, and after B ended', async () => {
+ const a = startPlanRunA()
+
+ const before = await registry.execute('shell_execute', { command: MUTATING }, 1, a)
+ expect(before).toContain('Refused')
+
+ const b = startBypassRunB()
+ const during = await registry.execute('shell_execute', { command: MUTATING }, 1, a)
+ expect(during).toContain('Refused')
+
+ // B is allowed to do exactly what A may not. Without this the test would
+ // pass on a build where nothing runs at all.
+ const bRan = await registry.execute('shell_execute', { command: MUTATING }, 1, b)
+ expect(bRan).not.toContain('Refused')
+
+ endAgentRun(b)
+ const after = await registry.execute('shell_execute', { command: MUTATING }, 1, a)
+ expect(after).toContain('Refused')
+
+ endAgentRun(a)
+ })
+
+ it('negative control: the same call on the module global runs through while B is up', async () => {
+ const a = startPlanRunA()
+ // Unthreaded, exactly as every executor gate read it before C1.
+ expect(await registry.execute('shell_execute', { command: MUTATING })).toContain('Refused')
+
+ const b = startBypassRunB()
+ // The global now belongs to B, so A's read-only guarantee is simply gone.
+ expect(await registry.execute('shell_execute', { command: MUTATING })).not.toContain('Refused')
+
+ endAgentRun(b)
+ endAgentRun(a)
+ })
+
+ it('A may still run its inspection commands', async () => {
+ const a = startPlanRunA()
+ const out = await registry.execute('shell_execute', { command: 'git status' }, 1, a)
+ expect(out).not.toContain('Refused')
+ endAgentRun(a)
+ })
+})
+
+describe("A's plan lands in A's conversation", () => {
+ it('todo_write follows the run, not whichever run started last', async () => {
+ const a = startPlanRunA()
+ const b = startBypassRunB()
+
+ await registry.execute('todo_write', { todos: [{ content: 'read the router', status: 'in_progress' }] }, 1, a)
+
+ expect(useTodoStore.getState().getTodos('conv-A').map((t) => t.content)).toEqual(['read the router'])
+ expect(useTodoStore.getState().getTodos('conv-B')).toEqual([])
+
+ endAgentRun(b)
+ endAgentRun(a)
+ })
+
+ it('negative control: unthreaded, the same plan lands in B', async () => {
+ const a = startPlanRunA()
+ const b = startBypassRunB()
+
+ await registry.execute('todo_write', { todos: [{ content: 'read the router', status: 'in_progress' }] })
+
+ expect(useTodoStore.getState().getTodos('conv-B').map((t) => t.content)).toEqual(['read the router'])
+ expect(useTodoStore.getState().getTodos('conv-A')).toEqual([])
+
+ endAgentRun(b)
+ endAgentRun(a)
+ })
+})
+
+describe("B's cleanup does not strip A's workspace", () => {
+ it("A's reads still resolve against its own jail root after B ended", async () => {
+ const a = startPlanRunA()
+ const b = startBypassRunB()
+ endAgentRun(b)
+
+ backendCalls.length = 0
+ await registry.execute('file_read', { path: 'src/main.ts' }, 1, a)
+ const call = backendCalls.find((c) => c.cmd === 'fs_read')
+ expect(call?.body.workingDirectory).toBe('/repo-a')
+ expect(call?.body.chatId).toBe('plan-a')
+
+ endAgentRun(a)
+ })
+
+ it('negative control: unthreaded, the same read has lost its root entirely', async () => {
+ const a = startPlanRunA()
+ const b = startBypassRunB()
+ endAgentRun(b)
+
+ backendCalls.length = 0
+ await registry.execute('file_read', { path: 'src/main.ts' })
+ const call = backendCalls.find((c) => c.cmd === 'fs_read')
+ // Nulled by B on its way out, so the bridge falls back to
+ // agent-workspace/default and the write lands nowhere near the project.
+ expect(call?.body.workingDirectory).toBeUndefined()
+ expect(call?.body.chatId).toBeUndefined()
+
+ endAgentRun(a)
+ })
+})
+
+describe("a chat-artifact run does not capture the coding run's writes", () => {
+ it("A's file_write hits the disk path while B's is captured", async () => {
+ // A is a Bypass coding run here (Plan has no writes), B is the plain-chat
+ // artifact run that used to swallow them.
+ const a = beginAgentRun({
+ chatId: 'code-a', conversationId: 'conv-A', workspace: ws('/repo-a'),
+ readOnlyShellTurn: false, artifactMode: false, mode: 'bypass',
+ })
+ const b = startBypassRunB()
+
+ const aOut = await registry.execute('file_write', { path: 'out.txt', content: 'hello' }, 1, a)
+ expect(aOut).toContain('File saved')
+ expect(backendCalls.some((c) => c.cmd === 'fs_write' && c.body.workingDirectory === '/repo-a')).toBe(true)
+
+ const bOut = await registry.execute('file_write', { path: 'note.md', content: 'hi' }, 1, b)
+ expect(bOut).toContain('nothing was written to disk')
+
+ endAgentRun(b)
+ endAgentRun(a)
+ })
+
+ it('negative control: unthreaded, the coding write is swallowed as a chat artifact', async () => {
+ const a = beginAgentRun({
+ chatId: 'code-a', conversationId: 'conv-A', workspace: ws('/repo-a'),
+ readOnlyShellTurn: false, artifactMode: false, mode: 'bypass',
+ })
+ const b = startBypassRunB()
+
+ backendCalls.length = 0
+ const aOut = await registry.execute('file_write', { path: 'out.txt', content: 'hello' })
+ expect(aOut).toContain('nothing was written to disk')
+ expect(backendCalls.some((c) => c.cmd === 'fs_write')).toBe(false)
+
+ endAgentRun(b)
+ endAgentRun(a)
+ })
+})
+
+describe('the retired names go through the same gate', () => {
+ it("git_commit under A's plan run is refused even while B is unrestricted", async () => {
+ const a = startPlanRunA()
+ const b = startBypassRunB()
+ expect(await registry.execute('git_commit', { message: 'wip' }, 1, a)).toContain('Refused')
+ expect(await registry.execute('git_commit', { message: 'wip' }, 1, b)).not.toContain('Refused')
+ endAgentRun(b)
+ endAgentRun(a)
+ })
+})
+
+describe('closing a run only clears the shared mirror when it owns it', () => {
+ it('A closing first leaves B intact', async () => {
+ const a = startPlanRunA()
+ const b = startBypassRunB()
+ // A is the older run, so it does not own the mirror any more.
+ endAgentRun(a)
+ const out = await registry.execute('shell_execute', { command: MUTATING }, 1, b)
+ expect(out).not.toContain('Refused')
+ endAgentRun(b)
+ })
+
+ it('an older run finishing does not take the newer run\'s context with it', async () => {
+ // B first, then A, so A owns the mirror. B finishing must leave it alone:
+ // this is the half a threaded call cannot see, and it is what a standalone
+ // tool call from another tab reads.
+ const b = startBypassRunB()
+ const a = startPlanRunA()
+ endAgentRun(b)
+
+ backendCalls.length = 0
+ await registry.execute('file_read', { path: 'src/main.ts' })
+ const call = backendCalls.find((c) => c.cmd === 'fs_read')
+ expect(call?.body.workingDirectory).toBe('/repo-a')
+ expect(call?.body.chatId).toBe('plan-a')
+ expect(await registry.execute('shell_execute', { command: MUTATING })).toContain('Refused')
+
+ endAgentRun(a)
+ })
+})
diff --git a/src/api/agent-context.ts b/src/api/agent-context.ts
index 9fb61363..e2b61e56 100644
--- a/src/api/agent-context.ts
+++ b/src/api/agent-context.ts
@@ -43,7 +43,41 @@ export interface CapturedArtifact {
content: string
mime: string
}
+/**
+ * The context of ONE agent run, threaded explicitly (plan 2.6.6 C1,
+ * ERZWINGUNG / blocker S3).
+ *
+ * The singleton below is still here for callers outside a loop, but it can
+ * never be the ENFORCEMENT point: two runs are reachable from the UI at once
+ * (a Codex run survives the tab switch, a second Codex conversation frees the
+ * send, the Chat/Agent send is not locked). With only the global, a Bypass run
+ * B flipped the read-only flag of a Plan run A mid-run, B's cleanup nulled A's
+ * workspace, A's todo_write landed in the wrong conversation, and a chat
+ * artifact run captured Codex writes.
+ *
+ * So every run gets its own object, the hook hands it to the executor, the
+ * executor hands it to the tool, and the tool's gate reads ITS run. Nothing
+ * about run B can be observed by a tool call belonging to run A.
+ */
+export interface AgentRunContext {
+ /** Unique per run. Ownership token for the singleton mirror below. */
+ token: string
+ chatId: string | null
+ conversationId: string | null
+ workspace: AgentWorkspace | null
+ artifactMode: boolean
+ readOnlyShellTurn: boolean
+ /**
+ * Coding-agent preset this run started under ('ask' | 'bypass' | 'plan'),
+ * null off the Code tab. Carried so a gate can name the reason it refused.
+ */
+ mode: string | null
+ artifacts: CapturedArtifact[]
+}
+
interface AgentCtxState {
+ /** Token of the run that currently owns the singleton mirror. */
+ runToken: string | null
chatId: string | null
/** The conversation this loop belongs to, VERBATIM. Distinct from `chatId`,
* which is a filesystem-safe workspace SLUG derived from id + title. Any UI
@@ -60,7 +94,66 @@ interface AgentCtxState {
artifacts: CapturedArtifact[]
}
const _g = globalThis as typeof globalThis & { __LU_AGENT_CTX?: AgentCtxState }
-const ctx: AgentCtxState = _g.__LU_AGENT_CTX ?? (_g.__LU_AGENT_CTX = { chatId: null, conversationId: null, workspace: null, model: null, artifactMode: false, readOnlyShellTurn: false, artifacts: [] })
+const ctx: AgentCtxState = _g.__LU_AGENT_CTX ?? (_g.__LU_AGENT_CTX = { runToken: null, chatId: null, conversationId: null, workspace: null, model: null, artifactMode: false, readOnlyShellTurn: false, artifacts: [] })
+
+let _runSeq = 0
+
+/**
+ * Open a run context and mirror it into the singleton for every caller that
+ * does not thread (standalone tool calls, older surfaces). Returns the object
+ * the caller must pass down to its tool calls.
+ */
+export function beginAgentRun(init: {
+ chatId?: string | null
+ conversationId?: string | null
+ workspace?: AgentWorkspace | null
+ artifactMode?: boolean
+ readOnlyShellTurn?: boolean
+ mode?: string | null
+}): AgentRunContext {
+ _runSeq += 1
+ const run: AgentRunContext = {
+ token: `run-${Date.now().toString(36)}-${_runSeq}`,
+ chatId: init.chatId ? String(init.chatId) : null,
+ conversationId: init.conversationId ? String(init.conversationId) : null,
+ workspace: normalizeWorkspace(init.workspace),
+ artifactMode: init.artifactMode === true,
+ readOnlyShellTurn: init.readOnlyShellTurn === true,
+ mode: init.mode ?? null,
+ artifacts: [],
+ }
+ ctx.runToken = run.token
+ ctx.chatId = run.chatId
+ ctx.conversationId = run.conversationId
+ ctx.workspace = run.workspace
+ ctx.artifactMode = run.artifactMode
+ ctx.readOnlyShellTurn = run.readOnlyShellTurn
+ ctx.artifacts = run.artifacts
+ return run
+}
+
+/**
+ * Close a run. The singleton is only cleared when THIS run still owns it, so a
+ * short Bypass run that started and finished inside a long Plan run cannot
+ * strip the Plan run's workspace or read-only flag on its way out.
+ */
+export function endAgentRun(run: AgentRunContext | null | undefined): void {
+ if (!run) {
+ clearActiveChatId()
+ return
+ }
+ run.artifacts = []
+ if (ctx.runToken !== run.token) return
+ clearActiveChatId()
+}
+
+/** Read a field from the run when one was threaded, else from the singleton. */
+function pick<K extends keyof AgentCtxState & keyof AgentRunContext>(
+ run: AgentRunContext | null | undefined,
+ key: K,
+): AgentRunContext[K] | AgentCtxState[K] {
+ return run ? run[key] : ctx[key]
+}
/**
* The text model driving the current agent loop. Pinned by useAgentChat right
@@ -86,16 +179,16 @@ export function setActiveChatId(id: string | null | undefined): void {
ctx.chatId = id ? String(id) : null
}
-export function getActiveChatId(): string | null {
- return ctx.chatId
+export function getActiveChatId(run?: AgentRunContext | null): string | null {
+ return pick(run, 'chatId')
}
export function setActiveConversationId(id: string | null | undefined): void {
ctx.conversationId = id ? String(id) : null
}
-export function getActiveConversationId(): string | null {
- return ctx.conversationId
+export function getActiveConversationId(run?: AgentRunContext | null): string | null {
+ return pick(run, 'conversationId')
}
export function setActiveAgentModel(model: ActiveAgentModel | null | undefined): void {
@@ -107,6 +200,7 @@ export function getActiveAgentModel(): ActiveAgentModel | null {
}
export function clearActiveChatId(): void {
+ ctx.runToken = null
ctx.chatId = null
ctx.conversationId = null
ctx.workspace = null
@@ -128,8 +222,8 @@ export function setReadOnlyShellTurn(on: boolean): void {
ctx.readOnlyShellTurn = !!on
}
-export function isReadOnlyShellTurn(): boolean {
- return ctx.readOnlyShellTurn
+export function isReadOnlyShellTurn(run?: AgentRunContext | null): boolean {
+ return pick(run, 'readOnlyShellTurn')
}
// ── Chat-tools artifact mode (David 2026-06-12) ────────────────
@@ -146,16 +240,30 @@ export function setChatArtifactMode(on: boolean): void {
if (!on) ctx.artifacts = []
}
-export function isChatArtifactMode(): boolean {
- return ctx.artifactMode
+export function isChatArtifactMode(run?: AgentRunContext | null): boolean {
+ return pick(run, 'artifactMode')
}
-export function captureChatArtifact(name: string, content: string, mime: string): void {
- ctx.artifacts.push({ name, content, mime })
+export function captureChatArtifact(
+ name: string,
+ content: string,
+ mime: string,
+ run?: AgentRunContext | null,
+): void {
+ const sink = run ? run.artifacts : ctx.artifacts
+ sink.push({ name, content, mime })
}
/** Return the captured artifacts and clear the buffer (drain). */
-export function takeChatArtifacts(): CapturedArtifact[] {
+export function takeChatArtifacts(run?: AgentRunContext | null): CapturedArtifact[] {
+ if (run) {
+ const taken = run.artifacts
+ run.artifacts = []
+ // The singleton mirrors the same array while this run owns it, so hand it
+ // a fresh one instead of leaving the drained reference behind.
+ if (ctx.runToken === run.token) ctx.artifacts = []
+ return taken
+ }
const out = ctx.artifacts
ctx.artifacts = []
return out
@@ -175,7 +283,7 @@ export function takeChatArtifacts(): CapturedArtifact[] {
* useAgentChat / useCodex right after setActiveChatId. Sandbox mode
* passes null so the bridge falls back to ~/agent-workspace/<slug>/.
*/
-export function setActiveWorkspace(ws: AgentWorkspace | null | undefined): void {
+export function normalizeWorkspace(ws: AgentWorkspace | null | undefined): AgentWorkspace | null {
if (ws && ws.kind === 'folder' && ws.path) {
// Defensive: filter out blanks + dedupe extras + drop the primary if
// a caller accidentally listed it as both. Keeps the public shape
@@ -189,21 +297,35 @@ export function setActiveWorkspace(ws: AgentWorkspace | null | undefined): void
),
)
: []
- ctx.workspace = {
+ return {
kind: 'folder',
path: ws.path,
extraPaths: cleanedExtras.length > 0 ? cleanedExtras : undefined,
}
- } else {
- // Sandbox (or unset) → leave pointer null so the bridge falls back
- // to its own per-chat sandbox path. Setting it to { kind: 'sandbox' }
- // would just duplicate state the bridge already owns.
- ctx.workspace = null
}
+ // Sandbox (or unset) leaves the pointer null so the bridge falls back to its
+ // own per-chat sandbox path. Setting it to { kind: 'sandbox' } would just
+ // duplicate state the bridge already owns.
+ return null
+}
+
+export function setActiveWorkspace(
+ ws: AgentWorkspace | null | undefined,
+ run?: AgentRunContext | null,
+): void {
+ const normalized = normalizeWorkspace(ws)
+ if (run) {
+ run.workspace = normalized
+ // Mirror only while this run owns the singleton, so a second run cannot
+ // repoint a first run's jail root (plan C1 ERZWINGUNG).
+ if (ctx.runToken === run.token) ctx.workspace = normalized
+ return
+ }
+ ctx.workspace = normalized
}
-export function getActiveWorkspace(): AgentWorkspace | null {
- return ctx.workspace
+export function getActiveWorkspace(run?: AgentRunContext | null): AgentWorkspace | null {
+ return pick(run, 'workspace')
}
/**
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.ts
index 6ed51f51..21a7a2ba 100644
--- a/src/api/agents/sub-agent.ts
+++ b/src/api/agents/sub-agent.ts
@@ -13,6 +13,7 @@
import type { MCPToolDefinition } from '../mcp/types'
import { executeParallel, type ExecutionRequest } from './tool-executor'
+import type { AgentRunContext } from '../agent-context'
import { AgentBudget } from './budget'
import { explainError as explainToolError } from './error-hints'
@@ -93,7 +94,7 @@ export function _setDepth(n: number): void {
export type SubAgentRunner = (
goal: string,
context: string,
- options: { budget: AgentBudget }
+ options: { budget: AgentBudget; run?: AgentRunContext }
) => Promise<string>
/**
@@ -104,7 +105,7 @@ export type SubAgentRunner = (
export async function defaultSubAgentRunner(
goal: string,
context: string,
- options: { budget: AgentBudget }
+ options: { budget: AgentBudget; run?: AgentRunContext }
): Promise<string> {
const { useModelStore } = await import('../../stores/modelStore')
const { getProviderForModel } = await import('../providers')
@@ -153,11 +154,16 @@ export async function defaultSubAgentRunner(
toolName: tc.function.name,
args: tc.function.arguments,
parentToolCallId: 'sub-agent',
+ // A sub-agent inherits its parent's run, so its tool calls are gated by
+ // the same conversation and mode instead of whatever the process-wide
+ // singleton happens to hold (plan 2.6.6 C1).
+ run: options.run,
}))
const registry = toolRegistry
const results = await executeParallel(requests, {
getTool: (name) => registry.resolveExecutable(name),
- execute: ((name: string, args: Record<string, any>) => registry.execute(name, args)) as any,
+ execute: (name: string, args: Record<string, any>, callRun?: AgentRunContext) =>
+ registry.execute(name, args, 1, callRun),
explainError: (toolName, err) => explainToolError(toolName, err),
})
@@ -188,8 +194,8 @@ export async function defaultSubAgentRunner(
*/
export function buildDelegateExecutor(
runner: SubAgentRunner = defaultSubAgentRunner
-): (args: Record<string, any>) => Promise<string> {
- return async (args: Record<string, any>) => {
+): (args: Record<string, any>, run?: AgentRunContext) => Promise<string> {
+ return async (args: Record<string, any>, run?: AgentRunContext) => {
if (_inFlight >= SUB_AGENT_MAX_PARALLEL) {
return `Error: Maximum sub-agent concurrency (${SUB_AGENT_MAX_PARALLEL}) reached. Wait for a running sub-agent to finish, or continue the task yourself.`
}
@@ -200,7 +206,7 @@ export function buildDelegateExecutor(
_inFlight++
try {
const budget = new AgentBudget({ ...SUB_AGENT_BUDGET })
- return await runner(goal, context, { budget })
+ return await runner(goal, context, { budget, run })
} catch (err) {
return `Error: ${err instanceof Error ? err.message : String(err)}`
} finally {
diff --git a/src/api/agents/tool-executor.ts b/src/api/agents/tool-executor.ts
index fd367151..fff8c45a 100644
--- a/src/api/agents/tool-executor.ts
+++ b/src/api/agents/tool-executor.ts
@@ -17,6 +17,7 @@
*/
import type { AgentToolCall } from '../../types/agent-mode'
+import type { AgentRunContext } from '../agent-context'
import { deriveSideEffectKey } from './side-effect-key'
import { validateToolArgs, formatValidationErrors, type JsonSchema } from './args-validator'
import { stableArgsHash } from './block-helpers'
@@ -35,6 +36,14 @@ export interface ExecutionRequest {
args: Record<string, any>
/** Optional parent id for sub-agent lineage. */
parentToolCallId?: string
+ /**
+ * The run this call belongs to (plan 2.6.6 C1, ERZWINGUNG). Carries the
+ * conversation id and the coding-agent mode down to the executor gates, so
+ * they check against THIS run instead of a process-wide global that a second,
+ * interleaving run can overwrite. Undefined on surfaces that do not thread
+ * yet; those keep the singleton behaviour.
+ */
+ run?: AgentRunContext
}
export interface ExecutionResult {
@@ -60,13 +69,22 @@ export interface ExecutionResult {
validationError?: string
}
-export type ExecutorFn = (args: Record<string, any>) => Promise<string>
+/**
+ * Dispatch one registered tool. The third argument is the run the call belongs
+ * to (see ExecutionRequest.run); a runtime that does not care simply declares
+ * two parameters.
+ */
+export type ExecutorFn = (
+ name: string,
+ args: Record<string, any>,
+ run?: AgentRunContext,
+) => Promise<string>
export interface ExecutorRuntime {
/** Resolve a tool by name — returns undefined for unknown tools. */
getTool: (name: string) => ExecutorToolDef | undefined
/** Execute a registered tool against args; returns string result. */
- execute: ExecutorFn & ((name: string, args: Record<string, any>) => Promise<string>)
+ execute: ExecutorFn
/** Optional — called before dispatch to gate on user approval. */
awaitApproval?: (req: ExecutionRequest, tool: ExecutorToolDef) => Promise<boolean>
/** Optional — cache lookup pre-dispatch (Phase 6). Returns a cached result or undefined. */
@@ -313,7 +331,7 @@ async function runSingle(
// Dispatch.
try {
- const result = await runtime.execute(req.toolName, dispatchedArgs)
+ const result = await runtime.execute(req.toolName, dispatchedArgs, req.run)
return finalize({
id: req.id,
toolName: req.toolName,
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 97b9a1d5..46425c21 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -4,6 +4,7 @@ import type { JSONSchemaProp, MCPToolDefinition } from './types'
import type { ToolRegistry } from './tool-registry'
import { backendCall, fetchExternal } from '../backend'
import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact, isReadOnlyShellTurn } from '../agent-context'
+import type { AgentRunContext } from '../agent-context'
import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
import { WorkflowEngine } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
@@ -25,14 +26,14 @@ import { RETIRED_MUTATING_NAMES } from '../../lib/retired-tools'
* a caller that needs an absolute project path to resolve MUST pass the real
* `workingDirectory` here (it becomes the root).
*/
-function chatCtx(): { chatId?: string; workingDirectory?: string } {
- const id = getActiveChatId()
+function chatCtx(run?: AgentRunContext): { chatId?: string; workingDirectory?: string } {
+ const id = getActiveChatId(run)
if (!id) return {}
// If the agent loop picked a real folder, thread it through so the
// bridge resolves relative paths against that folder instead of the
// per-chat sandbox. The workspace pointer is set on loop start by
// useAgentChat / useCodex (see agent-context.setActiveWorkspace).
- const ws = getActiveWorkspace()
+ const ws = getActiveWorkspace(run)
if (ws?.kind === 'folder' && ws.path) {
return { chatId: id, workingDirectory: ws.path }
}
@@ -476,8 +477,8 @@ async function executeWebFetch(args: Record<string, any>): Promise<string> {
}
}
-async function executeFileRead(args: Record<string, any>): Promise<string> {
- const data = await backendCall('fs_read', { path: args.path, ...chatCtx() })
+async function executeFileRead(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+ const data = await backendCall('fs_read', { path: args.path, ...chatCtx(run) })
// A binary file comes back as a marker with its size, never as content.
// Handing the model raw bytes-as-text is a corruption trap: it treats them as
// content and a later file_write persists that string, mangling the file.
@@ -512,18 +513,18 @@ function mimeForName(name: string): string {
return map[ext] || 'text/plain'
}
-async function executeFileWrite(args: Record<string, any>): Promise<string> {
+async function executeFileWrite(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const content = typeof args.content === 'string' ? args.content : String(args.content ?? '')
// Plain-chat artifact mode (ChatGPT-style, David 2026-06-12): in the NORMAL
// chat, a "file write" must NOT touch disk — capture it so it renders inline
// with a preview + Download button. The Coding Agent / full Agent leave
// artifact mode OFF and fall through to the real fs_write below.
- if (isChatArtifactMode()) {
+ if (isChatArtifactMode(run)) {
const name = artifactBaseName(args.path)
- captureChatArtifact(name, content, mimeForName(name))
+ captureChatArtifact(name, content, mimeForName(name), run)
return `Created "${name}" (${formatBytes(content.length)}). It is shown to the user right here in the chat with a preview and a Download button — nothing was written to disk. Do not call file_read on it; just tell the user it's ready.`
}
- const data = await backendCall('fs_write', { path: args.path, content, ...chatCtx() })
+ const data = await backendCall('fs_write', { path: args.path, content, ...chatCtx(run) })
// Rust returns {status: 'saved'|'unchanged', path: <absolute>, bytes}. Surface
// the real path so the model (and the file-change event) knows WHERE the write
// landed — especially important when chatId is None and Rust routes a relative
@@ -535,11 +536,11 @@ async function executeFileWrite(args: Record<string, any>): Promise<string> {
return JSON.stringify(data)
}
-async function executeFileEdit(args: Record<string, any>): Promise<string> {
+async function executeFileEdit(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
// Plain-chat artifact mode has no files on disk — file_edit makes no sense
// there. Steer to file_write (which captures a document artifact) instead of
// silently reaching into the agent sandbox.
- if (isChatArtifactMode()) {
+ if (isChatArtifactMode(run)) {
return 'file_edit is not available in plain chat (there are no files on disk here). Use file_write to create or replace a document.'
}
const path = typeof args.path === 'string' ? args.path : ''
@@ -551,7 +552,7 @@ async function executeFileEdit(args: Record<string, any>): Promise<string> {
// existing text file — for a new file the model must use file_write.
let data: any
try {
- data = await backendCall('fs_read', { path, ...chatCtx() })
+ data = await backendCall('fs_read', { path, ...chatCtx(run) })
} catch (e) {
return `Error: file_edit could not read ${path}: ${e instanceof Error ? e.message : String(e)}. To create a new file use file_write.`
}
@@ -574,25 +575,25 @@ async function executeFileEdit(args: Record<string, any>): Promise<string> {
}
}
- const w = await backendCall('fs_write', { path, content: res.content, ...chatCtx() })
+ const w = await backendCall('fs_write', { path, content: res.content, ...chatCtx(run) })
if (w.status === 'saved' && w.path) return `Edited ${w.path} (1 replacement).`
if (w.status === 'unchanged' && w.path) return `No change written to ${w.path} (content already matched).`
return JSON.stringify(w)
}
-async function executeFileList(args: Record<string, any>): Promise<string> {
+async function executeFileList(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const data = await backendCall('fs_list', {
path: args.path,
recursive: args.recursive || false,
pattern: args.pattern || null,
// NOTE: the model does NOT get to pick the jail root. `workingDirectory`
// comes only from chatCtx() (the active, user-chosen workspace). The
- // file-tree UI browser needs to list arbitrary picked folders, so it calls
- // the `fs_list` backend command DIRECTLY (FileTree.tsx) instead of through
+ // explorer UI needs to list arbitrary picked folders, so it calls the
+ // `fs_list` backend command DIRECTLY (ExplorerPanel.tsx) instead of through
// this model tool. Security review 2.5.7: passing the model's own
// `workingDirectory` through here let a prompt-injected model set
// `workingDirectory: "C:/Users/<user>/.ssh"` and enumerate any directory.
- ...chatCtx(),
+ ...chatCtx(run),
})
if (Array.isArray(data.entries)) {
return data.entries
@@ -602,12 +603,12 @@ async function executeFileList(args: Record<string, any>): Promise<string> {
return JSON.stringify(data)
}
-async function executeFileSearch(args: Record<string, any>): Promise<string> {
+async function executeFileSearch(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const data = await backendCall('fs_search', {
path: args.path,
pattern: args.pattern,
max_results: args.maxResults || 50,
- ...chatCtx(),
+ ...chatCtx(run),
})
if (Array.isArray(data.results)) {
return data.results
@@ -620,13 +621,13 @@ async function executeFileSearch(args: Record<string, any>): Promise<string> {
return JSON.stringify(data)
}
-async function executeShellExecute(args: Record<string, any>): Promise<string> {
+async function executeShellExecute(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
// Background-task actions: the three shell_task_* tools folded in (2.6.6).
const task = typeof args.task === 'string' ? args.task : ''
if (task === 'list') return executeShellTaskList()
if (task === 'status' || task === 'kill') {
- if (task === 'kill' && isReadOnlyShellTurn()) {
- return 'Refused: this turn is read-only (/review or Code-Review Mode); killing a task changes state.'
+ if (task === 'kill' && isReadOnlyShellTurn(run)) {
+ return 'Refused: this turn is read-only (/review, Code-Review Mode or Plan mode); killing a task changes state.'
}
const id = args.task_id ?? args.id
if (!id) return `shell_execute: task "${task}" needs a task_id.`
@@ -642,8 +643,8 @@ async function executeShellExecute(args: Record<string, any>): Promise<string> {
// Read-only turn (/review …): the classifier is the gate now that the typed
// read-only inspectors are gone. Conservative on purpose: chained commands
// are refused outright, a read-only mode that can be talked around is none.
- if (isReadOnlyShellTurn() && (args.background || !isReadOnlyCommand(command))) {
- return 'Refused: this turn is read-only (/review or Code-Review Mode). Only inspection commands run here: git status/log/diff/show/blame, ls, cat, pwd. One command, no chaining.'
+ if (isReadOnlyShellTurn(run) && (args.background || !isReadOnlyCommand(command))) {
+ return 'Refused: this turn is read-only (/review, Code-Review Mode or Plan mode). Only inspection commands run here: git status/log/diff/show/blame, ls, cat, pwd. One command, no chaining.'
}
if (args.background) return executeShellExecuteBg({ command, cwd: args.cwd })
@@ -662,7 +663,7 @@ async function executeShellExecute(args: Record<string, any>): Promise<string> {
timeout,
shell: args.shell || null,
stdin: typeof args.stdin === 'string' && args.stdin ? args.stdin : null,
- ...chatCtx(),
+ ...chatCtx(run),
})
const output = data.stdout || ''
const err = data.stderr || ''
@@ -699,8 +700,8 @@ async function executeShellExecute(args: Record<string, any>): Promise<string> {
return output || (err ? `stderr: ${err}` : 'Done.')
}
-async function executeCodeExecute(args: Record<string, any>): Promise<string> {
- const data = await backendCall('execute_code', { code: args.code, timeout: 30000, ...chatCtx() })
+async function executeCodeExecute(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
+ const data = await backendCall('execute_code', { code: args.code, timeout: 30000, ...chatCtx(run) })
const output = data.stdout || ''
const err = data.stderr || ''
if (data.timedOut) return `Timed out.\n${err}`
@@ -708,22 +709,22 @@ async function executeCodeExecute(args: Record<string, any>): Promise<string> {
return output || (err ? `stderr: ${err}` : 'Done.')
}
-async function runShell(command: string, cwd: string | undefined, timeout = 60000) {
+async function runShell(command: string, cwd: string | undefined, timeout = 60000, run?: AgentRunContext) {
return backendCall('shell_execute', {
command,
args: null,
cwd: cwd || null,
timeout,
shell: null,
- ...chatCtx(),
+ ...chatCtx(run),
})
}
-async function executeShellExecuteBg(args: Record<string, any>): Promise<string> {
+async function executeShellExecuteBg(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const { bgStart } = await import('../agents/bg-tasks')
// Thread the chat context through, or the task starts in LU's own directory
// instead of the workspace the foreground shell tool uses.
- const { id } = await bgStart({ command: args.command, cwd: args.cwd, ...chatCtx() })
+ const { id } = await bgStart({ command: args.command, cwd: args.cwd, ...chatCtx(run) })
return `Task started: ${id}. Use shell_task_status to poll, shell_task_kill to cancel.`
}
@@ -748,9 +749,9 @@ async function executeShellTaskList(): Promise<string> {
return tasks.map(renderBgStatusOneLine).join('\n')
}
-async function executeGitStatus(args: Record<string, any>): Promise<string> {
+async function executeGitStatus(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const { parseGitStatus, renderGitStatus } = await import('../agents/git-tools')
- const data = await runShell('git status --porcelain=2 --branch', args.cwd)
+ const data = await runShell('git status --porcelain=2 --branch', args.cwd, undefined, run)
if (data.exitCode && data.exitCode !== 0) {
return `git_status failed: ${data.stderr || data.stdout || `exit ${data.exitCode}`}`
}
@@ -758,7 +759,7 @@ async function executeGitStatus(args: Record<string, any>): Promise<string> {
return renderGitStatus(parsed)
}
-async function executeGitCommit(args: Record<string, any>): Promise<string> {
+async function executeGitCommit(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const { buildGitCommitCommand } = await import('../agents/git-tools')
const cmd = buildGitCommitCommand({
message: args.message,
@@ -766,7 +767,7 @@ async function executeGitCommit(args: Record<string, any>): Promise<string> {
allTracked: !!args.allTracked,
})
if (!cmd) return 'git_commit: a non-empty `message` is required.'
- const data = await runShell(cmd, args.cwd)
+ const data = await runShell(cmd, args.cwd, undefined, run)
const output = `${data.stdout || ''}\n${data.stderr || ''}`.trim()
if (data.exitCode && data.exitCode !== 0) {
return `git_commit failed (exit ${data.exitCode}):\n${output}`
@@ -775,14 +776,14 @@ async function executeGitCommit(args: Record<string, any>): Promise<string> {
return m ? `Committed on ${m[1]} as ${m[2]}.\n${output}` : output
}
-async function executeGitPush(args: Record<string, any>): Promise<string> {
+async function executeGitPush(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const { shellQuote } = await import('../agents/git-tools')
const flags: string[] = []
if (args.setUpstream) flags.push('-u')
if (args.remote) flags.push(shellQuote(args.remote))
if (args.branch) flags.push(shellQuote(args.branch))
const cmd = `git push ${flags.join(' ')}`.trim()
- const data = await runShell(cmd, args.cwd, 120000)
+ const data = await runShell(cmd, args.cwd, 120000, run)
const output = `${data.stdout || ''}\n${data.stderr || ''}`.trim()
if (data.exitCode && data.exitCode !== 0) {
return `git_push failed (exit ${data.exitCode}):\n${output}`
@@ -790,11 +791,11 @@ async function executeGitPush(args: Record<string, any>): Promise<string> {
return output || 'git push: ok.'
}
-async function executeGitLog(args: Record<string, any>): Promise<string> {
+async function executeGitLog(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const { parseGitLog } = await import('../agents/git-tools')
const limit = typeof args.limit === 'number' ? Math.max(1, Math.min(200, args.limit)) : 20
const cmd = `git log --oneline -n ${limit}`
- const data = await runShell(cmd, args.cwd)
+ const data = await runShell(cmd, args.cwd, undefined, run)
if (data.exitCode && data.exitCode !== 0) {
return `git_log failed: ${data.stderr || data.stdout || `exit ${data.exitCode}`}`
}
@@ -803,13 +804,13 @@ async function executeGitLog(args: Record<string, any>): Promise<string> {
return entries.map((e) => `${e.sha} ${e.subject}`).join('\n')
}
-async function executeGitDiff(args: Record<string, any>): Promise<string> {
+async function executeGitDiff(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const { shellQuote } = await import('../agents/git-tools')
const parts = ['git', 'diff']
if (args.staged) parts.push('--cached')
if (args.ref) parts.push(shellQuote(String(args.ref)))
if (args.path) parts.push('--', shellQuote(String(args.path)))
- const data = await runShell(parts.join(' '), args.cwd, 120000)
+ const data = await runShell(parts.join(' '), args.cwd, 120000, run)
if (data.exitCode && data.exitCode !== 0 && data.exitCode !== 1) {
return `git_diff failed: ${data.stderr || `exit ${data.exitCode}`}`
}
@@ -838,7 +839,7 @@ async function executeProjectInit(args: Record<string, any>): Promise<string> {
return renderInitPlan(recipe)
}
-async function executePrResume(args: Record<string, any>): Promise<string> {
+async function executePrResume(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const { parsePrUrl, normalisePrJson, renderPrResume } = await import('../agents/pr-resume')
const { shellQuote } = await import('../agents/git-tools')
const loc = parsePrUrl(String(args.url ?? ''))
@@ -851,6 +852,7 @@ async function executePrResume(args: Record<string, any>): Promise<string> {
`gh pr view ${loc.number} --repo ${repo} --json title,body,state,headRefName,baseRefName,author,comments`,
args.cwd,
60000,
+ run,
)
if (view.exitCode && view.exitCode !== 0) {
return `pr_resume: gh pr view failed (exit ${view.exitCode}): ${view.stderr || view.stdout || ''}`
@@ -866,6 +868,7 @@ async function executePrResume(args: Record<string, any>): Promise<string> {
`gh pr diff ${loc.number} --repo ${repo}`,
args.cwd,
60000,
+ run,
)
return renderPrResume({
...meta,
@@ -873,7 +876,7 @@ async function executePrResume(args: Record<string, any>): Promise<string> {
})
}
-async function executeGhPrCreate(args: Record<string, any>): Promise<string> {
+async function executeGhPrCreate(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const { buildGhPrCreateCommand } = await import('../agents/git-tools')
const cmd = buildGhPrCreateCommand({
title: args.title,
@@ -881,7 +884,7 @@ async function executeGhPrCreate(args: Record<string, any>): Promise<string> {
base: args.base,
})
if (!cmd) return 'gh_pr_create: a non-empty `title` is required.'
- const data = await runShell(cmd, args.cwd, 60000)
+ const data = await runShell(cmd, args.cwd, 60000, run)
const output = `${data.stdout || ''}\n${data.stderr || ''}`.trim()
if (data.exitCode && data.exitCode !== 0) {
return `gh_pr_create failed (exit ${data.exitCode}):\n${output}`
@@ -891,7 +894,7 @@ async function executeGhPrCreate(args: Record<string, any>): Promise<string> {
return urlMatch ? `Opened PR: ${urlMatch[0]}\n${output}` : output
}
-async function executeRunTests(args: Record<string, any>): Promise<string> {
+async function executeRunTests(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
const { commandForRunner, detectRunnerFromFiles, parseForRunner, renderResult } =
await import('../agents/test-runner')
@@ -905,7 +908,7 @@ async function executeRunTests(args: Record<string, any>): Promise<string> {
const listing = await backendCall('fs_list', {
path: '.',
recursive: false,
- ...chatCtx(),
+ ...chatCtx(run),
})
// fs_list returns { entries, count } — NOT `items`. Reading the wrong
// key made `names` always [] → detectRunnerFromFiles([]) = 'unknown' →
@@ -931,7 +934,7 @@ async function executeRunTests(args: Record<string, any>): Promise<string> {
cwd: args.cwd || null,
timeout: args.timeout || 300000,
shell: null,
- ...chatCtx(),
+ ...chatCtx(run),
}
const data = await backendCall('shell_execute', shellArgs)
if (data.timedOut) {
@@ -1213,14 +1216,14 @@ async function executeVideoGenerateMlx(prompt: string, merged: Record<string, an
return 'Video generation timed out after 60 minutes; the generation was stopped.'
}
-async function executeTodoWrite(args: Record<string, any>): Promise<string> {
+async function executeTodoWrite(args: Record<string, any>, run?: AgentRunContext): Promise<string> {
// Purely conversation state: no backend call, no permission gate, nothing
// that can fail on a machine. The one real failure is having no conversation
// to attach the plan to, which happens when a tool runs outside a loop.
// The CONVERSATION id, not getActiveChatId(): that one is a filesystem slug
// derived from id + title, and PlanBar reads the plan out of chatStore by the
// real id. Keying by the slug wrote the plan where nothing ever looks.
- const convId = getActiveConversationId()
+ const convId = getActiveConversationId(run)
if (!convId) return 'Error: no active conversation to attach a plan to.'
const todos = writeTodos(convId, args.todos)
@@ -1381,7 +1384,7 @@ const RETIRED_HINT: Record<string, string> = {
shell_task_list: 'shell_execute with task: "list"',
}
-const RETIRED_EXECUTORS: Record<string, (args: Record<string, any>) => Promise<string>> = {
+const RETIRED_EXECUTORS: Record<string, (args: Record<string, any>, run?: AgentRunContext) => Promise<string>> = {
git_status: executeGitStatus,
git_log: executeGitLog,
git_diff: executeGitDiff,
@@ -1422,15 +1425,16 @@ export const RETIRED_EXECUTOR_NAMES: ReadonlySet<string> = new Set(Object.keys(R
export async function runRetiredTool(
name: string,
args: Record<string, any>,
+ run?: AgentRunContext,
): Promise<string | null> {
- const run = RETIRED_EXECUTORS[name]
- if (!run) return null
+ const exec = RETIRED_EXECUTORS[name]
+ if (!exec) return null
// The read-only gate lives on shell_execute's command classifier; a retired
// mutating name would walk straight past it via this redirect.
- if (isReadOnlyShellTurn() && RETIRED_MUTATING_NAMES.has(name)) {
- return `Refused: this turn is read-only (/review or Code-Review Mode); ${name} changes state.`
+ if (isReadOnlyShellTurn(run) && RETIRED_MUTATING_NAMES.has(name)) {
+ return `Refused: this turn is read-only (/review, Code-Review Mode or Plan mode); ${name} changes state.`
}
- const result = await run(args)
+ const result = await exec(args, run)
const hint = RETIRED_HINT[name]
return hint ? `${result}\n\n(Note: ${name} is retired, next time use ${hint}.)` : result
}
diff --git a/src/api/mcp/tool-registry.ts b/src/api/mcp/tool-registry.ts
index 449f4167..1fbc5e1d 100644
--- a/src/api/mcp/tool-registry.ts
+++ b/src/api/mcp/tool-registry.ts
@@ -5,8 +5,18 @@ import type { OllamaTool } from '../../types/agent-mode'
import type { ToolDefinition } from '../providers/types'
import { MUTATING_TOOLS } from '../../lib/mutating-tools'
import { RETIRED_TOOL_NAMES, retiredPermissionLevel } from '../../lib/retired-tools'
+import type { AgentRunContext } from '../agent-context'
-type ToolExecutor = (args: Record<string, any>) => Promise<string>
+/**
+ * The optional second argument is the run this call belongs to (plan 2.6.6 C1).
+ * Tools whose gate depends on the run (read-only turn, todo target
+ * conversation, artifact capture, workspace jail) read it from there instead of
+ * the process-wide singleton, so a second interleaving run cannot move their
+ * goalposts mid-call. Tools that do not care simply ignore it.
+ */
+type ToolExecutor = (args: Record<string, any>, run?: AgentRunContext) => Promise<string>
+/** The pre-2.6.6 shape, still accepted from external servers and tests. */
+type LegacyToolExecutor = (args: Record<string, any>) => Promise<string>
/**
* External-tool executor gets the tool name too, because one MCP server
* owns many tools and routes by name. The registry wraps it into a
@@ -41,7 +51,7 @@ export class ToolRegistry {
registerExternal(
serverId: string,
tools: MCPToolDefinition[],
- executor: ExternalToolExecutor | ToolExecutor
+ executor: ExternalToolExecutor | LegacyToolExecutor
) {
const isTwoArg = executor.length >= 2
for (const tool of tools) {
@@ -49,7 +59,7 @@ export class ToolRegistry {
const bound: ToolExecutor = isTwoArg
? (args: Record<string, any>) =>
(executor as ExternalToolExecutor)(name, args)
- : (executor as ToolExecutor)
+ : (executor as LegacyToolExecutor)
this.tools.set(name, {
definition: { ...tool, source: 'external', serverId },
executor: bound,
@@ -123,14 +133,19 @@ export class ToolRegistry {
// ── Execution ─────────────────────────────────────────────────
- async execute(name: string, args: Record<string, any>, maxRetries = 1): Promise<string> {
+ async execute(
+ name: string,
+ args: Record<string, any>,
+ maxRetries = 1,
+ run?: AgentRunContext,
+ ): Promise<string> {
const entry = this.tools.get(name)
if (!entry) {
// Retired names (2.6.6 tool merge) still run: a restored session or a
// model that knows git_status from its context must not burn the step
// on "Unknown tool". Dynamic import keeps the module graph acyclic.
const { runRetiredTool } = await import('./builtin-tools')
- const redirected = await runRetiredTool(name, args)
+ const redirected = await runRetiredTool(name, args, run)
if (redirected !== null) return redirected
return `Error: Unknown tool "${name}"`
}
@@ -144,7 +159,7 @@ export class ToolRegistry {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
- const result = await entry.executor(args)
+ const result = await entry.executor(args, run)
// If result is an error and we have retries left, retry
if (result.startsWith('Error:') && attempt < maxRetries) {
// Only retry on transient errors (timeout, network)
diff --git a/src/components/chat/CodexModeDropdown.tsx b/src/components/chat/CodexModeDropdown.tsx
new file mode 100644
index 00000000..cc1a0ae2
--- /dev/null
+++ b/src/components/chat/CodexModeDropdown.tsx
@@ -0,0 +1,161 @@
+import { useState } from 'react'
+import { ChevronDown, ShieldCheck, Zap, ClipboardList, Cloud } from 'lucide-react'
+import { useChatStore } from '../../stores/chatStore'
+import { useCodexStore } from '../../stores/codexStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import {
+ CODEX_MODES, CODEX_MODE_LABELS, CODEX_MODE_SHORT, CODEX_MODE_DESCRIPTIONS,
+ resolveCodexMode, type CodexMode,
+} from '../../lib/codex-mode'
+
+/**
+ * Ask / Bypass / Plan for the Coding Agent (plan 2.6.6, C1).
+ *
+ * Lives in the CODE composer only, hooked in through ChatInput's
+ * `composerActions` so ChatInput itself stays surface-neutral and the Chat tab
+ * inherits nothing. The mode is remembered per conversation, with
+ * settings.codexDefaultMode as the fallback; picking one here NEVER writes the
+ * global settings, so another conversation and the Agent surface are untouched.
+ *
+ * A switch takes effect from the NEXT send. While a run is in flight the
+ * trigger says so and the pick is parked, because the running turn resolved its
+ * knobs when it started and quietly changing them mid-run is how a read-only
+ * guarantee gets lost.
+ */
+const MODE_ICON: Record<CodexMode, typeof ShieldCheck> = {
+ ask: ShieldCheck,
+ bypass: Zap,
+ plan: ClipboardList,
+}
+
+const MODE_ACCENT: Record<CodexMode, string> = {
+ ask: 'text-blue-400',
+ bypass: 'text-amber-400',
+ plan: 'text-purple-400',
+}
+
+const MODE_ACTIVE_ROW: Record<CodexMode, string> = {
+ ask: 'bg-blue-500/10 text-blue-600 dark:text-blue-400',
+ bypass: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',
+ plan: 'bg-purple-500/10 text-purple-600 dark:text-purple-400',
+}
+
+export function CodexModeDropdown({ openUpward = false }: { openUpward?: boolean } = {}) {
+ const [open, setOpen] = useState(false)
+ const activeConvId = useChatStore((s) => s.activeConversationId)
+ const defaultMode = useSettingsStore((s) => s.settings.codexDefaultMode)
+ const modeByConversation = useCodexStore((s) => s.modeByConversation)
+ const parkedByConversation = useCodexStore((s) => s.parkedModeByConversation)
+ const chooseCodexMode = useCodexStore((s) => s.chooseCodexMode)
+ const generating = useGenerationStore((s) => s.generating)
+
+ const runActive = !!activeConvId && generating[activeConvId] === true
+ const current = resolveCodexMode(
+ activeConvId ? modeByConversation[activeConvId] : undefined,
+ defaultMode,
+ )
+ const parked = activeConvId ? parkedByConversation[activeConvId] : undefined
+ // Only worth showing while a run holds the change back. Once it is applied,
+ // parked and current are the same value.
+ const pending = runActive && parked && parked !== current ? parked : null
+
+ const CurrentIcon = MODE_ICON[current]
+
+ const pick = (mode: CodexMode) => {
+ if (!activeConvId) return
+ chooseCodexMode(activeConvId, mode, runActive)
+ setOpen(false)
+ }
+
+ return (
+ <div className="relative">
+ <button
+ onClick={() => setOpen(!open)}
+ title={
+ runActive
+ ? 'A run is in flight. A change here applies to the next message.'
+ : CODEX_MODE_DESCRIPTIONS[current]
+ }
+ className="flex items-center gap-1 px-2 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500 transition-colors text-[0.55rem]"
+ >
+ <CurrentIcon size={10} className={MODE_ACCENT[current]} />
+ <span className={MODE_ACCENT[current]}>{CODEX_MODE_SHORT[current]}</span>
+ {pending ? (
+ <span className="text-[0.5rem] text-amber-500">
+ {`then ${CODEX_MODE_SHORT[pending]}`}
+ </span>
+ ) : runActive ? (
+ // A run is in flight and nothing is parked yet. Say it on the
+ // trigger, not only in the panel, so "applies to the next message" is
+ // visible before the user clicks.
+ <span className="w-1 h-1 rounded-full bg-amber-400" />
+ ) : null}
+ <ChevronDown size={8} className={`transition-transform ${open ? 'rotate-180' : ''}`} />
+ </button>
+
+ {open && (
+ <>
+ <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
+ <div className={`absolute right-0 z-50 w-60 rounded-lg bg-white dark:bg-[#262626] border border-gray-200 dark:border-white/10 shadow-xl py-1.5 ${openUpward ? 'bottom-full mb-1' : 'top-full mt-1'}`}>
+ {!activeConvId ? (
+ <p className="px-3 py-1.5 text-[0.5rem] text-gray-400">
+ Open a coding chat first, the mode lives on the conversation.
+ </p>
+ ) : (
+ <>
+ {runActive && (
+ <p className="px-3 pb-1 text-[0.5rem] leading-snug text-amber-600 dark:text-amber-400/90">
+ A run is in flight. Your pick applies from the next message.
+ </p>
+ )}
+ <div className="px-1.5 space-y-0.5">
+ {CODEX_MODES.map((mode) => {
+ const Icon = MODE_ICON[mode]
+ const isActive = mode === current
+ const isPending = mode === pending
+ return (
+ <button
+ key={mode}
+ onClick={() => pick(mode)}
+ className={`w-full flex items-start gap-1.5 px-2 py-1 rounded text-left transition-colors ${
+ isActive
+ ? MODE_ACTIVE_ROW[mode]
+ : 'text-gray-500 hover:bg-gray-50 dark:hover:bg-white/[0.04] hover:text-gray-700 dark:hover:text-gray-300'
+ }`}
+ >
+ <Icon size={10} className={`mt-px shrink-0 ${isActive ? '' : 'text-gray-400'}`} />
+ <span className="min-w-0">
+ <span className="flex items-center gap-1">
+ <span className="text-[0.55rem] font-medium">{CODEX_MODE_LABELS[mode]}</span>
+ {isActive && <span className="text-[0.45rem] text-gray-400">active</span>}
+ {isPending && <span className="text-[0.45rem] text-amber-500">next</span>}
+ </span>
+ <span className="block text-[0.5rem] leading-snug text-gray-400">
+ {CODEX_MODE_DESCRIPTIONS[mode]}
+ </span>
+ </span>
+ </button>
+ )
+ })}
+ </div>
+ {/* The one thing Bypass deliberately does NOT lift. Said here
+ because a switch labelled "bypass permissions" that still
+ asks would otherwise read as a broken toggle. */}
+ <div className="mt-1 pt-1 border-t border-gray-200 dark:border-white/[0.06] px-3">
+ <p className="flex items-start gap-1 py-1 text-[0.5rem] leading-snug text-gray-400">
+ <Cloud size={9} className="mt-px shrink-0" />
+ <span>
+ Bypass never lifts the cloud shell confirm. A remote model reaching your
+ local shell unattended stays a decision you make each time.
+ </span>
+ </p>
+ </div>
+ </>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index d17db6ce..b60021b7 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -15,6 +15,8 @@ import { SmallModelModeToggle } from './SmallModelModeToggle'
import { WorkingAnchor } from './WorkingAnchor'
import { useCodexConfirmStore } from '../../stores/codexConfirmStore'
import { PluginsDropdown } from './PluginsDropdown'
+import { CodexModeDropdown } from './CodexModeDropdown'
+import { PlanApprovalBar } from './PlanApprovalBar'
import { ModelSelector } from '../models/ModelSelector'
import { GoalBar } from './GoalBar'
import { LoopBar } from './LoopBar'
@@ -508,8 +510,11 @@ export function CodexView() {
isGenerating={isRunning || codexGenerating}
slashCommands
composerModel={<ModelSelector openUpward surface="code" />}
- composerAbove={<><LoopBar onStop={stopCodex} /><GoalBar /></>}
- composerActions={<PluginsDropdown openUpward />}
+ composerAbove={<><LoopBar onStop={stopCodex} /><GoalBar /><PlanApprovalBar onApprove={(text) => sendInstruction(text)} /></>}
+ // Ask / Bypass / Plan sits here, in the CODE composer only (plan
+ // C1). ChatInput stays surface-neutral, so the Chat tab inherits
+ // nothing from it.
+ composerActions={<><CodexModeDropdown openUpward /><PluginsDropdown openUpward /></>}
/>
</div>
diff --git a/src/components/chat/PlanApprovalBar.tsx b/src/components/chat/PlanApprovalBar.tsx
new file mode 100644
index 00000000..3c8a9faf
--- /dev/null
+++ b/src/components/chat/PlanApprovalBar.tsx
@@ -0,0 +1,87 @@
+// "Approve and run" after a Plan-mode run (plan 2.6.6, C1 / blocker S7).
+//
+// The plan is a function of UNTRUSTED repo content: a README, a file name or an
+// AGENTS.md in the workspace can steer what it says. So two things are fixed
+// here and are not up for convenience:
+//
+// 1. The card shows the FULL plan text, the concrete commands and target
+// paths, not the todo titles. The user approves what they can read.
+// 2. The execution never lands in Bypass implicitly. The target mode is
+// resolved from the user's own visible choices and printed ON the button,
+// so "Approve and run (Ask)" is a promise about what happens next.
+
+import { useState } from 'react'
+import { ClipboardCheck, ChevronDown, X } from 'lucide-react'
+import { useChatStore } from '../../stores/chatStore'
+import { useCodexStore } from '../../stores/codexStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { resolveApproveTargetMode, CODEX_MODE_SHORT, CODEX_MODE_DESCRIPTIONS } from '../../lib/codex-mode'
+import { CODEX_PLAN_APPROVED_INSTRUCTION } from '../../lib/codex-plan-prompt'
+
+export function PlanApprovalBar({ onApprove }: { onApprove: (instruction: string) => void }) {
+ const [expanded, setExpanded] = useState(true)
+ const activeConversationId = useChatStore((s) => s.activeConversationId)
+ const approval = useCodexStore((s) =>
+ activeConversationId ? s.planApprovalByConversation[activeConversationId] : undefined,
+ )
+ const parked = useCodexStore((s) =>
+ activeConversationId ? s.parkedModeByConversation[activeConversationId] : undefined,
+ )
+ const prePlan = useCodexStore((s) =>
+ activeConversationId ? s.prePlanModeByConversation[activeConversationId] : undefined,
+ )
+ const chooseCodexMode = useCodexStore((s) => s.chooseCodexMode)
+ const setPlanApproval = useCodexStore((s) => s.setPlanApproval)
+ const generating = useGenerationStore((s) => s.generating)
+
+ if (!activeConversationId || !approval) return null
+ // A run is already going: the card would offer a second parallel send.
+ if (generating[activeConversationId] === true) return null
+
+ const target = resolveApproveTargetMode({ parked, previous: prePlan })
+
+ const approve = () => {
+ // Switch the conversation out of Plan mode FIRST, so the send that follows
+ // resolves its knobs under the mode printed on the button.
+ chooseCodexMode(activeConversationId, target, false)
+ setPlanApproval(activeConversationId, null)
+ onApprove(CODEX_PLAN_APPROVED_INSTRUCTION)
+ }
+
+ return (
+ <div className="w-full max-w-[70%] mx-auto px-3 pb-1">
+ <div className="w-full rounded-md border border-purple-500/25 bg-purple-500/[0.04]">
+ <div className="flex items-center gap-1.5 px-2 py-1">
+ <ClipboardCheck size={9} className="text-purple-400 shrink-0" />
+ <span className="text-[0.55rem] uppercase tracking-wider text-gray-500 shrink-0">plan ready</span>
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="flex-1 min-w-0 flex items-center gap-1 text-left text-[0.55rem] text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
+ >
+ <span>{expanded ? 'Hide the full plan' : 'Show the full plan'}</span>
+ <ChevronDown size={9} className={`transition-transform ${expanded ? 'rotate-180' : ''}`} />
+ </button>
+ <button
+ onClick={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"
+ >
+ {`Approve and run (${CODEX_MODE_SHORT[target]})`}
+ </button>
+ <button
+ onClick={() => setPlanApproval(activeConversationId, null)}
+ title="Dismiss the plan without running it"
+ className="flex items-center justify-center w-4 h-4 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors shrink-0"
+ >
+ <X size={10} />
+ </button>
+ </div>
+ {expanded && (
+ <pre className="mx-2 mb-1.5 max-h-56 overflow-auto scrollbar-thin whitespace-pre-wrap break-words rounded bg-black/[0.03] dark:bg-white/[0.03] px-2 py-1.5 text-[0.55rem] leading-relaxed text-gray-700 dark:text-gray-300">
+ {approval.planText}
+ </pre>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/chat/__tests__/plan-done-vs-applied.test.ts b/src/components/chat/__tests__/plan-done-vs-applied.test.ts
index 38740eb7..9fe167d5 100644
--- a/src/components/chat/__tests__/plan-done-vs-applied.test.ts
+++ b/src/components/chat/__tests__/plan-done-vs-applied.test.ts
@@ -65,7 +65,9 @@ describe('the plan moved into the panel (C2)', () => {
it('the coding composer no longer carries a plan', () => {
const src = read('../CodexView.tsx')
- expect(src).toMatch(/composerAbove=\{<><LoopBar onStop=\{stopCodex\} \/><GoalBar \/><\/>\}/)
+ // C1 added the plan APPROVAL card here (a button plus the plan text the
+ // user is approving); the plan itself still lives only in the panel.
+ expect(src).toMatch(/composerAbove=\{<><LoopBar onStop=\{stopCodex\} \/><GoalBar \/><PlanApprovalBar /)
expect(src).not.toMatch(/PlanBar/)
})
diff --git a/src/hooks/__tests__/agent-shell-gate.test.ts b/src/hooks/__tests__/agent-shell-gate.test.ts
index bb7057fb..f9b0edc6 100644
--- a/src/hooks/__tests__/agent-shell-gate.test.ts
+++ b/src/hooks/__tests__/agent-shell-gate.test.ts
@@ -67,8 +67,12 @@ describe('wiring in useAgentChat', () => {
it('NEGATIVE CONTROL: the Codex side of the gate is untouched', () => {
const codex = read('../useCodex.ts')
- expect(codex).toContain('confirmShell: settings.codexConfirmShell')
- expect(codex).toContain('cloudConfirmShell: settings.codexCloudConfirmShell')
+ // Since 2.6.6 C1 the Code tab feeds the SAME two settings into the shared
+ // gate through the mode preset instead of calling it inline. Same inputs,
+ // same helper, and the cloud arm survives all three modes.
+ expect(codex).toContain('codexModeKnobs({')
+ expect(codex).toContain('codexConfirmShell: settings.codexConfirmShell')
+ expect(codex).toContain('codexCloudConfirmShell: settings.codexCloudConfirmShell')
})
it('the settings toggle is always visible now, since it governs Agent too', () => {
diff --git a/src/hooks/__tests__/codex-create-tool-gate.test.ts b/src/hooks/__tests__/codex-create-tool-gate.test.ts
index b013f004..25f83d65 100644
--- a/src/hooks/__tests__/codex-create-tool-gate.test.ts
+++ b/src/hooks/__tests__/codex-create-tool-gate.test.ts
@@ -169,7 +169,10 @@ describe('the wiring in useCodex', () => {
it('the asset line never fires in review mode or on a read-only command', () => {
// A read-only slash command strips MUTATING_TOOLS for the turn, so the
// generators are gone there too. Promising them is the same broken promise.
- expect(src).toMatch(/!reviewMode && !readOnlyTurn && !settings\.smallModelMode/)
+ // Since 2.6.6 C1 the three read-only reasons (Code-Review Mode, a read-only
+ // slash command, Plan mode) are one flag, and the asset line reads it.
+ expect(src).toMatch(/const assetsPossible = !effectiveReadOnly && !settings\.smallModelMode/)
+ expect(src).toMatch(/const effectiveReadOnly = settings\.codexReviewMode === true \|\| readOnlyTurn \|\| codexMode === 'plan'/)
})
it('the asset promise left the always-on prompt body', () => {
diff --git a/src/hooks/__tests__/codex-mode-wiring.test.ts b/src/hooks/__tests__/codex-mode-wiring.test.ts
new file mode 100644
index 00000000..481d4146
--- /dev/null
+++ b/src/hooks/__tests__/codex-mode-wiring.test.ts
@@ -0,0 +1,175 @@
+/**
+ * C1 BINDUNG: the presets sit OVER the existing knobs and never write them.
+ *
+ * There is no render harness for these hooks in this repo, so the binding
+ * properties are guarded at the source the same way decay-wiring.test.ts guards
+ * the request builder. Each of these is something a well-meaning refactor would
+ * undo silently, and each has a price:
+ *
+ * - resolving the mode outside sendInstruction breaks "applies from the next
+ * send" outright,
+ * - a preset that writes settings.codexConfirmShell reaches the Agent surface
+ * immediately, because codexShellGate is consumed by BOTH loops since G15a,
+ * - a switch point still reading the raw setting means the preset is
+ * decorative on exactly that switch.
+ *
+ * The live half (settings really are untouched by a pick) is the runtime block
+ * at the bottom, against the real settings store.
+ *
+ * Run: npx vitest run src/hooks/__tests__/codex-mode-wiring.test.ts
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+
+const backing = new Map<string, string>()
+;(globalThis as unknown as { window: unknown }).window = globalThis
+globalThis.localStorage = {
+ getItem: (k: string) => backing.get(k) ?? null,
+ setItem: (k: string, v: string) => void backing.set(k, String(v)),
+ removeItem: (k: string) => void backing.delete(k),
+ clear: () => backing.clear(),
+ key: (i: number) => [...backing.keys()][i] ?? null,
+ get length() { return backing.size },
+} as Storage
+
+const read = (file: string) => readFileSync(resolve(__dirname, '..', file), 'utf8')
+const codex = read('useCodex.ts')
+const agent = read('useAgentChat.ts')
+
+const { useCodexStore } = await import('../../stores/codexStore')
+const { useSettingsStore } = await import('../../stores/settingsStore')
+
+describe('the mode is resolved per send, from the conversation', () => {
+ it('applies a parked pick at the start of the send', () => {
+ expect(codex).toMatch(/applyParkedMode\(convId\)/)
+ })
+
+ it('resolves the mode against settings.codexDefaultMode, per send', () => {
+ expect(codex).toMatch(/codexModeFor\(convId, settings\.codexDefaultMode\)/)
+ })
+
+ it('derives the effective knobs from the mode plus the settings', () => {
+ expect(codex).toMatch(/const knobs = codexModeKnobs\(\{/)
+ expect(codex).toMatch(/mode: codexMode,/)
+ })
+})
+
+describe('the three switch points read the preset, not the raw setting', () => {
+ it('the exec confirm gate is knobs.confirmExec', () => {
+ expect(codex).toMatch(/awaitApproval: knobs\.confirmExec/)
+ // Negative control: the pre-C1 shape called the gate inline with the
+ // setting, which no preset could reach.
+ expect(codex).not.toMatch(/awaitApproval: codexConfirmEnabled\(\{/)
+ })
+
+ it('Stage-and-Approve is knobs.stageWrites', () => {
+ expect(codex).toMatch(/if \(knobs\.stageWrites\) \{/)
+ expect(codex).not.toMatch(/if \(settings\.codexStageMode\) \{/)
+ })
+
+ it('the read-only chain is one flag, and all three gates use it', () => {
+ expect(codex).toMatch(/const effectiveReadOnly = settings\.codexReviewMode === true \|\| readOnlyTurn \|\| codexMode === 'plan'/)
+ // catalog strip (native), catalog strip (hermes), runtime mutation filter
+ expect(codex.match(/effectiveReadOnly/g)?.length ?? 0).toBeGreaterThanOrEqual(5)
+ // Negative control: the old pair that hung on the slash flag alone.
+ expect(codex).not.toMatch(/settings\.codexReviewMode \|\| readOnlyTurn/)
+ })
+
+ it('the run carries the read-only flag, so the executor gates check THIS run', () => {
+ expect(codex).toMatch(/readOnlyShellTurn: effectiveReadOnly/)
+ expect(codex).not.toMatch(/setReadOnlyShellTurn\(/)
+ })
+})
+
+describe('a preset never writes the global settings', () => {
+ it('useCodex does not call updateSettings at all', () => {
+ expect(codex).not.toMatch(/updateSettings\(/)
+ })
+
+ it('the store action that the dropdown calls is per conversation', () => {
+ // chooseCodexMode takes a conversation id; there is no global setter.
+ const store = readFileSync(resolve(__dirname, '../../stores/codexStore.ts'), 'utf8')
+ expect(store).toMatch(/chooseCodexMode: \(conversationId, mode, runActive\)/)
+ expect(store).not.toMatch(/updateSettings/)
+ })
+})
+
+describe('the Agent surface is untouched by the Code tab mode', () => {
+ it('its cloud shell gate inputs are settings-only, byte for byte', () => {
+ expect(agent).toContain(
+ 'codexConfirmEnabled({\n'
+ + ' confirmShell: false,\n'
+ + ' cloudConfirmShell: settings.codexCloudConfirmShell,\n'
+ + ' providerId,\n'
+ + ' })',
+ )
+ })
+
+ it('never imports the mode model', () => {
+ expect(agent).not.toMatch(/codex-mode/)
+ expect(agent).not.toMatch(/codexModeKnobs|codexModeFor|CodexMode\b/)
+ })
+
+ it('opens its run with mode null, so no preset can be inferred from it', () => {
+ expect(agent).toMatch(/mode: null,/)
+ })
+})
+
+describe('cleanup is owned by the run, not by whoever finishes last', () => {
+ it.each([['useCodex', codex], ['useAgentChat', agent]])('%s closes its own run', (_n, source) => {
+ expect(source).toMatch(/endAgentRun\(run\)/)
+ // Negative control: the blind reset that nulled a concurrent run's context.
+ expect(source).not.toMatch(/clearActiveChatId\(\)/)
+ })
+})
+
+describe('runtime: a pick in one conversation leaves everything else alone', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ useCodexStore.setState({
+ modeByConversation: {},
+ parkedModeByConversation: {},
+ prePlanModeByConversation: {},
+ planApprovalByConversation: {},
+ })
+ })
+
+ it('Bypass in X does not move the settings by a single byte', () => {
+ const before = JSON.stringify(useSettingsStore.getState().settings)
+ useCodexStore.getState().chooseCodexMode('X', 'bypass', false)
+ expect(JSON.stringify(useSettingsStore.getState().settings)).toBe(before)
+ })
+
+ it('Bypass in X leaves the Agent surface inputs identical', () => {
+ const inputs = () => {
+ const s = useSettingsStore.getState().settings
+ return JSON.stringify({
+ confirmShell: false,
+ cloudConfirmShell: s.codexCloudConfirmShell,
+ })
+ }
+ const before = inputs()
+ useCodexStore.getState().chooseCodexMode('X', 'bypass', false)
+ expect(inputs()).toBe(before)
+ })
+
+ it('Bypass in X leaves conversation Y on the default, which still asks', () => {
+ useCodexStore.getState().chooseCodexMode('X', 'bypass', false)
+ const defaultMode = useSettingsStore.getState().settings.codexDefaultMode
+ expect(defaultMode).toBe('ask')
+ expect(useCodexStore.getState().codexModeFor('Y', defaultMode)).toBe('ask')
+ })
+
+ it('negative control: the preset-as-settings-write shape trips both assertions', () => {
+ const before = JSON.stringify(useSettingsStore.getState().settings)
+ // Exactly what C1 BINDUNG forbids: pushing the preset into the settings.
+ // Ask is the visible case (confirm on, stage on), and it would follow the
+ // user into every other conversation.
+ useSettingsStore.getState().updateSettings({ codexConfirmShell: true, codexStageMode: true })
+ expect(JSON.stringify(useSettingsStore.getState().settings)).not.toBe(before)
+ // ... and it would have reached the Agent surface through the same object.
+ useSettingsStore.getState().updateSettings({ codexCloudConfirmShell: false })
+ expect(useSettingsStore.getState().settings.codexCloudConfirmShell).toBe(false)
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index e96a05b1..54f25c3f 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -11,7 +11,7 @@ import {
import { v4 as uuid } from 'uuid'
import { streamProviderTurn } from '../lib/provider-stream'
import { createHermesDisplayFilter, createThinkStreamSplitter } from '../lib/hermes-stream'
-import { setActiveChatId, setActiveConversationId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, renderWorkspaceSection, setChatArtifactMode, takeChatArtifacts, setReadOnlyShellTurn } from '../api/agent-context'
+import { beginAgentRun, endAgentRun, chatWorkspaceSlug, setActiveAgentModel, renderWorkspaceSection, takeChatArtifacts, type AgentRunContext } from '../api/agent-context'
import { isOllamaLocal } from '../api/backend'
import { requestGenerationCancel } from '../api/vram-handoff'
import { resolveWorkspace } from '../api/agents/workspace-resolve'
@@ -346,12 +346,6 @@ export function useAgentChat() {
// title from colliding.
const convForSlug = useChatStore.getState().conversations.find((c) => c.id === convId)
const slug = chatWorkspaceSlug(convId, convForSlug?.title)
- setActiveChatId(slug)
- setActiveConversationId(convId)
- // Read-only turn: shell_execute stays offered (it carries the git
- // inspectors since the 2.6.6 merge), the executor refuses everything
- // that is not an inspection command. clearActiveChatId() resets it.
- setReadOnlyShellTurn(opts?.readOnly === true)
// Multi-Repo Agent (B15) + workspace unification (B17): pin the
// resolved workspace so chatCtx() in builtin-tools.ts threads it
@@ -363,12 +357,31 @@ export function useAgentChat() {
perChat: useAgentModeStore.getState().workspaces[convId],
defaultWorkspace: settings.defaultWorkspace,
})
- setActiveWorkspace(resolvedWorkspace)
- // Chat-tools (plain chat) → "file writes" become in-chat artifacts (preview
- // + download), never disk writes (ChatGPT-style, David 2026-06-12). Full
- // Agent mode keeps writing to disk, so this is ON only for chatToolsMode.
- setChatArtifactMode(opts?.chatToolsMode === true)
+ // Open the run context (plan 2.6.6 C1, ERZWINGUNG). Everything a tool gate
+ // needs travels on THIS object and is handed to each tool call, so a
+ // Coding run that starts or ends while this one is in flight cannot flip
+ // our read-only flag, repoint our workspace, or capture our writes.
+ //
+ // Read-only turn: shell_execute stays offered (it carries the git
+ // inspectors since the 2.6.6 merge), the executor refuses everything that
+ // is not an inspection command.
+ //
+ // Chat-tools (plain chat) → "file writes" become in-chat artifacts
+ // (preview + download), never disk writes (ChatGPT-style, David
+ // 2026-06-12). Full Agent mode keeps writing to disk, so artifactMode is
+ // ON only for chatToolsMode.
+ const run: AgentRunContext = beginAgentRun({
+ chatId: slug,
+ conversationId: convId,
+ workspace: resolvedWorkspace,
+ readOnlyShellTurn: opts?.readOnly === true,
+ artifactMode: opts?.chatToolsMode === true,
+ // The Ask/Bypass/Plan presets are a Code-tab concept. The Agent surface
+ // keeps reading the plain settings, which is the whole point of C1's
+ // BINDUNG: a Bypass in a coding conversation must not reach here.
+ mode: null,
+ })
// Feature EE (v2.5.0) — pin the text model driving this loop so the VRAM
// hand-off orchestrator (image/video generation) knows which model to
@@ -1554,6 +1567,7 @@ export function useAgentChat() {
id: e.ac.id,
toolName: e.ac.toolName,
args: e.ac.args,
+ run,
}))
const auditIds = new Map<string, string>()
@@ -1562,8 +1576,8 @@ export function useAgentChat() {
// Timeout backstop shared with Codex (audit B9): before this the
// Agent loop had NO ceiling around a tool call, so one hung tool
// wedged the whole run with no way out but a restart.
- execute: (name: string, args: Record<string, any>) =>
- raceWithToolTimeout(toolRegistry.execute(name, args), name, toolCallCapMs(name, args, settings)),
+ execute: (name: string, args: Record<string, any>, callRun?: AgentRunContext) =>
+ raceWithToolTimeout(toolRegistry.execute(name, args, 1, callRun), name, toolCallCapMs(name, args, settings)),
lookupCache: convId ? makeInTurnCacheLookup({ convId, turnStartMs }) : undefined,
explainError: (toolName, err) => explainToolError(toolName, err),
awaitApproval: async (req) => {
@@ -1610,6 +1624,11 @@ export function useAgentChat() {
}
}
},
+ }, {
+ // ExecutorOptions, not the runtime: abortSignal has always belonged
+ // to the third argument, and passing it inside the runtime object
+ // meant Stop never kept the not-yet-started calls of a batch from
+ // firing. A stopped run has to stop doing things.
abortSignal: abort.signal,
})
@@ -1978,9 +1997,9 @@ export function useAgentChat() {
abortRef.current = null
// Chat-tools artifact mode: attach any files the model "wrote" (captured
// in-memory, NOT on disk) to the assistant message so they render inline
- // with a preview + Download button. takeChatArtifacts drains the buffer;
- // clearActiveChatId() then resets the mode for the next run.
- const capturedArtifacts = takeChatArtifacts()
+ // with a preview + Download button. takeChatArtifacts drains this run's
+ // buffer; endAgentRun() then closes the run context.
+ const capturedArtifacts = takeChatArtifacts(run)
if (capturedArtifacts.length) {
useChatStore.getState().updateMessageArtifacts(
convId!, assistantMessage.id,
@@ -1993,8 +2012,10 @@ export function useAgentChat() {
// this is where the result becomes durable.
void flushChatPersist()
// Drop the per-run workspace scope so standalone tool calls from
- // other tabs don't accidentally land in this chat's folder.
- clearActiveChatId()
+ // other tabs don't accidentally land in this chat's folder. Only when
+ // this run still owns the shared mirror, so a Coding run that outlives
+ // us keeps its own jail root (plan C1 ERZWINGUNG).
+ endAgentRun(run)
// Reject any pending approvals so their promises don't hang forever
drainApprovals(convId)
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 6c5bd135..0d99ea87 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -13,11 +13,13 @@ import { allowedInReadOnlyTurn } from '../lib/mutating-tools'
import { applyGoalCommand } from '../lib/goal-command'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { useAgentLoopStore } from '../stores/agentLoopStore'
-import { CODEX_CONFIRM_TOOLS, codexConfirmEnabled } from './codexShellGate'
+import { CODEX_CONFIRM_TOOLS } from './codexShellGate'
import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { streamProviderTurn, type StreamedProviderTurn } from '../lib/provider-stream'
import { createHermesDisplayFilter } from '../lib/hermes-stream'
-import { setActiveChatId, setActiveConversationId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, setReadOnlyShellTurn } from '../api/agent-context'
+import { beginAgentRun, endAgentRun, chatWorkspaceSlug, setActiveAgentModel, type AgentRunContext } from '../api/agent-context'
+import { codexModeKnobs, CODEX_MODE_LABELS, type CodexMode } from '../lib/codex-mode'
+import { CODEX_PLAN_SYSTEM_PROMPT } from '../lib/codex-plan-prompt'
import { resolveWorkspace } from '../api/agents/workspace-resolve'
import { useAgentModeStore } from '../stores/agentModeStore'
import { loadLurules, renderRulesSection, type RulesReader } from '../lib/lurules'
@@ -305,13 +307,24 @@ export function useCodex() {
convId = store.createConversation(activeModel, persona?.systemPrompt || '', 'codex')
}
+ // Mode of THIS conversation (plan 2.6.6, C1). A pick made while the
+ // previous run was still going has been parked; a send is where it takes
+ // effect, which is exactly what the dropdown promises. The mode is read
+ // per sendInstruction and NEVER written back into the global settings.
+ useCodexStore.getState().applyParkedMode(convId)
+ const codexMode: CodexMode = useCodexStore
+ .getState()
+ .codexModeFor(convId, settings.codexDefaultMode)
+ // A fresh instruction supersedes a plan that was waiting for approval. The
+ // approve button re-sends through here too, so it clears its own card and
+ // the plan run below is what puts a new one up.
+ useCodexStore.getState().setPlanApproval(convId, null)
+
// Per-chat agent workspace → `~/agent-workspace/<slug>/`.
// Slug uses the chat title so the folder is recognisable in
// Explorer; falls back to a stable id-derived suffix when the
// title is empty. Cleared in the finally block.
const convForSlug = store.conversations.find((c) => c.id === convId)
- setActiveChatId(chatWorkspaceSlug(convId, convForSlug?.title))
- setActiveConversationId(convId)
// Multi-Repo Agent (B15) + Codex/Agent workspace unification (B17):
// pin the resolved workspace so the bridge resolves relative paths
@@ -322,7 +335,6 @@ export function useCodex() {
perChat: useAgentModeStore.getState().workspaces[convId],
defaultWorkspace: settings.defaultWorkspace,
})
- setActiveWorkspace(codexWorkspace)
// Init codex thread if needed
if (!codexStore.getThread(convId)) {
@@ -348,18 +360,19 @@ export function useCodex() {
// Pin the tool-containment workspace to the SAME folder the model is told
// to use (workDir). resolveWorkspace() above only sees the agent-mode
// per-chat store + settings.defaultWorkspace — it MISSES the folder the
- // Code tab's FileTree picker sets (codexStore.workingDirectory), which is
+ // Code tab's explorer picker sets (codexStore.workingDirectory), which is
// the primary way to pick a repo in the Code tab. Without this, containment
// stayed pinned to the per-chat sandbox while the model was told to work in
// a real folder, so every file_list/file_read of the working dir failed
// with "path escapes the allowed workspace" (live cloud find, 2026-07-11).
- if (workDir && workDir !== '.') {
- setActiveWorkspace({
- kind: 'folder',
- path: workDir,
- extraPaths: codexWorkspace && codexWorkspace.kind === 'folder' ? codexWorkspace.extraPaths : undefined,
- })
- }
+ const runWorkspace =
+ workDir && workDir !== '.'
+ ? {
+ kind: 'folder' as const,
+ path: workDir,
+ extraPaths: codexWorkspace && codexWorkspace.kind === 'folder' ? codexWorkspace.extraPaths : undefined,
+ }
+ : codexWorkspace
// `/goal` is bookkeeping, not a prompt. Handle it here and show the result;
// every LATER turn picks the goal up from the system prompt below.
@@ -388,6 +401,39 @@ export function useCodex() {
return
}
+ // Same for Plan mode: it is read-only for the whole conversation, so a
+ // command whose job is to change something has nowhere to land. Saying so
+ // beats narrating work that silently could not happen.
+ if (codexMode === 'plan' && slash && !slash.command.readOnly) {
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'user', content: rawInstruction, timestamp: Date.now(),
+ })
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'assistant', timestamp: Date.now(),
+ content: `Plan mode is read-only, and /${slash.command.name} needs to write files or run commands. Switch the mode dropdown to "${CODEX_MODE_LABELS.ask}" first, or use a read-only command such as /review, /plan, /diff or /explain.`,
+ })
+ return
+ }
+
+ // Read-only for the whole turn: Code-Review Mode, a read-only slash
+ // command, or Plan mode. The most restrictive of the three wins, and the
+ // runtime filter below hangs on THIS, not on the slash flag alone, so the
+ // persistent conversation mode is enforced on every step.
+ const effectiveReadOnly = settings.codexReviewMode === true || readOnlyTurn || codexMode === 'plan'
+
+ // Open the run context. Everything a tool gate needs (conversation, jail
+ // root, read-only flag, mode) travels on THIS object from here on, so a
+ // second run that starts or ends in the middle cannot move it (plan C1
+ // ERZWINGUNG, blocker S3). The finally closes it, and closing only clears
+ // the process-wide mirror when this run still owns it.
+ const run: AgentRunContext = beginAgentRun({
+ chatId: chatWorkspaceSlug(convId, convForSlug?.title),
+ conversationId: convId,
+ workspace: runWorkspace,
+ readOnlyShellTurn: effectiveReadOnly,
+ mode: codexMode,
+ })
+
// Add instruction event
codexStore.addEvent(convId, {
id: uuid(), type: 'instruction', content: instruction, timestamp: Date.now(),
@@ -469,24 +515,43 @@ export function useCodex() {
// list-stripping below (MUTATING_TOOLS) still enforces it
// programmatically even if the model tries to call a write tool anyway.
const reviewMode = settings.codexReviewMode === true
+ // Effective knobs for this run = f(mode, settings). The mode is a PRESET
+ // over the switches that already exist; nothing here is ever written back
+ // into the settings, so a Bypass in this conversation cannot reach another
+ // conversation or the Agent surface (plan C1 BINDUNG). The cloud shell
+ // gate is inside codexConfirmEnabled and stays armed in all three modes.
+ const knobs = codexModeKnobs({
+ mode: codexMode,
+ settings: {
+ codexConfirmShell: settings.codexConfirmShell,
+ codexCloudConfirmShell: settings.codexCloudConfirmShell,
+ codexStageMode: settings.codexStageMode,
+ codexReviewMode: settings.codexReviewMode,
+ },
+ providerId,
+ readOnlyTurn,
+ })
// The merged shell_execute stays offered on read-only turns (it carries
- // git status/log/diff now); the executor refuses everything else while
- // this flag is up. Cleared in the finally below.
- setReadOnlyShellTurn(reviewMode || readOnlyTurn)
- // Review mode always wins; otherwise Small-Model Mode swaps in the lean
- // prompt (Knob 2) for small local models.
+ // git status/log/diff now); the executor refuses everything else while the
+ // run's flag is up. The flag lives on the run object (set at
+ // beginAgentRun), not on a process-wide global.
+ // Review mode always wins; then Plan mode's own prompt; otherwise
+ // Small-Model Mode swaps in the lean prompt (Knob 2) for small local
+ // models.
const baseCodexPrompt = reviewMode
? CODEX_REVIEW_SYSTEM_PROMPT
- : settings.smallModelMode
- ? CODEX_SYSTEM_PROMPT_LEAN
- : CODEX_SYSTEM_PROMPT
+ : knobs.planPrompt
+ ? CODEX_PLAN_SYSTEM_PROMPT
+ : 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.
// A read-only slash command generates nothing either, and its own
// MUTATING_TOOLS filter has already stripped the generators, so promising
// them there is the same broken promise reviewMode was fixed for.
- const assetsPossible = !reviewMode && !readOnlyTurn && !settings.smallModelMode
+ const assetsPossible = !effectiveReadOnly && !settings.smallModelMode
const assetLine = !assetsPossible
? ''
: wantsMediaTools(instruction)
@@ -581,7 +646,10 @@ export function useCodex() {
// Build message history
const conv = useChatStore.getState().conversations.find(c => c.id === convId)
- if (!conv) return
+ // The only bail-out between opening the run and the try/finally that closes
+ // it. Close it here too, or the run context outlives a turn that never
+ // started and the next standalone tool call inherits its jail root.
+ if (!conv) { endAgentRun(run); return }
void diagLog('pre-loop', {
activeModel, providerId, strategy, workDir,
@@ -1010,7 +1078,7 @@ export function useCodex() {
// this turn was started by a read-only slash command. Belt-and-braces
// with the system prompt — covers the model ignoring the instruction
// and trying anyway.
- const codexTools = (settings.codexReviewMode || readOnlyTurn)
+ const codexTools = effectiveReadOnly
? codexToolsAll.filter((t) => allowedInReadOnlyTurn(t.name))
: codexToolsAll
// Tool-list sizing is a MODEL-STRENGTH decision (audit B3):
@@ -1252,7 +1320,7 @@ export function useCodex() {
const def = toolRegistry.getToolByName(t.name)
if (!def) return true
if (!(CODEX_CATEGORIES as readonly string[]).includes(def.category)) return false
- if ((settings.codexReviewMode || readOnlyTurn) && !allowedInReadOnlyTurn(t.name)) return false
+ if (effectiveReadOnly && !allowedInReadOnlyTurn(t.name)) return false
return true
},
)
@@ -1436,14 +1504,19 @@ export function useCodex() {
// /plan (read-only) was offered file_read/file_list/file_search only, on
// every one of its six requests, and still created a file on disk.
// Review Mode carried the identical hole since 2.5.6.
- if (settings.codexReviewMode || readOnlyTurn) {
+ if (effectiveReadOnly) {
const blocked = toolCalls.filter((tc) => !allowedInReadOnlyTurn(tc.function?.name ?? ''))
if (blocked.length) {
toolCalls = toolCalls.filter((tc) => allowedInReadOnlyTurn(tc.function?.name ?? ''))
const names = [...new Set(blocked.map((tc) => tc.function.name))].join(', ')
+ const why = readOnlyTurn
+ ? `a read-only command (/${slash!.command.name})`
+ : codexMode === 'plan'
+ ? 'Plan mode'
+ : 'Code Review Mode'
messages.push({
role: 'user',
- content: `${names} is not available on this turn, it is ${readOnlyTurn ? `a read-only command (/${slash!.command.name})` : 'Code Review Mode'}. Do not try to change anything. Finish with the written answer using what you have already read.`,
+ content: `${names} is not available on this turn, it is ${why}. Do not try to change anything. Finish with the written answer using what you have already read.`,
})
}
}
@@ -1652,6 +1725,9 @@ export function useCodex() {
id: e.ac.id,
toolName: e.ac.toolName,
args: e.injectedArgs,
+ // The run this batch belongs to. Every executor gate downstream
+ // reads it instead of the module global (plan C1 ERZWINGUNG).
+ run,
}))
const auditIds = new Map<string, string>()
@@ -1689,7 +1765,7 @@ export function useCodex() {
// loop forever — and the timer is cleared when the tool wins (B10),
// instead of parking a live closure for up to 615 s per call.
const withTimeout = (name: string, args: Record<string, any>) =>
- raceWithToolTimeout(toolRegistry.execute(name, args), name, toolCallCapMs(name, args, settings))
+ raceWithToolTimeout(toolRegistry.execute(name, args, 1, run), name, toolCallCapMs(name, args, settings))
// Multi-File Stage-and-Approve (B10). When the user has codex
// stage mode on, file_write calls don't hit the disk — they
@@ -1808,7 +1884,10 @@ export function useCodex() {
}
const dispatchTool = (name: string, args: Record<string, any>): Promise<string> => {
- if (settings.codexStageMode) {
+ // Stage-and-Approve follows the MODE preset, not the raw setting:
+ // Ask stages every write for review, Bypass writes straight through,
+ // Plan never gets here because the write tools are stripped.
+ if (knobs.stageWrites) {
if (name === 'file_write') return stageFileWrite(args)
if (name === 'file_edit') return stageFileEdit(args)
// Read-your-writes: staged content is invisible on disk, so reads
@@ -1859,11 +1938,11 @@ export function useCodex() {
// toggle looked broken on cloud models. Same default, but the cloud arm
// is now settings.codexCloudConfirmShell — a real switch the user owns.
// See codexConfirmEnabled for the whole rule.
- awaitApproval: codexConfirmEnabled({
- confirmShell: settings.codexConfirmShell,
- cloudConfirmShell: settings.codexCloudConfirmShell,
- providerId,
- })
+ //
+ // 2.6.6 (plan C1): the mode preset decides whether this gate is
+ // armed. Ask forces it on, Bypass turns the LOCAL arm off, and
+ // codexConfirmEnabled keeps the cloud arm alive in every mode.
+ awaitApproval: knobs.confirmExec
? async (req) => {
if (!CODEX_CONFIRM_TOOLS.has(req.toolName)) return true
const a = req.args || {}
@@ -1873,7 +1952,10 @@ export function useCodex() {
return useCodexConfirmStore.getState().ask({
toolName: req.toolName,
command: String(a.command ?? a.code ?? a.script ?? '').slice(0, 800),
- cloudReason: !settings.codexConfirmShell && providerId === 'lu-cloud',
+ // "we ask because it is a cloud model" only holds when the
+ // user did not ask for it themselves and Ask mode is not
+ // what put the gate up.
+ cloudReason: !settings.codexConfirmShell && codexMode !== 'ask' && providerId === 'lu-cloud',
}, abort.signal)
}
: undefined,
@@ -1903,6 +1985,11 @@ export function useCodex() {
}
}
},
+ }, {
+ // ExecutorOptions, not the runtime: abortSignal has always belonged
+ // to the third argument, and passing it inside the runtime object
+ // meant Stop never kept the not-yet-started calls of a batch from
+ // firing. A stopped run has to stop doing things.
abortSignal: abort.signal,
})
@@ -2205,12 +2292,29 @@ export function useCodex() {
void extractMemoriesFromPair(instruction, fullContent, convId).catch(() => {})
}
+ // Plan mode finished: put the plan up for approval (plan C1, blocker
+ // S7). The card carries the FULL answer, the concrete commands and
+ // target paths, not the todo titles: the plan is a function of untrusted
+ // repo content, so the user approves what they can actually read. The
+ // mode the approval runs under is resolved in the UI and shown ON the
+ // button, and it is never Bypass unless the user picked Bypass by hand.
+ if (convId && codexMode === 'plan' && !userStoppedRef.current && fullContent.trim()) {
+ useCodexStore.getState().setPlanApproval(convId, {
+ planText: fullContent.trim(),
+ messageId: assistantMsg.id,
+ createdAt: Date.now(),
+ })
+ }
+
setIsRunning(false)
useGenerationStore.getState().setGenerating(convId, false)
useGenerationStore.getState().clearAborter(convId)
runningRef.current = false
abortRef.current = null
- clearActiveChatId()
+ // Close THIS run. The process-wide mirror is only cleared when this run
+ // still owns it, so a run that outlives us keeps its workspace and its
+ // read-only flag (plan C1 ERZWINGUNG, blocker S3).
+ endAgentRun(run)
// The turn is done, including the hidden tool history inserted above, so
// put it on disk now. Persistence is coalesced while the run streams
diff --git a/src/lib/__tests__/codex-mode.test.ts b/src/lib/__tests__/codex-mode.test.ts
new file mode 100644
index 00000000..ecc9443a
--- /dev/null
+++ b/src/lib/__tests__/codex-mode.test.ts
@@ -0,0 +1,196 @@
+/**
+ * Ask / Bypass / Plan as a preset over the existing knobs (plan 2.6.6, C1).
+ *
+ * Every claim here has a negative control right next to it, because the whole
+ * point of the feature is what it REFUSES: if a test only proves plan mode
+ * denies file_write, it has not proved the denial comes from plan mode.
+ *
+ * Run: npx vitest run src/lib/__tests__/codex-mode.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import {
+ codexModeKnobs, codexModeRuleset, decideForTool, resolveCodexMode,
+ resolveApproveTargetMode, isCodexMode, CODEX_MODES, CODEX_MODE_LABELS,
+ type CodexMode,
+} from '../codex-mode'
+import { MUTATING_TOOLS } from '../mutating-tools'
+
+const SETTINGS = {
+ codexConfirmShell: false,
+ codexCloudConfirmShell: true,
+ codexStageMode: false,
+ codexReviewMode: false,
+}
+
+const knobs = (mode: CodexMode, over: Partial<typeof SETTINGS> = {}, providerId = 'ollama', readOnlyTurn = false) =>
+ codexModeKnobs({ mode, settings: { ...SETTINGS, ...over }, providerId, readOnlyTurn })
+
+describe('the dropdown labels are the ones the plan pins', () => {
+ it('reads Ask permissions / Bypass permissions / Plan mode', () => {
+ expect(CODEX_MODE_LABELS.ask).toBe('Ask permissions')
+ expect(CODEX_MODE_LABELS.bypass).toBe('Bypass permissions')
+ expect(CODEX_MODE_LABELS.plan).toBe('Plan mode')
+ expect(CODEX_MODES).toEqual(['ask', 'bypass', 'plan'])
+ })
+})
+
+describe('mode resolution: conversation first, then the global default', () => {
+ it('takes the conversation mode when it has one', () => {
+ expect(resolveCodexMode('bypass', 'ask')).toBe('bypass')
+ })
+ it('falls back to the global default when it has none', () => {
+ expect(resolveCodexMode(undefined, 'plan')).toBe('plan')
+ })
+ it('falls back to ask when neither is a mode', () => {
+ expect(resolveCodexMode(undefined, undefined)).toBe('ask')
+ // Negative control: junk from a downgraded persist file is not a mode.
+ expect(resolveCodexMode('yolo', 'nonsense')).toBe('ask')
+ expect(isCodexMode('yolo')).toBe(false)
+ })
+})
+
+describe('switch point 1: the exec confirm gate', () => {
+ it('Ask forces it on, whatever the setting says', () => {
+ expect(knobs('ask').confirmExec).toBe(true)
+ expect(knobs('ask', { codexConfirmShell: false }).confirmExec).toBe(true)
+ })
+ it('Bypass turns the LOCAL arm off', () => {
+ expect(knobs('bypass', { codexConfirmShell: true }).confirmExec).toBe(false)
+ })
+ it('negative control: the same settings under Ask still confirm', () => {
+ expect(knobs('ask', { codexConfirmShell: true }).confirmExec).toBe(true)
+ })
+})
+
+describe('switch point 2: Stage-and-Approve for file_write / file_edit', () => {
+ it('Ask stages even when the setting is off', () => {
+ expect(knobs('ask', { codexStageMode: false }).stageWrites).toBe(true)
+ })
+ it('Bypass does not stage even when the setting is on', () => {
+ expect(knobs('bypass', { codexStageMode: true }).stageWrites).toBe(false)
+ })
+ it('Plan does not stage, it has no writes to stage', () => {
+ expect(knobs('plan', { codexStageMode: true }).stageWrites).toBe(false)
+ })
+})
+
+describe('switch point 3: the read-only chain', () => {
+ it('Plan arms it and swaps in the plan prompt', () => {
+ expect(knobs('plan').readOnly).toBe(true)
+ expect(knobs('plan').planPrompt).toBe(true)
+ })
+ it('negative control: Ask and Bypass leave it disarmed', () => {
+ expect(knobs('ask').readOnly).toBe(false)
+ expect(knobs('bypass').readOnly).toBe(false)
+ expect(knobs('ask').planPrompt).toBe(false)
+ expect(knobs('bypass').planPrompt).toBe(false)
+ })
+ it('the more restrictive of mode and Code-Review Mode wins', () => {
+ expect(knobs('bypass', { codexReviewMode: true }).readOnly).toBe(true)
+ expect(knobs('ask', { codexReviewMode: true }).readOnly).toBe(true)
+ })
+ it('a read-only slash command arms it in every mode', () => {
+ for (const mode of CODEX_MODES) {
+ expect(knobs(mode, {}, 'ollama', true).readOnly).toBe(true)
+ }
+ })
+ it('the plan prompt is never used outside Plan mode, even on a read-only turn', () => {
+ expect(knobs('ask', {}, 'ollama', true).planPrompt).toBe(false)
+ expect(knobs('bypass', { codexReviewMode: true }).planPrompt).toBe(false)
+ })
+})
+
+describe('the cloud shell gate survives all three modes', () => {
+ it.each(CODEX_MODES)('%s still confirms on lu-cloud', (mode) => {
+ expect(knobs(mode, { codexConfirmShell: false, codexCloudConfirmShell: true }, 'lu-cloud').confirmExec).toBe(true)
+ })
+ it('negative control: the same three modes on a local provider do not all confirm', () => {
+ expect(knobs('bypass', { codexConfirmShell: false }, 'ollama').confirmExec).toBe(false)
+ })
+ it('the user can still switch the cloud arm off themselves, and that is the ONLY way', () => {
+ expect(knobs('bypass', { codexCloudConfirmShell: false }, 'lu-cloud').confirmExec).toBe(false)
+ // Bypass alone never reaches that state.
+ expect(knobs('bypass', { codexCloudConfirmShell: true }, 'lu-cloud').confirmExec).toBe(true)
+ })
+})
+
+describe('the preset never writes anything', () => {
+ it('leaves the settings object it was handed byte-identical', () => {
+ const settings = { ...SETTINGS, codexConfirmShell: true, codexStageMode: true }
+ const before = JSON.stringify(settings)
+ for (const mode of CODEX_MODES) {
+ codexModeKnobs({ mode, settings, providerId: 'lu-cloud', readOnlyTurn: false })
+ }
+ expect(JSON.stringify(settings)).toBe(before)
+ })
+ it('negative control: a preset that DID write would be visible here', () => {
+ const settings = { ...SETTINGS }
+ const before = JSON.stringify(settings)
+ // This is the shape the plan forbids: the preset pushed into the settings.
+ ;(settings as { codexConfirmShell: boolean }).codexConfirmShell = false
+ ;(settings as { codexStageMode: boolean }).codexStageMode = true
+ expect(JSON.stringify(settings)).not.toBe(before)
+ })
+})
+
+describe('the ruleset behind the presets', () => {
+ const mutatingExceptShell = [...MUTATING_TOOLS].filter((n) => n !== 'shell_execute')
+
+ it('Plan denies every mutating tool by name', () => {
+ const rules = codexModeRuleset('plan')
+ for (const name of mutatingExceptShell) {
+ expect(decideForTool(rules, name)).toBe('deny')
+ }
+ })
+ it('Plan keeps shell_execute allowed by NAME, its gate is the command classifier', () => {
+ expect(decideForTool(codexModeRuleset('plan'), 'shell_execute')).toBe('allow')
+ })
+ it('Plan still allows the readers', () => {
+ for (const name of ['file_read', 'file_list', 'file_search', 'todo_write']) {
+ expect(decideForTool(codexModeRuleset('plan'), name)).toBe('allow')
+ }
+ })
+ it('negative control: Bypass allows exactly what Plan denies', () => {
+ const rules = codexModeRuleset('bypass')
+ for (const name of mutatingExceptShell) {
+ expect(decideForTool(rules, name)).toBe('allow')
+ }
+ })
+ it('Ask asks for the exec tools and the writes, and allows the rest', () => {
+ const rules = codexModeRuleset('ask')
+ for (const name of ['shell_execute', 'code_execute', 'shell_execute_background', 'file_write', 'file_edit']) {
+ expect(decideForTool(rules, name)).toBe('ask')
+ }
+ expect(decideForTool(rules, 'file_read')).toBe('allow')
+ })
+ it('a trailing star matches by prefix, so bash-style globs can follow later', () => {
+ expect(decideForTool([{ pattern: 'git_*', decision: 'deny' }], 'git_push')).toBe('deny')
+ expect(decideForTool([{ pattern: 'git_*', decision: 'deny' }], 'file_read')).toBe('allow')
+ })
+})
+
+describe('Approve and run never lands in Bypass by itself (blocker S7)', () => {
+ it('a mode parked during the plan run wins', () => {
+ expect(resolveApproveTargetMode({ parked: 'bypass', previous: 'ask' })).toBe('bypass')
+ expect(resolveApproveTargetMode({ parked: 'ask', previous: 'ask' })).toBe('ask')
+ })
+ it('without a parked pick, a Bypass from before the plan becomes Ask', () => {
+ expect(resolveApproveTargetMode({ previous: 'bypass' })).toBe('ask')
+ })
+ it('negative control: inheriting the previous mode verbatim would have said bypass', () => {
+ const naive = (previous: CodexMode) => previous
+ expect(naive('bypass')).toBe('bypass')
+ expect(resolveApproveTargetMode({ previous: 'bypass' })).not.toBe(naive('bypass'))
+ })
+ it('a conversation that STARTED in plan mode gets Ask, never the global default', () => {
+ expect(resolveApproveTargetMode({})).toBe('ask')
+ // Even when that default is Bypass: the resolver is not given it at all.
+ expect(resolveApproveTargetMode({ previous: undefined, parked: undefined })).toBe('ask')
+ })
+ it('an Ask from before the plan is kept', () => {
+ expect(resolveApproveTargetMode({ previous: 'ask' })).toBe('ask')
+ })
+ it('parking Plan again is not a pick, it falls through to the rules', () => {
+ expect(resolveApproveTargetMode({ parked: 'plan', previous: 'bypass' })).toBe('ask')
+ })
+})
diff --git a/src/lib/__tests__/codex-plan-longrun.test.ts b/src/lib/__tests__/codex-plan-longrun.test.ts
new file mode 100644
index 00000000..bc5e0db4
--- /dev/null
+++ b/src/lib/__tests__/codex-plan-longrun.test.ts
@@ -0,0 +1,89 @@
+/**
+ * A Plan-mode run is a LONG read: it explores before it writes anything down,
+ * and with the context decay from wave one the same file legitimately comes
+ * back several times, because its bytes aged out of the prompt in between.
+ *
+ * That is exactly the shape detector 3 of the loop guard was built to kill, so
+ * plan mode would be unusable if the two were not composed correctly (S1). This
+ * pins the composition: a realistic plan run with five identical reads of one
+ * file across thirteen steps does NOT halt while those re-reads are the
+ * sanctioned kind, and the negative control shows the guard is still awake.
+ *
+ * Run: npx vitest run src/lib/__tests__/codex-plan-longrun.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { AgentLoopGuard } from '../agent-loop-guard'
+
+type Call = { name: string; args: string }
+
+const read = (path: string): Call => ({ name: 'file_read', args: JSON.stringify({ path }) })
+const list = (path: string): Call => ({ name: 'file_list', args: JSON.stringify({ path }) })
+const search = (q: string): Call => ({ name: 'file_search', args: JSON.stringify({ pattern: q }) })
+
+const keyOf = (c: Call) => `${c.name}|${c.args}`
+
+/**
+ * What a plan run actually looks like: one central file read again and again as
+ * the picture fills in, with different look-arounds in between. Thirteen steps,
+ * five reads of src/router.ts.
+ */
+const ROUTER = read('src/router.ts')
+const STEPS: Call[][] = [
+ [ROUTER],
+ [list('src')],
+ [ROUTER],
+ [search('registerRoute')],
+ [ROUTER],
+ [read('src/app.ts')],
+ [list('src/routes')],
+ [ROUTER],
+ [search('middleware')],
+ [read('src/server.ts')],
+ [list('tests')],
+ [ROUTER],
+ [search('router')],
+]
+
+describe('a long read-only plan run is not mistaken for a loop', () => {
+ it('does not halt over 13 steps with 5 identical reads, while the decay owns them', () => {
+ const guard = new AgentLoopGuard()
+ let firstRouter = true
+ const verdicts = STEPS.map((calls) => {
+ // The builder capped the newest result of this read, so the model no
+ // longer holds those bytes. The FIRST read is not a re-read.
+ const trimmedReadKeys = new Set<string>()
+ if (calls.includes(ROUTER)) {
+ if (!firstRouter) trimmedReadKeys.add(keyOf(ROUTER))
+ firstRouter = false
+ }
+ return guard.recordBatch(calls, { trimmedReadKeys })
+ })
+
+ expect(STEPS.length).toBeGreaterThanOrEqual(12)
+ expect(STEPS.filter((s) => s.includes(ROUTER)).length).toBeGreaterThanOrEqual(5)
+ expect(verdicts.some((v) => v.action === 'halt')).toBe(false)
+ })
+
+ it('negative control: the same 13 steps WITHOUT the decay marking halt', () => {
+ const guard = new AgentLoopGuard()
+ const verdicts = STEPS.map((calls) => guard.recordBatch(calls))
+ expect(verdicts.some((v) => v.action === 'halt')).toBe(true)
+ })
+
+ it('negative control: the guard still halts a genuine stall inside a plan run', () => {
+ const guard = new AgentLoopGuard()
+ // Same batch three times in a row is a stall whatever the decay says.
+ const verdicts = [1, 2, 3].map(() =>
+ guard.recordBatch([ROUTER], { trimmedReadKeys: new Set([keyOf(ROUTER)]) }),
+ )
+ expect(verdicts.some((v) => v.action === 'halt')).toBe(true)
+ })
+
+ it('a plan run that never repeats a read is untouched', () => {
+ const guard = new AgentLoopGuard()
+ const verdicts = Array.from({ length: 14 }, (_, i) =>
+ guard.recordBatch([read(`src/file-${i}.ts`)]),
+ )
+ expect(verdicts.every((v) => v.action === 'ok')).toBe(true)
+ })
+})
diff --git a/src/lib/__tests__/readonly-enforcement.test.ts b/src/lib/__tests__/readonly-enforcement.test.ts
index db28ae48..00d6e5d7 100644
--- a/src/lib/__tests__/readonly-enforcement.test.ts
+++ b/src/lib/__tests__/readonly-enforcement.test.ts
@@ -73,7 +73,12 @@ describe('read-only batch guard', () => {
describe('both hooks still carry the guard', () => {
it('useCodex filters the batch, not just the catalog', () => {
const src = read('../../hooks/useCodex.ts')
- expect(src).toContain('if (settings.codexReviewMode || readOnlyTurn) {')
+ // Since 2.6.6 C1 the three read-only reasons are one flag, and the runtime
+ // filter hangs on the PERSISTENT conversation mode as well as the slash
+ // turn, so Plan mode is enforced on every step and not only when a
+ // read-only command started the turn.
+ expect(src).toContain("const effectiveReadOnly = settings.codexReviewMode === true || readOnlyTurn || codexMode === 'plan'")
+ expect(src).toContain('if (effectiveReadOnly) {')
expect(src).toContain('toolCalls = toolCalls.filter((tc) => allowedInReadOnlyTurn(tc.function?.name ?? \'\'))')
})
diff --git a/src/lib/codex-mode.ts b/src/lib/codex-mode.ts
new file mode 100644
index 00000000..a5d15616
--- /dev/null
+++ b/src/lib/codex-mode.ts
@@ -0,0 +1,227 @@
+/**
+ * Coding-agent permission modes (plan 2.6.6, C1).
+ *
+ * Three user-visible presets sit OVER the knobs that already exist
+ * (confirm gate, stage mode, review / read-only chain), so the three
+ * overlapping systems get ONE operating logic instead of a fourth:
+ *
+ * Ask confirm every arbitrary-exec tool, stage file_write / file_edit
+ * Bypass local asking off, staging off, the CLOUD shell gate stays
+ * Plan the read-only chain armed for the whole conversation, plus a
+ * dedicated plan system prompt (see codex-plan-prompt.ts)
+ *
+ * BINDING (plan C1): a preset NEVER writes the global settings. The mode is
+ * resolved per send inside useCodex and turned into effective knobs here.
+ * useAgentChat and every other conversation keep reading the settings
+ * unchanged, so a Bypass in conversation X cannot flip conversation Y or the
+ * Agent surface (codexShellGate is consumed by BOTH loops since G15a).
+ *
+ * Internally a mode is a ruleset {pattern -> ask | allow | deny}, the opencode
+ * schema as the model (R3). The UI only ever shows the three presets; bash
+ * globs like "git push*" are a later expansion of the same shape.
+ */
+
+import { MUTATING_TOOLS } from './mutating-tools'
+import { codexConfirmEnabled } from '../hooks/codexShellGate'
+
+export type CodexMode = 'ask' | 'bypass' | 'plan'
+
+export const CODEX_MODES: readonly CodexMode[] = ['ask', 'bypass', 'plan'] as const
+
+/** English labels, exactly as the plan specifies them for the dropdown. */
+export const CODEX_MODE_LABELS: Record<CodexMode, string> = {
+ ask: 'Ask permissions',
+ bypass: 'Bypass permissions',
+ plan: 'Plan mode',
+}
+
+/** One word, for the "Approve and run (Ask)" button and the composer trigger. */
+export const CODEX_MODE_SHORT: Record<CodexMode, string> = {
+ ask: 'Ask',
+ bypass: 'Bypass',
+ plan: 'Plan',
+}
+
+export const CODEX_MODE_DESCRIPTIONS: Record<CodexMode, string> = {
+ ask: 'Confirm commands, review edits before they land',
+ bypass: 'Run without asking. Cloud shell still confirms',
+ plan: 'Read only. Writes a plan, then waits for approval',
+}
+
+export function isCodexMode(v: unknown): v is CodexMode {
+ return v === 'ask' || v === 'bypass' || v === 'plan'
+}
+
+/**
+ * The mode this conversation runs under: its own pick wins, otherwise the
+ * global default from settings, otherwise 'ask'. Nothing else is consulted.
+ */
+export function resolveCodexMode(
+ conversationMode: unknown,
+ defaultMode: unknown,
+): CodexMode {
+ if (isCodexMode(conversationMode)) return conversationMode
+ if (isCodexMode(defaultMode)) return defaultMode
+ return 'ask'
+}
+
+export type PermissionDecision = 'ask' | 'allow' | 'deny'
+
+export interface CodexModeRule {
+ /** Tool-name pattern. '*' matches anything, a trailing '*' is a prefix. */
+ pattern: string
+ decision: PermissionDecision
+}
+
+/** The arbitrary-code-execution tools, same set the H2 confirm gate uses. */
+const EXEC_TOOLS = ['shell_execute', 'code_execute', 'shell_execute_background'] as const
+/** Staged-and-approved writes in Ask mode. */
+const WRITE_TOOLS = ['file_write', 'file_edit'] as const
+
+/**
+ * The ruleset behind a preset. Plan mode derives its denials from
+ * MUTATING_TOOLS so the catalog strip, the runtime filter and this table can
+ * never drift apart. shell_execute stays 'allow' by name on purpose: since the
+ * 2.6.6 tool merge it carries the git inspectors, so its GATE is the command
+ * classifier in the executor, not the tool name (see allowedInReadOnlyTurn).
+ */
+export function codexModeRuleset(mode: CodexMode): CodexModeRule[] {
+ if (mode === 'bypass') return [{ pattern: '*', decision: 'allow' }]
+ if (mode === 'plan') {
+ return [
+ ...[...MUTATING_TOOLS]
+ .filter((name) => name !== 'shell_execute')
+ .sort()
+ .map((pattern): CodexModeRule => ({ pattern, decision: 'deny' })),
+ { pattern: '*', decision: 'allow' },
+ ]
+ }
+ return [
+ ...EXEC_TOOLS.map((pattern): CodexModeRule => ({ pattern, decision: 'ask' })),
+ ...WRITE_TOOLS.map((pattern): CodexModeRule => ({ pattern, decision: 'ask' })),
+ { pattern: '*', decision: 'allow' },
+ ]
+}
+
+function patternMatches(pattern: string, name: string): boolean {
+ if (pattern === '*') return true
+ if (pattern.endsWith('*')) return name.startsWith(pattern.slice(0, -1))
+ return pattern === name
+}
+
+/** First matching rule wins, exactly like the opencode permission table. */
+export function decideForTool(rules: readonly CodexModeRule[], toolName: string): PermissionDecision {
+ for (const rule of rules) {
+ if (patternMatches(rule.pattern, toolName)) return rule.decision
+ }
+ return 'allow'
+}
+
+export interface CodexModeKnobs {
+ /** awaitApproval is wired for the arbitrary-exec tools this run. */
+ confirmExec: boolean
+ /** file_write / file_edit go through Stage-and-Approve instead of disk. */
+ stageWrites: boolean
+ /** The read-only chain is armed: catalog strip, shell flag, runtime filter. */
+ readOnly: boolean
+ /** Swap in the plan system prompt (explore, write the plan, stop). */
+ planPrompt: boolean
+}
+
+export interface CodexModeKnobInput {
+ mode: CodexMode
+ settings: {
+ codexConfirmShell?: boolean
+ codexCloudConfirmShell?: boolean
+ codexStageMode?: boolean
+ codexReviewMode?: boolean
+ }
+ /** Provider driving this run, for the cloud arm of the shell gate. */
+ providerId: string
+ /** True when a read-only slash command (/review, /plan, ...) started the turn. */
+ readOnlyTurn?: boolean
+}
+
+/**
+ * Effective knobs = f(mode, settings). Pure, so the gate path and the request
+ * path cannot disagree, and so a test can prove no settings write happens.
+ *
+ * The cloud shell gate is deliberately untouched in all three modes: Bypass
+ * turns the LOCAL asking off and leaves codexCloudConfirmShell to decide for
+ * lu-cloud, which is the security decision the plan pins down.
+ *
+ * Where a mode and Code-Review Mode or a read-only slash command disagree, the
+ * more restrictive behaviour wins.
+ */
+export function codexModeKnobs(input: CodexModeKnobInput): CodexModeKnobs {
+ const { mode, settings, providerId } = input
+ const reviewMode = settings.codexReviewMode === true
+ const readOnlyTurn = input.readOnlyTurn === true
+ const cloudConfirmShell = settings.codexCloudConfirmShell !== false
+ const restrictedRead = reviewMode || readOnlyTurn
+
+ if (mode === 'bypass') {
+ return {
+ // Local asking off, cloud gate untouched.
+ confirmExec: codexConfirmEnabled({ confirmShell: false, cloudConfirmShell, providerId }),
+ // Restrictive wins: a read-only turn has nothing to stage anyway.
+ stageWrites: false,
+ readOnly: restrictedRead,
+ planPrompt: false,
+ }
+ }
+
+ if (mode === 'plan') {
+ return {
+ // Nothing mutating survives the read-only chain, so the confirm gate
+ // keeps following the user's own settings here. The cloud arm is what
+ // must never soften, and codexConfirmEnabled carries it.
+ confirmExec: codexConfirmEnabled({
+ confirmShell: settings.codexConfirmShell === true,
+ cloudConfirmShell,
+ providerId,
+ }),
+ stageWrites: false,
+ readOnly: true,
+ planPrompt: true,
+ }
+ }
+
+ return {
+ // Ask means ask, on every provider.
+ confirmExec: true,
+ // opencode asks on edits too in ask/plan. We use the Stage-and-Approve
+ // queue that already exists for exactly that review step.
+ stageWrites: !restrictedRead,
+ readOnly: restrictedRead,
+ planPrompt: false,
+ }
+}
+
+/**
+ * Which mode "Approve and run" executes the plan under (plan C1, blocker S7).
+ *
+ * The plan is a function of UNTRUSTED repo content (READMEs, file names, an
+ * AGENTS.md), so the execution never lands in Bypass implicitly. Order:
+ * 1. a mode the user explicitly parked during the plan run wins, it is their
+ * last visible choice and the button shows it,
+ * 2. otherwise the mode from BEFORE plan mode, except Bypass, which becomes
+ * Ask,
+ * 3. a conversation that STARTED in plan mode gets Ask, never the global
+ * default (which could itself be Bypass).
+ */
+export function resolveApproveTargetMode(input: {
+ parked?: unknown
+ previous?: unknown
+}): CodexMode {
+ // 1. The user's last visible choice during the plan run wins.
+ if (isCodexMode(input.parked) && input.parked !== 'plan') return input.parked
+ // 2. The mode from before plan mode, minus Bypass: an untrusted plan never
+ // inherits an unattended run.
+ if (isCodexMode(input.previous) && input.previous !== 'plan' && input.previous !== 'bypass') {
+ return input.previous
+ }
+ // 3. Started in plan mode, or came from Bypass: Ask. Never the global
+ // default, which could itself be Bypass.
+ return 'ask'
+}
diff --git a/src/lib/codex-plan-prompt.ts b/src/lib/codex-plan-prompt.ts
new file mode 100644
index 00000000..6ad12690
--- /dev/null
+++ b/src/lib/codex-plan-prompt.ts
@@ -0,0 +1,47 @@
+/**
+ * Plan-mode system prompt (plan 2.6.6, C1).
+ *
+ * Deliberately NOT the review prompt. Review Mode produces inline comments on
+ * code somebody already wrote, which is the wrong voice for "work out what we
+ * are about to do". Plan mode explores read-only, writes the plan through
+ * todo_write so the plan panel carries it live, spells out the concrete
+ * commands and target paths in its answer, and then STOPS and waits for the
+ * user to approve.
+ *
+ * The prompt is the polite half. The hard half is the read-only chain
+ * (catalog strip, shell flag, runtime filter), which refuses a mutation
+ * whatever the model was told.
+ */
+export const CODEX_PLAN_SYSTEM_PROMPT = `You are the Coding Agent in PLAN MODE inside LU. You investigate and you plan. You change NOTHING. Every write tool is removed from your list and every state-changing shell command is refused, so attempting one only wastes a step.
+
+PLAN MODE CONTRACT (binding):
+- You MAY call: file_read, file_list, file_search, todo_write, web_fetch, web_search, and shell_execute for INSPECTION ONLY (git status/log/diff/show/blame, ls, cat, pwd; one command, no chaining).
+- You MUST NOT call: file_write, file_edit, image_generate, video_generate, run_workflow, screenshot, delegate_task, or any shell command that changes state (commit, push, install, tests, deletes, moves).
+- Read enough of the real code to be specific. A plan built on guesses is worse than no plan.
+
+How to work:
+1. Explore first. Find the files that actually have to change and read them.
+2. Call todo_write with the full step list as soon as the shape is clear, then keep it current as your understanding sharpens. The user follows the run through that list.
+3. Finish with the plan in text. For every step name the exact target path and the exact command you intend to run, so the user is approving concrete actions and not a summary. Say what you will verify at the end and name anything you are unsure about.
+4. Then STOP. Do not ask "shall I proceed" and do not start implementing. The user approves the plan with a button, and the run continues from there.
+
+Format of the final answer:
+## Plan
+Numbered steps. Each step: what changes, in which file (path), and the command to run if there is one.
+## Verification
+The exact commands that prove it worked.
+## Risks
+Anything that could go wrong or that you could not determine. One line each, or "none".
+
+Be direct. No flattery, no filler.`
+
+/**
+ * What "Approve and run" sends. The plan itself is already in the history as
+ * the previous assistant message, so this only has to release the brake and
+ * pin the model to what the user actually approved.
+ */
+export const CODEX_PLAN_APPROVED_INSTRUCTION =
+ 'The plan above is approved. Execute it now, step by step, exactly as written. '
+ + 'Keep the todo list current as you go. If a step turns out to be wrong or impossible, '
+ + 'stop at that step and say why instead of improvising a different change. '
+ + 'Run the verification commands from the plan at the end and report the result.'
diff --git a/src/stores/__tests__/codexStore-mode.test.ts b/src/stores/__tests__/codexStore-mode.test.ts
new file mode 100644
index 00000000..3fc75acf
--- /dev/null
+++ b/src/stores/__tests__/codexStore-mode.test.ts
@@ -0,0 +1,158 @@
+/**
+ * The per-conversation mode slice (plan 2.6.6, C1 + R1 DOWNGRADE-KONTRAKT).
+ *
+ * Two things are load-bearing and both have a price:
+ * - a pick made while a run is in flight must NOT change the running turn,
+ * it parks and applies at the next send (that is what the dropdown says),
+ * - the persist shape stays additive at version 0, because the D1 A/B has a
+ * 2.6.5 build and a 2.6.6 build sharing one WebView profile and zustand
+ * throws the whole persisted state away on a version mismatch.
+ *
+ * Run: npx vitest run src/stores/__tests__/codexStore-mode.test.ts
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+
+// zustand/persist reads window.localStorage; the vitest env is 'node'. Assigned
+// before the store import below, which is why that import is not hoisted to the
+// top of the file.
+const backing = new Map<string, string>()
+;(globalThis as unknown as { window: unknown }).window = globalThis
+globalThis.localStorage = {
+ getItem: (k: string) => backing.get(k) ?? null,
+ setItem: (k: string, v: string) => void backing.set(k, String(v)),
+ removeItem: (k: string) => void backing.delete(k),
+ clear: () => backing.clear(),
+ key: (i: number) => [...backing.keys()][i] ?? null,
+ get length() { return backing.size },
+} as Storage
+
+const { useCodexStore } = await import('../codexStore')
+
+const KEY = 'locally-uncensored-codex'
+
+beforeEach(() => {
+ localStorage.clear()
+ useCodexStore.setState({
+ modeByConversation: {},
+ parkedModeByConversation: {},
+ prePlanModeByConversation: {},
+ planApprovalByConversation: {},
+ workingDirectory: '',
+ })
+})
+
+describe('resolution: the conversation first, then the global default', () => {
+ it('uses the conversation mode when it has one', () => {
+ useCodexStore.getState().chooseCodexMode('x', 'bypass', false)
+ expect(useCodexStore.getState().codexModeFor('x', 'ask')).toBe('bypass')
+ })
+
+ it('falls back to the global default for a conversation that never picked', () => {
+ expect(useCodexStore.getState().codexModeFor('fresh', 'plan')).toBe('plan')
+ })
+
+ it('a pick in X leaves Y on the default: the modes do not leak sideways', () => {
+ useCodexStore.getState().chooseCodexMode('X', 'bypass', false)
+ expect(useCodexStore.getState().codexModeFor('Y', 'ask')).toBe('ask')
+ // Negative control: a global write would have moved Y too.
+ expect(useCodexStore.getState().modeByConversation.Y).toBeUndefined()
+ })
+})
+
+describe('a switch during a run parks and applies at the next send', () => {
+ it('does not touch the running turn', () => {
+ useCodexStore.getState().chooseCodexMode('x', 'ask', false)
+ useCodexStore.getState().chooseCodexMode('x', 'bypass', true)
+ expect(useCodexStore.getState().codexModeFor('x', 'ask')).toBe('ask')
+ expect(useCodexStore.getState().parkedModeByConversation.x).toBe('bypass')
+ })
+
+ it('the next send applies it and clears the park', () => {
+ useCodexStore.getState().chooseCodexMode('x', 'ask', false)
+ useCodexStore.getState().chooseCodexMode('x', 'bypass', true)
+ useCodexStore.getState().applyParkedMode('x')
+ expect(useCodexStore.getState().codexModeFor('x', 'ask')).toBe('bypass')
+ expect(useCodexStore.getState().parkedModeByConversation.x).toBeUndefined()
+ })
+
+ it('negative control: applying with nothing parked changes nothing', () => {
+ useCodexStore.getState().chooseCodexMode('x', 'ask', false)
+ useCodexStore.getState().applyParkedMode('x')
+ useCodexStore.getState().applyParkedMode('x')
+ expect(useCodexStore.getState().codexModeFor('x', 'ask')).toBe('ask')
+ })
+})
+
+describe('the mode from before Plan mode is remembered', () => {
+ it('records the pre-plan mode on the way in', () => {
+ useCodexStore.getState().chooseCodexMode('x', 'bypass', false)
+ useCodexStore.getState().chooseCodexMode('x', 'plan', false)
+ expect(useCodexStore.getState().prePlanModeByConversation.x).toBe('bypass')
+ })
+
+ it('records it when the plan pick was parked during a run', () => {
+ useCodexStore.getState().chooseCodexMode('x', 'ask', false)
+ useCodexStore.getState().chooseCodexMode('x', 'plan', true)
+ useCodexStore.getState().applyParkedMode('x')
+ expect(useCodexStore.getState().prePlanModeByConversation.x).toBe('ask')
+ })
+
+ it('a conversation that started in plan mode has nothing to inherit', () => {
+ useCodexStore.getState().chooseCodexMode('x', 'plan', false)
+ expect(useCodexStore.getState().prePlanModeByConversation.x).toBeUndefined()
+ })
+
+ it('plan to plan does not overwrite what came before', () => {
+ useCodexStore.getState().chooseCodexMode('x', 'ask', false)
+ useCodexStore.getState().chooseCodexMode('x', 'plan', false)
+ useCodexStore.getState().chooseCodexMode('x', 'plan', false)
+ expect(useCodexStore.getState().prePlanModeByConversation.x).toBe('ask')
+ })
+})
+
+describe('the plan approval card', () => {
+ it('is set and cleared per conversation', () => {
+ useCodexStore.getState().setPlanApproval('x', { planText: '## Plan\n1. do it', messageId: 'm1', createdAt: 1 })
+ expect(useCodexStore.getState().planApprovalByConversation.x?.planText).toContain('## Plan')
+ expect(useCodexStore.getState().planApprovalByConversation.y).toBeUndefined()
+ useCodexStore.getState().setPlanApproval('x', null)
+ expect(useCodexStore.getState().planApprovalByConversation.x).toBeUndefined()
+ })
+})
+
+describe('R1 DOWNGRADE-KONTRAKT: the persist shape stays additive at version 0', () => {
+ const persisted = () => JSON.parse(localStorage.getItem(KEY) ?? '{}')
+
+ it('writes the conversation modes next to the working directory and nothing else', () => {
+ useCodexStore.getState().setWorkingDirectory('/repo')
+ useCodexStore.getState().chooseCodexMode('x', 'plan', false)
+ const raw = persisted()
+ expect(Object.keys(raw.state).sort()).toEqual(['modeByConversation', 'workingDirectory'])
+ expect(raw.state.modeByConversation).toEqual({ x: 'plan' })
+ expect(raw.state.workingDirectory).toBe('/repo')
+ })
+
+ it('leaves the store version at 0, so a 2.6.5 build still reads this file', () => {
+ useCodexStore.getState().setWorkingDirectory('/repo')
+ // zustand writes `version: 0` explicitly, or omits it on the default.
+ expect(persisted().version ?? 0).toBe(0)
+ })
+
+ it('the transient halves never reach the disk', () => {
+ useCodexStore.getState().chooseCodexMode('x', 'plan', true)
+ useCodexStore.getState().setPlanApproval('x', { planText: 'p', messageId: 'm', createdAt: 1 })
+ const state = persisted().state ?? {}
+ expect(state.parkedModeByConversation).toBeUndefined()
+ expect(state.prePlanModeByConversation).toBeUndefined()
+ expect(state.planApprovalByConversation).toBeUndefined()
+ // Negative control: the key that IS meant to persist is there.
+ expect(state).toHaveProperty('modeByConversation')
+ })
+
+ it('a downgrade that drops the key costs only the conversation modes', () => {
+ // What a 2.6.5 build writes back: it knows workingDirectory and nothing else.
+ localStorage.setItem(KEY, JSON.stringify({ state: { workingDirectory: '/repo' }, version: 0 }))
+ useCodexStore.setState({ modeByConversation: {} })
+ expect(useCodexStore.getState().codexModeFor('x', 'bypass')).toBe('bypass')
+ })
+})
diff --git a/src/stores/__tests__/sessionStores.test.ts b/src/stores/__tests__/sessionStores.test.ts
index 0eff2fac..82f507d5 100644
--- a/src/stores/__tests__/sessionStores.test.ts
+++ b/src/stores/__tests__/sessionStores.test.ts
@@ -11,7 +11,6 @@ describe('codexStore', () => {
chatMode: 'lu',
threads: {},
workingDirectory: '',
- fileTree: [],
})
})
diff --git a/src/stores/codexStore.ts b/src/stores/codexStore.ts
index 1e351a25..1b141a05 100644
--- a/src/stores/codexStore.ts
+++ b/src/stores/codexStore.ts
@@ -1,45 +1,145 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
-import type { ChatMode, CodexThread, CodexEvent, FileTreeNode } from '../types/codex'
+import type { ChatMode, CodexThread, CodexEvent } from '../types/codex'
+import { resolveCodexMode, type CodexMode } from '../lib/codex-mode'
+
+/**
+ * A finished plan waiting for "Approve and run" (plan 2.6.6, C1 / blocker S7).
+ * `planText` is the model's FULL final answer, not the todo titles: the user is
+ * approving concrete commands and target paths, and the titles alone are not a
+ * basis for that.
+ */
+export interface CodexPlanApproval {
+ planText: string
+ /** Message id the plan came from, so a later run does not resurrect it. */
+ messageId: string
+ createdAt: number
+}
interface CodexState {
chatMode: ChatMode
threads: Record<string, CodexThread>
workingDirectory: string
- fileTree: FileTreeNode[]
/**
- * Bump counter — incremented every time a Codex run mutates the working
+ * Bump counter, incremented every time a Codex run mutates the working
* directory (file_write, file_change, terminal commands that can modify
- * files). FileTree subscribes to this and reloads when it changes, so
- * new/deleted files appear without a manual refresh.
+ * files). The explorer panel subscribes to this and reloads when it changes,
+ * so new/deleted files appear without a manual refresh.
*/
fileTreeVersion: number
+ /**
+ * Ask / Bypass / Plan per conversation (plan 2.6.6, C1). The ONLY persisted
+ * part of the mode slice, and additive: codexStore stays at persist version 0
+ * so a 2.6.5 build can read this state back without zustand discarding it
+ * (R1 DOWNGRADE-KONTRAKT). A downgrade plus re-upgrade loses the conversation
+ * modes and nothing else, and they fall back to settings.codexDefaultMode.
+ */
+ modeByConversation: Record<string, CodexMode>
+ /**
+ * A mode picked while a run is in flight. It does NOT touch the running turn:
+ * a switch takes effect from the next send, which is what the dropdown says.
+ * Transient on purpose, an app restart has no run to park anything for.
+ */
+ parkedModeByConversation: Record<string, CodexMode>
+ /** The mode this conversation had before it went into Plan mode. */
+ prePlanModeByConversation: Record<string, CodexMode>
+ /** Plan finished, waiting for approval. Cleared when the run is approved. */
+ planApprovalByConversation: Record<string, CodexPlanApproval>
+
setChatMode: (mode: ChatMode) => void
setWorkingDirectory: (dir: string) => void
- setFileTree: (tree: FileTreeNode[]) => void
bumpFileTreeVersion: () => void
+ /**
+ * The user picked a mode in the dropdown. While a run is active the pick is
+ * PARKED and applied by the next send; otherwise it lands immediately.
+ */
+ chooseCodexMode: (conversationId: string, mode: CodexMode, runActive: boolean) => void
+ /** Apply a parked pick. Called once at the start of every send. */
+ applyParkedMode: (conversationId: string) => void
+ /** The conversation's mode, falling back to the global default. */
+ codexModeFor: (conversationId: string | null | undefined, defaultMode: unknown) => CodexMode
+ setPlanApproval: (conversationId: string, approval: CodexPlanApproval | null) => void
+
getThread: (conversationId: string) => CodexThread | undefined
initThread: (conversationId: string, workingDir: string) => string
addEvent: (conversationId: string, event: CodexEvent) => void
setThreadStatus: (conversationId: string, status: CodexThread['status']) => void
}
+/** Drop one key from a record without leaving an undefined hole behind. */
+function omit<T>(map: Record<string, T>, key: string): Record<string, T> {
+ if (!(key in map)) return map
+ const next = { ...map }
+ delete next[key]
+ return next
+}
+
export const useCodexStore = create<CodexState>()(
persist(
(set, get) => ({
chatMode: 'lu',
threads: {},
workingDirectory: '',
- fileTree: [],
fileTreeVersion: 0,
+ modeByConversation: {},
+ parkedModeByConversation: {},
+ prePlanModeByConversation: {},
+ planApprovalByConversation: {},
setChatMode: (mode) => set({ chatMode: mode }),
setWorkingDirectory: (dir) => set({ workingDirectory: dir }),
- setFileTree: (tree) => set({ fileTree: tree }),
bumpFileTreeVersion: () => set((state) => ({ fileTreeVersion: state.fileTreeVersion + 1 })),
+ chooseCodexMode: (conversationId, mode, runActive) =>
+ set((state) => {
+ // Parked either way: it is the user's last VISIBLE choice, which is
+ // what "Approve and run" reads to decide its target mode. While a run
+ // is active that is all it is, the running turn keeps its own mode.
+ const parked = { ...state.parkedModeByConversation, [conversationId]: mode }
+ if (runActive) return { parkedModeByConversation: parked }
+ const current = state.modeByConversation[conversationId]
+ const prePlan =
+ mode === 'plan' && current !== 'plan' && current
+ ? { ...state.prePlanModeByConversation, [conversationId]: current }
+ : state.prePlanModeByConversation
+ return {
+ parkedModeByConversation: parked,
+ prePlanModeByConversation: prePlan,
+ modeByConversation: { ...state.modeByConversation, [conversationId]: mode },
+ }
+ }),
+
+ applyParkedMode: (conversationId) =>
+ set((state) => {
+ const parked = state.parkedModeByConversation[conversationId]
+ if (!parked) return state
+ const current = state.modeByConversation[conversationId]
+ const prePlan =
+ parked === 'plan' && current !== 'plan' && current
+ ? { ...state.prePlanModeByConversation, [conversationId]: current }
+ : state.prePlanModeByConversation
+ return {
+ parkedModeByConversation: omit(state.parkedModeByConversation, conversationId),
+ prePlanModeByConversation: prePlan,
+ modeByConversation: { ...state.modeByConversation, [conversationId]: parked },
+ }
+ }),
+
+ codexModeFor: (conversationId, defaultMode) =>
+ resolveCodexMode(
+ conversationId ? get().modeByConversation[conversationId] : undefined,
+ defaultMode,
+ ),
+
+ setPlanApproval: (conversationId, approval) =>
+ set((state) => ({
+ planApprovalByConversation: approval
+ ? { ...state.planApprovalByConversation, [conversationId]: approval }
+ : omit(state.planApprovalByConversation, conversationId),
+ })),
+
getThread: (conversationId) => get().threads[conversationId],
initThread: (conversationId, workingDir) => {
@@ -64,7 +164,7 @@ export const useCodexStore = create<CodexState>()(
const thread = state.threads[conversationId]
if (!thread) return state
// Auto-bump fileTreeVersion for events that can mutate the working
- // directory. FileTree watches this and re-reads the directory.
+ // directory. The explorer panel watches this and re-reads.
const mutatesFs =
event.type === 'file_change' ||
event.type === 'terminal_output' // shell/code execution can touch files
@@ -103,8 +203,18 @@ export const useCodexStore = create<CodexState>()(
// wants to stay in the Coding Agent, they pick it from the sidebar
// each session. workingDirectory still persists so it remembers the
// last project path.
+ // ADDITIVE ONLY, and the store version stays 0 (plan R1
+ // DOWNGRADE-KONTRAKT). The D1 A/B has a 2.6.5 build and a 2.6.6 build
+ // sharing one WebView profile, and zustand is hard about a version
+ // mismatch: without a migrate it throws the whole persisted state away,
+ // with one the old build stamps its version back and the migration runs
+ // AGAIN on the next 2.6.6 start. Staying at version 0 and only adding a
+ // key means the old build reads what it knows and ignores the rest; a
+ // downgrade plus re-upgrade costs the conversation modes and nothing
+ // else, and those fall back to settings.codexDefaultMode.
partialize: (state) => ({
workingDirectory: state.workingDirectory,
+ modeByConversation: state.modeByConversation,
}),
// Existing installs have a persisted `chatMode: 'codex'` (or similar) in
// localStorage from v2.3.8 and earlier. partialize only affects writes,