From 5a733e91f1cac33b7f9b9705aa96c70a4030493c Mon Sep 17 00:00:00 2001 From: Kunping Wang <146500293+wang-kaopu@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:30:21 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(open-with):=20=E6=94=AF=E6=8C=81=20WSL?= =?UTF-8?q?=20=E5=A4=96=E9=83=A8=E6=89=93=E5=BC=80=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/open-external.ts | 157 +++++++++++++++++++++++++++++++----- tests/open-external.spec.ts | 73 +++++++++++++++-- 2 files changed, 203 insertions(+), 27 deletions(-) diff --git a/src/open-external.ts b/src/open-external.ts index 6a1ef67f..2e121900 100644 --- a/src/open-external.ts +++ b/src/open-external.ts @@ -6,10 +6,11 @@ * The client runs in a browser / DSH Desktop renderer where a raw `vscode://` * navigation is unreliable, so both actions fan out through this host route * and spawn the platform opener with an argv array (no shell interpolation). - * The command builders are pure — the platform is injectable — so every - * per-platform branch is unit-testable without spawning anything. + * WSL is special: Node reports `linux`, while the actual desktop handlers live + * on Windows, so its commands cross the interop boundary explicitly. */ -import { spawn } from 'node:child_process' +import { execFileSync, spawn } from 'node:child_process' +import { readFileSync } from 'node:fs' import { parentOf, requireAbsolute } from './fs-tree.ts' import { SidebarError } from './wire.ts' @@ -22,9 +23,58 @@ export interface ExternalCommand { args: string[] } -/** Reveal/select a path in the OS file manager. On Linux there is no common - * select protocol — the containing directory is opened instead (KISS). */ -export function revealCommand(path: string, platform: NodeJS.Platform = process.platform): ExternalCommand { +/** Injectable WSL command seams keep the command builders pure in unit tests. */ +export interface WslCommandOptions { + wsl?: boolean + toWindowsPath?: (path: string) => string + windowsExecutable?: (path: string) => string +} + +/** Runtime seams used only to make launch/error behavior testable off-host. */ +export interface LaunchExternalOptions { + platform?: NodeJS.Platform + wsl?: boolean + distroName?: string + commandOptions?: Omit + spawn?: typeof spawn +} + +/** True when this Linux host is backed by Windows Subsystem for Linux. */ +export function isWslRuntime(): boolean { + if (process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP) return true + try { + return /microsoft|wsl/i.test(readFileSync('/proc/version', 'utf8')) + } catch { + return false + } +} + +/** Run WSL's built-in path translator by absolute path so + * `appendWindowsPath=false` cannot make the helper disappear from PATH. */ +function wslPath(mode: '-u' | '-w', value: string): string { + const translated = execFileSync('/usr/bin/wslpath', [mode, value], { encoding: 'utf8' }).trim() + if (translated === '') throw new Error(`wslpath returned no translation for ${value}`) + return translated +} + +/** Linux/WSL absolute path -> Windows path understood by Explorer. */ +function windowsPathOf(path: string): string { + return wslPath('-w', path) +} + +/** Windows executable path -> its WSL mount path, without relying on PATH. */ +function windowsExecutableOf(path: string): string { + return wslPath('-u', path) +} + +/** Reveal/select a path in the OS file manager. On plain Linux there is no + * common select protocol — the containing directory is opened instead. + * Under WSL the desktop file manager is Windows Explorer. */ +export function revealCommand( + path: string, + platform: NodeJS.Platform = process.platform, + options: WslCommandOptions = {}, +): ExternalCommand { switch (platform) { case 'darwin': return { command: 'open', args: ['-R', path] } @@ -33,14 +83,27 @@ export function revealCommand(path: string, platform: NodeJS.Platform = process. case 'win32': return { command: 'explorer.exe', args: [`/select,${path}`] } default: { + if (options.wsl) { + const toWindowsPath = options.toWindowsPath ?? windowsPathOf + const windowsExecutable = options.windowsExecutable ?? windowsExecutableOf + return { + command: windowsExecutable('C:\\Windows\\explorer.exe'), + args: [`/select,${toWindowsPath(path)}`], + } + } const parent = parentOf(path) return { command: 'xdg-open', args: [parent ?? path] } } } } -/** Hand a custom-scheme URL to the OS protocol handler. */ -export function urlCommand(url: string, platform: NodeJS.Platform = process.platform): ExternalCommand { +/** 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( + url: string, + platform: NodeJS.Platform = process.platform, + options: WslCommandOptions = {}, +): ExternalCommand { switch (platform) { case 'darwin': return { command: 'open', args: [url] } @@ -49,12 +112,33 @@ export function urlCommand(url: string, platform: NodeJS.Platform = process.plat case 'win32': return { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] } default: + if (options.wsl) { + const windowsExecutable = options.windowsExecutable ?? windowsExecutableOf + return { + command: windowsExecutable('C:\\Windows\\System32\\rundll32.exe'), + args: ['url.dll,FileProtocolHandler', url], + } + } return { command: 'xdg-open', args: [url] } } } +/** Convert the built-in VSCode-family local-file URL to its Remote-WSL form. + * A POSIX path produces `scheme://file//...`; keep one leading slash when it + * moves behind the `wsl+` authority. Other custom schemes are left + * alone and merely dispatched through the Windows protocol handler. */ +export function wslRemoteEditorUrl(url: string, distroName: string): string { + const match = /^(vscode(?:-insiders)?|cursor):\/\/file(\/\/.*)$/i.exec(url) + if (match === null) return url + const distro = distroName.trim() + if (distro === '') { + throw new SidebarError('internal', 'WSL_DISTRO_NAME is unavailable; cannot build a Remote-WSL editor URL', 500) + } + return `${match[1]}://vscode-remote/wsl+${distro}${match[2].slice(1)}` +} + /** Validate a URL-scheme open target: a parseable custom-scheme URL (never - * http/https — those would only dump the URL into a browser tab). */ + * http/https — those would only dump the URL into a browser tab). */ export function validateExternalUrl(raw: string): string { if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) { throw new SidebarError('bad-request', 'url must be a custom-scheme URL') @@ -71,19 +155,48 @@ export function validateExternalUrl(raw: string): string { return raw } +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) +} + /** - * Launch one external open action and return immediately (detached, no - * stdio). Spawn failures are reported through the child's 'error' event — - * by then the route already returned, so the event is swallowed (the OS - * dialog about a missing handler is the user-visible outcome either way). + * 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. */ -export function launchExternal(action: OpenExternalAction, value: string): { started: true } { - const platform = process.platform - const spec = action === 'reveal' - ? revealCommand(requireAbsolute(value), platform) - : urlCommand(validateExternalUrl(value), platform) - const child = spawn(spec.command, spec.args, { detached: true, stdio: 'ignore' }) - child.on('error', () => { /* opener missing/denied: handled by the OS */ }) - child.unref() - return { started: true } +export function launchExternal( + action: OpenExternalAction, + value: string, + options: LaunchExternalOptions = {}, +): Promise<{ started: true }> { + const platform = options.platform ?? process.platform + const wsl = options.wsl ?? (platform === 'linux' && isWslRuntime()) + const commandOptions: WslCommandOptions = { ...options.commandOptions, wsl } + + let spec: ExternalCommand + if (action === 'reveal') { + spec = 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) + } + + 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() + }) } diff --git a/tests/open-external.spec.ts b/tests/open-external.spec.ts index d83477ce..3d34f8ec 100644 --- a/tests/open-external.spec.ts +++ b/tests/open-external.spec.ts @@ -1,13 +1,27 @@ /** * Host external-open helpers: per-platform opener commands (pure, injected * platform) and the URL validation that guards the spawn route. The actual - * spawns are not exercised — the route runs in the DSH host process and the - * OS outcome is not testable here. + * OS handlers are not launched in unit tests. */ -import { describe, expect, it } from 'vitest' -import { launchExternal, revealCommand, urlCommand, validateExternalUrl } from '../src/open-external.ts' +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi } from 'vitest' +import { + launchExternal, + revealCommand, + urlCommand, + validateExternalUrl, + wslRemoteEditorUrl, +} from '../src/open-external.ts' import { SidebarError } from '../src/wire.ts' +const wslCommands = { + wsl: true, + toWindowsPath: (path: string): string => path === '/a/b.txt' ? 'C:\\a\\b.txt' : path, + windowsExecutable: (path: string): string => path.endsWith('explorer.exe') + ? '/windows/explorer.exe' + : '/windows/System32/rundll32.exe', +} + describe('revealCommand', () => { it('darwin: `open -R ` selects the file in Finder', () => { expect(revealCommand('/a/b.txt', 'darwin')).toEqual({ command: 'open', args: ['-R', '/a/b.txt'] }) @@ -24,6 +38,13 @@ describe('revealCommand', () => { expect(revealCommand('/a/b.txt', 'linux')).toEqual({ command: 'xdg-open', args: ['/a'] }) expect(revealCommand('/', 'linux')).toEqual({ command: 'xdg-open', args: ['/'] }) }) + + it('wsl: translates the path and selects it with an absolute Windows Explorer command', () => { + expect(revealCommand('/a/b.txt', 'linux', wslCommands)).toEqual({ + command: '/windows/explorer.exe', + args: ['/select,C:\\a\\b.txt'], + }) + }) }) describe('urlCommand', () => { @@ -41,6 +62,31 @@ describe('urlCommand', () => { it('linux: `xdg-open ` launches the registered protocol handler', () => { expect(urlCommand('zed://file/x', 'linux')).toEqual({ command: 'xdg-open', args: ['zed://file/x'] }) }) + + it('wsl: dispatches custom schemes through the absolute Windows URL handler', () => { + expect(urlCommand('zed://file//home/u/f.ts', 'linux', wslCommands)).toEqual({ + command: '/windows/System32/rundll32.exe', + args: ['url.dll,FileProtocolHandler', 'zed://file//home/u/f.ts'], + }) + }) +}) + +describe('wslRemoteEditorUrl', () => { + it('converts VS Code and Cursor POSIX file URLs to Remote-WSL URLs', () => { + expect(wslRemoteEditorUrl('vscode://file//home/u/f.ts', 'Ubuntu-22.04')) + .toBe('vscode://vscode-remote/wsl+Ubuntu-22.04/home/u/f.ts') + expect(wslRemoteEditorUrl('cursor://file//mnt/d/dev/f.ts', 'Ubuntu-22.04')) + .toBe('cursor://vscode-remote/wsl+Ubuntu-22.04/mnt/d/dev/f.ts') + }) + + it('leaves non-VSCode-family schemes unchanged', () => { + expect(wslRemoteEditorUrl('zed://file//home/u/f.ts', 'Ubuntu-22.04')) + .toBe('zed://file//home/u/f.ts') + }) + + it('rejects a Remote-WSL conversion when the distro name is unavailable', () => { + expect(() => wslRemoteEditorUrl('vscode://file//home/u/f.ts', '')).toThrow(SidebarError) + }) }) describe('validateExternalUrl', () => { @@ -62,7 +108,7 @@ describe('validateExternalUrl', () => { }) }) -describe('launchExternal validation (pre-spawn)', () => { +describe('launchExternal validation and spawn lifecycle', () => { it('rejects relative reveal paths before anything is spawned', () => { expect(() => launchExternal('reveal', 'relative/path')).toThrow(SidebarError) }) @@ -70,4 +116,21 @@ describe('launchExternal validation (pre-spawn)', () => { it('rejects invalid URLs before anything is spawned', () => { expect(() => launchExternal('url', 'https://example.com')).toThrow(SidebarError) }) + + it('rejects instead of reporting started when the opener emits a spawn error', async () => { + const child = new EventEmitter() + const unref = vi.fn() + const fakeSpawn = vi.fn(() => Object.assign(child, { unref })) as unknown as typeof import('node:child_process').spawn + const pending = launchExternal('url', 'zed://file//tmp/a.ts', { + platform: 'linux', + wsl: false, + spawn: fakeSpawn, + }) + const assertion = expect(pending).rejects.toMatchObject({ code: 'internal' }) + + child.emit('error', Object.assign(new Error('spawn xdg-open ENOENT'), { code: 'ENOENT' })) + + await assertion + expect(unref).toHaveBeenCalledTimes(1) + }) }) From a0fd003e98ba0e4a629a157819714e1edd180e48 Mon Sep 17 00:00:00 2001 From: Kunping Wang <146500293+wang-kaopu@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:30:56 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(open-with):=20=E6=94=B6=E7=AA=84=20WSL?= =?UTF-8?q?=20Remote=20URL=20=E6=AD=A3=E5=88=99=E6=8D=95=E8=8E=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/open-external.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/open-external.ts b/src/open-external.ts index 2e121900..4f7bd107 100644 --- a/src/open-external.ts +++ b/src/open-external.ts @@ -130,11 +130,14 @@ export function urlCommand( export function wslRemoteEditorUrl(url: string, distroName: string): string { const match = /^(vscode(?:-insiders)?|cursor):\/\/file(\/\/.*)$/i.exec(url) if (match === null) return url + const scheme = match[1] + const remotePath = match[2] + if (scheme === undefined || remotePath === undefined) return url const distro = distroName.trim() if (distro === '') { throw new SidebarError('internal', 'WSL_DISTRO_NAME is unavailable; cannot build a Remote-WSL editor URL', 500) } - return `${match[1]}://vscode-remote/wsl+${distro}${match[2].slice(1)}` + return `${scheme}://vscode-remote/wsl+${distro}${remotePath.slice(1)}` } /** Validate a URL-scheme open target: a parseable custom-scheme URL (never