Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

tech(M2): `background: true` streifte die einzige harte Shell-Sperre ab

Davida277b9211aff
diff --git a/src/api/mcp/__tests__/shell-bg-forwards-shell.test.ts b/src/api/mcp/__tests__/shell-bg-forwards-shell.test.ts
new file mode 100644
index 00000000..afb58d0f
--- /dev/null
+++ b/src/api/mcp/__tests__/shell-bg-forwards-shell.test.ts
@@ -0,0 +1,141 @@
+/**
+ * `shell_execute` bewirbt im Schema ein Feld `shell` ("powershell" | "cmd" |
+ * "bash"). Der Vordergrundpfad reicht es an die Bridge durch, der
+ * Hintergrundpfad hat es stillschweigend weggeworfen: `executeShellExecuteBg`
+ * bekam nur `{ command, cwd }`, und `bgStart` — das `shell?: string` sehr wohl
+ * kennt — sah nie einen Wert. Ein Modell, das
+ * `{ command, shell: "bash", background: true }` schickt, lief damit ohne jede
+ * Meldung in der Plattform-Default-Shell.
+ *
+ * Bis ba9557df waere das Durchreichen gefaehrlich gewesen: `shell_task_start_impl`
+ * baute auf Windows immer PowerShells `-NoProfile -NonInteractive -Command`,
+ * egal welche Shell benannt war — ein durchgereichtes `shell: "cmd"` waere in
+ * die interaktive Eingabeaufforderung gelaufen. Seit ba9557df leitet
+ * `shell::shell_argv` die Argumentform aus dem Shell-NAMEN ab, damit ist das
+ * Durchreichen folgenlos richtig.
+ *
+ * Run: npx vitest run src/api/mcp/__tests__/shell-bg-forwards-shell.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const backendCalls: { cmd: string; body: Record<string, unknown> }[] = []
+
+vi.mock('../../backend', () => ({
+ backendCall: vi.fn(async (cmd: string, body: Record<string, unknown>) => {
+ backendCalls.push({ cmd, body })
+ if (cmd === 'shell_execute') return { stdout: 'ran', stderr: '', exitCode: 0 }
+ if (cmd === 'shell_task_start') return { id: 'task-1' }
+ if (cmd === 'shell_task_kill') return { ok: true, cancelled: true }
+ return { ok: true }
+ }),
+ fetchExternal: vi.fn(async () => ({ ok: true, status: 200, text: async () => '' })),
+}))
+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 '../builtin-tools'
+import { ToolRegistry } from '../tool-registry'
+
+const registry = new ToolRegistry()
+registerBuiltinTools(registry)
+
+function bodyOf(cmd: string): Record<string, unknown> {
+ const call = backendCalls.find((c) => c.cmd === cmd)
+ expect(call, `kein ${cmd} am Backend angekommen`).toBeDefined()
+ return call?.body ?? {}
+}
+
+/** Der `args`-Block, den `shell_task_start` von `bgStart` bekommt. */
+function startArgs(): Record<string, unknown> {
+ // Der Rust-Befehl nimmt einen EINZIGEN `args: Value` (StartArgs); ein flacher
+ // Payload waere an der Bridge abgelehnt worden.
+ const wrapped = bodyOf('shell_task_start').args
+ expect(wrapped, 'shell_task_start ohne `args`-Wrapper').toBeTypeOf('object')
+ return wrapped as Record<string, unknown>
+}
+
+/** Der flache Payload, den der Vordergrundpfad an `shell_execute` schickt. */
+function execPayload(): Record<string, unknown> {
+ return bodyOf('shell_execute')
+}
+
+beforeEach(() => { backendCalls.length = 0 })
+
+describe('shell_execute: `shell` erreicht auch den Hintergrundpfad', () => {
+ it('das Schema verspricht `shell` — genau deshalb muss es ankommen', () => {
+ const props = registry.getToolByName('shell_execute')?.inputSchema.properties
+ expect(props?.shell).toBeDefined()
+ // Und `background` steht im selben Schema, ohne Einschraenkung auf `shell`.
+ expect(props?.background).toBeDefined()
+ })
+
+ it('MUTATIONSSONDE: `shell: "bash"` + `background: true` kommt bis in bgStart an', async () => {
+ await registry.execute('shell_execute', {
+ command: 'npm run build',
+ shell: 'bash',
+ background: true,
+ })
+ // Die eine Zeile, die der Fix gerade macht. Nimmt man das Durchreichen an
+ // einer der beiden Stellen (Dispatch in executeShellExecute oder bgStart-
+ // Aufruf in executeShellExecuteBg) zurueck, faellt genau dieses expect um.
+ expect(startArgs().shell).toBe('bash')
+ expect(startArgs().command).toBe('npm run build')
+ })
+
+ it('"cmd" wird genauso durchgereicht — der Wert wird nicht auf eine Whitelist gefiltert', async () => {
+ // Der Name entscheidet auf Rust-Seite ueber die Argumentform (`/C` statt
+ // `-Command`); das Frontend hat hier nichts zu interpretieren.
+ await registry.execute('shell_execute', { command: 'dir', shell: 'cmd', background: true })
+ expect(startArgs().shell).toBe('cmd')
+ })
+
+ it('reicht `shell` zusammen mit `cwd` durch, ohne das eine gegen das andere zu tauschen', async () => {
+ await registry.execute('shell_execute', {
+ command: 'cargo build',
+ cwd: '/repo',
+ shell: 'powershell',
+ background: true,
+ })
+ expect(startArgs()).toMatchObject({ command: 'cargo build', cwd: '/repo', shell: 'powershell' })
+ })
+
+ it('Vordergrund und Hintergrund sind sich beim selben `shell` einig', async () => {
+ await registry.execute('shell_execute', { command: 'ls', shell: 'bash' })
+ expect(execPayload().shell).toBe('bash')
+ backendCalls.length = 0
+ await registry.execute('shell_execute', { command: 'ls', shell: 'bash', background: true })
+ expect(startArgs().shell).toBe('bash')
+ })
+
+ it('auch unter dem zurueckgezogenen Namen shell_execute_background', async () => {
+ // Der Redirect reicht die ROHEN Modell-Argumente an denselben Executor
+ // weiter — ohne den Fix in executeShellExecuteBg blieben sie hier haengen.
+ const out = await registry.execute('shell_execute_background', {
+ command: 'npm run dev',
+ shell: 'bash',
+ })
+ expect(out).toContain('Task started: task-1')
+ expect(startArgs().shell).toBe('bash')
+ })
+
+ it('NEGATIVKONTROLLE: ohne `shell` wird keins erfunden', async () => {
+ await registry.execute('shell_execute', { command: 'sleep 5', background: true })
+ // Kein String -> die Bridge faellt auf `default_shell` zurueck, wie bisher.
+ expect(startArgs().shell).toBeUndefined()
+ })
+
+ it('NEGATIVKONTROLLE: ein Nicht-String aus dem Modell wird verworfen, nicht weitergereicht', async () => {
+ // `args` kommen vom MODELL, das Schema ist nur ein Hinweis im Prompt. Ein
+ // `shell: 123` an der Bridge waere ein Deserialisierungsfehler statt eines
+ // Laufs — `argOptString` faengt das ab, anders als das vordere
+ // `args.shell || null`.
+ await registry.execute('shell_execute', { command: 'sleep 5', shell: 123, background: true })
+ expect(startArgs().shell).toBeUndefined()
+ backendCalls.length = 0
+ await registry.execute('shell_execute', { command: 'sleep 5', shell: '', background: true })
+ expect(startArgs().shell).toBeUndefined()
+ })
+})
diff --git a/src/api/mcp/__tests__/shell-bg-refusal-parity.test.ts b/src/api/mcp/__tests__/shell-bg-refusal-parity.test.ts
new file mode 100644
index 00000000..0fdecc5c
--- /dev/null
+++ b/src/api/mcp/__tests__/shell-bg-refusal-parity.test.ts
@@ -0,0 +1,146 @@
+/**
+ * Die eine harte Sperre des Terminal-Tools gilt dem KOMMANDO, nicht der
+ * Betriebsart.
+ *
+ * `rejectShellCommand` (--no-verify auf einem Commit) stand in
+ * `executeShellExecute` UNTER der Hintergrund-Weiche: `if (args.background)
+ * return executeShellExecuteBg(…)` kam zuerst, die Pruefung erst danach. Ein
+ * Modell streifte die Sperre damit durch simples Anhaengen von
+ * `background: true` ab — bestaetigt: der Vordergrund antwortete "Refused: git
+ * commit --no-verify skips…", derselbe Aufruf mit `background: true` lieferte
+ * "Task started: …" und setzte `shell_task_start` an der Bridge ab.
+ *
+ * Zweiter Eingang: der zurueckgezogene Name `shell_execute_background` laeuft
+ * ueber `runRetiredTool` DIREKT in `executeShellExecuteBg` und sieht
+ * `executeShellExecute` nie. Dieselbe Luecke, andere Tuer — deshalb sitzt die
+ * Pruefung an BEIDEN Stellen.
+ *
+ * Run: npx vitest run src/api/mcp/__tests__/shell-bg-refusal-parity.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const backendCalls: { cmd: string; body: Record<string, unknown> }[] = []
+
+vi.mock('../../backend', () => ({
+ backendCall: vi.fn(async (cmd: string, body: Record<string, unknown>) => {
+ backendCalls.push({ cmd, body })
+ if (cmd === 'shell_execute') return { stdout: 'ran', stderr: '', exitCode: 0 }
+ if (cmd === 'shell_task_start') return { id: 'task-1' }
+ if (cmd === 'shell_task_kill') return { ok: true, cancelled: true }
+ return { ok: true }
+ }),
+ fetchExternal: vi.fn(async () => ({ ok: true, status: 200, text: async () => '' })),
+}))
+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 '../builtin-tools'
+import { ToolRegistry } from '../tool-registry'
+
+const registry = new ToolRegistry()
+registerBuiltinTools(registry)
+
+/** Was die Bridge zu sehen bekommen hat. Eine abgelehnte Sperre heisst: nichts. */
+const started = () => backendCalls.filter((c) => c.cmd === 'shell_task_start')
+const ran = () => backendCalls.filter((c) => c.cmd === 'shell_execute')
+
+const NO_VERIFY = 'git commit --no-verify -m x'
+
+beforeEach(() => { backendCalls.length = 0 })
+
+describe('--no-verify wird in beiden Betriebsarten abgelehnt', () => {
+ it('Vordergrund: abgelehnt, nichts laeuft (Ausgangszustand, unveraendert)', async () => {
+ const out = await registry.execute('shell_execute', { command: NO_VERIFY })
+ expect(out).toMatch(/^Refused: git commit --no-verify/)
+ expect(ran()).toHaveLength(0)
+ })
+
+ it('MUTATIONSSONDE: `background: true` streift die Sperre NICHT mehr ab', async () => {
+ const out = await registry.execute('shell_execute', { command: NO_VERIFY, background: true })
+ expect(out).toMatch(/^Refused: git commit --no-verify/)
+ // Der eigentliche Beweis: kein Task an der Bridge. Vor dem Fix stand hier
+ // "Task started: task-1" und ein abgesetztes shell_task_start.
+ expect(started()).toHaveLength(0)
+ expect(backendCalls).toHaveLength(0)
+ })
+
+ it('Vordergrund und Hintergrund geben denselben Wortlaut zurueck', async () => {
+ const fg = await registry.execute('shell_execute', { command: NO_VERIFY })
+ const bg = await registry.execute('shell_execute', { command: NO_VERIFY, background: true })
+ expect(bg).toBe(fg)
+ })
+
+ it('auch mit weiteren Argumenten daneben — die Sperre haengt am Kommando', async () => {
+ const out = await registry.execute('shell_execute', {
+ command: NO_VERIFY,
+ cwd: '/repo',
+ shell: 'bash',
+ background: true,
+ })
+ expect(out).toMatch(/^Refused:/)
+ expect(started()).toHaveLength(0)
+ })
+
+ it('zweiter Eingang: der zurueckgezogene Name shell_execute_background', async () => {
+ // runRetiredTool ruft executeShellExecuteBg DIREKT — executeShellExecute und
+ // damit dessen Pruefung liegen auf diesem Weg gar nicht dazwischen.
+ const out = await registry.execute('shell_execute_background', { command: NO_VERIFY })
+ expect(out).toMatch(/^Refused: git commit --no-verify/)
+ expect(started()).toHaveLength(0)
+ })
+
+ it('fuehrender Leerraum und Zeilenumbruch sind kein Schlupfloch', async () => {
+ // Ueber den Redirect kommt `command` UNGETRIMMT an. commandKind() trimmt
+ // selbst, die Sperre greift also trotzdem — der Trim ist hier nicht die
+ // Luecke, die Reihenfolge war es.
+ for (const cmd of [` ${NO_VERIFY}`, `\n\t ${NO_VERIFY}`]) {
+ backendCalls.length = 0
+ expect(await registry.execute('shell_execute_background', { command: cmd })).toMatch(/^Refused:/)
+ expect(await registry.execute('shell_execute', { command: cmd, background: true })).toMatch(/^Refused:/)
+ expect(started()).toHaveLength(0)
+ }
+ })
+
+ it('NEGATIVKONTROLLE: ein harmloses Kommando laeuft im Hintergrund weiter', async () => {
+ // Sonst waere die Sperre nur zu breit gezogen statt richtig platziert.
+ const out = await registry.execute('shell_execute', { command: 'npm run build', background: true })
+ expect(out).toContain('Task started: task-1')
+ expect(started()).toHaveLength(1)
+ })
+
+ it('NEGATIVKONTROLLE: ein normaler Commit im Hintergrund laeuft weiter', async () => {
+ const out = await registry.execute('shell_execute', {
+ command: 'git commit -m "wip"',
+ background: true,
+ })
+ expect(out).toContain('Task started: task-1')
+ expect(started()).toHaveLength(1)
+ })
+
+ it('NEGATIVKONTROLLE: der Vordergrund fuehrt harmlose Kommandos weiter aus', async () => {
+ const out = await registry.execute('shell_execute', { command: 'echo hi' })
+ expect(out).toBe('ran')
+ expect(ran()).toHaveLength(1)
+ })
+
+ it('die Pruefung steht im Quelltext VOR der Hintergrund-Weiche', () => {
+ // Verhalten allein kann das nicht festnageln: der Guard in
+ // executeShellExecuteBg faengt denselben Fall ab, beide Reihenfolgen sehen
+ // von aussen identisch aus. Die Reihenfolge ist trotzdem die eigentliche
+ // Korrektur — der Guard im Hintergrund-Executor ist die zweite Tuer, nicht
+ // der Ersatz. Also wie in shell-honours-stop.test.ts am Quelltext gepinnt.
+ const here = dirname(fileURLToPath(import.meta.url))
+ const src = readFileSync(resolve(here, '../builtin-tools.ts'), 'utf8')
+ const check = src.indexOf('const refusal = rejectShellCommand(command)')
+ const branch = src.indexOf('if (args.background) return executeShellExecuteBg(')
+ expect(check).toBeGreaterThan(-1)
+ expect(branch).toBeGreaterThan(-1)
+ expect(check).toBeLessThan(branch)
+ })
+})
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 9ae0f10c..ec361139 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -695,12 +695,20 @@ async function executeShellExecute(
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 }, run, abort)
-
// The one refusal that stays hard after the merge: --no-verify on a commit.
+ // VOR der Hintergrund-Weiche: die Sperre gilt dem KOMMANDO, nicht der
+ // Betriebsart. Stand sie darunter, streifte ein Modell sie durch simples
+ // Anhaengen von `background: true` ab — eine harte Sperre, die man mit einem
+ // Flag abwaehlt, ist keine.
const refusal = rejectShellCommand(command)
if (refusal) return refusal
+ // `shell` muss mit: das Backend leitet die Argumentform seit ba9557df aus dem
+ // Shell-NAMEN ab (shell::shell_argv), das Durchreichen ist also folgenlos
+ // richtig. `stdin`, `args` und `timeout` bleiben absichtlich draussen — die
+ // kennt StartArgs auf der Rust-Seite gar nicht.
+ if (args.background) return executeShellExecuteBg({ command, cwd: args.cwd, shell: args.shell }, run, abort)
+
// An explicit timeout wins; otherwise a recognised test run keeps the old
// run_tests budget (300 s) instead of the shell default.
const timeout = argNumber(args, 'timeout') || commandTimeoutMs(command, 120000)
@@ -787,11 +795,29 @@ async function executeShellExecuteBg(
signal?: AbortSignal,
): Promise<string> {
const { bgStart, bgKill } = await import('../agents/bg-tasks')
+ const command = argString(args, 'command')
+ // ZWEITER Eingang derselben Sperre. executeShellExecute prueft schon vor der
+ // Hintergrund-Weiche, aber der zurueckgezogene Name `shell_execute_background`
+ // laeuft ueber runRetiredTool DIREKT hierher und sieht executeShellExecute nie
+ // — dort waere `--no-verify` sonst weiterhin frei. Doppelt geprueft auf dem
+ // Hauptpfad, das ist ein Regex und der Preis fuer eine Sperre ohne Hintertuer.
+ // Whitespace ist kein Schlupfloch: commandKind() trimmt selbst, ein
+ // ungetrimmtes `command` aus dem Redirect wird also genauso erkannt.
+ const { rejectShellCommand } = await import('../../lib/shell-command-classify')
+ const refusal = rejectShellCommand(command)
+ if (refusal) return refusal
// 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: argString(args, 'command'),
+ command,
cwd: argOptString(args, 'cwd'),
+ // Das Schema bewirbt `shell` fuer BEIDE Pfade; der Hintergrundpfad hat es
+ // bisher stillschweigend weggeworfen, ein `{shell:"bash", background:true}`
+ // lief in der Plattform-Default-Shell. `argOptString` statt des vorderen
+ // `args.shell || null`: fuer einen echten String identisch, aber es filtert
+ // Nicht-Strings raus, die der Bridge sonst als Deserialisierungsfehler um
+ // die Ohren fliegen — und `bgStart` nimmt ohnehin nur `string | undefined`.
+ shell: argOptString(args, 'shell'),
...chatCtx(run),
})
// A detached task outlives the turn that started it BY DESIGN, but it must