From f6f7629b236d307445cd101da1d5197592a6f625 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 22:57:16 +0800 Subject: [PATCH] =?UTF-8?q?fix(open-external):=20Windows=E3=80=8C=E5=9C=A8?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E4=B8=AD=E6=89=93=E5=BC=80=E3=80=8D=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=20cmd=20start=20=E2=86=92=20rundll32=20=E5=80=99?= =?UTF-8?q?=E9=80=89=E9=93=BE=EF=BC=8C=E5=85=A8=E5=A4=B1=E8=B4=A5=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E9=9D=99=E9=BB=98=E6=88=90=E5=8A=9F=EF=BC=88#412?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 现象(#412):Windows 上右键「在应用中打开」经常没反应。核实:`urlCommand` 的 win32 分支 只有 `rundll32.exe url.dll,FileProtocolHandler ` 一条候选,而 rundll32.exe 在任何 Windows 上都存在、spawn 必然成功 → 路由回 `{started:true}`,UI 拿不到任何失败信息。 修法: ① `urlCommand` → `urlCommands(...): ExternalCommand[]`(有序候选链):win32 为 `cmd.exe /d /c start "" ` → `rundll32.exe url.dll,FileProtocolHandler ` (空首参是 start 的窗口标题,缺了它带引号的 URL 会被当成标题、只弹空控制台); darwin / linux / android / WSL 仍是单元素,语义逐字不变。 ② URL 含 cmd 元字符(& % ^ ! | < > ")或控制字符时**跳过 cmd 分支**直接走 rundll32: Node 的 argv 引用拦不住 `cmd /c` 的第二次解析(%VAR% 展开、&/| 截断、^ 吞字符、" 打乱引用),而 rundll32 以单个 argv 收到 URL、什么都不解释。 ③ `launchExternal` 顺序尝试候选:只有 Node 发出 `spawn` 才算成功,同步抛错与 `error` 事件都推进到下一候选;**全部候选失败**时抛 `SidebarError('internal', …)`,消息里逐个 列出命令与底层报错(走既有 `{ok:false,error:{code,message}}` 信封)。 ④ 调用方一并改形状:`EditorHost.openWith` 返回「是否被接受」(失败仍 console.error 留痕), `FileTree` 据此把失败渲染进既有 `openInAppFailed` 错误条——复用词条,未新增词典 key。 测试: - tests/open-external.spec.ts:候选链顺序、元字符跳过规则、空格 URL 仍是单个 argv、 失败回退顺序、全失败错误形状(含 `&` URL 只尝试 rundll32、reveal 分支的 path 措辞)。 - tests/open-external-windows.spec.ts(Windows lane,pnpm test:windows):只注入两个 「不可能存在」的可执行名(`WindowsOpenerOptions` 测试缝),走**真实 spawn** 断言两条 候选都失败时错误被回报而不是静默成功;**绝不拉起任何应用**(detached:true 会开真窗口, 所以生产命令名一个都不在测试里出现)。 - tests/file-tree-open-with.spec.tsx / tests/editor-host.spec.tsx:被拒(返回 false)与 抛错的打开都必须落进错误条,console-only 即红。 判别性(临时还原源码改动后跑新增用例,随后逐字恢复、md5 校验一致): - 候选链退回单 rundll32(`if (false && …)`)→ 9 red(含 Windows lane 两条) - spawn error 仍回 `{started:true}`(旧的「从不失败」契约)→ 6 red - 去掉元字符跳过 → 11 red - FileTree 不再上报失败 → 3 red - EditorHost 恢复吞错 → 1 red 限制(写入设计文档):`start` 与 rundll32 在 handler 忽略 URL 时都退出 0, 「已启动但没打开」仍不可从退出码探测。 --- .../plans/2026-08-22-open-with-menu-design.md | 8 +- src/client/EditorHost.tsx | 37 ++-- src/client/FileTree.tsx | 16 +- src/client/TreePanel.tsx | 4 +- src/open-external.ts | 189 ++++++++++++++---- tests/editor-host.spec.tsx | 62 +++++- tests/file-tree-open-with.spec.tsx | 35 ++++ tests/open-external-windows.spec.ts | 77 +++++++ tests/open-external.spec.ts | 182 ++++++++++++++++- 9 files changed, 538 insertions(+), 72 deletions(-) create mode 100644 tests/open-external-windows.spec.ts diff --git a/docs/plans/2026-08-22-open-with-menu-design.md b/docs/plans/2026-08-22-open-with-menu-design.md index 4d560c43..6fb9392a 100644 --- a/docs/plans/2026-08-22-open-with-menu-design.md +++ b/docs/plans/2026-08-22-open-with-menu-design.md @@ -100,13 +100,17 @@ Cursor (SSH) - SSH 模式为**全局**(非每会话):DSH 无远程会话概念,文件树路径即宿主路径;该模型对应"DSH 跑在远端开发机上"的场景。 - 子菜单钳制为方向翻转而非高度裁剪:约 >15 个打开方式目标 + 矮视口 + 不利光标位仍可能溢出(compact 密度已把常规 4–8 目标场景收进安全区)。 - 翻转阈值镜像宿主 `Menu.module.css` 几何常量(218/10/165/12):宿主未来改尺寸时阈值偏保守(多翻一次方向),不会产生新越界;菜单打开期间窗口 resize 不重算 token,该次打开最坏退化为原始行为。 +- **「已启动但没打开」不可探测**(#412 修复后仍成立):`start` 与 rundll32 在 handler 忽略 URL 时都退出 0,链只能观测「这一步有没有启动起来」,观测不到 Windows 侧协议 handler 是否真的做了事。 + +**实施偏差(2026-10,#412 Windows「在应用中打开」没反应)**:上面的 `url` 分支在 win32 上**只有一个候选**(`rundll32`),而 `rundll32.exe` 在任何 Windows 上都存在、spawn 必然成功 → 路由照旧回 `{started: true}`、UI 毫无反馈——这就是 issue 里的「没反应」。四处改动:① `urlCommand` → **`urlCommands(url, platform, options): ExternalCommand[]`**(有序候选链;darwin/linux/android/WSL 仍是单元素,语义逐字不变),win32 链为 `cmd.exe /d /c start "" ` → `rundll32.exe url.dll,FileProtocolHandler `(空首参是 `start` 的窗口标题,缺了它带引号的 URL 会被当成标题、只弹一个空控制台)。② URL 含 cmd 元字符 `& % ^ ! | < > "` 或控制字符时**跳过 cmd 分支**:Node 的 argv 引用拦不住 `cmd /c` 的第二次解析,`%VAR%` 会展开、`&`/`|` 会截断命令、`^` 会吞掉后一个字符、`"` 会打乱引用,直接走 rundll32(它以单个 argv 收到 URL,什么都不解释)。③ `launchExternal` 改为**顺序尝试候选**:只有 Node 发出 `spawn` 才算成功,同步抛错与 `error` 事件都推进到下一候选;**全部候选失败**时抛 `SidebarError('internal', …)`,消息里逐个列出命令与底层报错(走既有 `{ok:false,error:{code,message}}` 信封,UI 可提示)。④ 调用方一并改形状:`EditorHost.openWith` 返回「是否被接受」(失败仍 `console.error` 留痕),`FileTree` 据此把失败渲染进既有的 `openInAppFailed` 提示条——**复用词条,未新增任何词典 key**。测试缝 `WindowsOpenerOptions`(`cmdExecutable` / `rundll32Executable`)只为把两个可执行名换成「不可能存在」,从而让 **Windows lane 用真实 `spawn`** 断言失败被回报(见下);生产代码永不设置它,也**绝不**在测试里拉起真的 `cmd.exe` / `rundll32.exe`(`detached: true` 会在 runner 上开真窗口)。`reveal` 侧未加同名缝:win32 只有 `explorer.exe` 一条,注入真名就等于在 CI 上开资源管理器窗口。 ## 测试 - `tests/open-with.spec.ts`:解析容错、目标解析与 SSH 过滤、URL 构建(本地/SSH/custom/坏模板)、校验器。 -- `tests/open-external.spec.ts`:三平台命令表、URL 校验、spawn 前校验。 +- `tests/open-external.spec.ts`:三平台命令表(`urlCommands` 候选链与顺序)、`& % ^ ! | < > "` 的 cmd 跳过规则、空格 URL 仍是单个 argv、失败回退顺序、全失败时的错误形状、URL 校验、spawn 前校验。 +- `tests/open-external-windows.spec.ts`(#412,Windows lane):注入两个不存在的可执行名 + **真实 `spawn`**,断言两条候选都失败时错误被回报(而不是静默 `{started: true}`),且 `&` URL 只尝试 rundll32;**全程不拉起任何应用**。 - `tests/open-external-client.spec.ts`(#522):SSH remote URL 客户端分流(不触 fetch)、本地/reveal/http(s) 留宿主、导航抛错 reject。 -- `tests/file-tree-open-with.spec.tsx`(jsdom):右键 → 子菜单/图钉;pin 不选中不关闭;选子项回调关闭菜单;SSH 标签后缀;未接线隐藏;翻转向量(down / down left / 卸载清理)。 +- `tests/file-tree-open-with.spec.tsx`(jsdom):右键 → 子菜单/图钉;pin 不选中不关闭;选子项回调关闭菜单;SSH 标签后缀;未接线隐藏;翻转向量(down / down left / 卸载清理);被拒/抛错的打开落进错误条(#412)。 - `tests/menu-flip.spec.tsx`:方向 token 纯函数(四象限、边界、窄面板)+ hook 属性生命周期 + layout.css 选择器与属性名的跨文件一致性。 - `tests/tab-bar-context-menu.spec.tsx`:追加翻转向量(顶部条 down、右缘 down left、下半空 token、卸载清理)。 - `tests/e2e/mount.e2e.ts`:「+」菜单首行 computed 高度 ≤30px(compact 密度的布局级证据)。 diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index d692be41..b7ddb652 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -100,6 +100,18 @@ function clampTreeWidth(value: number): number { return Math.min(TREE_WIDTH_MAX, Math.max(TREE_WIDTH_MIN, Math.round(value))) } +/** Whether one external-open call was accepted: a rejected launch is logged + * for diagnosis and answered `false`, so the caller can surface it. */ +function accepted(pending: Promise): Promise { + return pending.then( + () => true, + (error: unknown) => { + console.error('open external failed', error) + return false + }, + ) +} + export function EditorHost(props: { ctx: Context store: SidebarStore @@ -254,22 +266,23 @@ export function EditorHost(props: { * manager, or hand the target's URL to its opener — local `file` URLs go * to the host's external opener, while the SSH-remote form for * VSCode-family editors launches on the browser/client machine (see - * api.openExternal). Failures are logged only — a missing handler is the - * OS's/browser's dialog, not a sidebar error. */ - const openWith = (targetId: string, absolute: string): void => { + * api.openExternal). + * + * Answers whether the hand-off was accepted. The host route now reports a + * real failure when EVERY opener candidate fails (see + * `src/open-external.ts`) instead of the old silent `{ started: true }`, so + * a refusal is returned to the tree, which renders it — the log stays for + * diagnosis. A missing handler on the other machine is still the OS's or + * browser's own dialog. */ + const openWith = (targetId: string, absolute: string): Promise => { const target = openWithTargets.find(item => item.id === targetId) - if (target === undefined) return + if (target === undefined) return Promise.resolve(false) if (target.kind === 'reveal') { - void api.openExternal({ action: 'reveal', path: absolute }).catch( - (error: unknown) => { console.error('open external failed', error) }, - ) - return + return accepted(api.openExternal({ action: 'reveal', path: absolute })) } const url = openWithUrl(target, absolute, openWithConfig) - if (url === undefined) return - void api.openExternal({ action: 'url', url }).catch( - (error: unknown) => { console.error('open external failed', error) }, - ) + if (url === undefined) return Promise.resolve(false) + return accepted(api.openExternal({ action: 'url', url })) } /** Toggle one target's pinned state. The write is serialized (see diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index f97dc18e..64e69f57 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -459,8 +459,10 @@ export function FileTree(props: { openWithPinned?: string[] /** Whether the workspace is remote (appends the SSH hint to target labels). */ openWithSsh?: boolean - /** Open one plugin target externally (reveal or URL — the caller decides). */ - onOpenWith?: (targetId: string, path: string) => void + /** Open one plugin target externally (reveal or URL — the caller decides). + * It answers `false` (or rejects) when the hand-off did not happen, and the + * strip then reports it exactly like the host-backed rows. */ + onOpenWith?: (targetId: string, path: string) => void | boolean | Promise /** Toggle one plugin target's pinned state (the submenu row's pushpin). */ onToggleOpenWithPin?: (targetId: string) => void /** Insert `@` into the composer draft (file vs directory). */ @@ -1988,7 +1990,15 @@ export function FileTree(props: { // The plugin's own targets share one id space (pinned rows and // submenu children alike), so the caller gets the target id + path. if (id.startsWith('open-with:')) { - onOpenWith?.(id.slice('open-with:'.length), target.path) + // The caller owns the launch and answers whether it was accepted; + // a refusal (or a rejection) means nothing opened, so the failure + // lands in the same strip as the host-backed rows instead of only + // reaching the console (#412 was silence in this exact spot). + const pending = onOpenWith?.(id.slice('open-with:'.length), target.path) + void Promise.resolve(pending).then( + (accepted) => { if (accepted === false) reportOpenFailure(target.path) }, + () => { reportOpenFailure(target.path) }, + ) return } if (id === 'reveal-in-file-manager') { diff --git a/src/client/TreePanel.tsx b/src/client/TreePanel.tsx index 8e35aad7..4e413e2a 100644 --- a/src/client/TreePanel.tsx +++ b/src/client/TreePanel.tsx @@ -67,7 +67,9 @@ export function TreePanel(props: { openWithTargets?: OpenWithTarget[] openWithPinned?: string[] openWithSsh?: boolean - onOpenWith?: (targetId: string, path: string) => void + /** Open one plugin target (passed through to FileTree; `false`/rejection → + * the tree reports the failure in its strip). */ + onOpenWith?: (targetId: string, path: string) => void | boolean | Promise onToggleOpenWithPin?: (targetId: string) => void /** Show the plugin's own open-with targets even when the host lists local * applications for the path (the `openWithPluginTargets` setting; passed diff --git a/src/open-external.ts b/src/open-external.ts index 7fa14aaa..5140b133 100644 --- a/src/open-external.ts +++ b/src/open-external.ts @@ -30,12 +30,31 @@ export interface WslCommandOptions { windowsExecutable?: (path: string) => string } +/** + * Injectable Windows opener NAMES — a test-only seam, never set in production. + * + * Pointing them at executables that cannot exist lets the REAL `spawn` drive + * the whole fallback chain and its failure reporting on a real Windows runtime + * (see tests/open-external-windows.spec.ts) without launching an application: + * a binary that does not exist cannot start a browser, an editor or a console + * window on the runner. + */ +export interface WindowsOpenerOptions { + /** The `cmd.exe` that runs the `start` branch. */ + cmdExecutable?: string + /** The `rundll32.exe` that runs the `url.dll,FileProtocolHandler` branch. */ + rundll32Executable?: string +} + +/** Every command-builder seam: WSL path/executable projection + Windows opener names. */ +export type OpenerCommandOptions = WslCommandOptions & WindowsOpenerOptions + /** Runtime seams used only to make launch/error behavior testable off-host. */ export interface LaunchExternalOptions { platform?: NodeJS.Platform wsl?: boolean distroName?: string - commandOptions?: Omit + commandOptions?: Omit spawn?: typeof spawn } @@ -105,33 +124,75 @@ export function revealCommand( } } -/** Hand a custom-scheme URL to the OS protocol handler. WSL must dispatch to - * Windows because the registered desktop handlers live on that side. */ -export function urlCommand( +/** + * Characters `cmd.exe` interprets after Node has quoted each argv element for + * CreateProcess: `cmd /c` parses the command line AGAIN, so `%VAR%` expands, + * `&`/`|` split the command, `<`/`>` redirect, `^` escapes the next character, + * `!` triggers delayed expansion and `"` re-balances the quoting. A URL + * carrying any of them never reaches the `start` branch — it goes straight to + * rundll32, which receives the URL as one argv element and interprets nothing. + */ +const CMD_METACHARACTERS = /[&%^!|<>"]/ + +/** C0/C1 control characters count as metacharacters too: `cmd.exe` treats a + * raw CR/LF as a command separator, and `validateExternalUrl` returns the + * RAW string (`new URL` strips those characters, so validation passes). */ +const CMD_CONTROL_CHARACTERS = /\p{Cc}/u + +/** Whether `cmd.exe` would reinterpret any part of this URL — i.e. the `start` + * branch must be skipped and rundll32 used directly. */ +function cmdUnsafe(url: string): boolean { + return CMD_METACHARACTERS.test(url) || CMD_CONTROL_CHARACTERS.test(url) +} + +/** + * The URL openers to try, best first — the Windows chain exists because the + * `start` route and the rundll32 route fail in disjoint situations (#412: + * rundll32 alone reported `{ started: true }` while nothing opened). + * + * Every entry is an argv array (never a shell string). macOS/Linux keep their + * single opener and WSL keeps its single absolute-path Windows dispatcher (the + * registered handlers live on the Windows side of the interop boundary): this + * chain is a Windows fix, so their behavior is unchanged. + */ +export function urlCommands( url: string, platform: NodeJS.Platform = process.platform, - options: WslCommandOptions = {}, -): ExternalCommand { + options: OpenerCommandOptions = {}, +): ExternalCommand[] { switch (platform) { case 'darwin': - return { command: 'open', args: [url] } - // url.dll,FileProtocolHandler launches the registered protocol handler; - // `cmd /c start "" ` is the fallback if rundll32 misbehaves. - case 'win32': - return { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] } + return [{ command: 'open', args: [url] }] + case 'win32': { + const chain: ExternalCommand[] = [] + if (!cmdUnsafe(url)) { + // `start "" `: the empty argument is the window TITLE. Without it + // `start` treats the quoted URL as the title and opens a bare console + // window instead of the registered handler. + chain.push({ command: options.cmdExecutable ?? 'cmd.exe', args: ['/d', '/c', 'start', '', url] }) + } + // url.dll,FileProtocolHandler launches the registered protocol handler + // through ShellExecute (the route that historically worked for schemes + // `start` refused, and vice versa). + chain.push({ + command: options.rundll32Executable ?? 'rundll32.exe', + args: ['url.dll,FileProtocolHandler', url], + }) + return chain + } // Termux: `termux-open-url` is the Android intent dispatcher for URLs // (termux-open would route through the content chooser first). case 'android': - return { command: 'termux-open-url', args: [url] } + return [{ command: 'termux-open-url', args: [url] }] default: if (options.wsl) { const windowsExecutable = options.windowsExecutable ?? windowsExecutableOf - return { + return [{ command: windowsExecutable('C:\\Windows\\System32\\rundll32.exe'), args: ['url.dll,FileProtocolHandler', url], - } + }] } - return { command: 'xdg-open', args: [url] } + return [{ command: 'xdg-open', args: [url] }] } } @@ -174,14 +235,78 @@ function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error) } -function launchFailure(command: string, error: unknown): SidebarError { - return new SidebarError('internal', `failed to launch external opener "${command}": ${messageOf(error)}`, 500) +/** One attempted launch that failed; kept for the aggregated error message. */ +interface LaunchAttemptFailure { + command: string + error: unknown +} + +/** The structured failure of an action whose EVERY opener candidate died: + * `internal` on the wire, with each command and its underlying message named + * so the UI (and a bug report) can carry the real cause. */ +function launchFailure(action: OpenExternalAction, failures: readonly LaunchAttemptFailure[]): SidebarError { + const subject = action === 'url' ? 'url' : 'path' + const attempts = failures.map(f => `"${f.command}" (${messageOf(f.error)})`).join('; ') + return new SidebarError('internal', `failed to launch external opener for the ${subject}: ${attempts}`, 500) } /** - * Launch one external open action detached from the host. Success is reported - * only after Node emits `spawn`; an ENOENT/permission failure now rejects the - * route instead of being swallowed after `{ started: true }` was returned. + * Launch the first candidate that actually starts, in order. + * + * Success is reported only after Node emits `spawn`; a synchronous throw or an + * `error` event (ENOENT, EACCES, …) advances to the next candidate. When every + * candidate fails the promise rejects with a structured `SidebarError` naming + * them all — the route must never answer `{ started: true }` for an open that + * launched nothing (#412: that silent success is why the menu "did nothing"). + * + * Note what this can and cannot see: a detached candidate that starts but + * whose handler ignores the URL exits 0 (`start` and rundll32 both do), so the + * chain reports everything it can observe — the launch itself. + */ +function launchChain( + action: OpenExternalAction, + chain: readonly ExternalCommand[], + spawnExternal: typeof spawn, +): Promise<{ started: true }> { + const failures: LaunchAttemptFailure[] = [] + return new Promise((resolve, reject) => { + const attempt = (index: number): void => { + const spec = chain[index] + if (spec === undefined) { + reject(launchFailure(action, failures)) + return + } + let child: ReturnType + try { + child = spawnExternal(spec.command, spec.args, { detached: true, stdio: 'ignore' }) + } catch (error) { + failures.push({ command: spec.command, error }) + attempt(index + 1) + return + } + let settled = false + child.once('spawn', () => { + if (settled) return + settled = true + resolve({ started: true }) + }) + child.once('error', (error) => { + if (settled) return + settled = true + failures.push({ command: spec.command, error }) + attempt(index + 1) + }) + child.unref() + } + attempt(0) + }) +} + +/** + * Launch one external open action detached from the host. Both actions fan out + * through an ordered candidate chain (one entry on macOS/Linux/Android/WSL, the + * two Windows URL routes on win32) and reject with the aggregated failure when + * none of them starts. */ export function launchExternal( action: OpenExternalAction, @@ -190,28 +315,18 @@ export function launchExternal( ): Promise<{ started: true }> { const platform = options.platform ?? process.platform const wsl = options.wsl ?? (platform === 'linux' && isWslRuntime()) - const commandOptions: WslCommandOptions = { ...options.commandOptions, wsl } + const commandOptions: OpenerCommandOptions = { ...options.commandOptions, wsl } - let spec: ExternalCommand + // Validation stays synchronous and ahead of every spawn: a relative path or + // a non-scheme URL throws here, so nothing is launched for a bad request. + let chain: ExternalCommand[] if (action === 'reveal') { - spec = revealCommand(requireAbsolute(value), platform, commandOptions) + chain = [revealCommand(requireAbsolute(value), platform, commandOptions)] } else { let url = validateExternalUrl(value) if (wsl) url = wslRemoteEditorUrl(url, options.distroName ?? process.env.WSL_DISTRO_NAME ?? '') - spec = urlCommand(url, platform, commandOptions) + chain = urlCommands(url, platform, commandOptions) } - const spawnExternal = options.spawn ?? spawn - let child: ReturnType - try { - child = spawnExternal(spec.command, spec.args, { detached: true, stdio: 'ignore' }) - } catch (error) { - return Promise.reject(launchFailure(spec.command, error)) - } - - return new Promise((resolve, reject) => { - child.once('spawn', () => { resolve({ started: true }) }) - child.once('error', (error) => { reject(launchFailure(spec.command, error)) }) - child.unref() - }) + return launchChain(action, chain, options.spawn ?? spawn) } diff --git a/tests/editor-host.spec.tsx b/tests/editor-host.spec.tsx index 1b082388..50a4ed98 100644 --- a/tests/editor-host.spec.tsx +++ b/tests/editor-host.spec.tsx @@ -15,6 +15,7 @@ import { createRoot } from 'react-dom/client' import { act } from 'react-dom/test-utils' import type { Context } from '../src/context-types.ts' import { EditorHost } from '../src/client/EditorHost.tsx' +import { api } from '../src/client/api.ts' import { createBetterSidebarService, type FileViewerProps } from '../src/client/service.ts' import { allLeaves, createSidebarStore, type SidebarTab } from '../src/client/state.ts' @@ -37,7 +38,9 @@ vi.mock('../src/client/api.ts', () => ({ gitStatus: async () => ({ isRepo: false, entries: [] }), archiveBuild: async () => ({ id: 'ar-1', entries: 1 }), archiveStatus: async () => ({ state: 'ready', done: 1, total: 1, bytes: 1 }), - openExternal: async () => ({ started: true }), + // A `vi.fn` so the external-open cases can drive a refusal: the host route + // reports a real failure since #412 instead of a silent `{ started: true }`. + openExternal: vi.fn(async () => ({ started: true })), }, archiveDownloadUrl: () => '/sidebar/archive?id=ar-1', downloadUrl: () => '/sidebar/file', @@ -481,12 +484,19 @@ describe('EditorHost (files window)', () => { }) /** - * "Open to the Side" from a NATIVE tab must reach the host's own split, not - * the plugin's bottom workbench: a native right-Sidebar tab is absent from - * `bottomSplits`, so the old code fell through to `firstLeaf` — a pane the - * user had not expanded, i.e. "the menu item does nothing". + * Context-menu actions of a NATIVE tab's tree panel. + * + * "Open to the Side" must reach the host's own split, not the plugin's bottom + * workbench: a native right-Sidebar tab is absent from `bottomSplits`, so the + * old code fell through to `firstLeaf` — a pane the user had not expanded, + * i.e. "the menu item does nothing". + * + * "Open with" rows hand the launch to the host route; since #412 that route + * reports a real failure instead of a silent `{ started: true }`, so a refused + * launch must reach the tree's error strip (console-only feedback was the + * reported "no reaction"). */ -describe('EditorHost "open to the side"', () => { +describe('EditorHost native-tab context-menu actions', () => { /** A service whose openTab calls are recorded (surface undefined = native). */ function spyService(store: ReturnType): { service: ReturnType @@ -640,4 +650,44 @@ describe('EditorHost "open to the side"', () => { unmount() } }) + + it('reports a refused external open in the tree strip, not only in the console (#412)', async () => { + const store = createSidebarStore() + const { service } = spyService(store) + service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null }) + store.setSession('editor-home-session') + const ctx = fakeCtx(service) + // The failure the host route now reports when EVERY opener branch dies. + vi.mocked(api.openExternal).mockRejectedValueOnce(new Error('spawn cmd.exe ENOENT')) + const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { container, unmount } = await mountNative(ctx, store, service) + try { + const row = [...container.querySelectorAll('[role="button"]')] + .find(el => el.querySelector('[class*="explorerName"]')?.textContent === 'a.ts') + expect(row).toBeDefined() + act(() => { + row!.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 })) + }) + const parent = [...document.querySelectorAll('[role="menuitem"]')] + .find(el => el.getAttribute('aria-haspopup') === 'menu') + expect(parent).toBeDefined() + act(() => { parent!.click() }) + const vscodeRow = [...document.querySelectorAll('[role="menu"] [role="menu"] [role="menuitem"]')] + .find(el => el.textContent?.trim() === 'VS Code') + expect(vscodeRow).toBeDefined() + await act(async () => { + vscodeRow!.click() + await Promise.resolve() + await Promise.resolve() + }) + // The launch really happened through the host route… + expect(api.openExternal).toHaveBeenCalledWith({ action: 'url', url: 'vscode://file//tmp/a.ts' }) + // …its failure is logged for diagnosis AND rendered where the user looks. + expect(logged).toHaveBeenCalled() + expect(container.querySelector('[role="alert"]')?.textContent).toContain('Could not open: /tmp/a.ts') + } finally { + logged.mockRestore() + unmount() + } + }) }) diff --git a/tests/file-tree-open-with.spec.tsx b/tests/file-tree-open-with.spec.tsx index 60e22ce2..a05c644c 100644 --- a/tests/file-tree-open-with.spec.tsx +++ b/tests/file-tree-open-with.spec.tsx @@ -236,6 +236,41 @@ describe('FileTree plugin open-with menu', () => { expect(menuItems().some(item => item.textContent?.includes('Open with'))).toBe(false) expect(menuItems().some(item => item.getAttribute('aria-haspopup') === 'menu')).toBe(false) }) + + /** + * #412's failure mode was a click that produced NO feedback at all: the host + * route answered `{ started: true }` for a launch that opened nothing. The + * caller now answers whether the hand-off was accepted, and both refusals + * (a `false` answer and a rejected launch) must land in the strip the + * host-backed rows already use. + */ + it('reports a refused hand-off (caller answers false) in the action strip', async () => { + harness = await mountTree() + harness.onOpenWith.mockReturnValue(false) + openMenu(harness.container) + act(() => { submenuParent().click() }) + const zedRow = submenuRows().find(item => item.textContent?.trim() === 'Zed')! + await act(async () => { + zedRow.click() + await Promise.resolve() + await Promise.resolve() + }) + expect(harness.container.querySelector('[role="alert"]')?.textContent).toContain('Could not open: /tmp/a.ts') + }) + + it('reports a rejected hand-off in the same action strip', async () => { + harness = await mountTree() + harness.onOpenWith.mockRejectedValue(new Error('spawn cmd.exe ENOENT')) + openMenu(harness.container) + act(() => { submenuParent().click() }) + const zedRow = submenuRows().find(item => item.textContent?.trim() === 'Zed')! + await act(async () => { + zedRow.click() + await Promise.resolve() + await Promise.resolve() + }) + expect(harness.container.querySelector('[role="alert"]')?.textContent).toContain('Could not open: /tmp/a.ts') + }) }) describe('FileTree plugin open-with menu flip geometry (submenu clamping)', () => { diff --git a/tests/open-external-windows.spec.ts b/tests/open-external-windows.spec.ts new file mode 100644 index 00000000..01a871a0 --- /dev/null +++ b/tests/open-external-windows.spec.ts @@ -0,0 +1,77 @@ +/** + * Windows-lane evidence for #412 ("right-click → open in app does nothing"). + * + * The reported bug was a SILENT SUCCESS: the single `rundll32.exe` branch + * spawned fine on every Windows box, so the route answered `{ started: true }` + * while nothing opened. This file drives the REAL `spawn` — the only injection + * is the two Windows opener NAMES (a test-only seam, `WindowsOpenerOptions`), + * pointed at executables that cannot exist on any machine. On `ci-windows` + * (`pnpm test:windows`) that exercises the real Windows runtime: Node's own + * ENOENT for the first branch, the fallback to the second branch, and the + * aggregated failure the UI now surfaces instead of silence. + * + * NOTHING IS EVER LAUNCHED — not a browser, not an editor, not a console + * window. That is exactly why the seam exists: spawning the production + * `cmd.exe` / `rundll32.exe` here would start a real handler (`detached: true` + * gives the child its own console window on Windows), which would pop windows + * on the runner or hang the lane. An executable that does not exist cannot + * start anything. + * + * The file is deliberately NOT platform-gated: the same code runs on the + * ubuntu lane and on a dev machine (real spawn, real ENOENT), and on the + * Windows lane it is that same path on the real OS. + */ +import { describe, expect, it } from 'vitest' +import { launchExternal, urlCommands } from '../src/open-external.ts' +import { SidebarError } from '../src/wire.ts' + +/** Opener names that cannot exist: nothing on PATH matches, so spawn must fail. */ +const MISSING_CMD = 'dsh-missing-opener-412-cmd.exe' +const MISSING_RUNDLL32 = 'dsh-missing-opener-412-rundll32.exe' + +/** The seam bag both cases below inject (platform is win32, WSL is off). */ +const missingOpeners = { cmdExecutable: MISSING_CMD, rundll32Executable: MISSING_RUNDLL32 } + +describe('win32 URL opener chain on the real spawn path', () => { + it('pins the production chain these cases run against: cmd.exe first, rundll32 second', () => { + // The injected names only replace the executables; the SHAPE under test is + // the production one (an unskipped URL goes to `start` first). + expect(urlCommands('vscode://file/C:/a.ts', 'win32')).toEqual([ + { command: 'cmd.exe', args: ['/d', '/c', 'start', '', 'vscode://file/C:/a.ts'] }, + { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', 'vscode://file/C:/a.ts'] }, + ]) + }) + + it('reports both branches failing instead of a silent success', async () => { + const pending = launchExternal('url', 'vscode://file/C:/work/a.ts', { + platform: 'win32', + wsl: false, + commandOptions: missingOpeners, + }) + const outcome = await pending.then(() => null, (reason: unknown) => reason) + + expect(outcome).toBeInstanceOf(SidebarError) + const failure = outcome as SidebarError + expect(failure.code).toBe('internal') + expect(failure.status).toBe(500) + // Each branch is named WITH the OS's own message — two distinct ENOENTs + // prove both were attempted and both failures survived into the report. + expect(failure.message).toContain(MISSING_CMD) + expect(failure.message).toContain(MISSING_RUNDLL32) + expect(failure.message.match(/ENOENT/g)).toHaveLength(2) + }) + + it('reports only the rundll32 branch when a cmd metacharacter skips `start`', async () => { + const pending = launchExternal('url', 'myapp://file/a&b.ts', { + platform: 'win32', + wsl: false, + commandOptions: missingOpeners, + }) + const outcome = await pending.then(() => null, (reason: unknown) => reason) + + expect(outcome).toBeInstanceOf(SidebarError) + const failure = outcome as SidebarError + expect(failure.message).toContain(MISSING_RUNDLL32) + expect(failure.message).not.toContain(MISSING_CMD) + }) +}) diff --git a/tests/open-external.spec.ts b/tests/open-external.spec.ts index 496dd035..e1160a00 100644 --- a/tests/open-external.spec.ts +++ b/tests/open-external.spec.ts @@ -8,7 +8,7 @@ import { describe, expect, it, vi } from 'vitest' import { launchExternal, revealCommand, - urlCommand, + urlCommands, validateExternalUrl, wslRemoteEditorUrl, } from '../src/open-external.ts' @@ -52,31 +52,73 @@ describe('revealCommand', () => { }) }) -describe('urlCommand', () => { +describe('urlCommands', () => { it('darwin: `open ` launches the registered protocol handler', () => { - expect(urlCommand('vscode://file/x', 'darwin')).toEqual({ command: 'open', args: ['vscode://file/x'] }) + expect(urlCommands('vscode://file/x', 'darwin')).toEqual([{ command: 'open', args: ['vscode://file/x'] }]) }) - it('win32: rundll32 url.dll,FileProtocolHandler ', () => { - expect(urlCommand('cursor://file/x', 'win32')).toEqual({ - command: 'rundll32.exe', - args: ['url.dll,FileProtocolHandler', 'cursor://file/x'], + it('win32: `cmd /d /c start "" ` first, rundll32 as the fallback', () => { + expect(urlCommands('cursor://file/x', 'win32')).toEqual([ + { command: 'cmd.exe', args: ['/d', '/c', 'start', '', 'cursor://file/x'] }, + { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', 'cursor://file/x'] }, + ]) + }) + + it('win32: a URL with spaces stays ONE argv element (no shell string is built)', () => { + expect(urlCommands('cursor://file/C:/Program Files/a.ts', 'win32')[0]).toEqual({ + command: 'cmd.exe', + args: ['/d', '/c', 'start', '', 'cursor://file/C:/Program Files/a.ts'], }) }) + // `cmd /c` re-parses the command line after Node's quoting: an unskipped + // metacharacter would be expanded (`%VAR%`), split (`&`/`|`), escaped (`^`) + // or re-quoted (`"`) instead of reaching the handler verbatim. + it.each([ + ['&', 'myapp://file/a&b.ts'], + ['%', 'myapp://file/%PATH%/a.ts'], + ['^', 'myapp://file/a^b.ts'], + ['!', 'myapp://file/!x!/a.ts'], + ['|', 'myapp://file/a|b.ts'], + ['<', 'myapp://file/a', 'myapp://file/a>b.ts'], + ['"', 'myapp://file/a"b.ts'], + ])('win32: skips the cmd branch for a URL carrying %s (rundll32 only)', (_char, url) => { + expect(urlCommands(url, 'win32')).toEqual([ + { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] }, + ]) + }) + + it('win32: skips the cmd branch for a URL carrying a raw control character', () => { + // `new URL` strips CR/LF, but validateExternalUrl returns the RAW string, + // and cmd treats a newline as a command separator. + const url = 'myapp://file/a\n--x' + expect(urlCommands(url, 'win32').map(spec => spec.command)).toEqual(['rundll32.exe']) + }) + + it('win32: the opener names are injectable (the Windows-lane failure seam)', () => { + expect(urlCommands('zed://file/x', 'win32', { + cmdExecutable: 'missing-cmd-412.exe', + rundll32Executable: 'missing-rundll-412.exe', + })).toEqual([ + { command: 'missing-cmd-412.exe', args: ['/d', '/c', 'start', '', 'zed://file/x'] }, + { command: 'missing-rundll-412.exe', args: ['url.dll,FileProtocolHandler', 'zed://file/x'] }, + ]) + }) + it('linux: `xdg-open ` launches the registered protocol handler', () => { - expect(urlCommand('zed://file/x', 'linux')).toEqual({ command: 'xdg-open', args: ['zed://file/x'] }) + expect(urlCommands('zed://file/x', 'linux')).toEqual([{ command: 'xdg-open', args: ['zed://file/x'] }]) }) it('android (Termux): `termux-open-url ` dispatches the Android intent', () => { - expect(urlCommand('vscode://file/x', 'android')).toEqual({ command: 'termux-open-url', args: ['vscode://file/x'] }) + expect(urlCommands('vscode://file/x', 'android')).toEqual([{ command: 'termux-open-url', args: ['vscode://file/x'] }]) }) it('wsl: dispatches custom schemes through the absolute Windows URL handler', () => { - expect(urlCommand('zed://file//home/u/f.ts', 'linux', wslCommands)).toEqual({ + expect(urlCommands('zed://file//home/u/f.ts', 'linux', wslCommands)).toEqual([{ command: '/windows/System32/rundll32.exe', args: ['url.dll,FileProtocolHandler', 'zed://file//home/u/f.ts'], - }) + }]) }) }) @@ -117,6 +159,41 @@ describe('validateExternalUrl', () => { }) }) +/** One recorded spawn call plus the fake child it handed back. */ +interface RecordedSpawn { + command: string + args: readonly string[] + child: EventEmitter +} + +/** + * A `spawn` seam that records the argv of every ATTEMPT and never starts a + * process: the caller decides each attempt's outcome with `settle()`, so the + * chain's order, its fallback and its terminal error shape are all observable. + */ +function recordingSpawn(): { + spawn: typeof import('node:child_process').spawn + calls: RecordedSpawn[] + unref: ReturnType + settle: (index: number, outcome: 'spawn' | 'error', message?: string) => void +} { + const calls: RecordedSpawn[] = [] + const unref = vi.fn() + const spawnFn = ((command: string, args: readonly string[]) => { + const child = new EventEmitter() + Object.assign(child, { unref }) + calls.push({ command, args, child }) + return child + }) as unknown as typeof import('node:child_process').spawn + const settle = (index: number, outcome: 'spawn' | 'error', message = 'spawn failed'): void => { + const call = calls[index] + if (call === undefined) throw new Error(`no spawn attempt #${index} (got ${calls.length})`) + if (outcome === 'spawn') call.child.emit('spawn') + else call.child.emit('error', Object.assign(new Error(message), { code: 'ENOENT' })) + } + return { spawn: spawnFn, calls, unref, settle } +} + describe('launchExternal validation and spawn lifecycle', () => { it('rejects relative reveal paths before anything is spawned', () => { expect(() => launchExternal('reveal', 'relative/path')).toThrow(SidebarError) @@ -143,3 +220,86 @@ describe('launchExternal validation and spawn lifecycle', () => { expect(unref).toHaveBeenCalledTimes(1) }) }) + +describe('launchExternal Windows branch order and failure reporting', () => { + const url = 'vscode://file/C:/a.ts' + const win = { platform: 'win32' as const, wsl: false } + + it('spawns `cmd /d /c start "" ` first, with the URL as one argv element', () => { + const fake = recordingSpawn() + void launchExternal('url', url, { ...win, spawn: fake.spawn }).catch(() => {}) + expect(fake.calls.map(call => ({ command: call.command, args: call.args }))).toEqual([ + { command: 'cmd.exe', args: ['/d', '/c', 'start', '', url] }, + ]) + }) + + it('falls through to rundll32 when the cmd branch cannot spawn', async () => { + const fake = recordingSpawn() + const pending = launchExternal('url', url, { ...win, spawn: fake.spawn }) + fake.settle(0, 'error', 'spawn cmd.exe ENOENT') + expect(fake.calls.map(call => call.command)).toEqual(['cmd.exe', 'rundll32.exe']) + fake.settle(1, 'spawn') + await expect(pending).resolves.toEqual({ started: true }) + expect(fake.unref).toHaveBeenCalledTimes(2) + }) + + it('advances on a synchronous spawn throw as well', async () => { + const fake = recordingSpawn() + const calls: string[] = [] + const spawnFn = ((command: string, args: readonly string[]) => { + calls.push(command) + if (calls.length === 1) throw new Error('EINVAL: bad command line') + return fake.spawn(command, args) + }) as unknown as typeof import('node:child_process').spawn + const pending = launchExternal('url', url, { ...win, spawn: spawnFn }) + expect(calls).toEqual(['cmd.exe', 'rundll32.exe']) + fake.settle(0, 'spawn') + await expect(pending).resolves.toEqual({ started: true }) + }) + + it('skips the cmd branch for a `&` URL — the whole launch only tries rundll32', () => { + const fake = recordingSpawn() + void launchExternal('url', 'myapp://file/a&b.ts', { ...win, spawn: fake.spawn }).catch(() => {}) + expect(fake.calls.map(call => call.command)).toEqual(['rundll32.exe']) + expect(fake.calls[0]?.args).toEqual(['url.dll,FileProtocolHandler', 'myapp://file/a&b.ts']) + }) + + it('rejects with a structured failure naming EVERY dead branch (never a silent success)', async () => { + const fake = recordingSpawn() + const pending = launchExternal('url', url, { ...win, spawn: fake.spawn }) + fake.settle(0, 'error', 'spawn cmd.exe ENOENT') + fake.settle(1, 'error', 'spawn rundll32.exe EACCES') + const error = await pending.then(() => null, (reason: unknown) => reason) + + expect(error).toBeInstanceOf(SidebarError) + const failure = error as SidebarError + expect(failure.code).toBe('internal') + expect(failure.status).toBe(500) + expect(failure.message).toBe( + 'failed to launch external opener for the url: "cmd.exe" (spawn cmd.exe ENOENT); ' + + '"rundll32.exe" (spawn rundll32.exe EACCES)', + ) + expect(fake.unref).toHaveBeenCalledTimes(2) + }) + + it('reports a reveal failure with the same shape (one branch, `path` subject)', async () => { + const fake = recordingSpawn() + // Path absoluteness is checked with the HOST path module, so this case uses + // the linux branch (an absolute POSIX path) to pin the aggregated message + // of the reveal half. + const pending = launchExternal('reveal', '/a/b.txt', { + platform: 'linux', + wsl: false, + spawn: fake.spawn, + }) + fake.settle(0, 'error', 'spawn xdg-open ENOENT') + const error = await pending.then(() => null, (reason: unknown) => reason) + + expect(fake.calls.map(call => ({ command: call.command, args: call.args }))).toEqual([ + { command: 'xdg-open', args: ['/a'] }, + ]) + expect((error as SidebarError).message).toBe( + 'failed to launch external opener for the path: "xdg-open" (spawn xdg-open ENOENT)', + ) + }) +})