From 403c6900618effce7b22d1cc7801f29c86eb381d Mon Sep 17 00:00:00 2001 From: Joseph Hau Date: Wed, 25 Nov 2026 15:52:30 +0800 Subject: [PATCH] feat(terminal): support Directory Picker in Windows CMD (#4343) * feat(terminal): support Directory Picker in Windows CMD * fix: show CMD-specific directory integration status --- .github/workflows/test.yml | 2 +- application/i18n/locales/en/terminal.ts | 2 + application/i18n/locales/es/terminal.ts | 2 + application/i18n/locales/ru/terminal.ts | 2 + application/i18n/locales/zh-CN/terminal.ts | 2 + application/i18n/locales/zh-TW/terminal.ts | 2 + .../state/useComposeDirectoryPicker.ts | 3 +- .../state/useTerminalDirectorySession.test.ts | 17 +++- .../state/useTerminalDirectorySession.ts | 12 ++- .../terminal/ComposeDirectoryPicker.tsx | 1 - .../directory-picker-cross-platform.md | 12 ++- .../directory-picker-follow-up.md | 9 +- domain/directoryPicker.ts | 10 +- electron/bridges/cmdDirectoryIntegration.cjs | 98 +++++++++++++++++++ .../bridges/cmdDirectoryIntegration.test.cjs | 64 ++++++++++++ electron/bridges/directoryReportStream.cjs | 41 ++++++++ electron/bridges/localSessionCwd.cjs | 2 +- .../powerShellDirectoryIntegration.cjs | 62 +++--------- electron/bridges/terminalBridge.cjs | 10 +- .../services/terminalDirectory.test.ts | 35 +++++++ infrastructure/services/terminalDirectory.ts | 16 ++- .../terminalDirectory.windows.test.ts | 86 ++++++++++++++++ types/global/netcatty-bridge-session.d.ts | 2 +- 23 files changed, 416 insertions(+), 76 deletions(-) create mode 100644 electron/bridges/cmdDirectoryIntegration.cjs create mode 100644 electron/bridges/cmdDirectoryIntegration.test.cjs create mode 100644 electron/bridges/directoryReportStream.cjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0408865ee..d5d8cb2ff 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -154,7 +154,7 @@ jobs: NETCATTY_SSH_TEST_RUNTIME: electron run: node --test electron/bridges/sshChaChaTransport.test.cjs - - name: Exercise native PowerShell directory navigation in ConPTY + - name: Exercise native PowerShell and CMD directory navigation in ConPTY env: NETCATTY_DIRECTORY_WINDOWS_LIVE: "1" run: | diff --git a/application/i18n/locales/en/terminal.ts b/application/i18n/locales/en/terminal.ts index 1c2c7e97a..f45acd4d0 100644 --- a/application/i18n/locales/en/terminal.ts +++ b/application/i18n/locales/en/terminal.ts @@ -13,9 +13,11 @@ export const enTerminalMessages: Messages = { 'terminal.directory.refresh': 'Refresh', 'terminal.directory.unavailable': 'Directory navigation is unavailable for this session.', 'terminal.directory.integrationUnavailable': 'PowerShell directory integration is not ready. Startup arguments or execution policy may prevent it.', + 'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.', 'terminal.directory.nonFilesystem': 'The current PowerShell location is not a filesystem directory.', 'terminal.directory.busy': 'Wait for an empty shell prompt.', 'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.', + 'terminal.directory.accessDenied': 'Permission denied while listing this directory.', 'terminal.directory.changeFailed': 'Could not confirm the directory change. Refresh before retrying.', 'terminal.directory.unsupportedPath': 'This directory name cannot be sent safely to the terminal.', 'settings.terminal.behavior.contextChips': 'Context Chips', diff --git a/application/i18n/locales/es/terminal.ts b/application/i18n/locales/es/terminal.ts index b76445b09..f27494909 100644 --- a/application/i18n/locales/es/terminal.ts +++ b/application/i18n/locales/es/terminal.ts @@ -13,7 +13,9 @@ export const esTerminalMessages: Messages = { 'terminal.directory.refresh': 'Actualizar', 'terminal.directory.unavailable': 'La navegación de directorios no está disponible para esta sesión.', 'terminal.directory.integrationUnavailable': 'La integración de directorios de PowerShell no está lista. Los argumentos de inicio o la política de ejecución pueden impedirla.', + 'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.', 'terminal.directory.nonFilesystem': 'La ubicación actual de PowerShell no es un directorio del sistema de archivos.', + 'terminal.directory.accessDenied': 'Permiso denegado al listar este directorio.', 'terminal.directory.busy': 'Espera a que el prompt esté vacío.', 'terminal.directory.readFailed': 'No se pudo leer el directorio. Actualiza e inténtalo de nuevo.', 'terminal.directory.changeFailed': 'No se pudo confirmar el cambio. Actualiza antes de reintentar.', diff --git a/application/i18n/locales/ru/terminal.ts b/application/i18n/locales/ru/terminal.ts index 9514af5ad..c78b61a86 100644 --- a/application/i18n/locales/ru/terminal.ts +++ b/application/i18n/locales/ru/terminal.ts @@ -13,7 +13,9 @@ export const ruTerminalMessages: Messages = { 'terminal.directory.refresh': 'Обновить', 'terminal.directory.unavailable': 'Навигация по каталогам недоступна для этого сеанса.', 'terminal.directory.integrationUnavailable': 'Интеграция каталогов PowerShell не готова. Проверьте параметры запуска и политику выполнения.', + 'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.', 'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.', + 'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.', 'terminal.directory.busy': 'Дождитесь пустой командной строки.', 'terminal.directory.readFailed': 'Не удалось прочитать каталог. Попробуйте обновить.', 'terminal.directory.changeFailed': 'Не удалось подтвердить смену каталога. Обновите перед повтором.', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index 73d50821c..4919eb009 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -13,7 +13,9 @@ export const zhCNTerminalMessages: Messages = { 'terminal.directory.refresh': '刷新', 'terminal.directory.unavailable': '此会话暂不支持目录导航。', 'terminal.directory.integrationUnavailable': 'PowerShell 目录集成未就绪,启动参数或执行策略可能阻止了加载。', + 'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。', 'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。', + 'terminal.directory.accessDenied': '没有权限列出此目录。', 'terminal.directory.busy': '请等待终端回到空命令提示符。', 'terminal.directory.readFailed': '无法读取此目录,请刷新重试。', 'terminal.directory.changeFailed': '未能确认目录切换,请刷新后重试。', diff --git a/application/i18n/locales/zh-TW/terminal.ts b/application/i18n/locales/zh-TW/terminal.ts index 98e37a5bb..5fb0c8eb8 100644 --- a/application/i18n/locales/zh-TW/terminal.ts +++ b/application/i18n/locales/zh-TW/terminal.ts @@ -13,7 +13,9 @@ export const zhTWTerminalMessages: Messages = { 'terminal.directory.refresh': '重新整理', 'terminal.directory.unavailable': '此工作階段暫不支援目錄導覽。', 'terminal.directory.integrationUnavailable': 'PowerShell 目錄整合尚未就緒,啟動參數或執行原則可能阻止載入。', + 'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。', 'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。', + 'terminal.directory.accessDenied': '沒有權限列出此目錄。', 'terminal.directory.busy': '請等待終端回到空白命令提示字元。', 'terminal.directory.readFailed': '無法讀取此目錄,請重新整理後重試。', 'terminal.directory.changeFailed': '未能確認目錄切換,請重新整理後重試。', diff --git a/application/state/useComposeDirectoryPicker.ts b/application/state/useComposeDirectoryPicker.ts index 7cd69dc5a..ae445d8f8 100644 --- a/application/state/useComposeDirectoryPicker.ts +++ b/application/state/useComposeDirectoryPicker.ts @@ -109,9 +109,10 @@ export function useComposeDirectoryPicker(sessionId: string) { const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]); const cwdError = controller?.getCwdError() ?? null; + const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable' || error === 'nonFilesystem'; return { cwd, home, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered, parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending, - error: cwdError ?? (cwd && (error === 'unknown' || error === 'integrationUnavailable' || error === 'nonFilesystem') ? null : error), + error: cwdError ?? (cwd && waitsForCwd ? null : error), available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange, refresh, reload: load, change }; } diff --git a/application/state/useTerminalDirectorySession.test.ts b/application/state/useTerminalDirectorySession.test.ts index 137b671fe..bf6b80921 100644 --- a/application/state/useTerminalDirectorySession.test.ts +++ b/application/state/useTerminalDirectorySession.test.ts @@ -67,19 +67,28 @@ for (const platform of ['linux', 'darwin']) { }); } -test('Windows native PowerShell registers a Win32 controller without enabling CMD or POSIX wrappers', async t => { +test('Windows native shells register independent Win32 controllers alongside a Bash session', async t => { installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform: 'win32' })); - function Harness() { + function NativeShells() { useTerminalDirectorySession(options('native-powershell', 'local', 'powershell')); useTerminalDirectorySession(options('native-cmd', 'local', 'cmd')); return null; } + function Harness({ showNative }: { showNative: boolean }) { + const props = options('first-bash'); + props.host = { ...props.host, localShell: 'git-bash' }; + useTerminalDirectorySession(props); + return showNative ? React.createElement(NativeShells) : null; + } let root!: ReactTestRenderer; - await act(async () => { root = create(React.createElement(Harness)); }); + await act(async () => { root = create(React.createElement(Harness, { showNative: false })); }); t.after(async () => { await act(async () => { root.unmount(); }); }); + await act(async () => { root.update(React.createElement(Harness, { showNative: true })); }); + assert.equal(getTerminalDirectory('first-bash'), null); assert.equal(getTerminalDirectory('native-powershell')?.target.pathFlavor, 'win32'); assert.equal(getTerminalDirectory('native-powershell')?.target.authority, 'local:native-powershell'); - assert.equal(getTerminalDirectory('native-cmd'), null); + assert.equal(getTerminalDirectory('native-cmd')?.target.pathFlavor, 'win32'); + assert.equal(getTerminalDirectory('native-cmd')?.target.authority, 'local:native-cmd'); }); test('Windows SSH sessions do not inherit the local cwd platform limitation', async t => { diff --git a/application/state/useTerminalDirectorySession.ts b/application/state/useTerminalDirectorySession.ts index 801393202..ec6c92bf5 100644 --- a/application/state/useTerminalDirectorySession.ts +++ b/application/state/useTerminalDirectorySession.ts @@ -21,8 +21,9 @@ export function useTerminalDirectorySession(options: { live.current = options; const { sessionId, status, shellType, host } = options; const local = host.protocol === 'local'; + const windowsShell = shellType === 'powershell' || shellType === 'cmd' ? shellType : undefined; const supported = (local || ((host.protocol ?? 'ssh') === 'ssh' && !host.moshEnabled && !host.etEnabled)) - && (shellType !== 'powershell' || local) && shellType !== 'cmd' + && (!windowsShell || local) && host.deviceType !== 'network' && classifyDistroId(host.distro) !== 'network-device' && !hostRestrictsExtraSshChannels(host); useEffect(() => { @@ -40,10 +41,11 @@ export function useTerminalDirectorySession(options: { local, hostname: host.hostname, username: host.username || 'root', port: host.port, encoding: host.sftpEncoding, pathFlavor, + windowsShell, }, isCurrent), target: { authority: `${local ? 'local' : 'ssh'}:${backendId}`, pathFlavor }, capabilities: COMPLETE_DIRECTORY_CAPABILITIES, - buildChangeCommand: path => directoryChangeCommand(path, pathFlavor === 'win32' ? 'powershell' : 'posix', pathFlavor), + buildChangeCommand: path => directoryChangeCommand(path, windowsShell ?? 'posix', pathFlavor), isCurrent, isReady: () => live.current.isReady(), publish: cwd => live.current.publish(cwd), @@ -54,10 +56,10 @@ export function useTerminalDirectorySession(options: { // POSIX wrappers on Windows still use win32 PTYs. Neither their cwd nor // their path namespace is supported by readLocalSessionCwd/local FS. void bridge.getAppInfo?.().then(info => { - if ((info.platform === 'darwin' || info.platform === 'linux') && shellType !== 'powershell') register(); - else if (info.platform === 'win32' && shellType === 'powershell') register('win32'); + if ((info.platform === 'darwin' || info.platform === 'linux') && !windowsShell) register(); + else if (info.platform === 'win32' && windowsShell) register('win32'); }).catch(() => {}); } else register(); return () => { active = false; unregister(); }; - }, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, shellType]); + }, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, windowsShell]); } diff --git a/components/terminal/ComposeDirectoryPicker.tsx b/components/terminal/ComposeDirectoryPicker.tsx index 10512c7fa..8d91c00a8 100644 --- a/components/terminal/ComposeDirectoryPicker.tsx +++ b/components/terminal/ComposeDirectoryPicker.tsx @@ -124,7 +124,6 @@ export function ComposeDirectoryPicker({ sessionId, theme, onReturnFocus }: { - {!model.open && errorText && {errorText}} ); } diff --git a/docs/research/terminal-compose-context/directory-picker-cross-platform.md b/docs/research/terminal-compose-context/directory-picker-cross-platform.md index 66ad3a68b..d2511fd5e 100644 --- a/docs/research/terminal-compose-context/directory-picker-cross-platform.md +++ b/docs/research/terminal-compose-context/directory-picker-cross-platform.md @@ -9,6 +9,7 @@ | macOS/Linux 本地 POSIX | OSC 7;进程 cwd 回退 | 本地 FS | 现有交互 cd 策略,严格 cwd/realpath 确认 | | Unix SSH | 活动会话的严格查询/OSC 7 | 同一认证连接的 SFTP | 绑定原终端,按连接能力确认 | | Windows PowerShell 5.1/7 | 原 runspace 的 FileSystem ProviderPath | Windows 本地 FS | Set-Location -LiteralPath,等待新位置报告 | +| Windows CMD | 会话 PROMPT 的 `$P` | Windows 本地 FS | `cd /d`,等待原 CMD 报告目标位置 | ## 路径与能力模型 @@ -51,10 +52,18 @@ PSDrive 根的 ProviderPath 可能带尾部反斜杠,因此路径比较按根 原生 Windows 路径提示符使用独立的边界识别,覆盖深目录、折行、FileSystem provider 前缀和命名 PSDrive;UNC 位置支持域名、IP 服务器及含空格的共享名。`>` 后的内容继续作为当前输入,目录操作复用同一套空提示符、敏感输入和 TUI 检查。 +## CMD 会话集成 + +普通交互启动在原 `PROMPT` 前加入带会话标识的 OSC 属性,由 CMD 展开 `$P`。可见提示符、启动参数及命令状态沿用原会话设置。PTY 从输出中过滤属性,提交输入使旧报告失效。嵌套 CMD 会继承 `PROMPT`,因此读取位置时校验原进程及其子进程,等待控制权返回原 CMD。进程校验优先使用原生模块,缺少模块时使用 Windows CIM 查询。 + +目录切换要求空提示符,使用 `cd /d` 处理盘符绝对路径,随后确认新报告。引号保留空格和 Unicode 目录名,前导空格避开 DOSKEY 别名。含 `%`、`!` 的目标继续作为可浏览的条目,切换时显示路径限制;UNC 映射和扩展关闭的启动方式保留为后续适配。 + +目录列表遵循 Windows 访问权限。系统兼容链接拒绝枚举时,菜单显示权限原因,并保留父目录入口。等待原 CMD 会话报告位置时,菜单显示对应的 CMD 状态,收到有效报告后恢复目录导航。 + ## 后续设计方向 - POSIX hook:分别处理 bash 的 PROMPT_COMMAND、zsh 的启动链和 fish 事件,补齐事件上报。 -- CMD:围绕 PROMPT、`cd /d`、交互转义和 ERRORLEVEL 建立独立策略。 +- CMD:补充扩展关闭、提示符被启动脚本覆盖、变量展开字符和 UNC 映射场景。 - WSL/MSYS/Cygwin:以 distro/mount authority 组织目录 helper 和路径映射。 - 扩展远程环境:逐项明确活动 shell 与 SFTP/provider 的文件系统对应关系。 @@ -65,6 +74,7 @@ PSDrive 根的 ProviderPath 可能带尾部反斜杠,因此路径比较按根 - [PowerShell locations](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_locations):runspace、provider 与当前位置。 - [Set-Location](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/set-location) 与 [quoting rules](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules):LiteralPath 与字符串引用。 - [PowerShell execution policies](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies):脚本加载策略。 +- [CMD](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cmd)、[PROMPT](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/prompt)、[CD](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cd):启动参数、位置上报和盘符切换。 - [VS Code shell integration](https://code.visualstudio.com/docs/terminal/shell-integration) 与 [PowerShell 实现](https://github.com/microsoft/vscode/blob/ce233327f26ef7791b7fff0143c24e81a8126bd2/src/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1):会话注入、prompt 保留与 OSC 属性通道。 - [Windows Terminal shell integration](https://learn.microsoft.com/en-us/windows/terminal/tutorials/shell-integration)、[WSL filesystems](https://learn.microsoft.com/en-us/windows/wsl/filesystems):Windows shell 上报与文件系统命名空间。 - [Electron ASAR archives](https://www.electronjs.org/docs/latest/tutorial/asar-archives):外部 shell 的实体脚本资源。 diff --git a/docs/research/terminal-compose-context/directory-picker-follow-up.md b/docs/research/terminal-compose-context/directory-picker-follow-up.md index 7af163a57..14cc34c58 100644 --- a/docs/research/terminal-compose-context/directory-picker-follow-up.md +++ b/docs/research/terminal-compose-context/directory-picker-follow-up.md @@ -8,10 +8,11 @@ | --- | --- | --- | | A:路径与能力 | POSIX/Win32 路径模型;盘符/UNC 根;authority、cwd revision;独立 read/list/change/confirm 能力;可注入命令策略 | 将目标文件系统和 shell 语法分别建模,保持菜单可复用 | | B:PowerShell | 5.1/7 会话级脚本;原 runspace ProviderPath;私有位置报告;本地 FS;LiteralPath 切换和实际结果确认 | 用原 shell 状态串联展示、读取和执行 | +| C:CMD | 交互 CMD 的 PROMPT 上报;盘符目录读取与 `cd /d` 切换;原进程和新提示符确认 | 复用目录控制器,按 CMD 的变量展开和进程继承划定支持范围 | | 状态恢复 | provider 切换清空旧目录与列表;恢复 FileSystem 后重新读取;提交输入使旧报告失效 | 让菜单始终对应当前有效的文件系统位置 | | 生命周期 | 单会话请求排序、旧控制器失效、受管脚本清理、终端就绪门控 | 将异步操作与实际会话代次绑定 | -路径与状态回归覆盖盘符、UNC、链接、特殊字符、控制字节、草稿、广播隔离、重连和关闭芯片。Windows 原生 ConPTY 覆盖 PowerShell 5.1/7、PSDrive、provider、执行策略、状态码及真实 terminal bridge;现有 Windows CI 显式执行该组用例。macOS/Linux 继续覆盖真实 POSIX PTY 和 SSH fixture。 +Windows CI 使用原生 ConPTY 覆盖 PowerShell 5.1/7 以及 CMD 的特殊字符、跨盘符和嵌套会话。macOS/Linux 继续覆盖真实 POSIX PTY 和 SSH fixture。 ## 后续阶段 @@ -30,11 +31,9 @@ 交付目标是复用位置报告和控制器,保留原 prompt、PATH、历史与命令状态,按有效集成优先使用事件更新。 -### C:CMD 原生导航 +### CMD 覆盖扩展 -先完成 PROMPT、`cd /d`、命令扩展、delayed expansion、百分号/感叹号、编码和 ERRORLEVEL 的交互实验,再接入独立命令策略。 - -首个交付覆盖已验证的盘符绝对目录,并将路径限制体现为明确能力状态。UNC 的 pushd/popd 方案单独定义临时盘符、目录栈和退出清理语义。 +为 `%`、`!` 目录验证保留字面值的传递方式;为自定义 AutoRun、关闭命令扩展和前后台子进程补充原生用例。UNC 的 `pushd`/`popd` 单独定义临时盘符、目录栈和退出清理语义。 ### D:WSL、Git Bash 与 Cygwin diff --git a/domain/directoryPicker.ts b/domain/directoryPicker.ts index a07d05b99..2faee2824 100644 --- a/domain/directoryPicker.ts +++ b/domain/directoryPicker.ts @@ -3,7 +3,7 @@ import { resolveInteractiveTerminalCdIntent } from './sessionRestore'; import { isAbsoluteDirectoryPath, joinDirectoryPath, labelDirectoryPath, parentDirectoryPath, type DirectoryPathFlavor } from './directoryPath'; export type DirectoryEntry = { name: string; path: string; hidden: boolean }; -export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'nonFilesystem'; +export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'accessDenied' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'cmdIntegrationUnavailable' | 'nonFilesystem'; export class DirectoryPickerError extends Error { constructor(public readonly code: DirectoryPickerErrorCode) { super(code); } @@ -38,8 +38,14 @@ export const COMPLETE_DIRECTORY_CAPABILITIES: DirectoryCapabilities = Object.fre }); /** A shell adapter constructs input for the original interactive shell. */ -export function directoryChangeCommand(path: string, shell: 'posix' | 'powershell', flavor: DirectoryPathFlavor): string | null { +export function directoryChangeCommand(path: string, shell: 'posix' | 'powershell' | 'cmd', flavor: DirectoryPathFlavor): string | null { if (!isDirectoryPath(path, flavor)) return null; + if (shell === 'cmd') { + if (flavor !== 'win32' || !/^[a-z]:[\\/]/i.test(path) || /[%!]/.test(path)) return null; + // A leading space bypasses DOSKEY aliases. CMD expands % and ! in quotes. + const command = ` cd /d "${path.replace(/\//g, '\\')}"`; + return command.length <= 8191 ? command : null; + } // PowerShell recognizes smart single quotes as delimiters too. Doubling // only ASCII apostrophes would let a filename terminate the literal. if (shell === 'powershell') return `Microsoft.PowerShell.Management\\Set-Location -LiteralPath '${path.replace(/['\u2018\u2019\u201a\u201b]/g, quote => quote + quote)}'`; diff --git a/electron/bridges/cmdDirectoryIntegration.cjs b/electron/bridges/cmdDirectoryIntegration.cjs new file mode 100644 index 000000000..4bd29b95e --- /dev/null +++ b/electron/bridges/cmdDirectoryIntegration.cjs @@ -0,0 +1,98 @@ +const os = require('node:os'); +const path = require('node:path'); +const { randomBytes } = require('node:crypto'); +const { execFile } = require('node:child_process'); +const { createDirectoryReportStream } = require('./directoryReportStream.cjs'); + +const PROPERTY = '633;P;NetcattyCmdDirectory='; +const PREFIX = '\x1b]' + PROPERTY; + +function drivePath(value) { + return typeof value === 'string' && value.length <= 8192 && /^[a-z]:\\/i.test(value) + && !/[\x00-\x1f\x7f<>"|?*/:]/.test(value.slice(2)); +} + +function readWindowsProcessTree(pid, callback, { + loadNative = () => require('@vscode/windows-process-tree'), execFileFn = execFile, +} = {}) { + if (!Number.isSafeInteger(pid) || pid <= 0) return callback(null); + const fallback = () => { + const powershell = path.win32.join(process.env.SystemRoot || 'C:\\Windows', 'System32', + 'WindowsPowerShell', 'v1.0', 'powershell.exe'); + const command = `$ErrorActionPreference = 'Stop'; ` + + `$processes = @(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid} OR ParentProcessId = ${pid}"); ` + + `if (@($processes | Where-Object { $_.ProcessId -eq ${pid} -and $_.Name -eq 'cmd.exe' }).Count -eq 1 ` + + `-and $processes.Count -eq 1) { [Console]::WriteLine('idle') }`; + execFileFn(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command], { + windowsHide: true, timeout: 2800, maxBuffer: 64 * 1024, + }, (error, stdout) => callback(!error && stdout.trim() === 'idle' ? { pid, children: [] } : null)); + }; + try { + loadNative().getProcessTree(pid, tree => { + if (tree?.pid === pid && Array.isArray(tree.children)) callback(tree); + else fallback(); + }); + } catch { fallback(); } +} + +function isOriginalShellIdle(pid, getProcessTree) { + return new Promise(resolve => { + const timer = setTimeout(() => resolve(false), 3000); + const finish = ok => { clearTimeout(timer); resolve(ok); }; + try { + getProcessTree(pid, tree => finish(tree?.pid === pid && tree.children?.length === 0)); + } catch { finish(false); } + }); +} + +function createCmdDirectoryReader(nonce, home, getProcessTree = readWindowsProcessTree) { + let processId = null; + let revision = 0; + let state = null; + let pendingCheck = null; + return { + setProcessId(pid) { processId = pid; }, + invalidate() { state = null; }, + async read() { + const candidate = state; + const pid = processId; + // Nested CMD inherits PROMPT. Verify the original process has no active + // children and discard the result if the prompt changed during the check. + if (candidate && pid) { + if (pendingCheck?.candidate !== candidate || pendingCheck.pid !== pid) { + const promise = isOriginalShellIdle(pid, getProcessTree).finally(() => { + if (pendingCheck?.promise === promise) pendingCheck = null; + }); + pendingCheck = { candidate, pid, promise }; + } + if (await pendingCheck.promise && candidate === state && pid === processId) { + return { success: true, cwd: candidate.cwd, directoryState: candidate }; + } + } + return { success: false, error: 'CMD directory integration is not ready' }; + }, + consume: createDirectoryReportStream(PREFIX, value => { + const header = nonce + ';'; + if (!value.startsWith(header)) return; + const cwd = value.slice(header.length); + state = drivePath(cwd) ? { cwd, home: drivePath(home) ? home : null, provider: 'FileSystem', + revision: ++revision, shellKind: 'cmd', pathFlavor: 'win32' } : null; + }), + }; +} + +function prepareCmdDirectoryIntegration(shell, args, env, deps = {}) { + if ((deps.platform ?? process.platform) !== 'win32' || !/^cmd(\.exe)?$/i.test(path.win32.basename(shell)) + || !Array.isArray(args) || !args.every(arg => /^\/(d|q|e:on|v:(on|off))$/i.test(arg))) return null; + const nonce = randomBytes(32).toString('hex'); + // PROMPT expansion happens in CMD itself, preserving status and Unicode paths. + const key = Object.keys(env).find(name => name.toLowerCase() === 'prompt') ?? 'PROMPT'; + const prompt = env[key] || '$P$G'; + return { + args, + env: { [key]: `$E]${PROPERTY}${nonce};$P$E\\${prompt}` }, + reader: createCmdDirectoryReader(nonce, deps.home ?? os.homedir(), deps.getProcessTree), + }; +} + +module.exports = { PREFIX, createCmdDirectoryReader, prepareCmdDirectoryIntegration, readWindowsProcessTree }; diff --git a/electron/bridges/cmdDirectoryIntegration.test.cjs b/electron/bridges/cmdDirectoryIntegration.test.cjs new file mode 100644 index 000000000..a1e39344c --- /dev/null +++ b/electron/bridges/cmdDirectoryIntegration.test.cjs @@ -0,0 +1,64 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { PREFIX, createCmdDirectoryReader, prepareCmdDirectoryIntegration, readWindowsProcessTree } = require('./cmdDirectoryIntegration.cjs'); + +test('CMD prompt reports are session scoped, filtered and invalidated on new input', async () => { + const reader = createCmdDirectoryReader('session', 'C:\\Home', (pid, done) => done({ pid, children: [] })); + reader.setProcessId(10); + const frame = PREFIX + 'session;D:\\a & ^ ' + '\u4e2d\x1b\\'; + for (let i = 0; i < frame.length; i++) { + assert.equal(reader.consume('before' + frame.slice(0, i)) + reader.consume(frame.slice(i) + 'after'), 'beforeafter'); + assert.equal((await reader.read()).cwd, 'D:\\a & ^ \u4e2d'); + } + const before = await reader.read(); + assert.equal(reader.consume(PREFIX + 'other;C:\\bad\x07'), ''); + assert.deepEqual(await reader.read(), before); + reader.invalidate(); + assert.equal((await reader.read()).success, false); + reader.consume(PREFIX + 'session;D:\\\x07'); + assert.ok((await reader.read()).directoryState.revision > before.directoryState.revision); + reader.consume(PREFIX + 'session;\\\\server\\share\x07'); + assert.equal((await reader.read()).success, false); +}); + +test('CMD refuses nested or stale prompt reports while checking the original process', async () => { + let finish; + const reader = createCmdDirectoryReader('session', null, (_pid, done) => { finish = done; }); + reader.setProcessId(10); + reader.consume(PREFIX + 'session;C:\\base\x07'); + const nested = reader.read(); + finish({ pid: 10, children: [{ pid: 11 }] }); + assert.equal((await nested).success, false); + const stale = reader.read(); + reader.invalidate(); + finish({ pid: 10, children: [] }); + assert.equal((await stale).success, false); +}); + +test('CMD augments the inherited prompt and keeps custom launch arguments intact', () => { + const shell = 'C:\\Windows\\System32\\cmd.exe'; + const deps = { platform: 'win32' }; + const args = ['/d', '/v:on']; + const env = { Prompt: 'custom $P$G' }; + const plan = prepareCmdDirectoryIntegration(shell, args, env, deps); + assert.deepEqual(plan.args, args); + assert.match(plan.env.Prompt, /^\$E\]633;P;NetcattyCmdDirectory=[a-f0-9]{64};\$P\$E\\custom \$P\$G$/); + for (const unsupported of [['/c', 'echo hello'], ['/k', 'echo hello'], ['/e:off']]) { + assert.equal(prepareCmdDirectoryIntegration(shell, unsupported, env, deps), null); + } +}); + +test('CMD uses the Windows process query when the optional native module is absent', async () => { + const pid = 10; + const check = (error, stdout) => new Promise(resolve => readWindowsProcessTree(pid, resolve, { + loadNative: () => { throw new Error('optional module unavailable'); }, + execFileFn: (_file, args, options, done) => { + assert.match(args.at(-1), /ProcessId = 10 OR ParentProcessId = 10/); + assert.ok(options.windowsHide); + done(error, stdout); + }, + })); + assert.deepEqual(await check(null, 'idle\r\n'), { pid, children: [] }); + assert.equal(await check(null, ''), null); + assert.equal(await check(new Error('query failed'), 'idle'), null); +}); diff --git a/electron/bridges/directoryReportStream.cjs b/electron/bridges/directoryReportStream.cjs new file mode 100644 index 000000000..3d7da2c56 --- /dev/null +++ b/electron/bridges/directoryReportStream.cjs @@ -0,0 +1,41 @@ +const MAX_REPORT = 24 * 1024; + +/** Strip private OSC reports before forwarding terminal output. */ +function createDirectoryReportStream(prefix, onReport) { + let pending = ''; + let dropping = false; + return function consume(chunk) { + let input = pending + String(chunk); + pending = ''; + let output = ''; + while (input) { + if (dropping) { + const end = /\x07|\x1b\\/.exec(input); + if (!end) { pending = input.endsWith('\x1b') ? '\x1b' : ''; return output; } + input = input.slice(end.index + end[0].length); + dropping = false; + continue; + } + const start = input.indexOf(prefix); + if (start < 0) { + let keep = Math.min(input.length, prefix.length - 1); + while (keep > 0 && !prefix.startsWith(input.slice(-keep))) keep--; + pending = keep ? input.slice(-keep) : ''; + return output + input.slice(0, input.length - keep); + } + output += input.slice(0, start); + input = input.slice(start + prefix.length); + const end = /\x07|\x1b\\/.exec(input); + if (!end) { + if (input.length > MAX_REPORT) { dropping = true; pending = input.endsWith('\x1b') ? '\x1b' : ''; } + else pending = prefix + input; + return output; + } + if (end.index <= MAX_REPORT) onReport(input.slice(0, end.index)); + input = input.slice(end.index + end[0].length); + } + return output; + }; +} + +module.exports = { MAX_REPORT, createDirectoryReportStream }; diff --git a/electron/bridges/localSessionCwd.cjs b/electron/bridges/localSessionCwd.cjs index 6aa2ca1c3..7e7b4c296 100644 --- a/electron/bridges/localSessionCwd.cjs +++ b/electron/bridges/localSessionCwd.cjs @@ -99,7 +99,7 @@ function lsofBinaries(platform) { * * `cd` is a shell builtin, so the spawned process cwd changes even when the * shell never prints OSC 7. Linux reads `/proc//cwd`; macOS uses lsof - * because it has no procfs. Windows shells are not probed here. + * because it has no procfs. Integrated Windows shells report at the prompt. */ async function readLocalSessionCwd(session, deps = {}) { if ((deps.platform || process.platform) === 'win32' && session?.directoryIntegration) { diff --git a/electron/bridges/powerShellDirectoryIntegration.cjs b/electron/bridges/powerShellDirectoryIntegration.cjs index a1ddd83f3..d773cda2f 100644 --- a/electron/bridges/powerShellDirectoryIntegration.cjs +++ b/electron/bridges/powerShellDirectoryIntegration.cjs @@ -2,11 +2,11 @@ const fs = require('node:fs'); const path = require('node:path'); const { randomBytes } = require('node:crypto'); const tempDirBridge = require('./tempDirBridge.cjs'); +const { MAX_REPORT, createDirectoryReportStream } = require('./directoryReportStream.cjs'); // A private property on the existing OSC 633 property channel. Its payload is // consumed in the PTY owner, before logging, replay, prompt tracking or output. const PREFIX = '\x1b]633;P;NetcattyDirectory='; -const MAX_REPORT = 24 * 1024; function nativePath(value) { return typeof value === 'string' && value.length <= 8192 && !/[\x00-\x1f\x7f]/.test(value) @@ -15,12 +15,10 @@ function nativePath(value) { } function createDirectoryReportReader(nonce) { - let pending = ''; let revision = 0; let state = null; let processId = null; let sequence = 0; - let dropping = false; return { setProcessId(pid) { processId = pid; }, invalidate() { state = null; }, @@ -30,50 +28,20 @@ function createDirectoryReportReader(nonce) { error: state.provider === 'FileSystem' ? undefined : 'PowerShell location is not a filesystem', directoryState: { ...state, revision, shellKind: 'powershell', pathFlavor: 'win32' } }; }, - consume(chunk) { - let input = pending + String(chunk); - pending = ''; - let output = ''; - while (input) { - if (dropping) { - const end = /\x07|\x1b\\/.exec(input); - if (!end) { pending = input.endsWith('\x1b') ? '\x1b' : ''; return output; } - input = input.slice(end.index + end[0].length); - dropping = false; - continue; - } - const start = input.indexOf(PREFIX); - if (start < 0) { - let keep = Math.min(input.length, PREFIX.length - 1); - while (keep > 0 && !PREFIX.startsWith(input.slice(-keep))) keep--; - pending = keep ? input.slice(-keep) : ''; - return output + input.slice(0, input.length - keep); - } - output += input.slice(0, start); - input = input.slice(start + PREFIX.length); - const end = /\x07|\x1b\\/.exec(input); - if (!end) { - if (input.length > MAX_REPORT) { dropping = true; pending = input.endsWith('\x1b') ? '\x1b' : ''; } - else pending = PREFIX + input; - return output; - } - const payload = input.slice(0, end.index); - input = input.slice(end.index + end[0].length); - if (payload.length > MAX_REPORT || !/^[A-Za-z0-9+/]+={0,2}$/.test(payload)) continue; - try { - const report = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')); - if (report.version !== 1 || report.nonce !== nonce || report.pid !== processId - || !Number.isSafeInteger(report.sequence) || report.sequence <= sequence - || typeof report.provider !== 'string' || report.provider.length > 128) continue; - if (report.provider === 'FileSystem' && !nativePath(report.cwd)) continue; - sequence = report.sequence; - revision++; - state = { provider: report.provider, cwd: report.provider === 'FileSystem' ? report.cwd : null, - home: nativePath(report.home) ? report.home : null }; - } catch { /* Retain capability state only for validated reports. */ } - } - return output; - }, + consume: createDirectoryReportStream(PREFIX, payload => { + if (!/^[A-Za-z0-9+/]+={0,2}$/.test(payload)) return; + try { + const report = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')); + if (report.version !== 1 || report.nonce !== nonce || report.pid !== processId + || !Number.isSafeInteger(report.sequence) || report.sequence <= sequence + || typeof report.provider !== 'string' || report.provider.length > 128) return; + if (report.provider === 'FileSystem' && !nativePath(report.cwd)) return; + sequence = report.sequence; + revision++; + state = { provider: report.provider, cwd: report.provider === 'FileSystem' ? report.cwd : null, + home: nativePath(report.home) ? report.home : null }; + } catch { /* Retain capability state only for validated reports. */ } + }), }; } diff --git a/electron/bridges/terminalBridge.cjs b/electron/bridges/terminalBridge.cjs index a691c503d..a23cca6d6 100644 --- a/electron/bridges/terminalBridge.cjs +++ b/electron/bridges/terminalBridge.cjs @@ -65,6 +65,7 @@ const { isWindowsAppExecutionAliasPath } = require("../../lib/localShell.cjs"); const moshHandshake = require("./moshHandshake.cjs"); const tempDirBridge = require("./tempDirBridge.cjs"); const { preparePowerShellDirectoryIntegration } = require('./powerShellDirectoryIntegration.cjs'); +const { prepareCmdDirectoryIntegration } = require('./cmdDirectoryIntegration.cjs'); const { createTelnetAutoLogin, isAutoLoginWakeInput } = require("./telnetAutoLogin.cjs"); const telnetProtocol = require("./telnetProtocol.cjs"); const { createPtyOutputBuffer } = require("./ptyOutputBuffer.cjs"); @@ -1125,7 +1126,8 @@ async function startLocalSession(event, payload) { } } - const directoryIntegration = preparePowerShellDirectoryIntegration(shell, shellArgs); + const directoryIntegration = preparePowerShellDirectoryIntegration(shell, shellArgs) + ?? prepareCmdDirectoryIntegration(shell, shellArgs, env); let proc; try { proc = pty.spawn(shell, directoryIntegration?.args ?? shellArgs, { @@ -1139,7 +1141,7 @@ async function startLocalSession(event, payload) { useConptyDll: process.platform === "win32", }); } catch (error) { - directoryIntegration?.cleanup(); + directoryIntegration?.cleanup?.(); throw error; } directoryIntegration?.reader.setProcessId(proc.pid); @@ -1179,7 +1181,7 @@ async function startLocalSession(event, payload) { const { claimSessionSlot } = require("./sessionBootEpoch.cjs"); const claim = claimSessionSlot(sessions, sessionId, session, payload?.bootEpoch); if (!claim.ok) { - directoryIntegration?.cleanup(); + directoryIntegration?.cleanup?.(); try { proc.kill(); } catch { /* ignore */ } const supersededError = new Error("Local session superseded by a newer reconnect"); supersededError.code = "NETCATTY_BOOT_SUPERSEDED"; @@ -1279,7 +1281,7 @@ async function startLocalSession(event, payload) { const finalizeExit = () => { if (localExitFinalized) return; localExitFinalized = true; - directoryIntegration?.cleanup(); + directoryIntegration?.cleanup?.(); sessionLogStreamManager.stopStream(sessionId, logStreamToken); if (sessions.get(sessionId) !== session) return; ptyProcessTree.unregisterPid(sessionId); diff --git a/infrastructure/services/terminalDirectory.test.ts b/infrastructure/services/terminalDirectory.test.ts index 963228940..0a42d7293 100644 --- a/infrastructure/services/terminalDirectory.test.ts +++ b/infrastructure/services/terminalDirectory.test.ts @@ -45,6 +45,41 @@ test('Windows local IO never substitutes process cwd or home for absent integrat assert.equal(reads, 0); }); +test('CMD directory reads wait for a report from the expected shell', async () => { + const cwd = 'C:\\base'; + let shellKind: 'powershell' | 'cmd' | undefined; + let reads = 0; + const io = createTerminalDirectoryIO({ + getSessionPwd: async () => ({ success: true, cwd, directoryState: shellKind && { + revision: 1, provider: 'FileSystem', shellKind, pathFlavor: 'win32', cwd, home: null, + } }), + listLocalDir: async () => { reads++; return []; }, + } as unknown as NetcattyBridge, 'cmd', { local: true, hostname: '', username: '', pathFlavor: 'win32', windowsShell: 'cmd' }); + await assert.rejects(io.cwd(), { code: 'cmdIntegrationUnavailable' }); + shellKind = 'powershell'; + await assert.rejects(io.list(cwd), { code: 'cmdIntegrationUnavailable' }); + assert.equal(reads, 0); + shellKind = 'cmd'; + assert.equal(await io.cwd(), cwd); + assert.deepEqual(await io.list(cwd), { entries: [], home: null }); + assert.equal(reads, 1); +}); + +test('Windows local IO distinguishes denied listings from other read failures', async () => { + const cwd = 'C:\\legacy-junction'; + let failure = new Error("Error invoking remote method 'netcatty:local:list': Error: EPERM: operation not permitted, scandir"); + const io = createTerminalDirectoryIO({ + getSessionPwd: async () => ({ success: true, cwd, directoryState: { + revision: 1, provider: 'FileSystem', shellKind: 'cmd', pathFlavor: 'win32', cwd, home: null, + } }), + listLocalDir: async () => { throw failure; }, + } as unknown as NetcattyBridge, 'cmd', { local: true, hostname: '', username: '', pathFlavor: 'win32', windowsShell: 'cmd' }); + await assert.rejects(io.list(cwd), { code: 'accessDenied' }); + assert.equal(await io.cwd(), cwd); + failure = new Error('ENOENT: directory removed'); + await assert.rejects(io.list(cwd), failure); +}); + test('remote reads use only the exact terminal connection and always close their channel', async () => { const calls: unknown[] = []; const bridge = { diff --git a/infrastructure/services/terminalDirectory.ts b/infrastructure/services/terminalDirectory.ts index c78bbc69f..78fb3949a 100644 --- a/infrastructure/services/terminalDirectory.ts +++ b/infrastructure/services/terminalDirectory.ts @@ -14,12 +14,13 @@ export interface TerminalDirectoryIO { /** Uses the exact authenticated terminal transport; never dials another host. */ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: string, endpoint: { local: boolean; hostname: string; username: string; port?: number; encoding?: import('../../types').SftpFilenameEncoding; - pathFlavor?: DirectoryPathFlavor }, + pathFlavor?: DirectoryPathFlavor; windowsShell?: 'powershell' | 'cmd' }, isCurrent: () => boolean = () => true, ): TerminalDirectoryIO { const check = (signal?: AbortSignal) => { if (!isCurrent() || signal?.aborted) throw new DirectoryPickerError('unavailable'); }; const flavor = endpoint.pathFlavor ?? 'posix'; const nativeWindows = endpoint.local && flavor === 'win32'; + const windowsShell = endpoint.windowsShell ?? 'powershell'; let lastNativeRevision = 0; let submittedNativeRevision = -1; const valid = (path: string | null | undefined): path is string => isDirectoryPath(path, flavor); @@ -30,7 +31,9 @@ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: str }); check(); const state = result?.directoryState; - if (!state || state.shellKind !== 'powershell' || state.pathFlavor !== 'win32') throw new DirectoryPickerError('integrationUnavailable'); + if (!state || state.shellKind !== windowsShell || state.pathFlavor !== 'win32') { + throw new DirectoryPickerError(windowsShell === 'cmd' ? 'cmdIntegrationUnavailable' : 'integrationUnavailable'); + } if (state.provider !== 'FileSystem') throw new DirectoryPickerError('nonFilesystem'); if (!result.success || !valid(result.cwd) || !Number.isSafeInteger(state.revision) || state.revision < lastNativeRevision || state.revision <= submittedNativeRevision) throw new DirectoryPickerError('unknown'); @@ -77,7 +80,14 @@ export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: str if (!valid(path)) throw new DirectoryPickerError('unsupportedPath'); if (endpoint.local) { const native = nativeWindows ? await readNative() : null; - const files = await bridge.listLocalDir(path); + const files = await bridge.listLocalDir(path).catch((error: unknown) => { + // Electron IPC preserves the Node error message but drops its code. + if (nativeWindows && error instanceof Error && (/^(?:EACCES|EPERM)$/.test(String((error as NodeJS.ErrnoException).code)) + || /^(?:Error invoking remote method 'netcatty:local:list': )?(?:Error: )?(?:EACCES|EPERM):/.test(error.message))) { + throw new DirectoryPickerError('accessDenied'); + } + throw error; + }); check(signal); const home = nativeWindows ? native!.home : await bridge.getHomeDir?.().catch(() => null) ?? null; check(signal); diff --git a/infrastructure/services/terminalDirectory.windows.test.ts b/infrastructure/services/terminalDirectory.windows.test.ts index 448419d7e..d4a70bd45 100644 --- a/infrastructure/services/terminalDirectory.windows.test.ts +++ b/infrastructure/services/terminalDirectory.windows.test.ts @@ -207,3 +207,89 @@ test('real Windows terminal bridge strips reports and invalidates runspace cwd o assert.equal(session.directoryIntegration.read().success, false, 'direct AI/snippet PTY writes invalidate reports too'); await waitFor(() => session.directoryIntegration.read().success); }); + +test('native CMD lists and changes directories through the original ConPTY session', { + skip: !enabled, timeout: 60000, +}, async t => { + const bridge = require('../../electron/bridges/terminalBridge.cjs'); + const tempDir = require('../../electron/bridges/tempDirBridge.cjs'); + const { readLocalSessionCwd } = require('../../electron/bridges/localSessionCwd.cjs'); + tempDir.ensureTempDir(); + const fixture = fs.realpathSync.native(fs.mkdtempSync(tempDir.getTempFilePath('native-cmd-directory-'))); + const id = 'bridge-native-cmd'; + const target = path.join(fixture, 'space & (parentheses) ^ \u4e2d'); + const expandable = path.join(fixture, '%PATH%!'); + fs.mkdirSync(target); + fs.mkdirSync(expandable); + const sessions = new Map(); + let output = ''; + let proc: import('node-pty').IPty | undefined; + let exited = Promise.resolve(); + t.after(async () => { + proc?.kill(); + let timer: ReturnType | undefined; + await Promise.race([exited, new Promise(resolve => { timer = setTimeout(resolve, 5000); })]); + clearTimeout(timer); + await fs.promises.rm(fixture, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }); + }); + const sender = Object.assign(new EventEmitter(), { id: 113, isDestroyed: () => false, + send(channel: string, payload: { data?: string }) { if (channel === 'netcatty:data') output += payload.data ?? ''; } }); + bridge.init({ sessions, electronModule: { webContents: { fromId: () => sender } } }); + await bridge.startLocalSession({ sender }, { sessionId: id, shell: process.env.ComSpec || 'cmd.exe', + shellArgs: ['/d', '/e:on', '/v:on'], cwd: fixture, cols: 250 }); + const session = sessions.get(id); + proc = session.proc; + exited = new Promise(resolve => { proc!.onExit(() => resolve()); }); + const read = () => readLocalSessionCwd(session); + const waitFor = async (condition: () => boolean | Promise) => { + const deadline = Date.now() + 12000; + while (Date.now() < deadline) { + if (await condition()) return; + await new Promise(resolve => setTimeout(resolve, 25)); + } + assert.fail(output.slice(-2000)); + }; + const send = (data: string) => bridge.writeToSession({}, { sessionId: id, data }); + const io = createTerminalDirectoryIO({ + getSessionPwd: async () => read(), + listLocalDir: async (cwd: string) => fs.readdirSync(cwd, { withFileTypes: true }).map(entry => ({ name: entry.name, type: entry.isDirectory() ? 'directory' : 'file' })), + realpathLocal: async (cwd: string) => fs.realpathSync.native(cwd), + writeToSession: (_id: string, data: string) => send(data), + } as unknown as NetcattyBridge, id, { local: true, hostname: 'localhost', username: '', pathFlavor: 'win32', windowsShell: 'cmd' }); + const controller = createTerminalDirectoryController({ sessionId: id, io, isCurrent: () => true, isReady: () => true, + target: { authority: id, pathFlavor: 'win32' }, publish: () => {}, + buildChangeCommand: value => directoryChangeCommand(value, 'cmd', 'win32') }); + const signal = new AbortController().signal; + t.after(() => controller.dispose()); + await waitFor(async () => (await read()).cwd === fixture); + const outputStart = output.length; + send('doskey cd=echo CMD_ALIAS\r'); + await waitFor(async () => output.slice(outputStart).includes(fixture + '>') && (await read()).cwd === fixture); + assert.deepEqual((await controller.list(fixture, signal)).entries.map(entry => entry.path).sort(), [expandable, target].sort()); + await assert.rejects(controller.change(expandable, signal, () => assert.fail('unsafe path was sent')), { code: 'unsupportedPath' }); + await controller.change(target, signal, () => {}); + assert.equal(await controller.refresh(), target); + await controller.change(fixture, signal, () => {}); + assert.equal(await controller.refresh(), fixture); + + // A nested CMD inherits the private prompt, but cannot authorize operations. + send('cmd /d\r'); + const nestedStart = output.length; + await waitFor(() => output.slice(nestedStart).includes('(c) Microsoft Corporation')); + await waitFor(() => output.slice(nestedStart).includes(fixture + '>')); + assert.equal((await read()).success, false); + await assert.rejects(io.list(fixture), { code: 'cmdIntegrationUnavailable' }); + send('exit\r'); + await waitFor(async () => (await read()).cwd === fixture); + assert.ok(!output.includes('NetcattyCmdDirectory=')); + + // A temporary drive proves that /d switches the active drive as well as cwd. + const drive = 'ZYXWVUT'.split('').map(letter => letter + ':').find(candidate => !fs.existsSync(candidate + '\\')); + assert.ok(drive, 'available temporary drive'); + execFileSync('subst.exe', [drive, fixture]); + try { + await controller.change(drive + '\\', signal, () => {}); + assert.equal(await controller.refresh(), drive + '\\'); + await controller.change(fixture, signal, () => {}); + } finally { execFileSync('subst.exe', [drive, '/d']); } +}); diff --git a/types/global/netcatty-bridge-session.d.ts b/types/global/netcatty-bridge-session.d.ts index c00a16eb7..768461174 100644 --- a/types/global/netcatty-bridge-session.d.ts +++ b/types/global/netcatty-bridge-session.d.ts @@ -253,7 +253,7 @@ declare global { }, ): Promise<{ success: boolean; cwd?: string; error?: string; directoryState?: { revision: number; - shellKind: 'powershell'; + shellKind: 'powershell' | 'cmd'; pathFlavor: 'win32'; provider: string; cwd: string | null;