Merge pull request #612 from wang-kaopu/fix/issue-591-wsl-open-with
fix(open-with): handle external open actions under WSL
This commit is contained in:
2 files changed
+206
-27
No files matched your search
+138
-22
@@ -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<WslCommandOptions, 'wsl'>
|
||||
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] }
|
||||
@@ -41,14 +91,27 @@ export function revealCommand(path: string, platform: NodeJS.Platform = process.
|
||||
return { command: 'termux-open', args: [parent ?? 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] }
|
||||
@@ -61,12 +124,36 @@ export function urlCommand(url: string, platform: NodeJS.Platform = process.plat
|
||||
case 'android':
|
||||
return { command: 'termux-open-url', args: [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+<distro>` 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 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 `${scheme}://vscode-remote/wsl+${distro}${remotePath.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')
|
||||
@@ -83,19 +170,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<typeof spawn>
|
||||
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()
|
||||
})
|
||||
}
|
||||
@@ -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 <path>` selects the file in Finder', () => {
|
||||
expect(revealCommand('/a/b.txt', 'darwin')).toEqual({ command: 'open', args: ['-R', '/a/b.txt'] })
|
||||
@@ -29,6 +43,13 @@ describe('revealCommand', () => {
|
||||
expect(revealCommand('/a/b.txt', 'android')).toEqual({ command: 'termux-open', args: ['/a'] })
|
||||
expect(revealCommand('/', 'android')).toEqual({ command: 'termux-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', () => {
|
||||
@@ -50,6 +71,31 @@ describe('urlCommand', () => {
|
||||
it('android (Termux): `termux-open-url <url>` dispatches the Android intent', () => {
|
||||
expect(urlCommand('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({
|
||||
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', () => {
|
||||
@@ -71,7 +117,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)
|
||||
})
|
||||
@@ -79,4 +125,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)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user