diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4de734e4a..1ecec1a8e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -97,10 +97,9 @@ jobs: # way the desktop app does (stdin a pipe that stays open, stop on its end). windows-hub: name: Windows hub binary - # a Windows minute costs about twice a Linux one: main and manual runs only - if: github.event_name != 'pull_request' runs-on: windows-latest - timeout-minutes: 20 + # the native Rust tests' first build, before rust-cache has anything + timeout-minutes: 30 defaults: run: shell: bash @@ -114,6 +113,22 @@ jobs: - name: Install run: bun install --frozen-lockfile + # the runner has Git Bash; the test forces cmd.exe, the shell of a Windows device without it + - name: Bash tool on cmd.exe + run: bun test packages/core/test/tools/cmd-runtime.test.ts + + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable branch + with: + toolchain: stable + + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 + with: + workspaces: packages/daemon-rs + + # the Rust daemon's cmd.exe runs, cfg(windows) tests named windows_cmd_* + - name: Rust daemon on cmd.exe + run: cargo test --locked --manifest-path packages/daemon-rs/Cargo.toml windows_cmd + - name: Compile the Windows hub as the release does run: | bun scripts/build-cli.ts --target bun-windows-x64 --outfile dist/conclave.exe diff --git a/CHANGELOG.md b/CHANGELOG.md index 4929d1857..c973c4fc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,11 @@ like `## [0.4.16] - 2026-10-24`. ## [Unreleased] +### Fixed + +- Windows: commands work on PCs without Git Bash, using cmd.exe batch scripts. Quoted paths, multiline blocks, percent variables, exit codes and working-directory changes stay intact; command timeouts stop the process tree. +- The agent is told the device's actual execution shell and Windows command syntax instead of assuming Unix commands. + ### Changed - Desktop: Open folder… uses the native OS folder picker for this app's paired computer, then confirms the folder with the existing checks and Add as project. Other devices keep the in-app browser; cancelling keeps the current folder, and a native dialog failure opens the in-app browser with an explanation. diff --git a/packages/core/src/engine/commands.ts b/packages/core/src/engine/commands.ts index 32637014a..9d7903d5c 100644 --- a/packages/core/src/engine/commands.ts +++ b/packages/core/src/engine/commands.ts @@ -1,6 +1,6 @@ import type { Engine } from './engine'; import { expandCommand } from '../extensions/commands'; -import { checkPermission, dangerousCommand } from '../session/permissions'; +import { checkPermission, dangerousCommand, machineShell } from '../session/permissions'; import { BashTool } from '../tools/bash'; import { ReadTool } from '../tools/read'; import type { Tool } from '../tools/types'; @@ -172,6 +172,7 @@ export async function bashRefusal(engine: Engine, s: Session, command: string, s cwd: s.cwd, home: (await engine.machineHome(engine.machineFor(s))) ?? '/', workspaceRoots: [s.cwd, ...engine.config.get().permissions.additionalDirectories], + shell: machineShell(engine.machineFor(s)), }); if (v.decision === 'allow' && dangerousCommand(command)) v = { decision: 'ask', reason: 'Potentially destructive command' }; if (v.decision === 'deny') return v.reason; diff --git a/packages/core/src/engine/engine.ts b/packages/core/src/engine/engine.ts index 898c03fa2..447bd1f07 100644 --- a/packages/core/src/engine/engine.ts +++ b/packages/core/src/engine/engine.ts @@ -2741,6 +2741,7 @@ export class Engine implements EngineApi { session, agent, modelRef, mode, toolNames, platform: info?.platform ?? process.platform, hostname: info?.hostname, + shell: info?.shell, isGitRepo: isGit, deviceName: this.devices.list().find((d) => d.id === session.device)?.name ?? session.device, projectInstructions, profile, skills, firstMessage, diff --git a/packages/core/src/engine/extensions-api.ts b/packages/core/src/engine/extensions-api.ts index b03085000..158e39a06 100644 --- a/packages/core/src/engine/extensions-api.ts +++ b/packages/core/src/engine/extensions-api.ts @@ -48,7 +48,7 @@ import { claudeHome, codexHome, parseJsonc } from '../config'; import type { AgentDef, HookInput, HookOutcome, InstalledPlugin, MarketplaceEntry, RuntimeHookCommand } from '../extensions/types'; import type { Tool } from '../tools/types'; import { filterTools, untrustedOffers } from '../tools'; -import { checkPermission, dangerousCommand } from '../session/permissions'; +import { checkPermission, dangerousCommand, machineShell } from '../session/permissions'; import { mcpFromClaude, mcpFromCodexToml, mcpFromGemini, mcpFromOpenCode, readForeignHooks } from '../extensions/compat'; import { mcpConnectPlan } from '../extensions/cli-sync'; import { oauthFailure } from '../extensions/mcp-oauth'; @@ -301,6 +301,7 @@ function permissionFor( cwd: ctx.session.cwd, home: ctx.home, workspaceRoots: [ctx.session.cwd, ...cfg.permissions.additionalDirectories], + shell: machineShell(engine.machineFor(ctx.session)), }); let dangerous: string | false = false; if (tool.name === 'Bash' && typeof input.command === 'string') { diff --git a/packages/core/src/machine/local.ts b/packages/core/src/machine/local.ts index 7cb764016..e7840b90f 100644 --- a/packages/core/src/machine/local.ts +++ b/packages/core/src/machine/local.ts @@ -54,6 +54,15 @@ function untrackGroup(pid: number | undefined): void { function killTree(pid: number | undefined, signal: NodeJS.Signals): void { if (!pid) return; + if (process.platform === 'win32') { + // Windows has no process groups (kill(-pid) throws): taskkill /T ends the shell and its children + try { + Bun.spawnSync(['taskkill', '/pid', String(pid), '/T', '/F'], { stdout: 'ignore', stderr: 'ignore' }); + } catch { + /* already gone */ + } + return; + } try { process.kill(-pid, signal); return; @@ -67,6 +76,21 @@ function killTree(pid: number | undefined, signal: NodeJS.Signals): void { } } +export const isCmd = (shell: string) => /(^|[\\/])cmd(\.exe)?$/i.test(shell); + +/** cmd.exe looks in the current folder before PATH: a repo's git.bat would run under a Bash(git status) rule. Bash never does. */ +export const CMD_ENV = { NoDefaultCurrentDirectoryInExePath: '1' }; + +/** + * The argv that runs one command line: cmd.exe takes /d /v:off /s /c, every + * other shell -c. On Windows cmd's line goes in quotes that /s strips, with + * windowsVerbatimArguments so Bun adds no quoting of its own (as raw_arg in daemon-rs). + */ +export function shellArgv(shell: string, command: string): string[] { + if (!isCmd(shell)) return [shell, '-c', command]; + return [shell, '/d', '/v:off', '/s', '/c', process.platform === 'win32' ? `"${command}"` : command]; +} + /** Keeps the first and last part of a long stream and drops the middle. */ class HeadTailBuffer { private head = ''; @@ -268,7 +292,8 @@ export class LocalMachine implements Machine { platform: process.platform, arch: process.arch, home: os.homedir(), - shell: (process.platform !== 'win32' && process.env.SHELL) || this.shell(), + // SHELL describes the login shell, not necessarily what exec runs. + shell: this.shell(), clis, capabilities, }; @@ -642,16 +667,18 @@ export class LocalMachine implements Machine { if (opts.signal?.aborted) return { ...fail('Aborted before start'), exitCode: null, aborted: true }; const shell = this.shell(); - const argv = shell.endsWith('cmd.exe') ? [shell, '/d', '/s', '/c', command] : [shell, '-c', command]; + const argv = shellArgv(shell, command); + const verbatim = isCmd(shell); let proc: ReturnType>; try { proc = Bun.spawn(argv, { cwd, - env: this.env(opts.env), + env: verbatim ? { ...this.env(opts.env), ...CMD_ENV } : this.env(opts.env), stdin: opts.stdin !== undefined ? 'pipe' : 'ignore', stdout: 'pipe', stderr: 'pipe', - detached: true, + detached: process.platform !== 'win32', + windowsVerbatimArguments: verbatim, }); } catch (err) { return fail(`Failed to start shell: ${(err as Error).message}`); @@ -746,13 +773,18 @@ export class LocalMachine implements Machine { // a background shell (tools/shells.ts) names its command in the arguments const named = [command, ...args].join(' '); if (commandTouchesHubPrivate(named, cwd) || hubPrivateDirs().some((d) => cwd === d || cwd.startsWith(d + nodePath.sep))) throw Object.assign(new Error(privateRefusal(named)), { code: 'EACCES' }); - const proc = Bun.spawn([command, ...args], { + // a background shell asks for bash -c (tools/shells.ts): on Windows that is this machine's shell, which may be off PATH or cmd.exe + const shell = this.shell(); + const viaShell = (command === 'bash' || command === 'sh') && args.length === 2 && args[0] === '-c' && (process.platform === 'win32' || isCmd(shell)); + const verbatim = viaShell && isCmd(shell); + const proc = Bun.spawn(viaShell ? shellArgv(shell, args[1] as string) : [command, ...args], { cwd, - env: this.env(opts.env), + env: verbatim ? { ...this.env(opts.env), ...CMD_ENV } : this.env(opts.env), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', - detached: true, + detached: process.platform !== 'win32', + windowsVerbatimArguments: verbatim, }); trackGroup(proc.pid); const exited = proc.exited.then(() => { diff --git a/packages/core/src/session/permissions.ts b/packages/core/src/session/permissions.ts index 4f76497e2..e9a243696 100644 --- a/packages/core/src/session/permissions.ts +++ b/packages/core/src/session/permissions.ts @@ -3,6 +3,7 @@ import type { PermissionMode } from '../types'; import type { Tool } from '../tools/types'; import { toolIsReadOnly } from '../tools/types'; import { gatedConstructs, heredocLines, maskSafeHeredocs, parseCommand, quoteEnd, readHeredoc, startsComment, substitutionBodies, type Heredoc } from '../tools/bash-rules'; +import { isCmd } from '../machine/local'; /** * Permission rules use Claude Code syntax: @@ -223,6 +224,103 @@ export function bashRuleTargets(cmd: string): string[] { return [...out]; } +/** + * cmd.exe syntax these checks cannot read the way cmd does: % and ! expansion + * and ^ escapes change the line before cmd parses it, ( ) and if/for/call/start + * run commands in places the splitter does not look, plus redirects, line + * breaks and an unclosed quote. Returns the construct's name, or undefined. + */ +export function cmdUnsure(cmd: string): string | undefined { + if (/[%!^]/.test(cmd)) return 'cmd.exe expansion or ^ escape'; + if (/[\r\n]/.test(cmd)) return 'a line break'; + if ((cmd.match(/"/g)?.length ?? 0) % 2) return 'an unclosed quote'; + if (/[()]/.test(cmd)) return 'cmd.exe grouping or block'; + if (/[<>]/.test(cmd)) return 'redirect'; + if (cmdParts(cmd).some((p) => cmdNames(cmdCommand(p).name).some((n) => RUNS_OTHERS.has(n)))) return 'a command that runs other commands'; + return undefined; +} + +/** Keywords and programs that run a command line of their own, which the checks do not read. */ +const RUNS_OTHERS = new Set(['if', 'for', 'call', 'start', 'cmd', 'command', 'powershell', 'pwsh', 'powershell_ise', 'bash', 'sh', 'zsh', 'wsl', 'wscript', 'cscript', 'mshta', 'conhost', 'runas']); + +/** The commands of a cmd.exe line: & && | || separate them outside double quotes; single quotes, backslashes and # are plain text to cmd. */ +export function cmdParts(cmd: string): string[] { + const parts: string[] = []; + let cur = ''; + let quoted = false; + for (const c of cmd) { + if (c === '"') quoted = !quoted; + if (!quoted && (c === '&' || c === '|')) { + parts.push(cur); + cur = ''; + } else cur += c; + } + parts.push(cur); + return parts.map((p) => p.trim()).filter(Boolean); +} + +/** One cmd command as its program, as written (a quoted one without its quotes), and the rest: cmd ends a bare name at a space , ; or =. */ +function cmdCommand(part: string): { name: string; quoted: boolean; rest: string } { + const s = part.replace(/^[\s@]+/, ''); + if (s.startsWith('"')) { + const end = s.indexOf('"', 1); + return end === -1 ? { name: s.slice(1), quoted: true, rest: '' } : { name: s.slice(1, end), quoted: true, rest: s.slice(end + 1) }; + } + const name = /^[^\s,;=]*/.exec(s)![0]; + return { name, quoted: false, rest: s.slice(name.length) }; +} + +/** + * The names a program may go by for rules, lower case: as written, its file + * name after a \ or / path, the part before a glued /switch (cmd/c), each with + * and without .exe/.com/.bat/.cmd. Only for deny, ask and nested-shell checks, + * never to trust a program: dir.cmd is a script, not dir. + */ +function cmdNames(name: string): string[] { + const n = name.toLowerCase(); + const forms = [n, n.slice(Math.max(n.lastIndexOf('\\'), n.lastIndexOf('/')) + 1), n.split('/')[0]]; + return [...new Set(forms.flatMap((f) => [f, f.replace(/\.(exe|com|bat|cmd)$/, '')]))].filter(Boolean); +} + +/** Every command a cmd line may run, as written and under each name of its program, for deny and ask rules. */ +function cmdTargets(cmd: string): string[] { + return cmdParts(cmd).flatMap((p) => { + const { name, rest } = cmdCommand(p); + const args = rest.replace(/"/g, '').replace(/^[\s,;=]+/, '').trim(); + return [p, ...cmdNames(name).map((n) => `${n} ${args}`.trim())]; + }); +} + +/** + * cmd's own commands that only read. Built-ins only: cmd runs them before any + * file, while a program name (where, sort, git) may find a script in the + * folder first, and Windows programs share names, not flags, with POSIX ones + * (sort /o writes, date sets the clock). + */ +const CMD_READ_ONLY = new Set(['dir', 'type', 'echo', 'cd', 'chdir', 'ver', 'vol']); + +/** True when a cmd line has nothing the checks cannot read and each of its commands is a read-only built-in, written bare. */ +function cmdReadOnly(cmd: string): boolean { + return !cmdUnsure(cmd) && cmdParts(cmd).every((p) => { + const { name, quoted } = cmdCommand(p); + // a quoted or suffixed name ("dir", dir.cmd) is looked up as a file, not run as the built-in + return !quoted && /^[a-z]+$/i.test(name) && CMD_READ_ONLY.has(name.toLowerCase()); + }); +} + +/** The shell a machine runs commands in: a paired device's from its hello, the hub's own from shell(). */ +export function machineShell(machine: unknown): string | undefined { + const m = machine as { lastInfo?: { shell?: string }; shell?: () => string }; + if (m.lastInfo) return m.lastInfo.shell; + return typeof m.shell === 'function' ? m.shell() : undefined; +} + +/** A call's readOnly as the shell will run it: on cmd.exe the Bash tool's own bash reading can miss a command (echo hi #& del x). */ +export function callReadOnly(tool: Tool, input: Record, shell: string | undefined): boolean { + if (tool.name !== 'Bash' || !shell || !isCmd(shell) || typeof input?.command !== 'string') return toolIsReadOnly(tool, input); + return tool.readOnly !== false && !input.run_in_background && cmdReadOnly(input.command.trim()); +} + export interface CheckInput { tool: Tool; input: Record; @@ -236,6 +334,8 @@ export interface CheckInput { home: string; /** Directories edits may touch without asking in acceptEdits mode. */ workspaceRoots: string[]; + /** The shell the command runs in (machineShell). cmd.exe gets its own reading of a Bash command; unset reads it as bash. */ + shell?: string; } /** Bash as checkOne needs it, for preview_start's command (no import cycle with tools/bash.ts). */ @@ -256,7 +356,12 @@ export function checkPermission(c: CheckInput): PermissionCheck { function checkOne(c: CheckInput): PermissionCheck { const name = c.tool.name; - const readOnly = toolIsReadOnly(c.tool, c.input); + // cmd.exe: single quotes, backslashes and # hide nothing, so the bash reading may miss a command + const cmd = name === 'Bash' && !!c.content && !!c.shell && isCmd(c.shell) ? c.content : undefined; + const unsure = cmd !== undefined ? cmdUnsure(cmd) : undefined; + // the Bash tool's own readOnly reads the line as bash; sleep and watch waits are not read-only segments either way + // (BASH_RULES, preview_start's stand-in, is never read-only) + const readOnly = cmd !== undefined ? c.tool.readOnly !== false && !c.input?.run_in_background && cmdReadOnly(cmd) : toolIsReadOnly(c.tool, c.input); const rules = (list: string[]) => list.map(parseRule).filter((r) => toolMatches(r.tool, name)); const matchAny = (list: ParsedRule[]): ParsedRule | undefined => { @@ -268,7 +373,7 @@ function checkOne(c: CheckInput): PermissionCheck { }; // deny: any sub-command hit denies, including commands inside $( ) and backticks - const bashTargets = name === 'Bash' && c.content ? bashRuleTargets(c.content) : []; + const bashTargets = name === 'Bash' && c.content ? [...new Set([...bashRuleTargets(c.content), ...(cmd !== undefined ? cmdTargets(cmd) : [])])] : []; const denyRules = rules(c.rules.deny); for (const part of bashTargets) { const hit = denyRules.find((r) => contentMatches(r, name, part, c.cwd, c.home)); @@ -276,6 +381,9 @@ function checkOne(c: CheckInput): PermissionCheck { } const deny = matchAny(denyRules); if (deny) return { decision: 'deny', reason: `Denied by rule ${deny.raw}`, rule: deny.raw }; + // cmd syntax that hides which commands run cannot be cleared against a command deny rule: fail closed + const unsureDeny = unsure ? denyRules.find((r) => r.content !== undefined) : undefined; + if (unsureDeny) return { decision: 'deny', reason: `Denied: ${unsure} hides which commands run from rule ${unsureDeny.raw}`, rule: unsureDeny.raw }; if (c.mode === 'plan' && !readOnly && name !== 'ExitPlanMode') { return { decision: 'deny', reason: 'Plan mode is read-only. Present a plan with ExitPlanMode first.' }; @@ -283,7 +391,8 @@ function checkOne(c: CheckInput): PermissionCheck { // ask: like deny, any sub-command hit asks const askRules = rules(c.rules.ask); - const ask = matchAny(askRules) ?? bashTargets.map((p) => askRules.find((r) => contentMatches(r, name, p, c.cwd, c.home))).find(Boolean); + const ask = + matchAny(askRules) ?? bashTargets.map((p) => askRules.find((r) => contentMatches(r, name, p, c.cwd, c.home))).find(Boolean) ?? (unsure ? askRules.find((r) => r.content !== undefined) : undefined); if (ask) return { decision: 'ask', reason: `Rule ${ask.raw} requires approval`, rule: ask.raw }; const allowList = rules([...c.rules.allow, ...c.sessionAllow]); @@ -291,9 +400,9 @@ function checkOne(c: CheckInput): PermissionCheck { let gatedReason: string | undefined; if (name === 'Bash' && c.content) { const whole = c.content.trim(); - const gated = gatedConstructs(whole); + const gated = cmd !== undefined ? (unsure ? [unsure] : []) : gatedConstructs(whole); // a $(cat <<'EOF' ... EOF) commit message is one word here, so its lines are not sub-commands - const parts = splitBashCommand(maskSafeHeredocs(whole)); + const parts = cmd !== undefined ? cmdParts(whole) : splitBashCommand(maskSafeHeredocs(whole)); if (gated.length) { // only a bare "Bash" rule or a rule naming this exact command covers substitution, redirects and the like; // the comparison is literal, so a suggested exact rule covers its command even when it contains * diff --git a/packages/core/src/session/prompt.ts b/packages/core/src/session/prompt.ts index 366a4194a..c6cc66090 100644 --- a/packages/core/src/session/prompt.ts +++ b/packages/core/src/session/prompt.ts @@ -16,6 +16,8 @@ export interface PromptParts { toolNames: string[]; platform: string; hostname?: string; + /** The device's shell (MachineInfo.shell): on Windows cmd.exe means no Git Bash. */ + shell?: string; isGitRepo: boolean; deviceName: string; projectInstructions: Array<{ path: string; content: string }>; @@ -183,6 +185,17 @@ export function workflowStepNote(session: Session): string | undefined { return MODE_NOTES.workflow ?? WORKFLOW_STEP_FALLBACK; } +/** The Environment line on the device's OS and the shell the Bash tool runs in. */ +export function shellLine(platform: string, shell?: string): string { + if (platform === 'win32') { + if (shell && /(^|[\\/])cmd(\.exe)?$/i.test(shell)) return '- Shell: Windows cmd.exe (no bash). Foreground commands run as a batch script: use %%i in FOR loops, %% for a literal %, CALL for .cmd/.bat tools before more commands, and exit /b. Use dir, type, findstr, where or powershell -NoProfile -Command.'; + if (shell && /(^|[\\/])bash(\.exe)?$/i.test(shell)) return '- Shell: Windows with Git Bash: POSIX commands work; paths like D:\\x work as /d/x or D:/x'; + return `- Shell: Windows, ${shell ?? 'unknown (check before choosing shell syntax)'}`; + } + const os = platform === 'darwin' ? 'macOS' : platform === 'linux' ? 'Linux' : platform; + return `- Shell: ${os}, commands run in ${shell ?? 'the device shell (not reported)'}`; +} + /** * The system prompt is assembled from stable parts only (no clock times, no * per-turn data) so provider prompt caches keep hitting across turns. Dynamic @@ -196,6 +209,7 @@ export function buildSystemPrompt(p: PromptParts): SystemBlock[] { '# Environment', `- Working directory: ${p.session.cwd}`, `- Device: ${p.deviceName}${p.hostname ? ` (${p.hostname})` : ''}, platform ${p.platform}`, + shellLine(p.platform, p.shell), `- Git repository: ${p.isGitRepo ? 'yes' : 'no'}`, ...(p.testCommand ? [`- Test command: ${p.testCommand}`] : []), ...(p.workspace?.python3Only ? ['- Python: use python3; this device has no python command'] : []), diff --git a/packages/core/src/session/runner.ts b/packages/core/src/session/runner.ts index 76606272f..1d4d21bcb 100644 --- a/packages/core/src/session/runner.ts +++ b/packages/core/src/session/runner.ts @@ -15,7 +15,7 @@ import type { } from '../types'; import type { SendInput, SendResult } from '../client'; import type { ReadMark, Tool, ToolContext, ToolOutput } from '../tools/types'; -import { coerceInput, timeoutOutput, toolIsReadOnly, validateInput } from '../tools/types'; +import { coerceInput, timeoutOutput, validateInput } from '../tools/types'; import type { AgentDef } from '../extensions/types'; import type { ProviderMessage, SystemBlock, ToolSpec } from '../providers/types'; import { ProviderError } from '../providers/types'; @@ -32,7 +32,7 @@ import { seesImages } from '../providers/common'; import { pickedName } from '../attachments/prepare'; import { refusalPlanFor } from './member-fallbacks'; import { refusalStepOf, refusalWords, RefusalWalk, servedLabel, stepOfTarget, type FallbackTarget } from './refusal-fallback'; -import { checkPermission, dangerousCommand } from './permissions'; +import { callReadOnly, checkPermission, dangerousCommand, machineShell } from './permissions'; import { ReadTool } from '../tools/read'; import { maybeCompact, estimateRequestTokens, meteredTokens, partHash, type TokenMeter } from './compaction'; import { applyClearing } from './context-edit'; @@ -272,7 +272,7 @@ interface PromptSnapshot { /** The parts of a prompt read again once per user turn; the same text keeps the snapshot. */ function partsSignature(p: PromptParts): string { - return JSON.stringify([p.projectInstructions, p.skills.map((k) => [k.name, k.description]), p.isGitRepo, p.testCommand ?? '', p.workspace ?? {}, p.platform, p.hostname ?? '', p.deviceName, p.conclave ?? null, p.modelPin ?? '']); + return JSON.stringify([p.projectInstructions, p.skills.map((k) => [k.name, k.description]), p.isGitRepo, p.testCommand ?? '', p.workspace ?? {}, p.platform, p.shell ?? '', p.hostname ?? '', p.deviceName, p.conclave ?? null, p.modelPin ?? '']); } /** Every memory the snapshot shows is still there with the same text (new ones wait for the next rebuild). */ @@ -1604,7 +1604,7 @@ export class SessionRunner { continue; } const tool = resolveTool(toolMap, use.name); - const safe = tool && (toolIsReadOnly(tool, use.input) || CONCURRENT_TOOLS.has(tool.name)); + const safe = tool && (callReadOnly(tool, use.input, machineShell(engine.machineFor(this.session))) || CONCURRENT_TOOLS.has(tool.name)); if (safe) { batch.push(use); continue; @@ -1975,6 +1975,8 @@ export class SessionRunner { const home = (await engine.machineHome(machine)) ?? '/'; // a moved session's file tools map old paths to the current folder, so rules judge the path the tool will touch const oldRoots = engine.runnerExtensions.toolContext(session).pathMap?.roots; + // cmd.exe reads quotes and separators unlike bash, so a command is judged in the shell it runs in + const shell = machineShell(machine); const judge = (inp: Record) => { let content: string | undefined; try { @@ -1992,6 +1994,7 @@ export class SessionRunner { cwd: session.cwd, home, workspaceRoots: [session.cwd, ...cfg.permissions.additionalDirectories], + shell, }); }; let decision: { decision: 'allow' | 'ask' | 'deny'; reason: string }; @@ -2021,7 +2024,7 @@ export class SessionRunner { if (decision.decision === 'deny') return fail(`Permission denied: ${decision.reason}`, { denied: 'rule' }); // runner extensions (runner-ext.ts), for example the folder check after a session moved - const callCtx = { sessionId: this.id, session, tool, input, toolUseId: use.id, depth: this.depth, readOnly: toolIsReadOnly(tool, input), signal }; + const callCtx = { sessionId: this.id, session, tool, input, toolUseId: use.id, depth: this.depth, readOnly: callReadOnly(tool, input, shell), signal }; const extVerdict = await engine.runnerExtensions.beforeTool(callCtx, { failClosed: untrusted }); if (extVerdict?.decision === 'deny') return fail(extVerdict.reason, { denied: 'extension' }); if (extVerdict?.decision === 'ask' && decision.decision === 'allow') decision = { decision: 'ask', reason: extVerdict.reason }; @@ -2170,7 +2173,7 @@ export class SessionRunner { // after the offload, so a long result never cuts the instructions if (scoped) content = typeof content === 'string' ? `${content}\n\n${scoped}` : [...content, { type: 'text', text: scoped } as TextBlock]; - if (!toolIsReadOnly(tool, input)) { + if (!callReadOnly(tool, input, shell)) { engine.audit(this.id, `tool:${tool.name}`, tool.summarize?.(input) ?? oneLine(JSON.stringify(input), 300)); } diff --git a/packages/core/src/session/verify-gate.ts b/packages/core/src/session/verify-gate.ts index 10f1d555c..57059bfa1 100644 --- a/packages/core/src/session/verify-gate.ts +++ b/packages/core/src/session/verify-gate.ts @@ -40,7 +40,7 @@ import type { Session } from '../types'; import type { Machine } from '../machine/types'; import type { RunnerExtension } from './runner-ext'; import { wantsVerifyGate, agentHooksAllowed } from '../extensions/agent-hooks'; -import { checkPermission } from './permissions'; +import { checkPermission, machineShell } from './permissions'; import { BashTool } from '../tools/bash'; import { logger } from '../util/log'; @@ -175,6 +175,7 @@ export async function mayRunProjectCommand(engine: Engine, session: Session, com cwd: session.cwd, home, workspaceRoots: [session.cwd], + shell: machineShell(machine), }); return verdict.decision === 'allow'; } catch { diff --git a/packages/core/src/tools/bash.ts b/packages/core/src/tools/bash.ts index 6f946941f..6b483a6f7 100644 --- a/packages/core/src/tools/bash.ts +++ b/packages/core/src/tools/bash.ts @@ -7,6 +7,8 @@ import { isHeadless } from '../session/runner'; import { clampInt, fail, outputBudget, truncateMiddleOut } from './util'; import { KEEPS, KIND_NAMES, reduceOutput } from './compress'; import { HEAVY_COMMANDS_DEFAULT, HEAVY_WAIT_NOTE, heavyGate, isHeavyCommand } from './heavy-gate'; +import { isCmd } from '../machine/local'; +import type { MachineInfo } from '../types'; export interface BashInput { command: string; @@ -21,7 +23,7 @@ export const BASH_MAX_OUTPUT_CHARS = 30_000; const MACHINE_OUTPUT_CAP = 4 * 1024 * 1024; const PROGRESS_FLUSH_MS = 250; -const DESCRIPTION = `Run a shell command (bash -c) on the session's machine and return its combined stdout and stderr. +const DESCRIPTION = `Run a shell command on the session's machine and return its combined stdout and stderr. It runs in bash, or in cmd.exe on a Windows device without Git Bash; the Environment section names the shell. - The working directory persists between calls; environment variables and shell functions do not. Prefer absolute paths to cd. - timeout is in milliseconds (default ${BASH_DEFAULT_TIMEOUT_MS}, max ${BASH_MAX_TIMEOUT_MS}). Give a 5 to 10 word description of what the command does, e.g. "Run unit tests". @@ -71,6 +73,20 @@ export function extractCwd(text: string, marker: string): { text: string; cwd?: return { text: before + after, cwd: cwd || undefined }; } +/** Batch lines stay intact: wrapping or joining user text changes cmd's percent and parentheses parsing. */ +export function wrapCmdCommand(command: string): string { + return ['@echo off', 'chcp 65001 >nul', command.replace(/\r?\n/g, '\r\n'), ''].join('\r\n'); +} + +/** The shell the device runs commands in (MachineInfo.shell): a paired device's from its hello, no round trip. */ +async function deviceShell(ctx: ToolContext): Promise { + const m = ctx.machine as { lastInfo?: MachineInfo; shell?: () => string }; + if (m.lastInfo) return m.lastInfo.shell; + // the hub's own machine: its exec shell, without info()'s CLI version probes + if (typeof m.shell === 'function') return m.shell(); + return (await ctx.machine.info().catch(() => undefined))?.shell; +} + /** * The folder the next Bash call starts in, from what the shell printed. On a Windows * session (cwd like D:\x) only a Windows path counts: D:/x becomes D:\x, Git Bash's @@ -119,20 +135,38 @@ async function runForeground(input: BashInput, ctx: ToolContext): Promise { - if (stream !== 'stdout') return; - pending += chunk; - timer ??= setTimeout(flush, PROGRESS_FLUSH_MS); - }, - }); - if (timer) clearTimeout(timer); - flush(); + const shell = await deviceShell(ctx); + let script: string | undefined; + let res; + try { + if (shell && isCmd(shell)) { + const temp = await ctx.machine.exec('chcp 65001 >nul & set TEMP', { cwd: ctx.cwd, timeoutMs: 5_000, signal: ctx.signal }); + const dir = /^TEMP=([^\r\n]+)$/im.exec(temp.stdout)?.[1] ?? ''; + if (temp.exitCode !== 0 || !/^(?:[A-Za-z]:[\\/]|\\\\)[^\r\n]+$/.test(dir)) return fail('Could not locate the Windows temporary folder.'); + script = `${dir.replace(/[\\/]$/, '')}\\${marker}.cmd`; + await ctx.machine.writeFile(script, wrapCmdCommand(input.command)); + } + res = await ctx.machine.exec( + script ? `chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set __conclave_exit=%^errorlevel%& >&2 &2 cd & call exit /b %^__conclave_exit%` : wrapCommand(marker), + { + cwd: ctx.cwd, + env: bashEnv(ctx, { __CONCLAVE_CMD: input.command, ...(script ? { __CONCLAVE_SCRIPT: script } : {}) }), + timeoutMs, + signal: ctx.signal, + maxOutputBytes: MACHINE_OUTPUT_CAP, + onOutput: (chunk, stream) => { + if (stream !== 'stdout') return; + pending += chunk; + timer ??= setTimeout(flush, PROGRESS_FLUSH_MS); + }, + }); + } catch (err) { + return fail(`Could not run command: ${(err as Error).message}`); + } finally { + if (timer) clearTimeout(timer); + flush(); + if (script) await ctx.machine.remove(script).catch(() => {}); + } const err = extractCwd(res.stderr, marker); const out = extractCwd(res.stdout, marker); diff --git a/packages/core/src/workflows/run.ts b/packages/core/src/workflows/run.ts index 0a857adf9..e4671e9f3 100644 --- a/packages/core/src/workflows/run.ts +++ b/packages/core/src/workflows/run.ts @@ -17,7 +17,7 @@ import type { Engine } from '../engine/engine'; import type { Session } from '../types'; import type { Tool } from '../tools/types'; import type { WorkflowCallKind, WorkflowFinding, WorkflowRunStatus } from '../client/workflows'; -import { checkPermission, dangerousCommand } from '../session/permissions'; +import { checkPermission, dangerousCommand, machineShell } from '../session/permissions'; import { BashTool } from '../tools/bash'; import { suggestBashRule } from '../tools/bash-rules'; import { newId } from '../util/ids'; @@ -851,6 +851,7 @@ export class LiveRun { cwd, home, workspaceRoots: [cwd], + shell: machineShell(machine), }); if (dangerousCommand(command) && decision.decision === 'allow') decision = { decision: 'ask', reason: 'Potentially destructive command' }; const scope = await this.scopeVerdict('Bash', { command }, what); diff --git a/packages/core/test/engine/command-shell.test.ts b/packages/core/test/engine/command-shell.test.ts index 1bcc16f8e..b98b6d372 100644 --- a/packages/core/test/engine/command-shell.test.ts +++ b/packages/core/test/engine/command-shell.test.ts @@ -2,6 +2,10 @@ import { describe, test, expect } from 'bun:test'; import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { startTestEngine } from './harness'; +import { bashRefusal } from '../../src/engine/commands'; +import { mayRunProjectCommand } from '../../src/session/verify-gate'; +import type { Engine } from '../../src/engine/engine'; +import type { Session } from '../../src/types'; /** A project command whose !`cmd` line leaves a marker file when it runs. */ function addCommand(cwd: string): string { @@ -11,6 +15,25 @@ function addCommand(cwd: string): string { } describe('!`cmd` lines in a typed command', () => { + test('command and verify checks use the executing Windows shell', async () => { + const machine = { lastInfo: { shell: 'C:\\Windows\\System32\\cmd.exe' } }; + const engine = { + machineFor: () => machine, + machineHome: async () => 'C:\\Users\\owner', + permissionRulesFor: () => ({ allow: ['Bash'], ask: [], deny: ['Bash(mkdir:*)'] }), + runnerFor: () => ({ sessionAllow: [] }), + config: { get: () => ({ permissions: { additionalDirectories: [] } }) }, + trust: { isTrusted: () => false }, + requestApproval: () => { throw new Error('denied commands must not ask'); }, + } as unknown as Engine; + const command = "echo 'safe & mkdir cc-review-owned & echo '"; + for (const permissionMode of ['default', 'plan', 'bypass'] as const) { + const session = { id: 'windows-test', cwd: 'C:\\work', permissionMode } as Session; + expect(await bashRefusal(engine, session, command, 'test', new AbortController().signal)).toContain('Denied'); + expect(await mayRunProjectCommand(engine, session, command)).toBe(false); + } + }); + test('get the permission check a Bash call gets', async () => { const t = await startTestEngine({ script: [[{ text: 'ok' }]], approve: 'deny' }); try { diff --git a/packages/core/test/engine/platform-card.test.ts b/packages/core/test/engine/platform-card.test.ts index 3b7f7ce22..effffc12b 100644 --- a/packages/core/test/engine/platform-card.test.ts +++ b/packages/core/test/engine/platform-card.test.ts @@ -128,7 +128,8 @@ describe('the platform card in requests', () => { expect(sys).not.toContain('Settings > AI connections'); // 14,476 chars before the cut (v0.4.41), about 13.5k after // +350 for the identity lines at the top of BASE.md (who Conclave is and who made it) - expect(sys.length).toBeLessThan(14_250); + // +50 for the Environment's Shell line (the device's OS and shell, so Windows gets Windows commands) + expect(sys.length).toBeLessThan(14_300); const assistant = await t.engine.createSession({ title: 't', cwd: t.cwd, agent: 'assistant' }); await t.run(assistant.id, 'my day'); diff --git a/packages/core/test/session/permissions.test.ts b/packages/core/test/session/permissions.test.ts index 8794434bf..7ef219e54 100644 --- a/packages/core/test/session/permissions.test.ts +++ b/packages/core/test/session/permissions.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'bun:test'; -import { bashRuleTargets, checkPermission, type CheckInput } from '../../src/session/permissions'; +import { bashRuleTargets, callReadOnly, checkPermission, type CheckInput } from '../../src/session/permissions'; import { gatedConstructs, HEREDOC_WORD, maskSafeHeredocs, substitutionBodies, suggestBashRule } from '../../src/tools/bash-rules'; import { toolByName } from '../../src/tools'; import type { PermissionMode } from '../../src/types'; @@ -232,3 +232,122 @@ describe('a quote ends where bash ends it', () => { expect(gatedConstructs("cat <<'EOF'\nit's\nEOF")).toEqual([]); }); }); + +describe('a Bash command on a cmd.exe machine', () => { + const cmdCheck = (command: string, rules: { allow?: string[]; deny?: string[]; ask?: string[] } = {}, mode: PermissionMode = 'default', shell = 'cmd.exe') => + checkPermission({ + tool: bash, + input: { command }, + content: command.trim(), + mode, + rules: { allow: rules.allow ?? [], deny: rules.deny ?? [], ask: rules.ask ?? [] }, + sessionAllow: [], + cwd: '/work', + home: '/home/me', + workspaceRoots: ['/work'], + shell, + }); + const payload = "echo 'safe & mkdir cc-review-owned & echo '"; + + test('the bash reading calls the payload read-only (why cmd needs its own)', () => { + expect(check(payload, {}, 'plan').decision).toBe('allow'); + expect(check(payload, { deny: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('allow'); + }); + + test('callReadOnly reads a cmd line as cmd, so the runner audits and serializes it', () => { + expect(callReadOnly(bash, { command: payload }, undefined)).toBe(true); + expect(callReadOnly(bash, { command: payload }, 'C:\\Windows\\System32\\cmd.exe')).toBe(false); + expect(callReadOnly(bash, { command: 'echo hi #& del /q x' }, 'cmd.exe')).toBe(false); + expect(callReadOnly(bash, { command: 'dir' }, 'cmd.exe')).toBe(true); + expect(callReadOnly(bash, { command: 'dir', run_in_background: true }, 'cmd.exe')).toBe(false); + }); + + test('single quotes hide no command from a deny rule, in every mode', () => { + for (const mode of ['default', 'plan', 'bypass', 'acceptEdits'] as PermissionMode[]) { + expect(cmdCheck(payload, { deny: ['Bash(mkdir:*)'] }, mode).decision).toBe('deny'); + } + // the full path of cmd.exe, as a paired device reports it + expect(cmdCheck(payload, { deny: ['Bash(mkdir:*)'] }, 'bypass', 'C:\\Windows\\System32\\cmd.exe').decision).toBe('deny'); + }); + + test('the payload is not read-only: plan denies, default asks, an echo rule does not cover it', () => { + expect(cmdCheck(payload, {}, 'plan').decision).toBe('deny'); + expect(cmdCheck(payload).decision).toBe('ask'); + expect(cmdCheck(payload, { allow: ['Bash(echo:*)'] }).decision).toBe('ask'); + expect(cmdCheck(payload, { ask: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('ask'); + }); + + test('backslashes, # and case hide no command', () => { + expect(cmdCheck('echo \\& mkdir x', { deny: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('deny'); + expect(cmdCheck('git status # & mkdir x', { allow: ['Bash(git status:*)'], deny: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('deny'); + expect(cmdCheck('git status # & mkdir x', { allow: ['Bash(git status:*)'] }).decision).toBe('ask'); + expect(cmdCheck('echo hi & @MKDIR x', { deny: ['Bash(mkdir:*)'] }).decision).toBe('deny'); + expect(cmdCheck('echo hi & "mkdir.exe",x', { deny: ['Bash(mkdir:*)'] }).decision).toBe('deny'); + }); + + test('syntax the check cannot read fails closed against command deny and ask rules, even under an exact grant', () => { + for (const c of ['echo %X% & dir', 'mk^dir x', 'echo !X!', '(mkdir x)', 'if exist a mkdir x', 'echo "open', 'echo a\nmkdir x', 'cmd /c mkdir x']) { + expect(cmdCheck(c, { allow: [`Bash(${c})`], deny: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('deny'); + expect(cmdCheck(c, { ask: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('ask'); + expect(cmdCheck(c, {}, 'plan').decision).toBe('deny'); + } + expect(cmdCheck('git log > out.txt', { allow: ['Bash(git log:*)'] }).reason).toBe('Needs approval: redirect is not covered by Bash(git log:*)'); + }); + + test('plain commands behave as before', () => { + expect(cmdCheck('dir', {}, 'plan').decision).toBe('allow'); + expect(cmdCheck('cd src && type README.md', {}, 'plan').decision).toBe('allow'); + expect(cmdCheck('echo "a & b"', {}, 'plan').decision).toBe('allow'); + expect(cmdCheck('DIR /s', {}, 'plan').decision).toBe('allow'); + // a program, not a built-in: it may be a script in the folder, so it is not read-only + expect(cmdCheck('git status', {}, 'plan').decision).toBe('deny'); + expect(cmdCheck('git status', { allow: ['Bash(git status:*)'] }).decision).toBe('allow'); + expect(cmdCheck('npm test && git diff', { allow: ['Bash(npm test:*)', 'Bash(git diff:*)'] }).decision).toBe('allow'); + expect(cmdCheck('npm test & mkdir x', { allow: ['Bash(npm test:*)'] }).decision).toBe('ask'); + expect(cmdCheck('mkdir x', { deny: ['Bash(mkdir:*)'] }).decision).toBe('deny'); + expect(cmdCheck('mkdir x', {}, 'bypass').decision).toBe('allow'); + expect(cmdCheck('echo %PATH%', {}, 'bypass').decision).toBe('allow'); + }); + + test('Windows programs with POSIX names are not read-only', () => { + for (const c of ['sort /o output.txt input.txt', 'date 11-20-2026', 'find "x" a.txt', 'where git', 'hostname', 'tree']) { + expect(cmdCheck(c).decision).toBe('ask'); + expect(cmdCheck(c, {}, 'plan').decision).toBe('deny'); + expect(cmdCheck(c, {}, 'bypass').decision).toBe('allow'); + } + }); + + test('a script or quoted name is not trusted as the built-in it is named after', () => { + for (const c of ['dir.cmd', 'dir.bat /s', '"dir"', 'echo.bat hi', '.\\type.cmd x', 'dir & type.bat']) { + expect(cmdCheck(c).decision).toBe('ask'); + expect(cmdCheck(c, {}, 'plan').decision).toBe('deny'); + } + // a deny rule still sees the script under its plain name + expect(cmdCheck('mkdir.bat x', { deny: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('deny'); + expect(cmdCheck('C:\\tools\\mkdir.exe x', { deny: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('deny'); + }); + + test('a nested shell by path or glued switch fails closed against deny rules', () => { + for (const c of [ + 'C:\\Windows\\System32\\cmd.exe /c mkdir owned', + '"C:\\Windows\\System32\\cmd.exe" /c mkdir owned', + 'C:/Windows/System32/cmd.exe /c mkdir owned', + 'cmd.exe/c mkdir owned', + 'cmd/c mkdir owned', + 'echo hi & C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -c mkdir owned', + '"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -c ni owned', + ]) { + for (const mode of ['default', 'plan', 'bypass'] as PermissionMode[]) { + expect(cmdCheck(c, { deny: ['Bash(mkdir:*)'] }, mode).decision).toBe('deny'); + expect(cmdCheck(c, { allow: ['Bash'], deny: ['Bash(mkdir:*)'] }, mode).decision).toBe('deny'); + } + expect(cmdCheck(c, { ask: ['Bash(mkdir:*)'] }, 'bypass').decision).toBe('ask'); + expect(cmdCheck(c, {}, 'plan').decision).toBe('deny'); + } + }); + + test('a bash shell keeps the bash reading', () => { + expect(cmdCheck("echo 'a & b'", { allow: ['Bash(echo:*)'] }, 'default', '/bin/bash').decision).toBe('allow'); + expect(cmdCheck(payload, {}, 'plan', '/usr/bin/bash').decision).toBe('allow'); + }); +}); diff --git a/packages/core/test/session/project.test.ts b/packages/core/test/session/project.test.ts index 7ed9bd0dd..b6c4785e7 100644 --- a/packages/core/test/session/project.test.ts +++ b/packages/core/test/session/project.test.ts @@ -106,6 +106,17 @@ describe('workspace facts', () => { expect(env({ workspace: {} })).not.toContain('Python:'); expect(env({})).not.toContain('Check run when you stop'); }); + + test('the Environment block names the OS and shell', () => { + const base = { session: { cwd: '/w' }, agent: { name: 'coder', prompt: '' }, modelRef: 'm', mode: 'agent', toolNames: ['Bash'], platform: 'linux', isGitRepo: true, deviceName: 'hub', projectInstructions: [], profile: [], skills: [], subagents: [], date: '2026-10-20' } as never; + const env = (p: object) => buildSystemPrompt({ ...(base as object), ...p } as never)[1].text; + expect(env({ platform: 'win32', shell: 'C:\\WINDOWS\\system32\\cmd.exe' })).toContain('- Shell: Windows cmd.exe (no bash). Foreground commands run as a batch script: use %%i in FOR loops, %% for a literal %, CALL for .cmd/.bat tools before more commands, and exit /b.'); + expect(env({ platform: 'win32', shell: 'C:\\Program Files\\Git\\bin\\bash.exe' })).toContain('- Shell: Windows with Git Bash: POSIX commands work; paths like D:\\x work as /d/x or D:/x'); + expect(env({ shell: '/bin/bash' })).toContain('- Shell: Linux, commands run in /bin/bash'); + expect(env({ shell: '/bin/sh' })).toContain('commands run in /bin/sh'); + expect(env({ platform: 'win32' })).not.toContain('Git Bash'); + expect(env({ platform: 'win32', shell: 'C:\\msys64\\usr\\bin\\bash.exe' })).toContain('POSIX commands work'); + }); }); describe('workspace facts in a session', () => { diff --git a/packages/core/test/tools/bash.test.ts b/packages/core/test/tools/bash.test.ts index 216778a87..3067f7d65 100644 --- a/packages/core/test/tools/bash.test.ts +++ b/packages/core/test/tools/bash.test.ts @@ -1,7 +1,8 @@ import { afterAll, describe, expect, test } from 'bun:test'; import { mkdirSync, realpathSync } from 'node:fs'; import { join } from 'node:path'; -import { BashTool, isBlockingWait } from '../../src/tools/bash'; +import { BashTool, isBlockingWait, wrapCmdCommand, wrapCommand } from '../../src/tools/bash'; +import type { Machine } from '../../src/machine/types'; import { BashOutputTool } from '../../src/tools/bash-output'; import { KillShellTool } from '../../src/tools/kill-shell'; import { shellRegistry } from '../../src/tools/shells'; @@ -179,6 +180,81 @@ describe('Bash', () => { expect(other.isError).toBe(true); }); + test('a cmd.exe device gets the cmd wrapper; the cwd marker and exit code come back', async () => { + const sent: Array<{ command: string; env?: Record }> = []; + let script = ''; + let removed = ''; + const machine = { + id: 'win', + lastInfo: { shell: 'C:\\WINDOWS\\system32\\cmd.exe' }, + writeFile: async (_path: string, data: string) => { script = data; }, + remove: async (path: string) => { removed = path; }, + exec: async (command: string, opts: { env?: Record }) => { + sent.push({ command, env: opts.env }); + if (command === 'chcp 65001 >nul & set TEMP') return { exitCode: 0, stdout: 'TEMP=C:\\Temp\r\n', stderr: '' }; + const marker = /(__CONCLAVE_CWD_\w+__)/.exec(command)![1]; + return { exitCode: 2, stdout: 'File Not Found\r\n', stderr: `nope\r\n${marker}D:\\proj\\sub \r\n`, timedOut: false, aborted: false, durationMs: 5 }; + }, + } as unknown as Machine; + const out = await BashTool.run({ command: 'cd sub\ndir x' }, makeCtx({ cwd: 'D:\\proj', machine })); + const { command, env } = sent[1]!; + expect(script).toBe(wrapCmdCommand('cd sub\ndir x')); + expect(command).toMatch(/^chcp 65001 >nul & call "%__CONCLAVE_SCRIPT%" & call set __conclave_exit=%\^errorlevel%& >&2 &2 cd & call exit \/b %\^__conclave_exit%$/); + expect(env?.__CONCLAVE_CMD).toBe('cd sub\ndir x'); + expect(removed).toBe(env!.__CONCLAVE_SCRIPT!); + expect(out.isError).toBe(true); + expect(out.meta?.exitCode).toBe(2); + expect(out.meta?.cwd).toBe('D:\\proj\\sub'); + expect(text(out)).not.toContain('__CONCLAVE_CWD_'); + expect(text(out)).toContain('File Not Found'); + expect(text(out)).toContain('nope'); + }); + + test('cmd temporary scripts are removed on write or execution failure', async () => { + for (const stage of ['write', 'exec']) { + let removed = ''; + let scriptPath = ''; + const machine = { + id: 'win', + lastInfo: { shell: 'cmd.exe' }, + writeFile: async (path: string) => { + scriptPath = path; + if (stage === 'write') throw new Error('write failed'); + }, + remove: async (path: string) => { removed = path; }, + exec: async (command: string) => { + if (command.includes('set TEMP')) return { exitCode: 0, stdout: 'TEMP=C:\\Temp & More\r\nTEMP_OTHER=ignored\r\n' }; + throw new Error('exec failed'); + }, + } as unknown as Machine; + const out = await BashTool.run({ command: 'echo hi' }, makeCtx({ cwd: 'D:\\proj', machine })); + expect(out.isError).toBe(true); + expect(text(out)).toContain(`${stage} failed`); + expect(removed).toBe(scriptPath); + expect(removed).toStartWith('C:\\Temp & More\\'); + } + }); + + test('the cmd batch wrapper preserves lines and does not nest user parentheses', () => { + const command = 'rem setup\n:: note\nif exist a (\n echo 100%% (a)\n) else (\n echo b\n)'; + expect(wrapCmdCommand(command)).toBe(`@echo off\r\nchcp 65001 >nul\r\n${command.replace(/\n/g, '\r\n')}\r\n`); + }); + + test('a bash device still gets the POSIX wrapper', async () => { + const sent: string[] = []; + const machine = { + id: 'mac', + lastInfo: { shell: '/bin/zsh' }, + exec: async (command: string) => { + sent.push(command); + return { exitCode: 0, stdout: 'hi\n', stderr: '', timedOut: false, aborted: false, durationMs: 1 }; + }, + } as unknown as Machine; + await BashTool.run({ command: 'echo hi' }, makeCtx({ cwd: '/w', machine })); + const marker = /(__CONCLAVE_CWD_\w+__)/.exec(sent[0]!)![1]!; + expect(sent[0]).toBe(wrapCommand(marker)); + }); + test('readOnly and rule hooks', () => { const ro = BashTool.readOnly as (i: any) => boolean; expect(ro({ command: 'ls -la' })).toBe(true); diff --git a/packages/core/test/tools/cmd-runtime.test.ts b/packages/core/test/tools/cmd-runtime.test.ts new file mode 100644 index 000000000..5bfc65f14 --- /dev/null +++ b/packages/core/test/tools/cmd-runtime.test.ts @@ -0,0 +1,236 @@ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { copyFileSync, existsSync, linkSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { LocalMachine } from '../../src/machine/local'; +import type { ExecOptions, ExecResult } from '../../src/machine/types'; +import { BashTool } from '../../src/tools/bash'; +import { shellRegistry } from '../../src/tools/shells'; +import { makeCtx, text } from './helpers'; + +// The Windows runner has Git Bash; this machine always runs cmd.exe, the shell of a Windows device without it. +class CmdMachine extends LocalMachine { + override shell(): string { + return process.env.ComSpec || 'cmd.exe'; + } +} + +// every exec, the TEMP lookup included, sees this TEMP +class TempMachine extends CmdMachine { + constructor(private readonly temp: string) { + super(); + } + override exec(command: string, opts: ExecOptions): Promise { + return super.exec(command, { ...opts, env: { ...opts.env, TEMP: this.temp } }); + } +} + +const CALL_TIMEOUT = 20_000; +const TEST_TIMEOUT = 30_000; +const bun = process.execPath; +const machine = new CmdMachine(); +// cmd's output has CRLF line ends +const clean = (s: string) => s.replace(/\r/g, ''); +const same = (a: string | undefined, b: string) => a?.toLowerCase() === b.toLowerCase(); + +describe.skipIf(process.platform !== 'win32')('Bash tool on cmd.exe (Windows runtime)', () => { + let base = ''; + let root = ''; + let echoJs = ''; + let binDir = ''; + + beforeAll(() => { + // realpath turns the runner's 8.3 temp path (RUNNER~1) into the long form cmd reports + base = realpathSync.native(mkdtempSync(join(tmpdir(), 'cc-cmd-'))); + // the session cwd only: a % typed into a batch command would need doubling + root = join(base, 'cmd rt (x) 100% & y'); + mkdirSync(root); + binDir = join(base, 'bin dir'); + mkdirSync(binDir); + echoJs = join(binDir, 'echo args.js'); + writeFileSync(echoJs, 'console.log(JSON.stringify({ args: process.argv.slice(2), cwd: process.cwd() }));\nif (process.argv[2] === "exit") process.exit(Number(process.argv[3]));\n'); + writeFileSync( + join(binDir, 'cc-shim.cmd'), + // the shape npm writes: no CALL needed by the caller, %~dp0 for its own folder + ['@ECHO off', 'SETLOCAL', `"${bun}" "%~dp0\\echo args.js" %*`, 'exit /b %ERRORLEVEL%', ''].join('\r\n'), + ); + writeFileSync( + join(binDir, 'sleeper.js'), + 'const fs = require("node:fs");\nfs.writeFileSync(process.argv[2], "up");\nsetTimeout(() => fs.writeFileSync(process.argv[3], "late"), 3000);\n', + ); + }); + + afterAll(async () => { + await shellRegistry.disposeAll(); + if (base) rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); + }); + + const bash = (command: string, cwd = root, sessionId = 'sess_cmd_rt', timeout = CALL_TIMEOUT) => + BashTool.run({ command, timeout }, makeCtx({ cwd, machine, sessionId })); + + test('runs a quoted executable path with spaces and quoted arguments', async () => { + const exeDir = join(base, 'bun copy'); + mkdirSync(exeDir, { recursive: true }); + const exe = join(exeDir, 'bun.exe'); + if (!existsSync(exe)) { + try { + linkSync(bun, exe); + } catch { + copyFileSync(bun, exe); + } + } + const out = await bash(`"${exe}" "${echoJs}" alpha "two words"`); + expect({ isError: out.isError, exitCode: out.meta?.exitCode, out: clean(text(out)) }).toEqual({ + isError: false, + exitCode: 0, + out: expect.stringMatching(/^\{/), + }); + expect(JSON.parse(clean(text(out))).args).toEqual(['alpha', 'two words']); + }, TEST_TIMEOUT); + + test('starts in a cwd with spaces, parentheses, percent and ampersand, and leaves it unchanged', async () => { + const out = await bash(`"${bun}" "${echoJs}"`); + expect({ isError: out.isError, exitCode: out.meta?.exitCode, out: clean(text(out)) }).toEqual({ + isError: false, + exitCode: 0, + out: expect.stringMatching(/^\{/), + }); + expect(same(JSON.parse(clean(text(out))).cwd, root)).toBe(true); + expect(out.meta?.cwd).toBeUndefined(); + const cd = await bash('cd'); + expect(same(clean(text(cd)), root)).toBe(true); + expect(cd.meta?.cwd).toBeUndefined(); + }, TEST_TIMEOUT); + + test('a doubled percent prints a literal percent (batch semantics)', async () => { + const out = await bash('echo 100%%'); + expect(out.isError).toBeFalsy(); + expect(clean(text(out))).toBe('100%'); + }, TEST_TIMEOUT); + + test('types a file with a Unicode name and prints its UTF-8 text exactly', async () => { + const body = 'héllo wörld ✓ 日本語'; + const file = join(root, 'café.txt'); + writeFileSync(file, body); + const out = await bash(`type "${file.replace(/%/g, '%%')}"`); + expect(out.isError).toBeFalsy(); + expect(clean(text(out))).toBe(body); + }, TEST_TIMEOUT); + + test('TEMP with spaces, &, parentheses and % still runs, and leaves no script behind', async () => { + const temp = join(base, 'Temp & More (x) 100%'); + mkdirSync(temp, { recursive: true }); + const tm = new TempMachine(temp); + const call = (command: string) => BashTool.run({ command, timeout: CALL_TIMEOUT }, makeCtx({ cwd: root, machine: tm, sessionId: 'sess_cmd_temp' })); + // quoted: cmd expands % before it parses &, so a bare %TEMP% would split the line + const echoed = await call('echo "%TEMP%"'); + expect(echoed.isError).toBeFalsy(); + expect(same(clean(text(echoed)), `"${temp}"`)).toBe(true); + const failed = await call('echo in-temp\nexit /b 4'); + expect(failed.meta?.exitCode).toBe(4); + expect(clean(text(failed)).split('\n')[0]).toBe('in-temp'); + expect(readdirSync(temp)).toEqual([]); + }, TEST_TIMEOUT); + + test('echo with unescaped parentheses', async () => { + const out = await bash('echo (hello)'); + expect(out.isError).toBeFalsy(); + expect(clean(text(out))).toBe('(hello)'); + }, TEST_TIMEOUT); + + test('a variable set on one line expands on the next', async () => { + const out = await bash('set CC_A=one\nset CC_B=two\necho %CC_A%-%CC_B%'); + expect(out.isError).toBeFalsy(); + expect(clean(text(out))).toBe('one-two'); + }, TEST_TIMEOUT); + + test('multiline if, for, rem and ::', async () => { + const script = [ + 'rem a comment line', + ':: a label comment', + 'for %%i in (a b c) do (', + ' echo item-%%i', + ')', + 'if exist "%CD%" (', + ' echo yes', + ') else (', + ' echo no', + ')', + 'rem trailing comment', + ].join('\n'); + const out = await bash(script); + expect(out.isError).toBeFalsy(); + expect(clean(text(out))).toBe('item-a\nitem-b\nitem-c\nyes'); + }, TEST_TIMEOUT); + + test('cd /d moves the session and meta.cwd reports the new folder', async () => { + const sub = join(root, 'sub (1) 50% & z'); + mkdirSync(sub, { recursive: true }); + // batch semantics: a literal % in the command is written %% + const out = await bash(`cd /d "${sub.replace(/%/g, '%%')}"\n"${bun}" "${echoJs}"`); + expect({ isError: out.isError, exitCode: out.meta?.exitCode, out: clean(text(out)) }).toEqual({ + isError: false, + exitCode: 0, + out: expect.stringMatching(/^\{/), + }); + expect(same(out.meta?.cwd as string | undefined, sub)).toBe(true); + expect(same(JSON.parse(clean(text(out)).split('\n')[0] as string).cwd, sub)).toBe(true); + // the next call starts where the last one ended + const next = await bash('cd', out.meta?.cwd as string); + expect(same(clean(text(next)), sub)).toBe(true); + expect(next.meta?.cwd).toBeUndefined(); + }, TEST_TIMEOUT); + + test('cmd /c exit 7 reports exit code 7', async () => { + const out = await bash('cmd /c exit 7'); + expect(out.isError).toBe(true); + expect(out.meta?.exitCode).toBe(7); + }, TEST_TIMEOUT); + + test('exit /b 9 reports exit code 9', async () => { + const out = await bash('echo before\nexit /b 9'); + expect(out.isError).toBe(true); + expect(out.meta?.exitCode).toBe(9); + expect(clean(text(out)).split('\n')[0]).toBe('before'); + }, TEST_TIMEOUT); + + test('runs an npm-style .cmd shim from PATH without CALL', async () => { + const out = await bash(`set "PATH=${binDir};%PATH%"\ncc-shim hello "two words"`); + expect({ isError: out.isError, exitCode: out.meta?.exitCode, out: clean(text(out)) }).toEqual({ + isError: false, + exitCode: 0, + out: expect.stringMatching(/^\{/), + }); + const lines = clean(text(out)).split('\n'); + expect(lines).toHaveLength(1); + expect(JSON.parse(lines[0] as string).args).toEqual(['hello', 'two words']); + expect(out.meta?.cwd).toBeUndefined(); + const failed = await bash(`set "PATH=${binDir};%PATH%"\ncc-shim exit 5`); + expect(failed.meta?.exitCode).toBe(5); + }, TEST_TIMEOUT); + + test('a timeout kills the whole tree, so a child started by cmd never writes', async () => { + const started = join(base, 'started.txt'); + const sentinel = join(base, 'sentinel.txt'); + const out = await bash(`"${bun}" "${join(binDir, 'sleeper.js')}" "${started}" "${sentinel}"`, root, 'sess_cmd_rt', 1_000); + expect(out.isError).toBe(true); + expect(text(out)).toContain('timed out'); + await Bun.sleep(3_500); + expect(existsSync(started)).toBe(true); + expect(existsSync(sentinel)).toBe(false); + }, 10_000); + + test('a background command (bash -c) runs in cmd', async () => { + const ctx = makeCtx({ cwd: root, machine, sessionId: 'sess_cmd_bg' }); + const out = await BashTool.run({ command: 'echo os=%OS%', run_in_background: true, timeout: CALL_TIMEOUT }, ctx); + expect(out.isError).toBeFalsy(); + const shell = shellRegistry.get('sess_cmd_bg', String(out.meta?.shellId)); + expect(shell).toBeDefined(); + const ended = await Promise.race([shell!.done.then(() => true), Bun.sleep(15_000).then(() => false)]); + if (!ended) await shell!.kill(); + expect(ended).toBe(true); + expect(shell!.info.exitCode).toBe(0); + // Git Bash would print %OS% as it is + expect(clean(shell!.stdout.all()).trim()).toBe('os=Windows_NT'); + }, TEST_TIMEOUT); +}); diff --git a/packages/core/test/tools/local-machine.test.ts b/packages/core/test/tools/local-machine.test.ts index 29d360ce6..5f9d8766d 100644 --- a/packages/core/test/tools/local-machine.test.ts +++ b/packages/core/test/tools/local-machine.test.ts @@ -1,7 +1,7 @@ import { afterAll, describe, expect, test } from 'bun:test'; import { homedir } from 'node:os'; import { join } from 'node:path'; -import { LocalMachine } from '../../src/machine/local'; +import { LocalMachine, shellArgv } from '../../src/machine/local'; import { tempDir } from './helpers'; const m = new LocalMachine(); @@ -86,9 +86,26 @@ describe('LocalMachine', () => { expect(await s.exited).toBeNull(); }); + test('cmd.exe runs its line with /d /v:off /s /c', async () => { + const cmd = new LocalMachine(); + // stands in for cmd.exe: a script that prints the argv it got + const fake = join(dir, 'cmd.exe'); + await cmd.writeFile(fake, '#!/bin/sh\nprintf "%s|" "$@"\n'); + await cmd.exec(`chmod 755 '${fake}'`, { cwd: dir }); + (cmd as any).shellPath = fake; + const r = await cmd.exec('ver & call echo x', { cwd: dir }); + expect(r.stdout).toBe('/d|/v:off|/s|/c|ver & call echo x|'); + // a background shell's bash -c goes to cmd.exe too + const p = cmd.spawn('bash', ['-c', 'ver'], { cwd: dir }); + expect(await new Response(p.stdout as never).text()).toBe('/d|/v:off|/s|/c|ver|'); + expect(shellArgv('C:\\WINDOWS\\system32\\cmd.exe', 'ver')).toEqual(['C:\\WINDOWS\\system32\\cmd.exe', '/d', '/v:off', '/s', '/c', 'ver']); + expect(shellArgv('/usr/bin/bash', 'ver')).toEqual(['/usr/bin/bash', '-c', 'ver']); + }); + test('info lists platform and cached CLIs', async () => { const info = await m.info(); expect(info.platform).toBe(process.platform); + expect(info.shell).toBe(m.shell()); expect(info.home).toBe(homedir()); expect(info.clis.bun).toMatch(/^\d+\.\d+/); const again = await m.info(); diff --git a/packages/daemon-rs/src/info.rs b/packages/daemon-rs/src/info.rs index 72c2672cc..e156b0edf 100644 --- a/packages/daemon-rs/src/info.rs +++ b/packages/daemon-rs/src/info.rs @@ -145,11 +145,8 @@ async fn collect() -> Value { if clis.contains_key("git") { caps.push("git"); } - // on Windows SHELL (set inside Git Bash or MSYS) is not what exec runs: report the shell exec picks - let shell = match std::env::var("SHELL") { - Ok(s) if !s.is_empty() && !cfg!(windows) => s, - _ => crate::procs::shell().to_string(), - }; + // SHELL describes the login shell, not necessarily what exec runs. + let shell = crate::procs::shell(); json!({ "hostname": hostname(), "platform": platform(), diff --git a/packages/daemon-rs/src/procs.rs b/packages/daemon-rs/src/procs.rs index a96d25dab..0dd8915d3 100644 --- a/packages/daemon-rs/src/procs.rs +++ b/packages/daemon-rs/src/procs.rs @@ -82,8 +82,21 @@ pub fn kill_tree(pid: u32, sig: Sig) { #[cfg(windows)] pub fn kill_tree(pid: u32, _sig: Sig) { + use std::os::windows::process::CommandExt; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE}; + // no process groups on Windows: taskkill /T ends the shell and everything it started + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let tree = std::process::Command::new("taskkill") + .args(["/pid", &pid.to_string(), "/T", "/F"]) + .creation_flags(CREATE_NO_WINDOW) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + if matches!(tree, Ok(s) if s.success()) { + return; + } // SAFETY: plain Win32 calls on a process handle we open and close here. unsafe { let h = OpenProcess(PROCESS_TERMINATE, 0, pid); @@ -183,6 +196,13 @@ pub fn shell() -> &'static str { }) } +/// cmd.exe (also as ComSpec's full path), which takes /d /s /c instead of -c. +fn is_cmd(sh: &str) -> bool { + let l = sh.to_ascii_lowercase(); + let base = l.rsplit(|c: char| c == '\\' || c == '/').next().unwrap_or(""); + base == "cmd.exe" || base == "cmd" +} + /// The WSL launcher (WindowsApps or System32 bash.exe) runs Linux, where D:\ paths and Windows tools do not exist. fn is_wsl_launcher(p: &str) -> bool { let l = p.to_ascii_lowercase().replace('/', "\\"); @@ -217,6 +237,29 @@ pub fn windows_bash(path_var: &str, env: &dyn Fn(&str) -> Option, is_fil cands.into_iter().find(|c| !is_wsl_launcher(c) && is_file(c)) } +/// `sh` running `command`, for exec and spawn's background shells. cmd.exe gets /d /v:off /s /c and +/// the command in one pair of outer quotes that /s strips, so its own quotes reach cmd verbatim. +fn shell_command(sh: &str, command: &str) -> tokio::process::Command { + let mut cmd = tokio::process::Command::new(sh); + if is_cmd(sh) { + #[cfg(windows)] + { + cmd.args(["/d", "/v:off", "/s", "/c"]); + cmd.raw_arg(format!("\"{command}\"")); + } + } else { + cmd.arg("-c").arg(command); + } + cmd +} + +/// cmd.exe looks in the current folder before PATH, so a repo's git.bat would run under an allow rule for git; bash never does. +fn no_cwd_lookup(cmd: &mut tokio::process::Command, sh: &str) { + if is_cmd(sh) { + cmd.env("NoDefaultCurrentDirectoryInExePath", "1"); + } +} + fn configure(cmd: &mut tokio::process::Command, own_group: bool) { #[cfg(unix)] if own_group { @@ -300,17 +343,9 @@ pub async fn exec(command: String, opts: ExecOpts, mut abort: watch::Receiver return Err(WireError::coded(format!("Executable not found in $PATH: \"{command}\""), "ENOENT")), } }; - let mut cmd = tokio::process::Command::new(&program); - cmd.args(args).current_dir(&cwd).env_clear().envs(envs); + let mut cmd = if via_shell { + shell_command(shell(), &args[1]) + } else { + let mut c = tokio::process::Command::new(&program); + c.args(args); + c + }; + cmd.current_dir(&cwd).env_clear().envs(envs); + if via_shell { + no_cwd_lookup(&mut cmd, shell()); + } cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); configure(&mut cmd, true); let mut child = cmd.spawn().map_err(|e| spawn_error(&e, command))?; @@ -539,7 +587,14 @@ pub fn spawn(command: &str, args: &[String], cwd: &str, env: Option<&Map { pumps_done = true; } Some(sig) = kill_rx.recv() => { #[cfg(windows)] - { if !exited { let _ = child.start_kill(); } } + { + if !exited { + match pid { + Some(p) => kill_tree(p, sig), + None => { let _ = child.start_kill(); } + } + } + } #[cfg(unix)] { if let Some(p) = pid { kill_tree(p, sig); } } let _ = sig; @@ -748,6 +803,16 @@ mod tests { assert_eq!(b.finish(), "short"); } + #[test] + fn is_cmd_matches_cmd_exe_only() { + assert!(is_cmd("cmd.exe")); + assert!(is_cmd("C:\\WINDOWS\\system32\\CMD.EXE")); + assert!(is_cmd("cmd")); + assert!(!is_cmd("C:\\Program Files\\Git\\bin\\bash.exe")); + assert!(!is_cmd("/usr/bin/bash")); + assert!(!is_cmd("C:\\tools\\notcmd.exe")); + } + #[test] fn head_tail_counts_utf16() { let mut b = HeadTail::new(4); @@ -771,4 +836,171 @@ mod tests { let _ = c; }); } + + // Real cmd.exe and taskkill on Windows CI: cargo test windows_cmd + #[cfg(windows)] + mod win { + use super::*; + use futures_util::future::BoxFuture; + + fn rt() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap() + } + + fn comspec() -> String { + let c = std::env::var("ComSpec").unwrap_or_else(|_| "cmd.exe".into()); + assert!(is_cmd(&c), "ComSpec is not cmd: {c}"); + c + } + + /// shell_command with the real ComSpec: (exit code, stdout with \n line ends, stderr). + fn run_cmd(command: &str) -> (Option, String, String) { + rt().block_on(async { + let mut cmd = shell_command(&comspec(), command); + cmd.env("CV_WIN_CMD_VAR", "hello there").stdin(Stdio::null()); + let out = cmd.output().await.unwrap(); + (out.status.code(), String::from_utf8_lossy(&out.stdout).replace("\r\n", "\n"), String::from_utf8_lossy(&out.stderr).into_owned()) + }) + } + + fn temp_dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("cv win cmd {name} {}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn windows_cmd_runs_a_quoted_program_path_with_spaces_and_quoted_args() { + let dir = temp_dir("path"); + let bat = dir.join("say it.cmd"); + std::fs::write(&bat, "@echo [%~1] [%2]\r\n").unwrap(); + // first and last character are both quotes: without /s and the outer pair cmd would strip them + let (code, out, err) = run_cmd(&format!("\"{}\" \"x y\" \"z\"", bat.display())); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!((code, out.trim_end()), (Some(0), "[x y] [\"z\"]"), "stderr: {err}"); + } + + #[test] + fn windows_cmd_keeps_inner_quotes() { + let (code, out, err) = run_cmd("echo 'c'& echo \"a b\""); + assert_eq!((code, out.as_str()), (Some(0), "'c'\n\"a b\"\n"), "stderr: {err}"); + } + + #[test] + fn windows_cmd_expands_percent_vars_and_not_bang_vars() { + // /v:off: !NAME! stays literal + let (code, out, err) = run_cmd("echo %CV_WIN_CMD_VAR%^|!CV_WIN_CMD_VAR!"); + assert_eq!((code, out.trim_end()), (Some(0), "hello there|!CV_WIN_CMD_VAR!"), "stderr: {err}"); + } + + #[test] + fn windows_cmd_returns_the_exit_status() { + assert_eq!(run_cmd("exit 5").0, Some(5)); + assert_eq!(run_cmd("echo x>nul& exit 42").0, Some(42)); + assert_eq!(run_cmd("ver>nul").0, Some(0)); + } + + #[test] + fn windows_cmd_kill_tree_ends_the_shell_and_its_child() { + rt().block_on(async { + let mut cmd = shell_command(&comspec(), "ping -n 30 127.0.0.1 && echo after"); + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); + configure(&mut cmd, true); + let mut child = cmd.spawn().unwrap(); + let mut out = child.stdout.take().unwrap(); + tokio::time::sleep(Duration::from_millis(500)).await; + kill_tree(child.id().unwrap(), Sig::Term); + let mut buf = Vec::new(); + // ping holds the pipe too: EOF only comes once the whole tree is gone + tokio::time::timeout(Duration::from_secs(10), out.read_to_end(&mut buf)).await.expect("pipe still open, ping outlived kill_tree").unwrap(); + assert!(!child.wait().await.unwrap().success()); + assert!(!String::from_utf8_lossy(&buf).contains("after")); + }); + } + + fn cwd() -> String { + std::env::temp_dir().to_string_lossy().into_owned() + } + + fn exec_opts(timeout_ms: Option) -> ExecOpts { + ExecOpts { cwd: cwd(), env: None, timeout_ms, stdin: None, max_output: None } + } + + // exec and spawn run shell(): Git Bash on CI, cmd.exe without it. These commands mean the same in both. + #[test] + fn windows_cmd_exec_returns_output_and_exit_status() { + rt().block_on(async { + let (_abort, rx) = watch::channel(false); + let r = exec("echo hi&& exit 3".into(), exec_opts(None), rx, None).await; + assert_eq!(r["exitCode"].as_i64(), Some(3), "{r}"); + assert_eq!(r["stdout"].as_str().map(str::trim_end), Some("hi"), "{r}"); + }); + } + + #[test] + fn windows_cmd_exec_times_out_and_kills_the_tree() { + rt().block_on(async { + let (_abort, rx) = watch::channel(false); + let started = Instant::now(); + let r = exec("ping -n 30 127.0.0.1 && echo after".into(), exec_opts(Some(500.0)), rx, None).await; + assert_eq!(r["timedOut"], json!(true), "{r}"); + assert!(started.elapsed() < Duration::from_secs(10), "took {:?}", started.elapsed()); + assert!(!r["stdout"].as_str().unwrap().contains("after"), "{r}"); + }); + } + + struct Collect { + out: Mutex>, + exit: Mutex>>>, + } + + impl ProcSink for Collect { + fn output(&self, stream: &'static str, data: String) -> BoxFuture<'static, ()> { + if stream == "proc.stdout" { + self.out.lock().unwrap().extend(crate::js::decode_base64_lenient(&data)); + } + Box::pin(async {}) + } + fn exit(&self, code: Option) -> BoxFuture<'static, ()> { + if let Some(tx) = self.exit.lock().unwrap().take() { + let _ = tx.send(code); + } + Box::pin(async {}) + } + } + + fn collect() -> (Arc, tokio::sync::oneshot::Receiver>) { + let (tx, rx) = tokio::sync::oneshot::channel(); + (Arc::new(Collect { out: Mutex::new(Vec::new()), exit: Mutex::new(Some(tx)) }), rx) + } + + fn bash_c(command: &str) -> Vec { + vec!["-c".into(), command.into()] + } + + #[test] + fn windows_cmd_spawn_background_shell_returns_output_and_exit_status() { + rt().block_on(async { + let (sink, exit) = collect(); + let _h = spawn("bash", &bash_c("echo hi&& exit 3"), &cwd(), None, sink.clone()).unwrap(); + let code = tokio::time::timeout(Duration::from_secs(20), exit).await.expect("no proc.exit").unwrap(); + assert_eq!(code, Some(3)); + assert_eq!(String::from_utf8_lossy(&sink.out.lock().unwrap()).trim_end(), "hi"); + }); + } + + #[test] + fn windows_cmd_spawn_kill_ends_the_tree() { + rt().block_on(async { + let (sink, exit) = collect(); + let (h, _) = spawn("bash", &bash_c("ping -n 30 127.0.0.1 && echo after"), &cwd(), None, sink.clone()).unwrap(); + tokio::time::sleep(Duration::from_millis(500)).await; + h.kill.send(Sig::Term).unwrap(); + // proc.exit waits for both pipes, so a surviving ping would hold it back + let code = tokio::time::timeout(Duration::from_secs(10), exit).await.expect("no proc.exit, the tree outlived kill").unwrap(); + assert_ne!(code, Some(0)); + assert!(!String::from_utf8_lossy(&sink.out.lock().unwrap()).contains("after")); + }); + } + } } diff --git a/packages/web/src/features/devices/DevicesPage.tsx b/packages/web/src/features/devices/DevicesPage.tsx index fb65330ce..a061c7a7d 100644 --- a/packages/web/src/features/devices/DevicesPage.tsx +++ b/packages/web/src/features/devices/DevicesPage.tsx @@ -395,6 +395,14 @@ function DeviceDetail({ d, running }: { d: Device; running: Session[] }) { {d.info.shell} + {d.info.platform === 'win32' && /(^|[\\/])cmd(\.exe)?$/i.test(d.info.shell) && ( +

+ + Install Git for Windows + {' '} + for full shell support +

+ )} {d.info.capabilities.length > 0 && {capabilityWords(d.info.capabilities)}} {d.info.daemon && (