Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: resolve multiple high-frequency Windows feedback issues around shell execution (#17576)

YuTengjingb2bb1ee823d1
diff --git a/.agents/skills/typescript/SKILL.md b/.agents/skills/typescript/SKILL.md
index 3c62ab7ea76..0de21e8366e 100644
--- a/.agents/skills/typescript/SKILL.md
+++ b/.agents/skills/typescript/SKILL.md
@@ -22,8 +22,8 @@ user-invocable: false
## Async Patterns
- Prefer `async`/`await` over callbacks or `.then()` chains
-- Prefer async APIs over sync ones (avoid `*Sync`)
-- Use promise-based variants: `import { readFile } from 'fs/promises'`
+- **Async-first for IO**: new IO code (fs, child\_process, etc.) must use async APIs at its boundaries — use promise-based variants like `import { readFile } from 'fs/promises'`, never `*Sync` by default. Function coloring is asymmetric: async→sync migration is never needed, while sync→async (when IO gets slower, gains concurrency, or grows a subprocess/network call) forces rewriting every caller up the chain — sync-first debt that compounds. Micro-costs of async (thread-pool dispatch, cache races) are not valid reasons: races are solved by caching the promise instead of the result
+- `*Sync` is acceptable in exactly one place: call sites locked inside a synchronous contract you don't control — an existing sync signature chain (don't virally refactor a legacy sync chain in a bugfix, but new standalone modules must not extend such chains), or sync-only callbacks like `process.on('exit')`. Module-load-time and CLI startup init are NOT exceptions — use top-level `await` (ESM) there
- Use `Promise.all`, `Promise.race` for concurrent operations where safe
## Imports
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index afcb5f971ba..d18a32dc0dd 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -197,6 +197,31 @@ jobs:
files: ./coverage/app/lcov.info
flags: app
+ # Windows-only verification of the local shell execution strategy.
+ # The unit tests mock process.platform and fs.existsSync, so they prove
+ # nothing about real Windows behaviour: argument tokenization by the Windows
+ # CRT, Windows PowerShell 5.1 (which lacks `&&`), and the pwsh/5.1/cmd
+ # detection cascade against real install paths. The driver script only needs
+ # node builtins, so this job skips the monorepo install entirely.
+ test-windows-shell:
+ needs: check-duplicate-run
+ if: needs.check-duplicate-run.outputs.should_skip != 'true'
+ name: Test Windows Shell
+
+ runs-on: windows-latest
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - name: Install bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: '1.3.2'
+
+ - name: Verify Windows shell strategy
+ run: bun run packages/local-file-shell/scripts/verify-windows-shell.ts
+
test-desktop:
needs: check-duplicate-run
if: needs.check-duplicate-run.outputs.should_skip != 'true'
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index fa6c978baa3..e3c36e04eaf 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -18,6 +18,7 @@ import type {
} from '@lobechat/device-gateway-client';
import { GatewayClient } from '@lobechat/device-gateway-client';
import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';
+import { getShellInfo } from '@lobechat/local-file-shell';
import type { Command } from 'commander';
import { createLambdaClient } from '../api/client';
@@ -1006,6 +1007,8 @@ function collectSystemInfo(): DeviceSystemInfo {
return {
arch: os.arch(),
+ // Tell the server-side prompt builder which shell runCommand spawns here.
+ defaultShell: getShellInfo().displayName,
desktopPath: path.join(home, 'Desktop'),
documentsPath: path.join(home, 'Documents'),
downloadsPath: path.join(home, 'Downloads'),
diff --git a/apps/desktop/src/main/const/store.ts b/apps/desktop/src/main/const/store.ts
index 75ea8fcb5d4..97086cafad7 100644
--- a/apps/desktop/src/main/const/store.ts
+++ b/apps/desktop/src/main/const/store.ts
@@ -46,4 +46,5 @@ export const STORE_DEFAULTS: ElectronMainStore = {
storagePath: appStorageDir,
themeMode: 'system',
updateChannel: UPDATE_CHANNEL,
+ windowsShellMode: 'auto',
};
diff --git a/apps/desktop/src/main/controllers/ShellCommandCtr.ts b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
index ddca49426ab..2e17919e4dc 100644
--- a/apps/desktop/src/main/controllers/ShellCommandCtr.ts
+++ b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
@@ -1,12 +1,20 @@
import type {
+ DesktopShellSettings,
GetCommandOutputParams,
GetCommandOutputResult,
KillCommandParams,
KillCommandResult,
RunCommandParams,
RunCommandResult,
+ SetShellModeParams,
} from '@lobechat/electron-client-ipc';
-import { runCommand, ShellProcessManager } from '@lobechat/local-file-shell';
+import {
+ findGitBash,
+ getShellInfo,
+ runCommand,
+ setWindowsShellPreference,
+ ShellProcessManager,
+} from '@lobechat/local-file-shell';
import { createLogger } from '@/utils/logger';
@@ -23,6 +31,43 @@ const SIMPLE_LH_PREFIX = /^\s*(?:lh|lobe|lobehub)(?=\s|$)/;
export default class ShellCommandCtr extends ControllerModule {
static override readonly groupName = 'shellCommand';
+ /**
+ * Apply the persisted Windows shell preference before any command runs, so
+ * the local-file-shell detection chain honors it from the first execution.
+ */
+ beforeAppReady() {
+ if (process.platform !== 'win32') return;
+ const mode = this.app.storeManager.get('windowsShellMode', 'auto');
+ setWindowsShellPreference(mode);
+ logger.debug('Applied Windows shell preference:', mode);
+ }
+
+ @IpcMethod()
+ async getShellSettings(): Promise<DesktopShellSettings> {
+ const gitBashPath = process.platform === 'win32' ? await findGitBash() : undefined;
+ const { displayName, path } = await getShellInfo();
+
+ return {
+ currentShell: { displayName, path },
+ gitBashAvailable: !!gitBashPath,
+ gitBashPath,
+ mode: this.app.storeManager.get('windowsShellMode', 'auto'),
+ };
+ }
+
+ @IpcMethod()
+ async setShellMode({ mode }: SetShellModeParams): Promise<DesktopShellSettings> {
+ if (mode === 'gitbash' && !(await findGitBash())) {
+ throw new Error('Git Bash is not installed');
+ }
+
+ this.app.storeManager.set('windowsShellMode', mode);
+ setWindowsShellPreference(mode);
+ logger.info('Windows shell mode updated:', mode);
+
+ return this.getShellSettings();
+ }
+
@IpcMethod()
async handleRunCommand(params: RunCommandParams): Promise<RunCommandResult> {
const prefixMatch = SIMPLE_LH_PREFIX.exec(params.command);
diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.ts
index d40fa1c92a7..e7d1d538f0d 100644
--- a/apps/desktop/src/main/controllers/SystemCtr.ts
+++ b/apps/desktop/src/main/controllers/SystemCtr.ts
@@ -1,6 +1,7 @@
import process from 'node:process';
import type { ElectronAppState, ThemeMode } from '@lobechat/electron-client-ipc';
+import { getShellInfo } from '@lobechat/local-file-shell';
import { app, dialog, nativeTheme, shell } from 'electron';
import * as electronIs from 'electron-is';
import { getFonts2 } from 'font-list';
@@ -52,6 +53,8 @@ export default class SystemController extends ControllerModule {
return {
// System Info
arch,
+ // Tell the model which shell runCommand actually spawns (see local-file-shell).
+ defaultShell: (await getShellInfo()).displayName,
isLinux: platform === 'linux',
isMac: platform === 'darwin',
isWindows: platform === 'win32',
diff --git a/apps/desktop/src/main/controllers/TerminalCtr.ts b/apps/desktop/src/main/controllers/TerminalCtr.ts
index 9124e7d3290..d7b298b6083 100644
--- a/apps/desktop/src/main/controllers/TerminalCtr.ts
+++ b/apps/desktop/src/main/controllers/TerminalCtr.ts
@@ -39,7 +39,7 @@ export default class TerminalCtr extends ControllerModule {
@IpcMethod()
async createSession(params: TerminalCreateSessionParams): Promise<TerminalCreateSessionResult> {
try {
- const info = this.manager.create(params);
+ const info = await this.manager.create(params);
logger.debug(`created session ${info.id} (pid ${info.pid}, shell ${info.shell})`);
return info;
} catch (error) {
diff --git a/apps/desktop/src/main/modules/terminal/index.ts b/apps/desktop/src/main/modules/terminal/index.ts
index 98c3cf7ea9c..710ef76598f 100644
--- a/apps/desktop/src/main/modules/terminal/index.ts
+++ b/apps/desktop/src/main/modules/terminal/index.ts
@@ -1,7 +1,8 @@
import { randomUUID } from 'node:crypto';
-import { existsSync } from 'node:fs';
+import fs from 'node:fs/promises';
import os from 'node:os';
+import { detectWindowsShell } from '@lobechat/local-file-shell';
import type { IPty } from '@lydell/node-pty';
import { spawn } from '@lydell/node-pty';
@@ -38,11 +39,22 @@ interface PtySession {
pty: IPty;
}
-const getDefaultShell = () => {
- if (process.platform === 'win32') return process.env.ComSpec || 'powershell.exe';
+const getDefaultShell = async () => {
+ // Reuse the runCommand shell detection (pwsh → PowerShell 5.1 → cmd, or Git
+ // Bash when the user selected it in settings) instead of ComSpec, which
+ // effectively always points at cmd.exe.
+ if (process.platform === 'win32') return (await detectWindowsShell()).path;
return process.env.SHELL || (process.platform === 'darwin' ? '/bin/zsh' : '/bin/bash');
};
+const dirExists = async (candidate: string): Promise<boolean> => {
+ try {
+ return (await fs.stat(candidate)).isDirectory();
+ } catch {
+ return false;
+ }
+};
+
/**
* Owns the PTY processes for the in-app terminal. Sessions live in the main
* process so they survive renderer-side panel collapse / remount; the renderer
@@ -62,12 +74,12 @@ export class PtySessionManager {
this.sweepTimer.unref();
}
- create(options: CreatePtySessionOptions): PtySessionInfo {
+ async create(options: CreatePtySessionOptions): Promise<PtySessionInfo> {
this.evictLruIfFull();
const id = `pty_${randomUUID()}`;
- const shell = getDefaultShell();
- const cwd = options.cwd && existsSync(options.cwd) ? options.cwd : os.homedir();
+ const shell = await getDefaultShell();
+ const cwd = options.cwd && (await dirExists(options.cwd)) ? options.cwd : os.homedir();
const pty = spawn(shell, [], {
cols: options.cols,
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index bdbc3433a2b..6aa5753b521 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -20,6 +20,7 @@ import { GatewayClient } from '@lobechat/device-gateway-client';
import type { IdentitySource } from '@lobechat/device-identity';
import { deriveDeviceId, deriveScopedFallbackId } from '@lobechat/device-identity';
import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';
+import { getShellInfo } from '@lobechat/local-file-shell';
import { app, powerSaveBlocker } from 'electron';
import { isDev } from '@/const/env';
@@ -679,7 +680,7 @@ export default class GatewayConnectionService extends ServiceModule {
// ─── System Info ───
- private handleSystemInfoRequest(client: GatewayClient, request: SystemInfoRequestMessage) {
+ private async handleSystemInfoRequest(client: GatewayClient, request: SystemInfoRequestMessage) {
logger.info(`Received system_info_request: requestId=${request.requestId}`);
client.sendSystemInfoResponse({
requestId: request.requestId,
@@ -687,6 +688,8 @@ export default class GatewayConnectionService extends ServiceModule {
success: true,
systemInfo: {
arch: os.arch(),
+ // Tell the server-side prompt builder which shell runCommand spawns here.
+ defaultShell: (await getShellInfo()).displayName,
desktopPath: app.getPath('desktop'),
documentsPath: app.getPath('documents'),
downloadsPath: app.getPath('downloads'),
diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.ts
index dc23441cfa6..baf7706d9e2 100644
--- a/apps/desktop/src/main/types/store.ts
+++ b/apps/desktop/src/main/types/store.ts
@@ -3,6 +3,7 @@ import type {
ImessageBridgeConfig,
NetworkProxySettings,
UpdateChannel,
+ WindowsShellMode,
} from '@lobechat/electron-client-ipc';
import type { HeteroSessionDirPref } from '@lobechat/types';
@@ -53,6 +54,8 @@ export interface ElectronMainStore {
storagePath: string;
themeMode: 'dark' | 'light' | 'system';
updateChannel: UpdateChannel;
+ /** Shell used for agent command execution on Windows (ignored elsewhere). */
+ windowsShellMode: WindowsShellMode;
}
export type StoreKey = keyof ElectronMainStore;
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
index 3248421ce0e..23568d6bea3 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
@@ -32,6 +32,12 @@ const createServerVariableGenerators = (params: {
// session with no bound directory) leaves `{{workingDirectory}}` unmatched and
// leaks the literal into the local-system system prompt (LOBE-11473).
workingDirectory: () => '(not specified, use user Home directory as default)',
+ // Same leak-guard as workingDirectory: the real value arrives via
+ // `additionalVariables` (deviceSystemInfo.defaultShell) and overrides this.
+ // Without a device-reported value, describe the platform default instead of
+ // leaking the literal `{{defaultShell}}` token into the prompt.
+ defaultShell: () =>
+ 'the platform default shell (PowerShell on Windows, /bin/sh on macOS/Linux)',
};
};
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 16bf2970395..1ba720b783f 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -3452,6 +3452,11 @@ export class AiAgentService {
log('execAgent: fetched device system info for %s', deviceId);
return {
arch: systemInfo.arch,
+ // Devices that don't report defaultShell run an older client whose
+ // runner still hardcodes cmd.exe on Windows — describe that honestly
+ // instead of the new PowerShell default.
+ defaultShell:
+ systemInfo.defaultShell ?? (device?.platform === 'win32' ? 'cmd.exe' : '/bin/sh'),
desktopPath: systemInfo.desktopPath,
documentsPath: systemInfo.documentsPath,
downloadsPath: systemInfo.downloadsPath,
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 4a9849a1122..4bc59cc2b5e 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -910,6 +910,12 @@
"settingSystemTools.category.runtimeEnvironment.desc": "Development runtime environments for executing scripts and packages",
"settingSystemTools.detecting": "Detecting...",
"settingSystemTools.redetect": "Re-detect",
+ "settingSystemTools.shell.desc": "Shell used when the agent runs local commands on this machine",
+ "settingSystemTools.shell.mode.auto": "Automatic (PowerShell)",
+ "settingSystemTools.shell.mode.desc": "PowerShell is used by default. Git Bash appears as an option when Git for Windows is installed. Current shell:",
+ "settingSystemTools.shell.mode.gitbash": "Git Bash",
+ "settingSystemTools.shell.mode.title": "Windows Shell",
+ "settingSystemTools.shell.title": "Command Execution",
"settingSystemTools.status.available": "Available",
"settingSystemTools.status.notDetected": "Not detected",
"settingSystemTools.status.unavailable": "Unavailable",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 526a2ec7e97..0a1b593cedd 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -910,6 +910,12 @@
"settingSystemTools.category.runtimeEnvironment.desc": "用于执行脚本和安装依赖的开发运行环境",
"settingSystemTools.detecting": "检测中...",
"settingSystemTools.redetect": "重新检测",
+ "settingSystemTools.shell.desc": "Agent 在本机执行命令时使用的 Shell",
+ "settingSystemTools.shell.mode.auto": "自动(PowerShell)",
+ "settingSystemTools.shell.mode.desc": "默认使用 PowerShell;检测到 Git for Windows 后可选择 Git Bash。当前 Shell:",
+ "settingSystemTools.shell.mode.gitbash": "Git Bash",
+ "settingSystemTools.shell.mode.title": "Windows Shell",
+ "settingSystemTools.shell.title": "命令执行",
"settingSystemTools.status.available": "可用",
"settingSystemTools.status.notDetected": "未检测",
"settingSystemTools.status.unavailable": "不可用",
diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
index bf53bae6b3e..4e590507632 100644
--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
@@ -78,7 +78,7 @@ You have access to a set of tools to interact with the user's local file system:
- 'command': The shell command to execute.
- 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.
- 'run_in_background' (Optional): Set to true to return immediately after starting the terminal session. The result includes a 'shell_id' for later observation or termination.
- The command runs in cmd.exe on Windows or /bin/sh on macOS/Linux. The returned output reflects the tool's wait window, not necessarily the full command lifetime.
+ The command runs in {{defaultShell}}. When that shell is PowerShell, write PowerShell-compatible syntax; on Windows PowerShell 5.1 the &&/|| chain operators are NOT available — use ';' to sequence commands or 'if ($?) { ... }' for conditional chaining. The returned output reflects the tool's wait window, not necessarily the full command lifetime.
- Installing software: do NOT proactively install software on the user's system. Prefer tools that are already installed, or a no-install alternative. If a task genuinely needs a system-level or global install (e.g. \`brew install\`, \`apt\`/\`dnf install\`, \`npm i -g\`, \`pipx\`, a global \`pip install\`), ask the user first and explain why, rather than running the install on your own. Routine project-local dependency installs (e.g. \`npm\`/\`pnpm install\` inside a project, \`pip install\` inside an active virtualenv) are fine — run them as normal.
- Result semantics:
- 'success' indicates whether the tool call itself succeeded.
diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.ts
index 850c05aa0f2..01aa4281126 100644
--- a/packages/builtin-tool-local-system/src/systemRole.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.ts
@@ -67,7 +67,7 @@ You have access to a set of tools to interact with the user's local file system:
- 'command': The shell command to execute.
- 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.
- 'run_in_background' (Optional): Set to true to return immediately after starting the terminal session. The result includes a 'shell_id' for later observation or termination.
- The command runs in cmd.exe on Windows or /bin/sh on macOS/Linux. The returned output reflects the tool's wait window, not necessarily the full command lifetime.
+ The command runs in {{defaultShell}}. When that shell is PowerShell, write PowerShell-compatible syntax; on Windows PowerShell 5.1 the &&/|| chain operators are NOT available — use ';' to sequence commands or 'if ($?) { ... }' for conditional chaining. The returned output reflects the tool's wait window, not necessarily the full command lifetime.
- Installing software: do NOT proactively install software on the user's system. Prefer tools that are already installed, or a no-install alternative. If a task genuinely needs a system-level or global install (e.g. \`brew install\`, \`apt\`/\`dnf install\`, \`npm i -g\`, \`pipx\`, a global \`pip install\`), ask the user first and explain why, rather than running the install on your own. Routine project-local dependency installs (e.g. \`npm\`/\`pnpm install\` inside a project, \`pip install\` inside an active virtualenv) are fine — run them as normal.
- Result semantics:
- 'success' indicates whether the tool call itself succeeded.
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 326a1b63068..fd72ae00281 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -26,6 +26,12 @@ export interface GatewayDevice {
export interface DeviceSystemInfo {
arch: string;
+ /**
+ * Human-readable name of the shell that runCommand uses on this device
+ * (e.g. "PowerShell 7+ (pwsh)"). Optional for protocol compatibility with
+ * older devices that do not report it.
+ */
+ defaultShell?: string;
desktopPath: string;
documentsPath: string;
downloadsPath: string;
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index d6b7bc8ea8f..f8fe9d6e3a9 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -352,6 +352,29 @@ export interface GetCommandOutputResult {
success: boolean;
}
+/**
+ * User preference for the shell that runs agent commands on Windows.
+ * `auto` = pwsh 7 → Windows PowerShell 5.1 → cmd.exe detection chain.
+ */
+export type WindowsShellMode = 'auto' | 'gitbash';
+
+export interface DesktopShellSettings {
+ /** Shell currently used to execute commands (after applying the mode). */
+ currentShell: {
+ displayName: string;
+ path: string;
+ };
+ /** Whether Git for Windows is installed — controls showing the Git Bash option. */
+ gitBashAvailable: boolean;
+ /** Detected Git Bash executable path, when available. */
+ gitBashPath?: string;
+ mode: WindowsShellMode;
+}
+
+export interface SetShellModeParams {
+ mode: WindowsShellMode;
+}
+
export interface KillCommandParams {
shell_id: string;
}
diff --git a/packages/electron-client-ipc/src/types/system.ts b/packages/electron-client-ipc/src/types/system.ts
index d29c07a1d90..6694b59eff9 100644
--- a/packages/electron-client-ipc/src/types/system.ts
+++ b/packages/electron-client-ipc/src/types/system.ts
@@ -1,5 +1,7 @@
export interface ElectronAppState {
arch?: string; // e.g., 'x64', 'arm64'
+ /** Human-readable name of the shell that `runCommand` uses (e.g. "PowerShell 7+ (pwsh)"). */
+ defaultShell?: string;
isLinux?: boolean;
isMac?: boolean;
isWindows?: boolean;
diff --git a/packages/local-file-shell/scripts/verify-windows-shell.ts b/packages/local-file-shell/scripts/verify-windows-shell.ts
new file mode 100644
index 00000000000..bebd9610837
--- /dev/null
+++ b/packages/local-file-shell/scripts/verify-windows-shell.ts
@@ -0,0 +1,286 @@
+/**
+ * Real-Windows verification for the shell execution strategy.
+ *
+ * The unit tests in `__tests__/utils.test.ts` mock `process.platform` and
+ * `fs.promises.lstat`, so they can run anywhere but prove nothing about the
+ * actual Windows behaviour this package exists for. Three things can ONLY be
+ * verified on a real Windows kernel:
+ *
+ * 1. Argument tokenization — Node spawns without a shell, so a plain command
+ * string is re-parsed by the Windows CRT / PowerShell parser, mangling
+ * quotes and backslashes. `-EncodedCommand` is what sidesteps that, and
+ * there is no equivalent code path on POSIX to exercise.
+ * 2. Windows PowerShell 5.1 — only ships with Windows, and notably lacks the
+ * `&&` / `||` chain operators that pwsh 7 has.
+ * 3. The detection cascade — resolving real `System32\WindowsPowerShell\v1.0`
+ * and `Program Files\PowerShell\7` paths instead of mocked ones.
+ *
+ * Deliberately dependency-free (only `node:*` + this package's own `utils.ts`)
+ * so CI can run it with just bun + checkout, skipping a full monorepo install.
+ *
+ * Usage: bun run packages/local-file-shell/scripts/verify-windows-shell.ts
+ */
+import { spawn as spawnChild } from 'node:child_process';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { decodeClixml } from '../src/shell/clixml';
+import {
+ detectWindowsShell,
+ findGitBash,
+ getShellConfig,
+ normalizeEnvVarRefs,
+} from '../src/shell/utils';
+
+if (process.platform !== 'win32') {
+ console.log('⏭ Skipped: this verification only runs on Windows.');
+ process.exit(0);
+}
+
+let failed = 0;
+
+const check = (name: string, ok: boolean, detail: string) => {
+ if (!ok) failed++;
+ console.log(`${ok ? '✅' : '❌'} ${name}`);
+ console.log(` ${detail}`);
+};
+
+const fileExists = async (candidate: string): Promise<boolean> => {
+ try {
+ await fs.lstat(candidate);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+interface SpawnResult {
+ err: string;
+ exit: number;
+ out: string;
+}
+
+// NodeJS.ProcessEnv (not a structural Record) because app tsconfigs augment it
+// with required members; every call site derives its env from process.env, and
+// ProcessEnv is assignable to normalizeEnvVarRefs's structural parameter.
+/** Spawn without a shell, exactly like the production runner does. */
+const spawn = (cmd: string, args: string[], env: NodeJS.ProcessEnv): Promise<SpawnResult> =>
+ new Promise((resolve) => {
+ const child = spawnChild(cmd, args, { env, windowsHide: true });
+ let out = '';
+ let err = '';
+ child.stdout.on('data', (chunk: Buffer) => (out += chunk.toString('utf8')));
+ child.stderr.on('data', (chunk: Buffer) => (err += chunk.toString('utf8')));
+ child.on('error', () => resolve({ err: err.trim(), exit: -1, out: out.trim() }));
+ child.on('close', (code) => resolve({ err: err.trim(), exit: code ?? -1, out: out.trim() }));
+ });
+
+// A path with spaces AND a filename with spaces — the shape that gets torn
+// apart when the command string is re-tokenized.
+const fixtureDir = path.join(os.tmpdir(), 'lobe shell verify');
+const fixtureFile = path.join(fixtureDir, 'hello world.txt');
+await fs.mkdir(fixtureDir, { recursive: true });
+await fs.writeFile(fixtureFile, 'fixture-content');
+
+const env = { ...process.env, TOKEN: 'secret value & echo pwned' };
+
+// --- 1. Detection cascade against the real filesystem -----------------------
+
+const shell = await detectWindowsShell();
+check(
+ 'detects a PowerShell edition (not the cmd fallback)',
+ (shell.type === 'pwsh' || shell.type === 'powershell') && (await fileExists(shell.path)),
+ `type=${shell.type} path=${shell.path}`,
+);
+
+// --- 2. Quoted paths with spaces survive CRT tokenization -------------------
+
+{
+ const { args, cmd } = await getShellConfig(`Get-Content "${fixtureFile}"`);
+ const r = await spawn(cmd, args, env);
+ check(
+ 'quoted path with spaces survives argument tokenization',
+ r.exit === 0 && r.out === 'fixture-content',
+ `exit=${r.exit} out=${JSON.stringify(r.out)} ${r.err ? `err=${r.err}` : ''}`,
+ );
+}
+
+// --- 3. Native exit codes propagate instead of collapsing to 1 --------------
+
+{
+ const { args, cmd } = await getShellConfig('cmd /c exit 42');
+ const r = await spawn(cmd, args, env);
+ check('native exit code 42 propagates', r.exit === 42, `exit=${r.exit} (want 42)`);
+}
+
+{
+ const { args, cmd } = await getShellConfig('Get-ChildItem C:\\definitely-missing-path');
+ const r = await spawn(cmd, args, env);
+ check('trailing cmdlet failure exits 1', r.exit === 1, `exit=${r.exit} (want 1)`);
+}
+
+{
+ // An intentionally-ignored earlier failure must not leak into the exit code.
+ const { args, cmd } = await getShellConfig('cmd /c exit 7; Write-Output done');
+ const r = await spawn(cmd, args, env);
+ check(
+ 'stale $LASTEXITCODE does not override a successful final statement',
+ r.exit === 0 && r.out === 'done',
+ `exit=${r.exit} out=${JSON.stringify(r.out)}`,
+ );
+}
+
+// --- 4. Env-var rewriting against real Windows variables --------------------
+
+{
+ // %ProgramFiles(x86)% is a genuine Windows variable whose name contains
+ // parentheses and whose value contains spaces — the exact case that breaks
+ // when a value is inlined instead of rewritten to ${env:VAR}.
+ // Read from process.env directly: spreading it (as `env` does) drops the
+ // ProcessEnv index signature, so a computed key stops type-checking.
+ const expected = process.env['ProgramFiles(x86)'];
+ const command = normalizeEnvVarRefs('Get-Item %ProgramFiles(x86)% | % FullName', env, shell.type);
+ const { args, cmd } = await getShellConfig(command);
+ const r = await spawn(cmd, args, env);
+ check(
+ '%ProgramFiles(x86)% rewrites to a single token',
+ r.exit === 0 && !!expected && r.out === expected,
+ `rewritten=${command.split('\n')[0]} exit=${r.exit} out=${JSON.stringify(r.out)} want=${JSON.stringify(expected)}`,
+ );
+}
+
+{
+ // The secret must reach the child through the environment, never inlined
+ // into the command line where `&` would be interpreted.
+ const { args, cmd } = await getShellConfig('Write-Output "[$env:TOKEN]"');
+ const encoded = args.at(-1) ?? '';
+ const inlined = Buffer.from(encoded, 'base64').toString('utf16le').includes('echo pwned');
+ const r = await spawn(cmd, args, env);
+ check(
+ 'secret is passed via env, never inlined into the command line',
+ !inlined && r.exit === 0 && r.out === '[secret value & echo pwned]',
+ `inlined=${inlined} exit=${r.exit} out=${JSON.stringify(r.out)}`,
+ );
+}
+
+// --- 5. Windows PowerShell 5.1 specifically ---------------------------------
+
+const ps51 = path.join(
+ process.env.SystemRoot || 'C:\\Windows',
+ 'System32',
+ 'WindowsPowerShell',
+ 'v1.0',
+ 'powershell.exe',
+);
+
+if (await fileExists(ps51)) {
+ // getShellConfig emits identical args for both editions, so the same encoded
+ // payload can be replayed against 5.1 to prove it is compatible.
+ const { args } = await getShellConfig(`Get-Content "${fixtureFile}"; Write-Output ok`);
+ const r = await spawn(ps51, args, env);
+ check(
+ 'Windows PowerShell 5.1 runs the same encoded payload',
+ r.exit === 0 && r.out.includes('fixture-content') && r.out.includes('ok'),
+ `exit=${r.exit} out=${JSON.stringify(r.out)}`,
+ );
+
+ // Guards the systemRole prompt's claim that 5.1 has no && operator. If a
+ // future Windows update adds it, the prompt wording should be revisited.
+ const chain = await getShellConfig('Write-Output a && Write-Output b');
+ const rChain = await spawn(ps51, chain.args, env);
+ check(
+ "5.1 rejects '&&' (the prompt tells the model to use ';' instead)",
+ rChain.exit !== 0,
+ `exit=${rChain.exit} — nonzero confirms && is unsupported`,
+ );
+} else {
+ check('Windows PowerShell 5.1 is present', false, `not found at ${ps51}`);
+}
+
+// --- 6. cmd.exe fallback ----------------------------------------------------
+
+{
+ // The cmd branch rewrites PowerShell/bash syntax to %VAR% so the value is
+ // resolved by the shell instead of being pasted into the command line.
+ const command = normalizeEnvVarRefs('echo [$env:TOKEN]', env, 'cmd');
+ check(
+ 'cmd fallback rewrites $env:VAR to %VAR% without inlining the secret',
+ command === 'echo [%TOKEN%]',
+ `rewritten=${command}`,
+ );
+
+ // NB: no assertion on the resolved output for TOKEN. cmd expands %VAR%
+ // *before* parsing the line, so a value containing `&` still splits the
+ // command — an inherent cmd limitation that rewriting cannot fix, and one
+ // reason cmd is only the last-resort fallback. What rewriting does buy is
+ // keeping the secret out of argv (and thus out of process listings). Probe
+ // actual expansion with a metacharacter-free value instead.
+ const safeEnv = { ...env, LOBE_VERIFY_VALUE: 'plain-value' };
+ const safe = normalizeEnvVarRefs('echo [$env:LOBE_VERIFY_VALUE]', safeEnv, 'cmd');
+ const r = await spawn('cmd.exe', ['/c', safe], safeEnv);
+ check(
+ 'cmd resolves the rewritten %VAR% at runtime',
+ safe === 'echo [%LOBE_VERIFY_VALUE%]' && r.out === '[plain-value]',
+ `rewritten=${safe} out=${JSON.stringify(r.out)}`,
+ );
+}
+
+// --- 7. Non-ASCII output survives the OEM console code page -----------------
+
+{
+ // Without the UTF-8 encoding preamble, redirected output on a localized (or
+ // CP437 CI) console writes CJK text in the OEM code page while the runner
+ // reads UTF-8 — mojibake. Round-trip a CJK string through Write-Host (host
+ // stream) and Write-Output (success stream) to prove both paths survive.
+ const { args, cmd } = await getShellConfig('Write-Host "中文测试"; Write-Output "中文输出"');
+ const r = await spawn(cmd, args, env);
+ check(
+ 'CJK text survives redirected output (UTF-8 preamble)',
+ r.exit === 0 && `${r.out}\n${r.err}`.includes('中文') && r.out.includes('中文输出'),
+ `exit=${r.exit} out=${JSON.stringify(r.out)} err=${JSON.stringify(r.err)}`,
+ );
+}
+
+// --- 8. CLIXML on redirected stderr decodes to readable text ----------------
+
+{
+ // When stderr is redirected, PowerShell serializes non-stdout streams as
+ // CLIXML. decodeClixml (applied by the process manager before returning
+ // output) must recover the human-readable message.
+ const { args, cmd } = await getShellConfig('Write-Error "clixml-probe"; Write-Output done');
+ const r = await spawn(cmd, args, env);
+ const decoded = decodeClixml(r.err);
+ check(
+ 'CLIXML stderr decodes back to the original message',
+ r.err.length === 0 || (decoded.includes('clixml-probe') && !decoded.includes('<Objs')),
+ `rawErr=${JSON.stringify(r.err.slice(0, 120))} decoded=${JSON.stringify(decoded.slice(0, 120))}`,
+ );
+}
+
+// --- 9. Git Bash env-var rewriting survives MSYS2 name upper-casing ---------
+
+{
+ // MSYS2 imports some Windows variables with upper-cased names (ProgramFiles
+ // → PROGRAMFILES inside bash), so the rewritten reference must resolve
+ // regardless of which spelling bash ends up with. Only runnable when Git
+ // Bash is actually installed (it is on GitHub windows runners).
+ const gitBash = await findGitBash();
+ if (gitBash) {
+ const expected = process.env.ProgramFiles;
+ const command = normalizeEnvVarRefs('echo "%ProgramFiles%"', env, 'gitbash');
+ const r = await spawn(gitBash, ['-c', command], env);
+ check(
+ 'Git Bash resolves rewritten %ProgramFiles% despite MSYS2 upper-casing',
+ r.exit === 0 && !!expected && r.out === expected,
+ `rewritten=${command} exit=${r.exit} out=${JSON.stringify(r.out)} want=${JSON.stringify(expected)}`,
+ );
+ } else {
+ console.log('⏭ Git Bash not installed — skipping MSYS2 env-var check.');
+ }
+}
+
+await fs.rm(fixtureDir, { force: true, recursive: true });
+
+console.log(`\n${failed === 0 ? 'All checks passed' : `${failed} check(s) failed`}`);
+process.exit(failed === 0 ? 0 : 1);
diff --git a/packages/local-file-shell/src/shell/__tests__/clixml.test.ts b/packages/local-file-shell/src/shell/__tests__/clixml.test.ts
new file mode 100644
index 00000000000..572761a7c6b
--- /dev/null
+++ b/packages/local-file-shell/src/shell/__tests__/clixml.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+
+import { decodeClixml } from '../clixml';
+
+/** PS 5.1-style error stream serialization. */
+const ERROR_BLOCK =
+ '#< CLIXML\n' +
+ '<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">' +
+ '<S S="Error">boom : command failed_x000D__x000A_</S>' +
+ '<S S="Error"> + CategoryInfo : NotSpecified_x000D__x000A_</S>' +
+ '</Objs>';
+
+/** pwsh 7 Write-Host → InformationRecord serialization (no stream-typed <S>). */
+const INFORMATION_BLOCK =
+ '#< CLIXML\n' +
+ '<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">' +
+ '<Obj S="information" RefId="0"><TN RefId="0">' +
+ '<T>System.Management.Automation.InformationRecord</T><T>System.Object</T></TN>' +
+ '<ToString>=== 1. CMD: C:\\Users\\jalen ===</ToString>' +
+ '<Props><Obj N="MessageData" RefId="1"><TN RefId="1">' +
+ '<T>System.Management.Automation.HostInformationMessage</T><T>System.Object</T></TN>' +
+ '<ToString>=== 1. CMD: C:\\Users\\jalen ===</ToString>' +
+ '<Props><S N="Message">=== 1. CMD: C:\\Users\\jalen ===</S>' +
+ '<B N="NoNewLine">false</B></Props></Obj></Props></Obj>' +
+ '</Objs>';
+
+describe('decodeClixml', () => {
+ it('should return text without a CLIXML marker unchanged', () => {
+ expect(decodeClixml('plain stderr output')).toBe('plain stderr output');
+ });
+
+ it('should decode error-stream entries and unescape control characters', () => {
+ const decoded = decodeClixml(ERROR_BLOCK);
+
+ expect(decoded).toContain('boom : command failed\r\n');
+ expect(decoded).toContain('+ CategoryInfo : NotSpecified\r\n');
+ expect(decoded).not.toContain('CLIXML');
+ expect(decoded).not.toContain('<Objs');
+ });
+
+ it('should decode Write-Host information records via ToString and collapse duplicates', () => {
+ const decoded = decodeClixml(INFORMATION_BLOCK);
+
+ expect(decoded).toBe('=== 1. CMD: C:\\Users\\jalen ===\n');
+ });
+
+ it('should preserve plain text around CLIXML blocks', () => {
+ const decoded = decodeClixml(`before\n${ERROR_BLOCK}after`);
+
+ expect(decoded.startsWith('before\n')).toBe(true);
+ expect(decoded.endsWith('after')).toBe(true);
+ expect(decoded).toContain('boom : command failed');
+ });
+
+ it('should decode a truncated block without the closing tag', () => {
+ const truncated = ERROR_BLOCK.slice(0, ERROR_BLOCK.indexOf('</Objs>'));
+ const decoded = decodeClixml(truncated);
+
+ expect(decoded).toContain('boom : command failed');
+ expect(decoded).not.toContain('<Objs');
+ });
+
+ it('should unescape XML entities', () => {
+ const block =
+ '#< CLIXML\n<Objs Version="1.1.0.1"><S S="Error">a &lt; b &amp;&amp; c &gt; d</S></Objs>';
+
+ expect(decodeClixml(block)).toBe('a < b && c > d\n');
+ });
+});
diff --git a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts b/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts
index 6b00c79bf6c..bb1d8c2f0a8 100644
--- a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts
+++ b/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts
@@ -355,15 +355,22 @@ describe('ShellProcessManager', () => {
expect(result.error).toContain('not found');
});
- it('should remove process from registry after killing', async () => {
+ it('should keep the output retrievable after killing', async () => {
const process = createMockProcess();
- manager.register('test-1', createShellProcess(manager, 'test-1', process));
+ const shellProcess = createShellProcess(manager, 'test-1', process);
+ manager.register('test-1', shellProcess);
+ writeOutput(shellProcess, 'partial output before kill');
manager.kill('test-1');
+ // Simulate the tree kill terminating the child via signal (POSIX shape:
+ // no exit code) — getOutput must not wait for the observation timeout.
+ Object.defineProperty(process, 'signalCode', { configurable: true, value: 'SIGKILL' });
+ process.emit('exit', null, 'SIGKILL');
+ process.emit('close', null, 'SIGKILL');
- const result = await manager.getOutput({ shell_id: 'test-1' });
- expect(result.success).toBe(false);
- expect(result.error).toContain('not found');
+ const result = await manager.getOutput({ shell_id: 'test-1', timeout: 5000 });
+ expect(result.success).toBe(true);
+ expect(result.stdout).toBe('partial output before kill');
});
it('should handle kill error gracefully', () => {
diff --git a/packages/local-file-shell/src/shell/__tests__/runner.spawn-options.test.ts b/packages/local-file-shell/src/shell/__tests__/runner.spawn-options.test.ts
new file mode 100644
index 00000000000..37dc7489837
--- /dev/null
+++ b/packages/local-file-shell/src/shell/__tests__/runner.spawn-options.test.ts
@@ -0,0 +1,41 @@
+import type * as ChildProcess from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ShellProcessManager } from '../process-manager';
+import { runCommand } from '../runner';
+
+const spawnSpy = vi.hoisted(() => vi.fn());
+
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<typeof ChildProcess>();
+ spawnSpy.mockImplementation(actual.spawn);
+ return { ...actual, spawn: spawnSpy };
+});
+
+describe('runCommand spawn options', () => {
+ let processManager: ShellProcessManager;
+ let tmpDir: string;
+
+ beforeEach(() => {
+ spawnSpy.mockClear();
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lobehub-shell-spawn-options-'));
+ processManager = new ShellProcessManager(tmpDir);
+ });
+
+ afterEach(() => {
+ processManager.cleanupAll();
+ fs.rmSync(tmpDir, { force: true, recursive: true });
+ });
+
+ it('should hide the console window spawned for the shell on Windows', async () => {
+ const result = await runCommand({ command: 'echo hidden' }, { processManager });
+
+ expect(result.success).toBe(true);
+ expect(spawnSpy).toHaveBeenCalledTimes(1);
+ expect(spawnSpy.mock.calls[0][2]).toMatchObject({ windowsHide: true });
+ });
+});
diff --git a/packages/local-file-shell/src/shell/__tests__/utils.test.ts b/packages/local-file-shell/src/shell/__tests__/utils.test.ts
index 39b42998edc..ba32274625b 100644
--- a/packages/local-file-shell/src/shell/__tests__/utils.test.ts
+++ b/packages/local-file-shell/src/shell/__tests__/utils.test.ts
@@ -1,17 +1,491 @@
-import { describe, expect, it } from 'vitest';
+import fs from 'node:fs';
+import path from 'node:path';
-import { getShellConfig } from '../utils';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ findGitBash,
+ getShellConfig,
+ normalizeEnvVarRefs,
+ resetShellDetectionCache,
+ setWindowsShellPreference,
+} from '../utils';
+
+/** Restore process.platform to its real value after tampering in a test. */
+const realPlatform = process.platform;
+
+const setPlatform = (platform: NodeJS.Platform) => {
+ Object.defineProperty(process, 'platform', { configurable: true, value: platform });
+};
+
+const restorePlatform = () => {
+ Object.defineProperty(process, 'platform', { configurable: true, value: realPlatform });
+};
+
+/**
+ * Mock the async lstat probe used by executableExists so that only the given
+ * paths are reported as existing.
+ */
+const mockExisting = (...existing: string[]) =>
+ vi.spyOn(fs.promises, 'lstat').mockImplementation(async (p) => {
+ if (existing.includes(p.toString())) return {} as fs.Stats;
+ throw new Error('ENOENT');
+ });
+
+/** Decode an -EncodedCommand base64 (UTF-16LE) argument back to the original string. */
+const decodeEncodedCommand = (encoded: string): string =>
+ Buffer.from(encoded, 'base64').toString('utf16le');
+
+/**
+ * Guard appended to every PowerShell script so the final statement decides the
+ * exit code (`sh -c` / `cmd /c` convention): failing native commands propagate
+ * their real exit code instead of collapsing to 1, trailing cmdlet failures
+ * exit 1, and a stale $LASTEXITCODE never overrides a successful final
+ * statement (see getShellConfig).
+ */
+/** UTF-8 console setup prepended to every PowerShell script (see getShellConfig). */
+const ENCODING_PREAMBLE =
+ 'try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}' +
+ '\n$OutputEncoding = [System.Text.Encoding]::UTF8\n';
+
+const EXIT_CODE_GUARD =
+ '\n$__lobeExecOk = $?' +
+ '\nif (-not $__lobeExecOk) {' +
+ '\n if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }' +
+ '\n exit 1' +
+ '\n}';
describe('getShellConfig', () => {
- it('should return shell config for current platform', () => {
- const config = getShellConfig('echo hello');
+ const originalEnv = { ...process.env };
+
+ afterEach(() => {
+ restorePlatform();
+ resetShellDetectionCache();
+ vi.restoreAllMocks();
+ process.env = { ...originalEnv };
+ });
+
+ it('should return shell config for the current platform (regression)', async () => {
+ const config = await getShellConfig('echo hello');
if (process.platform === 'win32') {
- expect(config.cmd).toBe('cmd.exe');
- expect(config.args).toEqual(['/c', 'echo hello']);
+ // Actual assertions for win32 are covered by the dedicated cases below.
+ expect(config.cmd).toBeTruthy();
} else {
expect(config.cmd).toBe('/bin/sh');
expect(config.args).toEqual(['-c', 'echo hello']);
}
});
+
+ it('should keep /bin/sh -c behavior on darwin', async () => {
+ setPlatform('darwin');
+ const config = await getShellConfig('echo hello');
+ expect(config.cmd).toBe('/bin/sh');
+ expect(config.args).toEqual(['-c', 'echo hello']);
+ });
+
+ it('should keep /bin/sh -c behavior on linux', async () => {
+ setPlatform('linux');
+ const config = await getShellConfig('ls -la');
+ expect(config.cmd).toBe('/bin/sh');
+ expect(config.args).toEqual(['-c', 'ls -la']);
+ });
+
+ it('should use pwsh with -EncodedCommand when pwsh.exe is on PATH', async () => {
+ setPlatform('win32');
+ // NB: use a delimiter-safe fake dir. On the CI/dev host the default `path`
+ // module is POSIX, so PATH is split on ':'; a real 'C:\\...' entry would be
+ // torn apart. This still exercises the PATH-scan + join + encode logic.
+ const pwshDir = '/fake/tools/pwsh';
+ const pwshPath = path.join(pwshDir, 'pwsh.exe');
+ process.env.PATH = pwshDir;
+ mockExisting(pwshPath);
+
+ const config = await getShellConfig('Get-ChildItem "C:\\Program Files"');
+
+ expect(config.cmd).toBe(pwshPath);
+ expect(config.args.slice(0, 3)).toEqual(['-NoProfile', '-NonInteractive', '-EncodedCommand']);
+ expect(decodeEncodedCommand(config.args[3])).toBe(
+ `${ENCODING_PREAMBLE}Get-ChildItem "C:\\Program Files"${EXIT_CODE_GUARD}`,
+ );
+ });
+
+ it('should fall back to Windows PowerShell 5.1 when only powershell.exe exists', async () => {
+ setPlatform('win32');
+ process.env.PATH = 'C:\\Tools';
+ process.env.SystemRoot = 'C:\\Windows';
+ const powershellPath = path.join(
+ 'C:\\Windows',
+ 'System32',
+ 'WindowsPowerShell',
+ 'v1.0',
+ 'powershell.exe',
+ );
+ mockExisting(powershellPath);
+
+ const config = await getShellConfig('echo hi');
+
+ expect(config.cmd).toBe(powershellPath);
+ expect(config.args.slice(0, 3)).toEqual(['-NoProfile', '-NonInteractive', '-EncodedCommand']);
+ expect(decodeEncodedCommand(config.args[3])).toBe(
+ `${ENCODING_PREAMBLE}echo hi${EXIT_CODE_GUARD}`,
+ );
+ });
+
+ it('should fall back to cmd.exe /c when neither PowerShell edition exists', async () => {
+ setPlatform('win32');
+ process.env.PATH = 'C:\\Tools';
+ mockExisting();
+
+ const config = await getShellConfig('dir');
+
+ expect(config.cmd).toBe('cmd.exe');
+ expect(config.args).toEqual(['/c', 'dir']);
+ });
+
+ it('should cache the detection result across calls', async () => {
+ setPlatform('win32');
+ const pwshDir = '/fake/tools/pwsh';
+ const pwshPath = path.join(pwshDir, 'pwsh.exe');
+ process.env.PATH = pwshDir;
+ const lstatSpy = mockExisting(pwshPath);
+
+ await getShellConfig('echo one');
+ const callsAfterFirst = lstatSpy.mock.calls.length;
+ await getShellConfig('echo two');
+
+ expect(callsAfterFirst).toBeGreaterThan(0);
+ // Second call must not touch the filesystem again.
+ expect(lstatSpy.mock.calls.length).toBe(callsAfterFirst);
+ });
+
+ it('should share a single detection run between concurrent first calls', async () => {
+ setPlatform('win32');
+ const pwshDir = '/fake/tools/pwsh';
+ const pwshPath = path.join(pwshDir, 'pwsh.exe');
+ process.env.PATH = pwshDir;
+ const lstatSpy = mockExisting(pwshPath);
+
+ // Both calls start before either resolves — the promise cache must
+ // deduplicate them into one filesystem scan.
+ const [first, second] = await Promise.all([
+ getShellConfig('echo one'),
+ getShellConfig('echo two'),
+ ]);
+ const callsAfterBoth = lstatSpy.mock.calls.length;
+
+ expect(first.cmd).toBe(pwshPath);
+ expect(second.cmd).toBe(pwshPath);
+ await getShellConfig('echo three');
+ expect(lstatSpy.mock.calls.length).toBe(callsAfterBoth);
+ });
+
+ it('should find pwsh at the default install path when not on PATH', async () => {
+ setPlatform('win32');
+ process.env.PATH = 'C:\\Tools';
+ process.env.ProgramFiles = 'C:\\Program Files';
+ const defaultPwsh = path.join('C:\\Program Files', 'PowerShell', '7', 'pwsh.exe');
+ mockExisting(defaultPwsh);
+
+ const config = await getShellConfig('echo hi');
+
+ expect(config.cmd).toBe(defaultPwsh);
+ });
+
+ it('should find MS Store pwsh via its app-execution alias', async () => {
+ setPlatform('win32');
+ process.env.PATH = 'C:\\Tools';
+ process.env.LOCALAPPDATA = 'C:\\Users\\tester\\AppData\\Local';
+ // App-execution aliases are zero-byte reparse points, which is why the
+ // existence probe uses lstat (stat may fail to resolve the target).
+ const aliasPwsh = path.join(
+ 'C:\\Users\\tester\\AppData\\Local',
+ 'Microsoft',
+ 'WindowsApps',
+ 'pwsh.exe',
+ );
+ mockExisting(aliasPwsh);
+
+ const config = await getShellConfig('echo hi');
+
+ expect(config.cmd).toBe(aliasPwsh);
+ });
+});
+
+describe('normalizeEnvVarRefs', () => {
+ const env: Record<string, string | undefined> = {
+ 'HOME': '/home/tester',
+ 'PATH': 'C:\\Windows\\System32',
+ 'ProgramFiles(x86)': 'C:\\Program Files (x86)',
+ 'TOKEN': 'secret value & echo pwned',
+ 'USERPROFILE': 'C:\\Users\\tester',
+ };
+
+ describe('PowerShell target (pwsh / powershell)', () => {
+ it('should rewrite cmd style %VAR% to ${env:VAR} (PowerShell cannot resolve %VAR%)', () => {
+ expect(normalizeEnvVarRefs('echo %USERPROFILE%', env, 'pwsh')).toBe(
+ 'echo ${env:USERPROFILE}',
+ );
+ expect(normalizeEnvVarRefs('echo %USERPROFILE%', env, 'powershell')).toBe(
+ 'echo ${env:USERPROFILE}',
+ );
+ });
+
+ it('should rewrite names containing parentheses like %ProgramFiles(x86)%', () => {
+ // Rewriting (not pasting the raw value) matters here: the value contains
+ // spaces and would be split into multiple arguments by PowerShell.
+ expect(normalizeEnvVarRefs('cd %ProgramFiles(x86)%', env, 'pwsh')).toBe(
+ 'cd ${env:ProgramFiles(x86)}',
+ );
+ });
+
+ it('should match %VAR% names case-insensitively', () => {
+ expect(normalizeEnvVarRefs('echo %userprofile%', env, 'pwsh')).toBe(
+ 'echo ${env:userprofile}',
+ );
+ });
+
+ it('should leave unknown %VAR% untouched', () => {
+ expect(normalizeEnvVarRefs('echo %NOPE%', env, 'pwsh')).toBe('echo %NOPE%');
+ });
+
+ it('should leave native $env:VAR untouched (PowerShell resolves it itself)', () => {
+ expect(normalizeEnvVarRefs('echo $env:USERPROFILE', env, 'pwsh')).toBe(
+ 'echo $env:USERPROFILE',
+ );
+ });
+
+ it('should not corrupt $env:VAR assignments', () => {
+ const command = "$env:HTTP_PROXY='http://127.0.0.1:7890'; node app.js";
+ expect(normalizeEnvVarRefs(command, env, 'pwsh')).toBe(command);
+ });
+
+ it('should not corrupt PowerShell script variables colliding with env names', () => {
+ // `$path` is a legitimate PowerShell local variable; it must not be
+ // rewritten just because the PATH env var exists.
+ const command = 'foreach ($path in Get-ChildItem) { Write-Output $path }';
+ expect(normalizeEnvVarRefs(command, env, 'pwsh')).toBe(command);
+ });
+ });
+
+ describe('cmd target (fallback)', () => {
+ it('should leave %VAR% untouched (cmd resolves it natively)', () => {
+ expect(normalizeEnvVarRefs('echo %USERPROFILE%', env, 'cmd')).toBe('echo %USERPROFILE%');
+ });
+
+ it('should rewrite PowerShell style $env:VAR to %VAR%', () => {
+ expect(normalizeEnvVarRefs('echo $env:USERPROFILE', env, 'cmd')).toBe('echo %USERPROFILE%');
+ });
+
+ it('should rewrite bash style $VAR and ${VAR} to %VAR%', () => {
+ expect(normalizeEnvVarRefs('echo $HOME', env, 'cmd')).toBe('echo %HOME%');
+ expect(normalizeEnvVarRefs('echo ${HOME}/sub', env, 'cmd')).toBe('echo %HOME%/sub');
+ });
+
+ it('should never inline values (secrets with cmd metacharacters stay as references)', () => {
+ // Inlining the raw value would inject `& echo pwned` into the command line.
+ expect(normalizeEnvVarRefs('deploy --token $env:TOKEN', env, 'cmd')).toBe(
+ 'deploy --token %TOKEN%',
+ );
+ });
+
+ it('should leave unknown variables untouched', () => {
+ expect(normalizeEnvVarRefs('$env:NOPE $NOPE ${NOPE}', env, 'cmd')).toBe(
+ '$env:NOPE $NOPE ${NOPE}',
+ );
+ });
+
+ it('should match variable names case-insensitively', () => {
+ expect(normalizeEnvVarRefs('echo $env:UserProfile', env, 'cmd')).toBe('echo %UserProfile%');
+ });
+
+ it('should not mistake $env:VAR for a bash $env variable', () => {
+ // $env:USERPROFILE must become %USERPROFILE%, not "$env" + ":USERPROFILE".
+ expect(normalizeEnvVarRefs('$env:USERPROFILE', env, 'cmd')).toBe('%USERPROFILE%');
+ });
+
+ it('should rewrite a mixed command string', () => {
+ const command = 'copy $env:USERPROFILE\\a ${HOME}/b $HOME/c';
+ expect(normalizeEnvVarRefs(command, env, 'cmd')).toBe(
+ 'copy %USERPROFILE%\\a %HOME%/b %HOME%/c',
+ );
+ });
+ });
+});
+
+describe('Git Bash preference', () => {
+ const originalEnv = { ...process.env };
+ const gitBashPath = path.join('C:\\Program Files', 'Git', 'bin', 'bash.exe');
+
+ afterEach(() => {
+ restorePlatform();
+ setWindowsShellPreference('auto');
+ resetShellDetectionCache();
+ vi.restoreAllMocks();
+ process.env = { ...originalEnv };
+ });
+
+ it('should use bash -c when the user selected Git Bash and it is installed', async () => {
+ setPlatform('win32');
+ process.env.ProgramFiles = 'C:\\Program Files';
+ mockExisting(gitBashPath);
+ setWindowsShellPreference('gitbash');
+
+ const config = await getShellConfig('echo "hello world"');
+
+ expect(config.cmd).toBe(gitBashPath);
+ expect(config.args).toEqual(['-c', 'echo "hello world"']);
+ });
+
+ it('should fall back to the automatic chain when Git Bash is selected but missing', async () => {
+ setPlatform('win32');
+ const pwshDir = '/fake/tools/pwsh';
+ const pwshPath = path.join(pwshDir, 'pwsh.exe');
+ process.env.PATH = pwshDir;
+ mockExisting(pwshPath);
+ setWindowsShellPreference('gitbash');
+
+ const config = await getShellConfig('echo hi');
+
+ expect(config.cmd).toBe(pwshPath);
+ });
+
+ it('should skip System32 bash.exe (WSL launcher) during PATH scan', async () => {
+ setPlatform('win32');
+ const system32Bash = path.join('C:\\Windows\\System32', 'bash.exe');
+ process.env.PATH = 'C:\\Windows\\System32';
+ delete process.env.ProgramFiles;
+ delete process.env['ProgramFiles(x86)'];
+ delete process.env.LOCALAPPDATA;
+ mockExisting(system32Bash);
+
+ await expect(findGitBash()).resolves.toBeUndefined();
+ });
+
+ it('should re-run detection after the preference changes', async () => {
+ setPlatform('win32');
+ const pwshDir = '/fake/tools/pwsh';
+ const pwshPath = path.join(pwshDir, 'pwsh.exe');
+ process.env.PATH = pwshDir;
+ process.env.ProgramFiles = 'C:\\Program Files';
+ mockExisting(pwshPath, gitBashPath);
+
+ expect((await getShellConfig('echo one')).cmd).toBe(pwshPath);
+ setWindowsShellPreference('gitbash');
+ expect((await getShellConfig('echo two')).cmd).toBe(gitBashPath);
+ });
+});
+
+describe('normalizeEnvVarRefs (gitbash target)', () => {
+ const env: Record<string, string | undefined> = {
+ 'HOME': '/home/tester',
+ 'ProgramFiles(x86)': 'C:\\Program Files (x86)',
+ 'USERPROFILE': 'C:\\Users\\tester',
+ };
+
+ it('should rewrite cmd style %VAR% to ${VAR}', () => {
+ expect(normalizeEnvVarRefs('cd %USERPROFILE%', env, 'gitbash')).toBe('cd ${USERPROFILE}');
+ });
+
+ it('should rewrite to the canonical env key spelling (bash is case-sensitive)', () => {
+ expect(normalizeEnvVarRefs('cd %userprofile%', env, 'gitbash')).toBe('cd ${USERPROFILE}');
+ expect(normalizeEnvVarRefs('echo $env:home', env, 'gitbash')).toBe('echo ${HOME}');
+ });
+
+ it('should rewrite PowerShell style $env:VAR to ${VAR}', () => {
+ expect(normalizeEnvVarRefs('echo $env:USERPROFILE', env, 'gitbash')).toBe(
+ 'echo ${USERPROFILE}',
+ );
+ });
+
+ it('should leave bash-native $VAR and ${VAR} untouched', () => {
+ expect(normalizeEnvVarRefs('echo $HOME ${HOME}', env, 'gitbash')).toBe('echo $HOME ${HOME}');
+ });
+
+ it('should emit an upper-case fallback for mixed-case names (MSYS2 upper-cases some vars)', () => {
+ const mixedEnv = { ...env, ProgramFiles: 'C:\\Program Files' };
+ // Inside Git Bash the variable is spelled PROGRAMFILES (MSYS2 upper-cases
+ // it on import), so a plain ${ProgramFiles} would expand to empty.
+ expect(normalizeEnvVarRefs('ls "%ProgramFiles%"', mixedEnv, 'gitbash')).toBe(
+ 'ls "${ProgramFiles:-${PROGRAMFILES}}"',
+ );
+ expect(normalizeEnvVarRefs('echo $env:programfiles', mixedEnv, 'gitbash')).toBe(
+ 'echo ${ProgramFiles:-${PROGRAMFILES}}',
+ );
+ });
+
+ it('should leave names containing parentheses untouched (invalid bash identifiers)', () => {
+ expect(normalizeEnvVarRefs('dir "%ProgramFiles(x86)%"', env, 'gitbash')).toBe(
+ 'dir "%ProgramFiles(x86)%"',
+ );
+ });
+
+ it('should leave unknown variables untouched', () => {
+ expect(normalizeEnvVarRefs('echo %NOPE% $env:NOPE', env, 'gitbash')).toBe(
+ 'echo %NOPE% $env:NOPE',
+ );
+ });
+});
+
+describe('findGitBash package-manager installs', () => {
+ const originalEnv = { ...process.env };
+
+ afterEach(() => {
+ restorePlatform();
+ resetShellDetectionCache();
+ vi.restoreAllMocks();
+ process.env = { ...originalEnv };
+ });
+
+ it('should find bash under the default scoop root', async () => {
+ setPlatform('win32');
+ delete process.env.ProgramFiles;
+ delete process.env['ProgramFiles(x86)'];
+ delete process.env.LOCALAPPDATA;
+ delete process.env.SCOOP;
+ process.env.USERPROFILE = '/fake/home';
+ process.env.PATH = '';
+ const scoopBash = path.resolve(
+ '/fake/home',
+ 'scoop',
+ 'apps',
+ 'git',
+ 'current',
+ 'bin',
+ 'bash.exe',
+ );
+ mockExisting(scoopBash);
+
+ await expect(findGitBash()).resolves.toBe(scoopBash);
+ });
+
+ it('should honor a custom SCOOP root', async () => {
+ setPlatform('win32');
+ delete process.env.ProgramFiles;
+ delete process.env['ProgramFiles(x86)'];
+ delete process.env.LOCALAPPDATA;
+ delete process.env.USERPROFILE;
+ process.env.SCOOP = '/fake/scoop-root';
+ process.env.PATH = '';
+ const scoopBash = path.resolve('/fake/scoop-root', 'apps', 'git', 'current', 'bin', 'bash.exe');
+ mockExisting(scoopBash);
+
+ await expect(findGitBash()).resolves.toBe(scoopBash);
+ });
+
+ it('should derive bash from git.exe on PATH when bash itself is not shimmed', async () => {
+ setPlatform('win32');
+ delete process.env.ProgramFiles;
+ delete process.env['ProgramFiles(x86)'];
+ delete process.env.LOCALAPPDATA;
+ delete process.env.SCOOP;
+ delete process.env.USERPROFILE;
+ const gitCmdDir = '/fake/custom-git/cmd';
+ process.env.PATH = gitCmdDir;
+ const gitExe = path.join(gitCmdDir, 'git.exe');
+ const siblingBash = path.resolve(gitCmdDir, '..', 'bin', 'bash.exe');
+ mockExisting(gitExe, siblingBash);
+
+ await expect(findGitBash()).resolves.toBe(siblingBash);
+ });
});
diff --git a/packages/local-file-shell/src/shell/clixml.ts b/packages/local-file-shell/src/shell/clixml.ts
new file mode 100644
index 00000000000..3d0c2a6ebaf
--- /dev/null
+++ b/packages/local-file-shell/src/shell/clixml.ts
@@ -0,0 +1,87 @@
+/**
+ * Decode PowerShell CLIXML blocks embedded in redirected stderr.
+ *
+ * When powershell.exe / pwsh.exe runs with redirected stderr, records from its
+ * non-stdout streams (error, warning, verbose, information / Write-Host) are
+ * serialized to stderr as CLIXML: `#< CLIXML\n<Objs ...>...</Objs>`. Shown
+ * verbatim this is unreadable noise for the model and the user, so we extract
+ * the human-readable messages and replace each block in place — the same
+ * approach Ansible's `_parse_clixml` takes.
+ */
+
+const CLIXML_MARKER = '#< CLIXML';
+
+/** CLIXML escapes characters as `_xHHHH_` (UTF-16 code units). */
+const unescapeClixmlText = (text: string): string =>
+ text
+ .replaceAll(/_x([\dA-Fa-f]{4})_/g, (_, hex: string) =>
+ String.fromCharCode(Number.parseInt(hex, 16)),
+ )
+ .replaceAll('&lt;', '<')
+ .replaceAll('&gt;', '>')
+ .replaceAll('&quot;', '"')
+ .replaceAll('&apos;', "'")
+ .replaceAll('&amp;', '&');
+
+/** Stream-typed string records: `<S S="Error">text</S>` (PS 5.1 style). */
+const STREAM_ENTRY = /<S S="(?:Error|Warning|Verbose|Debug|Info)">([\S\s]*?)<\/S>/g;
+
+/**
+ * Rendered text of serialized records (`InformationRecord` / `HostInformationMessage`
+ * from Write-Host end up here). Nested objects repeat the same message in their
+ * own `<ToString>`, so consecutive duplicates are collapsed by the caller.
+ */
+const TO_STRING_ENTRY = /<ToString>([\S\s]*?)<\/ToString>/g;
+
+const extractBlockMessages = (block: string): string[] => {
+ const streamTexts = [...block.matchAll(STREAM_ENTRY)].map((m) => m[1]);
+ // Prefer explicit stream entries; fall back to record ToString renderings
+ // (information records carry no stream-typed <S> entries).
+ const texts =
+ streamTexts.length > 0 ? streamTexts : [...block.matchAll(TO_STRING_ENTRY)].map((m) => m[1]);
+
+ const messages: string[] = [];
+ for (const raw of texts) {
+ const text = unescapeClixmlText(raw);
+ if (messages.at(-1) === text) continue;
+ messages.push(text);
+ }
+ return messages;
+};
+
+/**
+ * Replace every CLIXML block in `text` with its decoded messages. Plain text
+ * around the blocks is preserved; input without a marker is returned as-is.
+ * Truncated blocks (output preview cuts) decode whatever entries survived.
+ */
+export const decodeClixml = (text: string): string => {
+ if (!text.includes(CLIXML_MARKER)) return text;
+
+ let result = '';
+ let cursor = 0;
+ while (cursor < text.length) {
+ const markerIndex = text.indexOf(CLIXML_MARKER, cursor);
+ if (markerIndex === -1) {
+ result += text.slice(cursor);
+ break;
+ }
+
+ result += text.slice(cursor, markerIndex);
+
+ const closeTag = '</Objs>';
+ const closeIndex = text.indexOf(closeTag, markerIndex);
+ const blockEnd = closeIndex === -1 ? text.length : closeIndex + closeTag.length;
+ const block = text.slice(markerIndex, blockEnd);
+
+ const messages = extractBlockMessages(block);
+ if (messages.length > 0) {
+ // Error-stream texts carry their own trailing newlines (`_x000D__x000A_`);
+ // ToString renderings do not — normalize so messages never run together.
+ result += messages.map((m) => (m.endsWith('\n') ? m : `${m}\n`)).join('');
+ }
+
+ cursor = blockEnd;
+ }
+
+ return result;
+};
diff --git a/packages/local-file-shell/src/shell/index.ts b/packages/local-file-shell/src/shell/index.ts
index 7546703e956..8d658027ac0 100644
--- a/packages/local-file-shell/src/shell/index.ts
+++ b/packages/local-file-shell/src/shell/index.ts
@@ -1,5 +1,20 @@
+export { decodeClixml } from './clixml';
export type { ShellProcess } from './process-manager';
export { ShellProcessManager } from './process-manager';
export type { RunCommandOptions } from './runner';
export { runCommand } from './runner';
-export { buildOutputPreview, getShellConfig, INLINE_OUTPUT_MAX_BYTES } from './utils';
+export {
+ buildOutputPreview,
+ detectWindowsShell,
+ findGitBash,
+ getShellConfig,
+ getShellInfo,
+ getWindowsShellPreference,
+ INLINE_OUTPUT_MAX_BYTES,
+ normalizeEnvVarRefs,
+ resetShellDetectionCache,
+ setWindowsShellPreference,
+ type ShellInfo,
+ type WindowsShellPreference,
+ type WindowsShellType,
+} from './utils';
diff --git a/packages/local-file-shell/src/shell/process-manager.ts b/packages/local-file-shell/src/shell/process-manager.ts
index 8f078748c60..d69623fb361 100644
--- a/packages/local-file-shell/src/shell/process-manager.ts
+++ b/packages/local-file-shell/src/shell/process-manager.ts
@@ -6,6 +6,7 @@ import path from 'node:path';
import treeKill from 'tree-kill';
import type { GetCommandOutputParams, GetCommandOutputResult, KillCommandResult } from '../types';
+import { decodeClixml } from './clixml';
import { buildOutputPreview } from './utils';
const DEFAULT_OBSERVATION_TIMEOUT_MS = 30_000;
@@ -152,7 +153,10 @@ export class ShellProcessManager {
const { process: childProcess } = shellProcess;
let exitCode = childProcess.exitCode ?? shellProcess.exitCode;
- if (exitCode === null) {
+ // A signal-terminated child (killCommand on POSIX) never gets an exitCode
+ // and its 'exit' event has already fired — waiting would just burn the
+ // full observation timeout before returning the killed command's output.
+ if (exitCode === null && childProcess.signalCode == null) {
const waitTimeout =
typeof timeout === 'number' && Number.isFinite(timeout)
? Math.min(Math.max(Math.trunc(timeout), 0), MAX_OBSERVATION_TIMEOUT_MS)
@@ -205,7 +209,9 @@ export class ShellProcessManager {
previewBytes.stderr,
);
let stdout = stdoutPreview.content;
- let stderr = stderrPreview.content;
+ // PowerShell serializes non-stdout streams as CLIXML when stderr is
+ // redirected — decode the blocks back into readable messages.
+ let stderr = decodeClixml(stderrPreview.content);
if (filter) {
try {
@@ -256,8 +262,10 @@ export class ShellProcessManager {
try {
killProcessTree(shellProcess.process);
- this.closeOutputFiles(shellProcess.outputFiles);
- this.processes.delete(shell_id);
+ // Keep the registry entry: getCommandOutput after a kill must still be
+ // able to return the output produced before termination, exactly like a
+ // naturally-exited command. Output fds are closed by the 'close' handler
+ // registered in register(); the entry itself lives until cleanupAll().
return { success: true };
} catch (error) {
return { error: (error as Error).message, success: false };
diff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.ts
index 1610cfca9ae..847a694b1fb 100644
--- a/packages/local-file-shell/src/shell/runner.ts
+++ b/packages/local-file-shell/src/shell/runner.ts
@@ -4,7 +4,7 @@ import type { SandboxPolicy } from '@lobechat/device-sandbox';
import type { RunCommandParams, RunCommandResult } from '../types';
import type { ShellOutputFiles, ShellProcess, ShellProcessManager } from './process-manager';
-import { getShellConfig } from './utils';
+import { detectWindowsShell, getShellConfig, normalizeEnvVarRefs } from './utils';
export interface RunCommandOptions {
logger?: {
@@ -34,8 +34,18 @@ export async function runCommand(
const logPrefix = `[runCommand: ${description || command.slice(0, 50)}]`;
logger?.debug(`${logPrefix} Starting`, { background: run_in_background, cwd, timeout });
- const shellConfig = getShellConfig(command);
const requestedEnv = extraEnv ? { ...process.env, ...extraEnv } : process.env;
+
+ // On Windows, rewrite env-var references the target shell cannot resolve
+ // natively into its own syntax (see normalizeEnvVarRefs), so a command
+ // authored in another shell dialect still resolves against the actual env.
+ // We do NOT rewrite on macOS/Linux: /bin/sh handles its own variable syntax,
+ // and rewriting here would break shell-local variables (e.g. `for x; do echo $x`).
+ const effectiveCommand =
+ process.platform === 'win32'
+ ? normalizeEnvVarRefs(command, requestedEnv, (await detectWindowsShell()).type)
+ : command;
+ const shellConfig = await getShellConfig(effectiveCommand);
let outputFiles: ShellOutputFiles | undefined;
let releaseSandbox: (() => void) | undefined;
@@ -66,6 +76,11 @@ export async function runCommand(
env: launchEnv,
shell: false,
stdio: ['pipe', shellOutputFiles.stdout.fd, shellOutputFiles.stderr.fd],
+ // The Electron main process is a GUI process without a console, so on
+ // Windows spawning a console program (powershell.exe / cmd.exe) allocates
+ // a new console window that flashes up for every command. windowsHide
+ // defaults to false in Node, so it must be set explicitly.
+ windowsHide: true,
});
const shellProcess: ShellProcess = {
diff --git a/packages/local-file-shell/src/shell/utils.ts b/packages/local-file-shell/src/shell/utils.ts
index 58fe23b71da..13833b73e0d 100644
--- a/packages/local-file-shell/src/shell/utils.ts
+++ b/packages/local-file-shell/src/shell/utils.ts
@@ -1,4 +1,5 @@
import fs from 'node:fs';
+import path from 'node:path';
/** Maximum preview bytes returned inline to prevent context explosion */
export const INLINE_OUTPUT_MAX_BYTES = 25 * 1024;
@@ -83,8 +84,365 @@ export const buildOutputPreview = (
}
};
-/** Get cross-platform shell configuration */
-export const getShellConfig = (command: string) =>
+/** Detected Windows shell flavour. */
+export type WindowsShellType = 'pwsh' | 'powershell' | 'cmd' | 'gitbash';
+
+/**
+ * User-facing Windows shell preference. `auto` runs the pwsh → PowerShell 5.1
+ * → cmd detection chain; `gitbash` uses Git Bash when installed (falling back
+ * to `auto` when it is not).
+ */
+export type WindowsShellPreference = 'auto' | 'gitbash';
+
+export interface ShellInfo {
+ /** Human-readable name surfaced to the model / UI, e.g. "PowerShell 7+ (pwsh)". */
+ displayName: string;
+ /** Absolute path to the shell executable used to spawn commands. */
+ path: string;
+ /** Shell flavour identifier. */
+ type: WindowsShellType | 'sh';
+}
+
+/**
+ * Check whether an executable exists at the given absolute path.
+ *
+ * Probed with `lstat` rather than a stat-based check: MS Store executables
+ * surface as zero-byte app-execution-alias reparse points (e.g.
+ * %LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe), and stat can fail to resolve
+ * the reparse target while lstat reliably reports the alias itself.
+ */
+const executableExists = async (candidate: string): Promise<boolean> => {
+ try {
+ await fs.promises.lstat(candidate);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+/** Return the first candidate that exists, preserving the list's priority order. */
+const firstExisting = async (candidates: string[]): Promise<string | undefined> => {
+ const results = await Promise.all(candidates.map((candidate) => executableExists(candidate)));
+ const index = results.indexOf(true);
+ return index === -1 ? undefined : candidates[index];
+};
+
+/**
+ * Locate `pwsh.exe` (PowerShell 7+) by scanning `PATH` first, then the default
+ * installation directory and the MS Store app-execution alias. Returns the
+ * absolute path or `undefined`.
+ */
+const findPwsh = async (): Promise<string | undefined> => {
+ const pathDirs = (process.env.PATH ?? '').split(path.delimiter).filter(Boolean);
+ const programFiles = process.env.ProgramFiles || 'C:\\Program Files';
+ const localAppData = process.env.LOCALAPPDATA;
+
+ return firstExisting([
+ ...pathDirs.map((dir) => path.join(dir, 'pwsh.exe')),
+ // Default install location for PowerShell 7 when it is not on PATH.
+ path.join(programFiles, 'PowerShell', '7', 'pwsh.exe'),
+ // MS Store install: the real package dir under WindowsApps is
+ // ACL-protected, so the only user-visible entry point is the
+ // app-execution alias — probed explicitly because GUI-launched processes
+ // do not always inherit the alias directory on PATH.
+ ...(localAppData ? [path.join(localAppData, 'Microsoft', 'WindowsApps', 'pwsh.exe')] : []),
+ ]);
+};
+
+/**
+ * Locate Git Bash (`bash.exe` shipped with Git for Windows).
+ *
+ * Lookup order:
+ * 1. Standard installer locations (Program Files / per-user / scoop).
+ * 2. `bash.exe` on `PATH` — skipping `System32`, whose `bash.exe` is the WSL
+ * launcher, not a Win32 bash.
+ * 3. Derived from `git.exe` on `PATH`: package managers like scoop only shim
+ * `git.exe`, so bash never appears on PATH even though it ships with the
+ * install (`<git-root>\bin\bash.exe`, with git.exe in `bin\` or `cmd\`).
+ */
+export const findGitBash = async (): Promise<string | undefined> => {
+ const programFiles = process.env.ProgramFiles || 'C:\\Program Files';
+ const programFilesX86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
+ const localAppData = process.env.LOCALAPPDATA;
+ const userProfile = process.env.USERPROFILE;
+
+ const standardCandidates = [
+ path.join(programFiles, 'Git', 'bin', 'bash.exe'),
+ path.join(programFilesX86, 'Git', 'bin', 'bash.exe'),
+ ...(localAppData ? [path.join(localAppData, 'Programs', 'Git', 'bin', 'bash.exe')] : []),
+ ...(process.env.SCOOP
+ ? [path.join(process.env.SCOOP, 'apps', 'git', 'current', 'bin', 'bash.exe')]
+ : []),
+ ...(userProfile
+ ? [path.join(userProfile, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe')]
+ : []),
+ ];
+ const standardHit = await firstExisting(standardCandidates);
+ if (standardHit) return standardHit;
+
+ const pathDirs = (process.env.PATH ?? '').split(path.delimiter).filter(Boolean);
+ const pathHit = await firstExisting(
+ pathDirs.filter((dir) => !/system32/i.test(dir)).map((dir) => path.join(dir, 'bash.exe')),
+ );
+ if (pathHit) return pathHit;
+
+ const gitDirs = await Promise.all(
+ pathDirs.map(async (dir) => ((await executableExists(path.join(dir, 'git.exe'))) ? dir : '')),
+ );
+ // git.exe lives in `<root>\bin` or `<root>\cmd`; bash is at `<root>\bin\bash.exe`.
+ return firstExisting(
+ gitDirs
+ .filter(Boolean)
+ .flatMap((dir) => [path.join(dir, 'bash.exe'), path.join(dir, '..', 'bin', 'bash.exe')])
+ .map((candidate) => path.resolve(candidate)),
+ );
+};
+
+/** Locate the built-in Windows PowerShell 5.1 (`powershell.exe`). */
+const findWindowsPowerShell = async (): Promise<string | undefined> => {
+ const systemRoot = process.env.SystemRoot || 'C:\\Windows';
+ const candidate = path.join(
+ systemRoot,
+ 'System32',
+ 'WindowsPowerShell',
+ 'v1.0',
+ 'powershell.exe',
+ );
+ return (await executableExists(candidate)) ? candidate : undefined;
+};
+
+/**
+ * Module-level cache for the Windows shell detection result. Detection touches
+ * the filesystem, so we only run it once per process.
+ */
+type WindowsShellInfo = ShellInfo & { type: WindowsShellType };
+
+/**
+ * The promise (not the resolved value) is cached so that concurrent first
+ * calls share a single detection run instead of racing duplicate filesystem
+ * scans.
+ */
+let cachedWindowsShell: Promise<WindowsShellInfo> | undefined;
+
+/**
+ * Current user preference. Set by the desktop main process from its persisted
+ * settings (see `setWindowsShellPreference`); defaults to automatic detection.
+ */
+let windowsShellPreference: WindowsShellPreference = 'auto';
+
+/**
+ * Reset the cached Windows shell detection result.
+ *
+ * @internal for tests only — production code should rely on the cache.
+ */
+export const resetShellDetectionCache = (): void => {
+ cachedWindowsShell = undefined;
+};
+
+/**
+ * Apply the user's Windows shell preference. Clears the detection cache so the
+ * next command picks up the new shell immediately.
+ */
+export const setWindowsShellPreference = (preference: WindowsShellPreference): void => {
+ if (windowsShellPreference === preference) return;
+ windowsShellPreference = preference;
+ cachedWindowsShell = undefined;
+};
+
+export const getWindowsShellPreference = (): WindowsShellPreference => windowsShellPreference;
+
+/**
+ * Detect the preferred Windows shell, preferring PowerShell 7 (`pwsh`), then
+ * Windows PowerShell 5.1 (`powershell`), and finally falling back to `cmd.exe`.
+ * The result is cached for the lifetime of the process.
+ */
+export const detectWindowsShell = (): Promise<WindowsShellInfo> => {
+ cachedWindowsShell ??= resolveWindowsShell();
+ return cachedWindowsShell;
+};
+
+const resolveWindowsShell = async (): Promise<WindowsShellInfo> => {
+ // Explicit user preference first. When Git Bash was selected but is no
+ // longer installed, silently fall back to the automatic chain instead of
+ // failing every command.
+ if (windowsShellPreference === 'gitbash') {
+ const gitBashPath = await findGitBash();
+ if (gitBashPath) {
+ return { displayName: 'Git Bash', path: gitBashPath, type: 'gitbash' };
+ }
+ }
+
+ const pwshPath = await findPwsh();
+ if (pwshPath) {
+ return { displayName: 'PowerShell 7+ (pwsh)', path: pwshPath, type: 'pwsh' };
+ }
+
+ const powershellPath = await findWindowsPowerShell();
+ if (powershellPath) {
+ return { displayName: 'Windows PowerShell 5.1', path: powershellPath, type: 'powershell' };
+ }
+
+ // Extremely unlikely: neither PowerShell edition is present. Fall back to cmd.
+ return { displayName: 'cmd.exe', path: 'cmd.exe', type: 'cmd' };
+};
+
+/**
+ * Describe the shell that commands run in on the current platform. Used by the
+ * desktop main process / CLI to tell the model which shell it is targeting.
+ */
+export const getShellInfo = async (): Promise<ShellInfo> =>
process.platform === 'win32'
- ? { args: ['/c', command], cmd: 'cmd.exe' }
- : { args: ['-c', command], cmd: '/bin/sh' };
+ ? detectWindowsShell()
+ : { displayName: '/bin/sh', path: '/bin/sh', type: 'sh' };
+
+/**
+ * Rewrite environment variable references in a command string to the **target
+ * shell's native syntax**, for the syntaxes that shell cannot resolve itself.
+ * The value is never inlined — the spawned process receives `env`, so the shell
+ * expands the reference from its own environment. Inlining raw values would
+ * both break tokenization (values like `C:\Program Files (x86)` contain
+ * spaces) and embed secrets passed via `env` into the child command line.
+ *
+ * - PowerShell target: only cmd-style `%VAR%` is rewritten (to `${env:VAR}`).
+ * `$env:VAR`, `$VAR` and `${VAR}` are valid PowerShell syntax that PowerShell
+ * resolves itself — rewriting them here would corrupt legitimate scripts (the
+ * `$env:FOO='bar'` assignment form, or script-local variables like
+ * `foreach ($path in ...)` colliding with the `PATH` env var).
+ * - cmd target: PowerShell/bash forms (`$env:VAR`, `${VAR}`, `$VAR`) are
+ * rewritten to `%VAR%`; existing `%VAR%` is already cmd-native.
+ * - Git Bash target: cmd-style `%VAR%` and PowerShell-style `$env:VAR` are
+ * rewritten to `${VAR}` (with an upper-case fallback for mixed-case names,
+ * since MSYS2 upper-cases some inherited variables); `$VAR` / `${VAR}` are
+ * bash-native and untouched.
+ *
+ * Only variables present in `env` are rewritten; unknown references are left
+ * untouched so the target shell can handle them. Windows variable names are
+ * case-insensitive, so existence checks go through a lower-cased key set.
+ */
+export const normalizeEnvVarRefs = (
+ command: string,
+ // Structural type instead of NodeJS.ProcessEnv: app tsconfigs augment
+ // ProcessEnv with required members, which would leak into this shared
+ // package's API and break callers/tests that build plain env objects.
+ env: Record<string, string | undefined>,
+ shell: WindowsShellType,
+): string => {
+ // Windows env var names are case-insensitive; build a lower-cased key set
+ // plus a map back to the actual key spelling for case-sensitive targets.
+ const envNames = new Set<string>();
+ const canonicalNames = new Map<string, string>();
+ for (const [key, value] of Object.entries(env)) {
+ if (value === undefined) continue;
+ envNames.add(key.toLowerCase());
+ canonicalNames.set(key.toLowerCase(), key);
+ }
+
+ if (shell === 'gitbash') {
+ // Unlike cmd/PowerShell, bash resolves variables case-sensitively, so the
+ // reference must be rewritten to the env key's actual spelling
+ // (`%userprofile%` → `${USERPROFILE}`).
+ const toBashRef = (match: string, name: string): string => {
+ const canonical = canonicalNames.get(name.toLowerCase());
+ if (canonical === undefined) return match;
+ const upper = canonical.toUpperCase();
+ // MSYS2 upper-cases a fixed set of inherited Windows variable names when
+ // building bash's environment (`ProgramFiles` → `PROGRAMFILES`, while
+ // e.g. `ProgramData` keeps its spelling). The set is runtime-internal,
+ // so for mixed-case names emit a fallback expansion that resolves
+ // whichever spelling bash actually has.
+ return canonical === upper ? `\${${upper}}` : `\${${canonical}:-\${${upper}}}`;
+ };
+ // %VAR% — cmd style, bash cannot resolve it. Names containing parentheses
+ // (e.g. %ProgramFiles(x86)%) are skipped: bash identifiers cannot contain
+ // them, so a rewrite would produce a reference bash rejects.
+ let result = command.replaceAll(/%([A-Z_][\w()]*)%/gi, (match, name: string) =>
+ name.includes('(') ? match : toBashRef(match, name),
+ );
+ // $env:VAR — PowerShell style, bash would read it as `$env` + literal `:VAR`.
+ result = result.replaceAll(/\$env:([A-Z_]\w*)/gi, toBashRef);
+ return result;
+ }
+
+ if (shell === 'pwsh' || shell === 'powershell') {
+ // cmd style: %VAR% — the name may contain parentheses, e.g. %ProgramFiles(x86)%.
+ // `${env:VAR}` expands as a single token even when the value has spaces.
+ return command.replaceAll(/%([A-Z_][\w()]*)%/gi, (match, name: string) =>
+ envNames.has(name.toLowerCase()) ? `\${env:${name}}` : match,
+ );
+ }
+
+ // cmd.exe target: rewrite to cmd-native %VAR%.
+ const toCmdRef = (match: string, name: string): string =>
+ envNames.has(name.toLowerCase()) ? `%${name}%` : match;
+
+ // PowerShell style first: $env:VAR — rewritten before bash `$VAR` so the
+ // `env:` prefix is consumed and never mistaken for a bash variable named `env`.
+ let result = command.replaceAll(/\$env:([A-Z_]\w*)/gi, toCmdRef);
+ // bash style: ${VAR}, then bare $VAR.
+ result = result.replaceAll(/\$\{([A-Z_]\w*)\}/gi, toCmdRef);
+ result = result.replaceAll(/\$([A-Z_]\w*)/gi, toCmdRef);
+ return result;
+};
+
+/** Get cross-platform shell configuration */
+export const getShellConfig = async (command: string): Promise<{ args: string[]; cmd: string }> => {
+ if (process.platform !== 'win32') {
+ // macOS / Linux behaviour is intentionally unchanged.
+ return { args: ['-c', command], cmd: '/bin/sh' };
+ }
+
+ const shell = await detectWindowsShell();
+
+ if (shell.type === 'gitbash') {
+ // bash receives the command as a single argv entry; no CRT re-tokenization
+ // problem applies (bash parses the string itself), so no encoding needed.
+ return { args: ['-c', command], cmd: shell.path };
+ }
+
+ if (shell.type === 'pwsh' || shell.type === 'powershell') {
+ // PowerShell collapses a native command's nonzero exit code to 1 unless the
+ // script explicitly exits with $LASTEXITCODE (documented -Command /
+ // -EncodedCommand behavior in both editions; verified against pwsh 7).
+ // Append an exit guard that mirrors the `sh -c` / `cmd /c` convention: the
+ // *final* statement decides. `$?` is captured first (assignments don't
+ // reset it); only when it is false do we exit nonzero — preferring the
+ // faithful native code (e.g. `python -c "sys.exit(42)"` → 42) and falling
+ // back to 1 for cmdlet failures. A stale nonzero $LASTEXITCODE from an
+ // intentionally-ignored earlier failure (`git diff --exit-code; cleanup`)
+ // must NOT override a successful final statement, and a trailing cmdlet
+ // failure must NOT be masked by a successful native command's 0.
+ // All branches verified empirically on pwsh 7 via -EncodedCommand.
+ // On localized Windows the console code page is an OEM one (e.g. CP936 on
+ // zh-CN), so redirected PowerShell output is written in that encoding while
+ // the runner reads the output files as UTF-8 — CJK text turns into mojibake.
+ // Force both the console output encoding (used by Write-Host / redirected
+ // streams) and $OutputEncoding (used when piping into native commands) to
+ // UTF-8 before the user command runs. The [Console] setter can throw when
+ // no console is attached, hence the try/catch.
+ const encodingPreamble =
+ 'try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}' +
+ '\n$OutputEncoding = [System.Text.Encoding]::UTF8\n';
+ const exitGuard =
+ '\n$__lobeExecOk = $?' +
+ '\nif (-not $__lobeExecOk) {' +
+ '\n if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }' +
+ '\n exit 1' +
+ '\n}';
+ const script = `${encodingPreamble}${command}${exitGuard}`;
+ // Pass the command via -EncodedCommand (UTF-16LE base64) instead of a plain
+ // argument. Node spawns processes without a shell, so the command string
+ // would otherwise be re-tokenized by the Windows CRT / PowerShell's own
+ // parser, which mangles quotes and backslashes in file paths. Encoding the
+ // command sidesteps that tokenization entirely — the same approach used by
+ // Ansible, VS Code Remote and Codex. See:
+ // https://github.com/lobehub/lobehub/pull/14697
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
+ return {
+ args: ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
+ cmd: shell.path,
+ };
+ }
+
+ // cmd.exe fallback (PowerShell not found): keep the legacy behaviour.
+ return { args: ['/c', command], cmd: shell.path };
+};
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index b11dbdfd1c2..fccaedff00a 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1067,6 +1067,13 @@ export default {
'Development runtime environments for executing scripts and packages',
'settingSystemTools.detecting': 'Detecting...',
'settingSystemTools.redetect': 'Re-detect',
+ 'settingSystemTools.shell.desc': 'Shell used when the agent runs local commands on this machine',
+ 'settingSystemTools.shell.mode.auto': 'Automatic (PowerShell)',
+ 'settingSystemTools.shell.mode.desc':
+ 'PowerShell is used by default. Git Bash appears as an option when Git for Windows is installed. Current shell:',
+ 'settingSystemTools.shell.mode.gitbash': 'Git Bash',
+ 'settingSystemTools.shell.mode.title': 'Windows Shell',
+ 'settingSystemTools.shell.title': 'Command Execution',
'settingSystemTools.status.available': 'Available',
'settingSystemTools.status.notDetected': 'Not detected',
'settingSystemTools.status.unavailable': 'Unavailable',
diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.ts
index 3ada19d21a7..9b35a761473 100644
--- a/src/features/SettingsSearch/items.ts
+++ b/src/features/SettingsSearch/items.ts
@@ -11,6 +11,8 @@ export interface SettingsSearchContext {
hideDocs: boolean;
isDesktop: boolean;
isLogin: boolean;
+ /** Whether the app is running on Windows (for Windows-only settings) */
+ isWindows: boolean;
showAiImage: boolean;
}
@@ -303,6 +305,26 @@ export const SETTINGS_SEARCH_ITEMS: SettingsSearchItem[] = [
tab: SettingsTabs.Appearance,
visible: (ctx) => ctx.isDesktop,
},
+ // System Tools
+ {
+ anchor: 'system-tools-shell',
+ descKey: 'settingSystemTools.shell.mode.desc',
+ keywords: [
+ 'shell',
+ 'bash',
+ 'git bash',
+ 'gitbash',
+ 'powershell',
+ 'pwsh',
+ 'cmd',
+ 'terminal',
+ 'command line',
+ 'windows shell',
+ ],
+ labelKey: 'settingSystemTools.shell.mode.title',
+ tab: SettingsTabs.SystemTools,
+ visible: (ctx) => ctx.isDesktop && ctx.isWindows,
+ },
// Advanced
{
anchor: 'advanced-dev-mode',
diff --git a/src/features/SettingsSearch/useSettingsSearch.ts b/src/features/SettingsSearch/useSettingsSearch.ts
index ec94b3e2533..366589c7ad1 100644
--- a/src/features/SettingsSearch/useSettingsSearch.ts
+++ b/src/features/SettingsSearch/useSettingsSearch.ts
@@ -13,6 +13,7 @@ import {
} from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
+import { getPlatform } from '@/utils/platform';
import {
SETTINGS_SEARCH_ITEMS,
@@ -102,6 +103,7 @@ export const useSettingsSearch = (
hideDocs: !!hideDocs,
isDesktop,
isLogin: !!isLogin,
+ isWindows: getPlatform() === 'Windows',
showAiImage: !!showAiImage,
};
diff --git a/src/helpers/GlobalAgentContextManager.ts b/src/helpers/GlobalAgentContextManager.ts
index b9c329d79ce..6791c373201 100644
--- a/src/helpers/GlobalAgentContextManager.ts
+++ b/src/helpers/GlobalAgentContextManager.ts
@@ -2,6 +2,9 @@ export interface LobeGlobalAgentContext {
// Other potential context
currentTime?: string;
+ /** Human-readable name of the shell that runCommand uses (Windows: PowerShell/cmd). */
+ defaultShell?: string;
+
// App's data directory
// Paths commonly used by agents
desktopPath?: string;
diff --git a/src/helpers/parserPlaceholder/index.ts b/src/helpers/parserPlaceholder/index.ts
index 4071b576db8..86101287270 100644
--- a/src/helpers/parserPlaceholder/index.ts
+++ b/src/helpers/parserPlaceholder/index.ts
@@ -162,9 +162,15 @@ export const VARIABLE_GENERATORS = {
* | `{{videosPath}}` | /Users/username/Videos |
* | `{{userDataPath}}` | /Users/username/Library/Application Support/LobeChat |
* | `{{workingDirectory}}` | /Users/username/Projects/my-project |
+ * | `{{defaultShell}}` | PowerShell 7+ (pwsh) |
*
*/
homePath: () => globalAgentContextManager.getContext().homePath ?? '',
+ // Fallback keeps the surrounding prompt sentence readable when the desktop
+ // context has not (yet) provided the detected shell.
+ defaultShell: () =>
+ globalAgentContextManager.getContext().defaultShell ??
+ 'the platform default shell (PowerShell on Windows, /bin/sh on macOS/Linux)',
desktopPath: () => globalAgentContextManager.getContext().desktopPath ?? '',
documentsPath: () => globalAgentContextManager.getContext().documentsPath ?? '',
downloadsPath: () => globalAgentContextManager.getContext().downloadsPath ?? '',
diff --git a/src/routes/(main)/settings/system-tools/features/ShellSection.tsx b/src/routes/(main)/settings/system-tools/features/ShellSection.tsx
new file mode 100644
index 00000000000..ceee668d12a
--- /dev/null
+++ b/src/routes/(main)/settings/system-tools/features/ShellSection.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { type WindowsShellMode } from '@lobechat/electron-client-ipc';
+import { type FormGroupItemType } from '@lobehub/ui';
+import { Form, Text } from '@lobehub/ui';
+import { Select } from '@lobehub/ui/base-ui';
+import { memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
+
+import { FORM_STYLE } from '@/const/layoutTokens';
+import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';
+import { desktopSettingsService } from '@/services/electron/settings';
+import { getPlatform } from '@/utils/platform';
+
+/**
+ * Windows-only: choose the shell that runs agent commands (automatic
+ * PowerShell chain vs Git Bash). Other platforms always use /bin/sh, so the
+ * whole section is hidden there.
+ */
+const ShellSection = memo(() => {
+ const { t } = useTranslation('setting');
+ const [updating, setUpdating] = useState(false);
+
+ const { data, mutate } = useSWR(
+ 'desktop-shell-settings',
+ desktopSettingsService.getShellSettings,
+ { revalidateOnFocus: false },
+ );
+
+ const handleChange = useCallback(
+ async (mode: WindowsShellMode) => {
+ setUpdating(true);
+ try {
+ const next = await desktopSettingsService.setShellMode(mode);
+ await mutate(next, { revalidate: false });
+ } finally {
+ setUpdating(false);
+ }
+ },
+ [mutate],
+ );
+
+ const options = [
+ { label: t('settingSystemTools.shell.mode.auto'), value: 'auto' as const },
+ // Only offer Git Bash when Git for Windows is actually installed.
+ ...(data?.gitBashAvailable
+ ? [{ label: t('settingSystemTools.shell.mode.gitbash'), value: 'gitbash' as const }]
+ : []),
+ ];
+
+ const shellGroup: FormGroupItemType = {
+ children: [
+ {
+ children: (
+ <Select
+ disabled={!data || updating}
+ options={options}
+ value={data?.mode ?? 'auto'}
+ onChange={handleChange}
+ />
+ ),
+ desc: (
+ <>
+ {t('settingSystemTools.shell.mode.desc')}
+ {data && (
+ <>
+ {' '}
+ <Text code fontSize={12} type={'secondary'}>
+ {data.currentShell.path}
+ </Text>
+ </>
+ )}
+ </>
+ ),
+ label: (
+ <SettingsSearchAnchor id={'system-tools-shell'}>
+ {t('settingSystemTools.shell.mode.title')}
+ </SettingsSearchAnchor>
+ ),
+ },
+ ],
+ desc: t('settingSystemTools.shell.desc'),
+ title: t('settingSystemTools.shell.title'),
+ };
+
+ return (
+ <Form
+ collapsible={false}
+ items={[shellGroup]}
+ itemsType={'group'}
+ variant={'filled'}
+ {...FORM_STYLE}
+ />
+ );
+});
+
+const GuardedShellSection = memo(() => {
+ if (getPlatform() !== 'Windows') return null;
+ return <ShellSection />;
+});
+
+export default GuardedShellSection;
diff --git a/src/routes/(main)/settings/system-tools/index.tsx b/src/routes/(main)/settings/system-tools/index.tsx
index 8ad3fbad22b..986136d9dc6 100644
--- a/src/routes/(main)/settings/system-tools/index.tsx
+++ b/src/routes/(main)/settings/system-tools/index.tsx
@@ -6,6 +6,7 @@ import { userGeneralSettingsSelectors } from '@/store/user/slices/settings/selec
import AppEnvironmentSection from './features/AppEnvironmentSection';
import CliTestSection from './features/CliTestSection';
+import ShellSection from './features/ShellSection';
import ToolDetectorSection from './features/ToolDetectorSection';
const Page = () => {
@@ -15,6 +16,7 @@ const Page = () => {
return (
<>
<SettingHeader title={t('tab.systemTools')} />
+ <ShellSection />
<ToolDetectorSection />
<AppEnvironmentSection />
{isDevMode ? <CliTestSection /> : null}
diff --git a/src/services/electron/settings.ts b/src/services/electron/settings.ts
index 2041cbebe6f..16f13399243 100644
--- a/src/services/electron/settings.ts
+++ b/src/services/electron/settings.ts
@@ -1,6 +1,7 @@
import {
type NetworkProxySettings,
type ShortcutUpdateResult,
+ type WindowsShellMode,
} from '@lobechat/electron-client-ipc';
import { ensureElectronIpc } from '@/utils/electron/ipc';
@@ -20,6 +21,20 @@ class DesktopSettingsService {
return ensureElectronIpc().networkProxy.getDesktopSettings();
};
+ /**
+ * Get shell settings for agent command execution (Windows shell selection)
+ */
+ getShellSettings = async () => {
+ return ensureElectronIpc().shellCommand.getShellSettings();
+ };
+
+ /**
+ * Set the Windows shell mode for agent command execution
+ */
+ setShellMode = async (mode: WindowsShellMode) => {
+ return ensureElectronIpc().shellCommand.setShellMode({ mode });
+ };
+
/**
* Set proxy settings
*/
diff --git a/src/store/electron/actions/app.ts b/src/store/electron/actions/app.ts
index 6c4158aafd3..68b43f9c2ad 100644
--- a/src/store/electron/actions/app.ts
+++ b/src/store/electron/actions/app.ts
@@ -50,6 +50,7 @@ export class ElectronAppActionImpl {
// Update the global agent context manager with relevant paths
// We typically only need paths in the agent context for now.
globalAgentContextManager.updateContext({
+ defaultShell: result.defaultShell,
desktopPath: result.userPath!.desktop,
documentsPath: result.userPath!.documents,
downloadsPath: result.userPath!.downloads,