The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(agent): "Always allow `npm test` here", and a readable approval card (CA K4)
purple6e16e5b7e655
diff --git a/e2e/ca-shots.spec.ts b/e2e/ca-shots.spec.tsnew file mode 100644index 00000000..320e0baa--- /dev/null+++ b/e2e/ca-shots.spec.ts@@ -0,0 +1,122 @@+import { test, expect, type Page } from '@playwright/test'+import { tauriMockInit, DEFAULT_MODEL_NAME } from './support/tauri-mock'+import { seedOnboardingDone } from './support/cloud-mock'+import { openNewChat } from './support/ui'++/**+ * Pictures of a coding run for the CA review (Code tab and Agent mode), not a+ * test of anything. Runs only when LU_CA_SHOTS names a folder:+ *+ * LU_CA_SHOTS=/path LU_E2E_PORT=5431 npx playwright test e2e/ca-shots.spec.ts --project=chromium+ */+const OUT = process.env.LU_CA_SHOTS++const MATH = [+ 'export function mean(xs: number[]): number {',+ ' return xs.reduce((a, b) => a + b, 0) / xs.length',+ '}',+ '',+ 'export function median(xs: number[]): number {',+ ' return 0 // TODO',+ '}',+].join('\n')++type Turn = { text?: string; thinking?: string; toolCalls?: Array<{ name: string; args: Record<string, unknown> }> }++const CODE_RUN: Turn[] = [+ { text: 'Let me look at the file first.', toolCalls: [{ name: 'file_read', args: { path: 'src/math.ts' } }] },+ {+ text: '`median` returns 0. I will sort a copy and take the middle.',+ toolCalls: [{+ name: 'file_edit',+ args: {+ path: 'src/math.ts',+ old_string: ' return 0 // TODO',+ new_string: ' const s = [...xs].sort((a, b) => a - b)\n const m = Math.floor(s.length / 2)\n return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2',+ },+ }],+ },+ { text: 'Now the tests.', toolCalls: [{ name: 'shell_execute', args: { command: 'npm test -- math' } }] },+ { text: '`median()` is implemented and the tests pass.\n\n- sorts a copy, so the input stays unchanged\n- even length: mean of the two middle values' },+]++type Theme = 'dark' | 'light'++async function boot(page: Page, turns: Turn[], width: number, theme: Theme, holdTools = false) {+ await page.addInitScript(tauriMockInit, {+ assistantReply: 'unused',+ modelName: DEFAULT_MODEL_NAME,+ replyChunkDelayMs: 6,+ agentTurns: turns,+ holdTools,+ toolDelayMs: 250,+ files: { 'math.ts': MATH },+ })+ await seedOnboardingDone(page)+ await page.setViewportSize({ width, height: 900 })+ await page.goto('/')+ const isDark = await page.evaluate(() => document.documentElement.classList.contains('dark'))+ if (isDark !== (theme === 'dark')) {+ await page.getByRole('banner').getByTitle(/^(Light|Dark) Mode$/).click()+ }+}++async function send(page: Page, text: string) {+ const composer = page.locator('textarea').first()+ await expect(composer).toBeEnabled({ timeout: 20_000 })+ await composer.fill(text)+ await composer.press('Enter')+}++async function shot(page: Page, name: string) {+ await page.waitForTimeout(600)+ await page.screenshot({ path: `${OUT}/${name}.png` })+}++test.describe('CA shots', () => {+ test.skip(!OUT, 'set LU_CA_SHOTS to a folder')+ for (const theme of ['dark', 'light'] as const) {+ for (const width of [1280, 375]) {+ test(`code tab ${theme} ${width}`, async ({ page }) => {+ await boot(page, CODE_RUN, width, theme)+ if (width >= 1024) await page.getByRole('button', { name: 'Code', exact: true }).click()+ else {+ await page.getByRole('banner').getByRole('button', { name: 'Main navigation' }).click().catch(() => {})+ await page.getByRole('button', { name: 'Code', exact: true }).first().click().catch(() => {})+ }+ await openNewChat(page)+ await send(page, 'median() in src/math.ts is missing, implement it and run the tests')+ // Ask mode: the edit and the shell command wait for the user.+ await page.waitForTimeout(2500)+ await shot(page, `code-${theme}-${width}-1-waiting`)+ for (let i = 0; i < 4; i++) {+ const allow = page.getByRole('button', { name: /^(Allow|Approve|Apply|Run|Accept)/ }).first()+ if (await allow.isVisible().catch(() => false)) {+ await allow.click()+ await page.waitForTimeout(1200)+ }+ }+ await page.waitForTimeout(2000)+ await shot(page, `code-${theme}-${width}-2-done`)+ })+ }+ }++ test('agent mode dark 1280', async ({ page }) => {+ await boot(page, CODE_RUN, 1280, 'dark')+ await openNewChat(page)+ await page.getByRole('main').getByRole('button', { name: 'Agent', exact: true }).click()+ await send(page, 'median() in src/math.ts is missing, implement it and run the tests')+ await page.waitForTimeout(2500)+ await shot(page, 'agent-dark-1280-1-waiting')+ for (let i = 0; i < 4; i++) {+ const allow = page.getByRole('button', { name: /^(Allow|Approve|Apply|Run|Accept)/ }).first()+ if (await allow.isVisible().catch(() => false)) {+ await allow.click()+ await page.waitForTimeout(1200)+ }+ }+ await page.waitForTimeout(2000)+ await shot(page, 'agent-dark-1280-2-done')+ })+})diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex 5f4e1aa9..91619e81 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -948,7 +948,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p}`}><Icon size={11} className="shrink-0 text-gray-400 dark:text-gray-500" />- <span className="min-w-0 truncate text-[0.72rem]">+ <span className="min-w-0 truncate t-control"><span className="font-medium text-gray-800 dark:text-gray-100">{base}{entry.isDir ? '/' : ''}</span>{dir && <span className="ml-1.5 t-micro text-gray-400 dark:text-gray-500">{dir}</span>}</span>diff --git a/src/components/chat/CodexConfirmDialog.tsx b/src/components/chat/CodexConfirmDialog.tsxindex 652578a0..1d13f279 100644--- a/src/components/chat/CodexConfirmDialog.tsx+++ b/src/components/chat/CodexConfirmDialog.tsx@@ -1,13 +1,19 @@// The coding agent's shell/code approval, inline in the transcript.//-// Two rewrites got it here. It started as `window.confirm`, an OS dialog with-// system chrome and the app origin in its title bar, which the owner called exactly-// what it looked like. The first replacement was a centred modal, which was-// small and tidy but still covered the conversation you were reading. This one-// sits in the stream under the tool call it belongs to, so the pending command-// reads as one more step of the run rather than an interruption of it.+// Three rewrites got it here. It started as `window.confirm`, an OS dialog with+// system chrome and the app origin in its title bar. The first replacement was+// a centred modal that covered the conversation. The second sat in the stream+// under its tool call but read like a debug line ("shell_execute needs your+// ok", then `command: …` and `timeout: 600000`). CA (13.11.2026) makes it a+// question a person reads: what will run, where, and three answers, one of+// them "always allow this here" (stores/commandRulesStore), like the large+// coding tools.//-// "Don't ask again" both allows the current command AND clears the setting that+// What runs is never hidden: for a plain command the card shows the command,+// for anything with a script, stdin or more fields it shows every field that+// shapes the process (renderApprovalPreview), as before.+//+// "Stop asking" both allows the current command AND clears the setting that// caused the prompt. Clearing without allowing would leave the task blocked on// a question that will not be asked again, which is not what the phrase means.@@ -15,11 +21,24 @@ import { useEffect, useRef } from 'react'import { Terminal } from 'lucide-react'import { useCodexConfirmStore } from '../../stores/codexConfirmStore'import { useSettingsStore } from '../../stores/settingsStore'+import { useCommandRulesStore } from '../../stores/commandRulesStore'+import { suggestRuleFor } from '../../lib/agent-core/command-rules'++/** Fields that only tune how a command runs, not what it does. */+const QUIET_FIELDS = new Set(['timeout', 'shell', 'background'])++/** The command alone when that is all that shapes the process. */+export function plainCommandOf(args: Record<string, unknown> | undefined): string | null {+ if (!args || typeof args.command !== 'string' || !args.command.trim()) return null+ const loud = Object.keys(args).filter((k) => k !== 'command' && k !== 'cwd' && !QUIET_FIELDS.has(k) && args[k] !== undefined && args[k] !== null && args[k] !== '')+ return loud.length === 0 ? args.command.trim() : null+}export function CodexConfirmDialog() {const pending = useCodexConfirmStore((s) => s.pending)const answer = useCodexConfirmStore((s) => s.answer)const updateSettings = useSettingsStore((s) => s.updateSettings)+ const allowRule = useCommandRulesStore((s) => s.allow)const card = useRef<HTMLDivElement>(null)// The card is the one thing the run waits for, so it must be on screen the@@ -32,6 +51,11 @@ export function CodexConfirmDialog() {if (!pending) return null+ const plain = plainCommandOf(pending.args)+ const cwd = typeof pending.args?.cwd === 'string' && pending.args.cwd.trim() ? pending.args.cwd.trim() : null+ const rule = pending.toolName === 'shell_execute' && pending.ruleScope && plain ? suggestRuleFor(plain) : null+ const isCommand = pending.toolName === 'shell_execute' || pending.toolName === 'code_execute' || pending.toolName === 'shell_execute_background'+const stopAsking = () => {// Clear whichever arm is asking. When the cloud arm is the reason, the// general confirm is already off, so clearing that one would change nothing@@ -41,37 +65,63 @@ export function CodexConfirmDialog() {answer(true)}+ const alwaysHere = () => {+ if (rule && pending.ruleScope) allowRule(pending.ruleScope, rule)+ answer(true)+ }+return (<div ref={card} className="px-1 py-0.5" data-codex-confirm>- <div className="rounded-lg border border-purple-500/20 bg-purple-500/[0.04] px-2 py-1.5">- <div className="flex items-center gap-1.5 t-micro text-gray-700 dark:text-gray-300">- <Terminal size={10} className="text-purple-400 shrink-0" />- <span className="font-mono">{pending.toolName}</span>- <span className="text-gray-500">needs your ok</span>+ <div className="rounded-lg border border-gray-200 dark:border-white/[0.1] bg-white dark:bg-white/[0.03] shadow-sm overflow-hidden">+ <div className="flex items-center gap-2 px-3 pt-2.5 pb-1.5">+ <Terminal size={14} className="text-gray-500 dark:text-gray-400 shrink-0" />+ <span className="t-body font-medium text-gray-800 dark:text-gray-100">+ {isCommand ? 'Run this command?' : 'Allow this step?'}+ </span>+ {pending.cloudReason && (+ <span className="ml-auto t-micro text-gray-500 dark:text-gray-400">asked because a cloud model is driving</span>+ )}</div>- <pre className="mt-1 max-h-20 overflow-auto rounded bg-black/5 dark:bg-black/30 px-1.5 py-1 t-micro font-mono text-gray-800 dark:text-gray-200 whitespace-pre-wrap break-all">- {pending.command || '(no command preview)'}- </pre>+ <div className="px-3">+ <pre+ data-testid="confirm-command"+ className="max-h-48 overflow-auto rounded-md bg-gray-950 dark:bg-black/50 px-3 py-2 t-mono leading-relaxed text-gray-100 whitespace-pre-wrap break-all"+ >+ {pending.command && !plain ? pending.command : plain ? <><span className="select-none text-gray-500">$ </span>{plain}</> : '(no command preview)'}+ </pre>+ {plain && cwd && (+ <div className="mt-1 t-micro text-gray-500 dark:text-gray-400 truncate" title={cwd}>in {cwd}</div>+ )}+ </div>- <div className="mt-1.5 flex items-center gap-1.5">+ <div className="flex flex-wrap items-center gap-1.5 px-3 pt-2 pb-2.5"><buttononClick={() => answer(true)}autoFocus- className="px-2 py-0.5 rounded t-micro font-medium bg-emerald-500/15 text-emerald-700 dark:text-emerald-300 hover:bg-emerald-500/25 transition-colors"+ className="inline-flex items-center gap-1.5 px-3 py-1 rounded-md t-control font-medium bg-gray-900 text-white hover:bg-gray-800 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-200 transition-colors">- Run+ Run <kbd className="t-micro opacity-60 font-sans">⏎</kbd></button>+ {rule && (+ <button+ onClick={alwaysHere}+ data-testid="confirm-always-here"+ title="Runs this command, and from now on commands that start like this run without asking in this folder. You can remove the rule in Settings → Agent."+ className="inline-flex items-center gap-1 px-3 py-1 rounded-md t-control text-gray-800 dark:text-gray-100 border border-gray-300 dark:border-white/15 hover:bg-gray-100 dark:hover:bg-white/[0.06] transition-colors max-w-full"+ >+ <span className="shrink-0">Always allow</span>+ <code className="font-mono t-micro truncate">{rule}</code>+ <span className="shrink-0">here</span>+ </button>+ )}<buttononClick={() => answer(false)}- className="px-2 py-0.5 rounded t-micro text-gray-600 dark:text-gray-400 hover:bg-gray-200/60 dark:hover:bg-white/5 transition-colors"+ className="inline-flex items-center gap-1.5 px-3 py-1 rounded-md t-control text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.06] transition-colors">- No+ No <kbd className="t-micro opacity-60 font-sans">Esc</kbd></button><div className="flex-1" />- {pending.cloudReason && (- <span className="text-[0.55rem] text-gray-500">cloud model</span>- )}<buttononClick={stopAsking}// What the click does, not more: it allows this command anddiff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsxindex fb611127..158730bf 100644--- a/src/components/chat/ToolCallBlock.tsx+++ b/src/components/chat/ToolCallBlock.tsx@@ -26,6 +26,8 @@ import { useWorkflowCardStore, workflowCardForCall } from '../../stores/workflowimport { parseWorkflowMark } from '../../api/mcp/workflow-mark'import { isSelfControlToolName } from '../../lib/settings-tool-names'import { useChatStore } from '../../stores/chatStore'+import { useCommandRulesStore } from '../../stores/commandRulesStore'+import { suggestRuleFor } from '../../lib/agent-core/command-rules'import { commandIcon } from '../../lib/shell-command-classify'import { requestGenerationCancel } from '../../api/vram-handoff'import { cancelBackgroundJob } from '../../lib/background-cancels'@@ -282,6 +284,10 @@ function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {const isRunning = toolCall.status === 'running'const isPending = toolCall.status === 'pending_approval'const isFailed = toolCall.status === 'failed' || toolCall.status === 'rejected'+ // CA K4: "Always allow `npm test` here", for a waiting shell call that knows its folder.+ const alwaysRule = isPending && toolCall.toolName === 'shell_execute' && toolCall.ruleScope && typeof toolCall.args?.command === 'string'+ ? suggestRuleFor(toolCall.args.command)+ : null// The first use of computer control in a chat waits here for the user's yes.const chatAsk = useComputerChatAsk(toolCall.toolName, isRunning, useChatStore((s) => s.activeConversationId))// A11 / C60: a change LU makes to itself waits here for Accept, and stays@@ -630,6 +636,20 @@ A user 2026-06-07 fix this lived inside the collapsed details, so a><Check size={10} /> Approve</button>+ {alwaysRule && (+ <button+ onClick={(e) => {+ e.stopPropagation()+ useCommandRulesStore.getState().allow(toolCall.ruleScope!, alwaysRule)+ onApprove()+ }}+ data-testid="approve-always-here"+ title="Approves this command, and from now on commands that start like this run without asking in this folder. You can remove the rule in Settings → Agent."+ className="flex items-center gap-1 px-2.5 py-1 rounded t-micro text-gray-700 dark:text-gray-200 border border-gray-300 dark:border-white/15 hover:bg-gray-100 dark:hover:bg-white/[0.06] transition-colors"+ >+ Always allow <code className="font-mono">{alwaysRule}</code> here+ </button>+ )}<buttononClick={(e) => { e.stopPropagation(); onReject() }}className="flex items-center gap-1 px-2.5 py-1 rounded t-micro font-medium text-red-700 dark:text-red-300 bg-red-500/10 dark:bg-red-500/10 hover:bg-red-500/15 dark:hover:bg-red-500/15 border border-red-500/20 dark:border-red-500/25 transition-colors"diff --git a/src/components/settings/CommandRulesSettings.tsx b/src/components/settings/CommandRulesSettings.tsxnew file mode 100644index 00000000..7ce2025a--- /dev/null+++ b/src/components/settings/CommandRulesSettings.tsx@@ -0,0 +1,51 @@+/**+ * Settings → Agent → Allowed commands (CA K4).+ *+ * The commands the user said "always allow here" for, per folder, with a way+ * to take each one back. Nothing is added from this screen: a rule only comes+ * from the user's own click on a waiting command.+ */+import { X } from 'lucide-react'+import { useCommandRulesStore } from '../../stores/commandRulesStore'++function scopeLabel(scope: string): string {+ return scope.startsWith('chat:') ? 'One chat’s own folder' : scope+}++export function CommandRulesSettings() {+ const rules = useCommandRulesStore((s) => s.rules)+ const remove = useCommandRulesStore((s) => s.remove)+ const scopes = Object.keys(rules).filter((k) => rules[k]?.length)++ return (+ <div className="space-y-2" data-testid="command-rules">+ <div className="t-micro text-gray-500 dark:text-gray-500 leading-relaxed">+ Commands that run without asking, because you chose “Always allow … here” on one of them. They only apply in that folder, every part of a combined command must be on the list, and dangerous commands stay blocked whatever this list says.+ </div>+ {scopes.length === 0 ? (+ <div className="t-micro text-gray-500">None yet.</div>+ ) : (+ scopes.map((scope) => (+ <div key={scope} className="rounded border border-gray-200 dark:border-white/10 p-2">+ <div className="t-micro text-gray-600 dark:text-gray-400 truncate" title={scope}>{scopeLabel(scope)}</div>+ <div className="mt-1 flex flex-wrap gap-1.5">+ {rules[scope].map((rule) => (+ <span key={rule} className="inline-flex items-center gap-1 rounded bg-gray-100 dark:bg-white/[0.06] pl-2 pr-1 py-0.5">+ <code className="font-mono t-micro text-gray-800 dark:text-gray-200">{rule}</code>+ <button+ type="button"+ onClick={() => remove(scope, rule)}+ aria-label={`Remove ${rule}`}+ className="p-0.5 rounded text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-black/5 dark:hover:bg-white/10"+ >+ <X size={10} />+ </button>+ </span>+ ))}+ </div>+ </div>+ ))+ )}+ </div>+ )+}diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex f6eb8fa8..5d0849bf 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -1,4 +1,5 @@import { SkillsSettings } from './SkillsSettings'+import { CommandRulesSettings } from './CommandRulesSettings'import { useState, useEffect, useLayoutEffect, useRef, type ReactNode, type ChangeEvent } from 'react'import { withDetail } from '../../lib/error-text'// `X` steht hier weiterhin, obwohl der Sprachabschnitt mit seinen Symbolen@@ -2543,6 +2544,12 @@ export function SettingsPage() {</Section>)}+ {FEATURE_FLAGS.AGENT_MODE && (+ <Section title="Allowed commands">+ <CommandRulesSettings />+ </Section>+ )}+{FEATURE_FLAGS.AGENT_WORKFLOWS && (<Section title="Agent Workflows"><WorkflowSection />diff --git a/src/components/settings/settings-nav.ts b/src/components/settings/settings-nav.tsindex a4b61dac..dbc91465 100644--- a/src/components/settings/settings-nav.ts+++ b/src/components/settings/settings-nav.ts@@ -115,7 +115,7 @@ export function sectionsFor(tab: SettingsTab, flags: SettingsSectionFlags): stri// Auto-Compact; eine Persona suchte sie beim Agenten und fand sie// dort nicht. Ein delegierter Lauf hat keinen Zuschauer — das ist// ein anderer Gegenstand als die Werte des Zugs, vor dem man sitzt.- ...(flags.agentMode ? ['Sub-agents', 'Skills'] : []),+ ...(flags.agentMode ? ['Sub-agents', 'Skills', 'Allowed commands'] : []),...(flags.agentWorkflows ? ['Agent Workflows'] : []),...(flags.agentMode ? ['MCP Servers', 'Coding Agent', 'Search Provider'] : []),]diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 24764a4a..5fc5c993 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -17,7 +17,8 @@ import { v4 as uuid } from 'uuid'import { streamProviderTurn, type StreamedProviderTurn } from '../lib/provider-stream'import { requestUsageTracker } from '../lib/request-usage'import { createHermesDisplayFilter, createThinkStreamSplitter, createTurnThinkingSink } from '../lib/hermes-stream'-import { beginAgentRun, endAgentRun, setActiveAgentModel, renderWorkspaceSection, takeChatArtifacts, type AgentRunContext } from '../api/agent-context'+import { beginAgentRun, endAgentRun, getActiveWorkspace, setActiveAgentModel, renderWorkspaceSection, takeChatArtifacts, type AgentRunContext } from '../api/agent-context'+import { commandAllowedHere, ruleScope } from '../stores/commandRulesStore'import { resolveChatWorkspaceSlug } from '../api/workspace-slug'import { isOllamaLocal } from '../api/backend'import { requestGenerationCancel } from '../api/vram-handoff'@@ -3092,7 +3093,13 @@ export function useAgentChat() {cloudOptIn: settings.codexCloudConfirmOptIn,providerId,})+ // CA K4: a command the user allowed for this folder ("Always allow+ // here") skips the card; chains need every part covered.+ // Never for a blocked tool: a rule answers "ask?", not "allowed?".+ const ruleAllows = permLevel !== 'blocked' && tc.function.name === 'shell_execute'+ && commandAllowedHere(ruleScope(getActiveWorkspace(run), convId), tc.function.arguments?.command)const needsApproval = (permLevel !== 'auto' || cloudShellConfirm)+ && !ruleAllows&& !(await approvalIsMoot(tc.function.name, tc.function.arguments ?? {}, run))// Exec-timeout parity with the Code tab (audit B8): without an// injected default the Rust side used its 120 s fallback, so the@@ -3109,6 +3116,10 @@ export function useAgentChat() {status: needsApproval ? 'pending_approval' : 'running',timestamp: Date.now(),}+ if (needsApproval && tc.function.name === 'shell_execute') {+ const scope = ruleScope(getActiveWorkspace(run), convId)+ if (scope) ac.ruleScope = scope+ }addBlock(runState, convId!, assistantMessage.id, {id: blockId,phase: 'tool_call',diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 41ad0b4d..bfef50df 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -39,7 +39,7 @@ import { codexAsksBefore } from '../lib/agent-approval-policy'import { buildHermesToolPrompt, buildHermesToolResult, buildHermesToolCall, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'import { streamProviderTurn, type StreamedProviderTurn } from '../lib/provider-stream'import { createHermesDisplayFilter, createThinkStreamSplitter, createTurnThinkingSink } from '../lib/hermes-stream'-import { beginAgentRun, endAgentRun, setActiveAgentModel, type AgentRunContext } from '../api/agent-context'+import { beginAgentRun, endAgentRun, getActiveWorkspace, setActiveAgentModel, type AgentRunContext } from '../api/agent-context'import { resolveChatWorkspaceSlug } from '../api/workspace-slug'import { codexModeKnobs, isCodexMode, stricterCodexMode, type CodexMode } from '../lib/codex-mode'import { CODEX_PLAN_SYSTEM_PROMPT } from '../lib/codex-plan-prompt'@@ -114,6 +114,7 @@ import { turnCaps } from '../lib/remote-turn-caps'import { useMemoryStore } from '../stores/memoryStore'import { extractMemoriesFromPair } from './useMemory'import { useCodexConfirmStore } from '../stores/codexConfirmStore'+import { commandAllowedHere, ruleScope } from '../stores/commandRulesStore'// ── Die Teile, die dieser Haken nicht mehr selbst traegt ────────────────────// Jedes dieser Module haelt EINEN geteilten Zustand oder EINE Regel, die// mehrere Stellen hier gemeinsam brauchen; der Dateikopf dort sagt jeweils,@@ -2497,6 +2498,11 @@ export function useCodex() {external: toolRegistry.getToolByName(req.toolName)?.source === 'external',})) return trueconst a = req.args || {}+ // CA K4: a command the user allowed for this folder runs without+ // the card. Every part of a chain must be covered, and the hard+ // block list still applies when it runs.+ const scope = ruleScope(getActiveWorkspace(req.run), convId)+ if (req.toolName === 'shell_execute' && commandAllowedHere(scope, a.command)) return true// In-app popup, not window.confirm. The native dialog carried OS// chrome and the app origin in its title bar, could not be// styled, and had no way to say "stop asking" (2026-07-24).@@ -2513,6 +2519,7 @@ export function useCodex() {// what put the gate up.cloudReason: !settings.codexConfirmShell && codexMode !== 'ask' && providerId === 'lu-cloud',...(convId ? { conversationId: convId } : {}),+ ...(scope ? { ruleScope: scope } : {}),}, abort.signal)}// Unattended by choice, stated in writing: awaitApproval is adiff --git a/src/lib/agent-core/__tests__/command-rules.test.ts b/src/lib/agent-core/__tests__/command-rules.test.tsnew file mode 100644index 00000000..5ea2cbcb--- /dev/null+++ b/src/lib/agent-core/__tests__/command-rules.test.ts@@ -0,0 +1,105 @@+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { beforeEach, describe, expect, it } from 'vitest'+import { commandAllowedByRules, splitCommandChain, suggestRuleFor } from '../command-rules'+import { commandAllowedHere, ruleScope, useCommandRulesStore } from '../../../stores/commandRulesStore'++describe('the rule offered for a command', () => {+ it.each([+ ['npm test -- math', 'npm test'],+ ['npm run build', 'npm run build'],+ ['npx vitest run src', 'npx vitest'],+ ['git status', 'git status'],+ ['cargo test --lib', 'cargo test'],+ ['python3 app.py "Hallo Welt"', 'python3 app.py'],+ ['ls -la', 'ls'],+ ['pytest -q', 'pytest'],+ ])('%s → %s', (cmd, rule) => {+ expect(suggestRuleFor(cmd)).toBe(rule)+ })++ it('is the exact command for programs whose arguments are the action', () => {+ expect(suggestRuleFor('rm -rf build')).toBe('rm -rf build')+ expect(suggestRuleFor('curl https://example.com')).toBe('curl https://example.com')+ })++ it('is nothing for chains, inline code, env prefixes and substitution', () => {+ expect(suggestRuleFor('npm test && npm run lint')).toBeNull()+ expect(suggestRuleFor('python3 -c "print(1)"')).toBeNull()+ expect(suggestRuleFor('node -e "x"')).toBeNull()+ expect(suggestRuleFor('FOO=1 npm test')).toBeNull()+ expect(suggestRuleFor('echo $(whoami)')).toBeNull()+ })+})++describe('splitting a command', () => {+ it('splits on && || ; | and newlines outside quotes', () => {+ expect(splitCommandChain('npm test && git status; ls | wc -l')).toEqual(['npm test', 'git status', 'ls', 'wc -l'])+ expect(splitCommandChain('echo "a && b"')).toEqual(['echo "a && b"'])+ })++ it('refuses substitution, redirection and background jobs', () => {+ for (const c of ['echo `id`', 'echo $(id)', 'echo "$(id)"', 'npm test > out.txt', 'cat < x', 'sleep 9 &', 'diff <(a) b']) {+ expect(splitCommandChain(c)).toBeNull()+ }+ })+})++describe('matching rules', () => {+ const rules = ['npm test', 'git status', 'rm -rf build']++ it('allows a command under a prefix, on whole words', () => {+ expect(commandAllowedByRules('npm test -- math', rules)).toBe(true)+ expect(commandAllowedByRules('npm testing', rules)).toBe(false)+ expect(commandAllowedByRules('npm install', rules)).toBe(false)+ })++ it('needs every part of a chain', () => {+ expect(commandAllowedByRules('npm test && git status', rules)).toBe(true)+ expect(commandAllowedByRules('npm test && rm -rf /', rules)).toBe(false)+ expect(commandAllowedByRules('npm test | sh', rules)).toBe(false)+ })++ it('takes an exact-only program only as written', () => {+ expect(commandAllowedByRules('rm -rf build', rules)).toBe(true)+ expect(commandAllowedByRules('rm -rf build ~', rules)).toBe(false)+ })++ it('never lets a rule cover substitution or a redirect', () => {+ expect(commandAllowedByRules('npm test $(curl evil)', rules)).toBe(false)+ expect(commandAllowedByRules('npm test > /etc/hosts', rules)).toBe(false)+ })++ it('never lets a prefix rule cover inline interpreter code', () => {+ expect(commandAllowedByRules('python3 -c "import os"', ['python3'])).toBe(false)+ })+})++describe('the rules store', () => {+ beforeEach(() => useCommandRulesStore.setState({ rules: {} }))++ it('keeps rules per folder and never across', () => {+ useCommandRulesStore.getState().allow('/work/a', 'npm test')+ expect(commandAllowedHere('/work/a', 'npm test -- x')).toBe(true)+ expect(commandAllowedHere('/work/b', 'npm test -- x')).toBe(false)+ useCommandRulesStore.getState().remove('/work/a', 'npm test')+ expect(commandAllowedHere('/work/a', 'npm test')).toBe(false)+ })++ it('scopes a sandboxed chat to itself', () => {+ expect(ruleScope({ kind: 'folder', path: '/work/a' }, 'c1')).toBe('/work/a')+ expect(ruleScope(null, 'c1')).toBe('chat:c1')+ expect(ruleScope(null, null)).toBeNull()+ })+})++describe('both approval gates read the rules', () => {+ const src = (p: string) => readFileSync(resolve(__dirname, '../../..', p), 'utf8')+ it('Code tab and Agent tab skip the card only for a covered shell command', () => {+ expect(src('hooks/useCodex.ts')).toMatch(/req\.toolName === 'shell_execute' && commandAllowedHere\(scope, a\.command\)/)+ expect(src('hooks/useAgentChat.ts')).toMatch(/permLevel !== 'blocked' && tc\.function\.name === 'shell_execute'\s*&& commandAllowedHere/)+ })+ it('the hard block list still sits at execution, outside the rules', () => {+ expect(src('api/mcp/builtin-tools.ts')).toContain('hardBlockedShellCommand(')+ })+})diff --git a/src/lib/agent-core/command-rules.ts b/src/lib/agent-core/command-rules.tsnew file mode 100644index 00000000..71e7836d--- /dev/null+++ b/src/lib/agent-core/command-rules.ts@@ -0,0 +1,142 @@+/**+ * "Always allow `npm test` here" (CA K4).+ *+ * Claude Code, Codex, Cursor, Windsurf and VS Code all let the user approve a+ * command once and for the future, scoped to a project and to the command's+ * prefix, so a run that tests after every edit does not ask twenty times. LU+ * only had "ask for every command" or "stop asking for everything". These are+ * the pure rules; the store keeps them per folder (stores/commandRulesStore).+ *+ * The safety properties:+ * - A chained command is allowed only when EVERY part is (`npm test && rm -rf x`+ * needs `rm` too). Pipes count as parts.+ * - Substitution (`$(…)`, backticks, `<(…)`) and output redirection are never+ * allowed by a rule: the part that runs or writes is not the prefix the user+ * approved.+ * - For programs that can do anything with their arguments (rm, sudo, curl,+ * sh, python -c …) the suggested rule is the exact command, never a prefix.+ * - The hard shell block list (lib/shell-command-classify) still applies at+ * execution, in every mode, whatever a rule says.+ */++/** Programs whose second word is the real command (`npm test`, `git status`). */+const TWO_WORD_PROGRAMS = new Set([+ 'npm', 'npx', 'pnpm', 'yarn', 'bun', 'bunx', 'deno', 'node', 'git', 'gh', 'cargo', 'go', 'pip', 'pip3', 'uv',+ 'poetry', 'make', 'docker', 'kubectl', 'dotnet', 'mvn', 'gradle', 'swift', 'rustup', 'brew', 'conda',+])++/** Programs a prefix rule must never cover: their arguments ARE the action. */+const EXACT_ONLY_PROGRAMS = new Set([+ 'rm', 'rmdir', 'sudo', 'su', 'doas', 'chmod', 'chown', 'dd', 'mkfs', 'curl', 'wget', 'sh', 'bash', 'zsh', 'fish',+ 'eval', 'exec', 'xargs', 'env', 'ssh', 'scp', 'rsync', 'mv', 'kill', 'killall', 'pkill', 'osascript', 'open',+ 'powershell', 'pwsh', 'cmd', 'reg', 'shutdown', 'reboot', 'launchctl', 'crontab',+])++/** Interpreters: a script file is a fine prefix, inline code is not. */+const INTERPRETERS = new Set(['python', 'python3', 'node', 'ruby', 'perl', 'php', 'deno', 'bun'])+const INLINE_CODE_FLAGS = new Set(['-c', '-e', '--eval', '-p', '--print', '-'])++/** Split on && || ; | and newlines, outside quotes. Null when the command has+ * substitution or redirection a rule must not cover. */+export function splitCommandChain(command: string): string[] | null {+ const parts: string[] = []+ let cur = ''+ let quote: '"' | "'" | null = null+ const s = command.trim()+ for (let i = 0; i < s.length; i++) {+ const ch = s[i]+ if (quote) {+ if (ch === '\\' && quote === '"' && i + 1 < s.length) { cur += ch + s[++i]; continue }+ if (ch === quote) quote = null+ // Substitution inside double quotes still runs.+ if (quote === '"' && ch === '$' && s[i + 1] === '(') return null+ if (quote === '"' && ch === '`') return null+ cur += ch+ continue+ }+ if (ch === '"' || ch === "'") { quote = ch; cur += ch; continue }+ if (ch === '\\' && i + 1 < s.length) { cur += ch + s[++i]; continue }+ if (ch === '`') return null+ if ((ch === '$' || ch === '<') && s[i + 1] === '(') return null+ if (ch === '>' || ch === '<') return null+ if (ch === '&' && s[i + 1] === '&') { parts.push(cur); cur = ''; i++; continue }+ if (ch === '|' && s[i + 1] === '|') { parts.push(cur); cur = ''; i++; continue }+ if (ch === '&') return null // background job: not the command that was approved+ if (ch === ';' || ch === '|' || ch === '\n' || ch === '\r') { parts.push(cur); cur = ''; continue }+ cur += ch+ }+ if (quote) return null+ parts.push(cur)+ const out = parts.map((p) => p.trim()).filter(Boolean)+ return out.length ? out : null+}++function words(part: string): string[] {+ return part.trim().split(/\s+/).filter(Boolean)+}++/** Leading `FOO=bar` assignments change what runs; a rule never skips them. */+function hasEnvPrefix(part: string): boolean {+ return /^[A-Za-z_][A-Za-z0-9_]*=/.test(part.trim())+}++function program(w: string): string {+ // `./node_modules/.bin/vitest` → vitest; `/usr/bin/git` → git.+ return w.split('/').pop()!.toLowerCase()+}++/**+ * The rule to offer for one command, or null when only "this once" is safe.+ * `npm test -- math` → `npm test`; `python3 app.py` → `python3 app.py`;+ * `rm -rf build` → the exact command; a chain → null.+ */+export function suggestRuleFor(command: string): string | null {+ const parts = splitCommandChain(command)+ if (!parts || parts.length !== 1) return null+ const part = parts[0]+ if (hasEnvPrefix(part)) return null+ const w = words(part)+ if (w.length === 0) return null+ const prog = program(w[0])+ if (EXACT_ONLY_PROGRAMS.has(prog)) return part+ if (INTERPRETERS.has(prog)) {+ // `python3 app.py`, `node script.js`, `bun test`: the script or the+ // subcommand, never the bare interpreter.+ if (w.length < 2 || INLINE_CODE_FLAGS.has(w[1]) || w[1].startsWith('-')) return null+ return `${w[0]} ${w[1]}`+ }+ if (TWO_WORD_PROGRAMS.has(prog) && w.length >= 2 && !w[1].startsWith('-')) {+ // `npm run build` keeps the script name: `npm run` alone would allow every script.+ if ((prog === 'npm' || prog === 'pnpm' || prog === 'yarn' || prog === 'bun') && w[1] === 'run' && w[2]) {+ return `${w[0]} run ${w[2]}`+ }+ return `${w[0]} ${w[1]}`+ }+ return w[0]+}++/** Does one part fall under one rule? Prefix on whole words only. */+function partMatches(part: string, rule: string): boolean {+ const p = words(part)+ const r = words(rule)+ if (r.length === 0 || p.length < r.length) return false+ if (hasEnvPrefix(part)) return false+ const prog = program(p[0])+ // An exact-only program needs the exact command, whatever the rule looks like.+ if (EXACT_ONLY_PROGRAMS.has(prog)) return p.join(' ') === r.join(' ')+ if (INTERPRETERS.has(prog) && INLINE_CODE_FLAGS.has(p[1] ?? '')) return false+ for (let i = 0; i < r.length; i++) {+ const a = i === 0 ? program(p[i]) : p[i]+ const b = i === 0 ? program(r[i]) : r[i]+ if (a !== b) return false+ }+ return true+}++/** True when every part of the command is covered by one of the rules. */+export function commandAllowedByRules(command: string, rules: readonly string[]): boolean {+ if (!rules.length) return false+ const parts = splitCommandChain(command)+ if (!parts) return false+ return parts.every((part) => rules.some((rule) => partMatches(part, rule)))+}diff --git a/src/stores/codexConfirmStore.ts b/src/stores/codexConfirmStore.tsindex d69584a0..0899d182 100644--- a/src/stores/codexConfirmStore.ts+++ b/src/stores/codexConfirmStore.ts@@ -34,6 +34,9 @@ export interface CodexConfirmRequest {/** The chat that asks, when known: a shared chat forwards the question to* the paired phone (lib/remote-chats-bridge). */conversationId?: string+ /** Where an "always allow here" rule would be kept (stores/commandRulesStore):+ * the run's folder, or this chat's own sandbox. Absent: no such button. */+ ruleScope?: string}interface Waiting {diff --git a/src/stores/commandRulesStore.ts b/src/stores/commandRulesStore.tsnew file mode 100644index 00000000..fe895d4b--- /dev/null+++ b/src/stores/commandRulesStore.ts@@ -0,0 +1,72 @@+/**+ * The commands the user said "always allow here" for (CA K4).+ *+ * Keyed by scope: a picked folder's path, or `chat:<id>` for a chat that works+ * in its own sandbox folder. Rules never cross folders: `npm test` allowed in+ * one project asks again in the next one. The pure matching lives in+ * lib/agent-core/command-rules.ts.+ */+import { create } from 'zustand'+import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'+import { commandAllowedByRules } from '../lib/agent-core/command-rules'++/** More than this per folder is a list nobody reads any more. */+export const MAX_RULES_PER_SCOPE = 50++interface CommandRulesState {+ rules: Record<string, string[]>+ allow: (scope: string, rule: string) => void+ remove: (scope: string, rule: string) => void+ clearScope: (scope: string) => void+}++export const useCommandRulesStore = create<CommandRulesState>()(+ persist(+ (set) => ({+ rules: {},+ allow: (scope, rule) =>+ set((s) => {+ const r = rule.trim()+ if (!scope || !r) return s+ const list = s.rules[scope] ?? []+ if (list.includes(r)) return s+ return { rules: { ...s.rules, [scope]: [...list, r].slice(-MAX_RULES_PER_SCOPE) } }+ }),+ remove: (scope, rule) =>+ set((s) => {+ const list = (s.rules[scope] ?? []).filter((x) => x !== rule)+ const next = { ...s.rules }+ if (list.length) next[scope] = list+ else delete next[scope]+ return { rules: next }+ }),+ clearScope: (scope) =>+ set((s) => {+ const next = { ...s.rules }+ delete next[scope]+ return { rules: next }+ }),+ }),+ {+ name: 'locally-uncensored-command-rules',+ storage: safeJSONStorage(),+ version: 1,+ // First version: nothing older to carry over.+ migrate: (persisted) => persisted as CommandRulesState,+ partialize: (s) => ({ rules: s.rules }),+ },+ ),+)++/** The scope a run's rules live under. */+export function ruleScope(workspace: { kind?: string; path?: string } | null | undefined, conversationId: string | null | undefined): string | null {+ if (workspace?.kind === 'folder' && workspace.path) return workspace.path+ return conversationId ? `chat:${conversationId}` : null+}++/** Is this shell command covered by a rule of this scope? */+export function commandAllowedHere(scope: string | null, command: unknown): boolean {+ if (!scope || typeof command !== 'string' || !command.trim()) return false+ return commandAllowedByRules(command, useCommandRulesStore.getState().rules[scope] ?? [])+}diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.tsindex 2f736306..c631afee 100644--- a/src/types/agent-mode.ts+++ b/src/types/agent-mode.ts@@ -111,6 +111,9 @@ export interface AgentToolCall {parentToolCallId?: string/** True when args passed JSON-schema validation (Phase 4). */schemaValidated?: boolean+ /** Where an "always allow here" rule for this shell call would be kept+ * (stores/commandRulesStore): set on a call that waits for approval. */+ ruleScope?: string/** Unified diff for file_write/file_edit, rendered by ToolCallBlock* (audit D5) instead of raw result text. */diff?: string