path-opener.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /** Cross-platform native path opener behavior. */
  2. type ExecFileCallback = (
  3. error: (Error & { code?: string | number }) | null,
  4. stdout: string,
  5. stderr: string,
  6. ) => void
  7. type ExecFileMock = (
  8. command: string,
  9. args: readonly string[],
  10. options: { encoding: string; signal: AbortSignal; windowsHide: boolean },
  11. callback: ExecFileCallback,
  12. ) => void
  13. const { execFileMock } = vi.hoisted(() => ({ execFileMock: vi.fn<ExecFileMock>() }))
  14. vi.mock('node:child_process', () => ({ execFile: execFileMock }))
  15. import { release as osRelease } from 'node:os'
  16. import { beforeEach, describe, expect, it, vi } from 'vitest'
  17. import { canOpenNativePath, nativeFileManager, revealNativePath, openNativeAssociatedPath, openNativePath, openNativeTextFile, type PathOpenerRunner } from '../src/index.ts'
  18. const signal = () => new AbortController().signal
  19. beforeEach(() => { execFileMock.mockReset() })
  20. describe('native path opener', () => {
  21. it('opens with macOS open(1)', async () => {
  22. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  23. await openNativePath('/Users/test/file.txt', signal(), { platform: 'darwin', run })
  24. expect(run).toHaveBeenCalledWith('open', ['/Users/test/file.txt'], expect.any(AbortSignal), 'hidden')
  25. })
  26. it('bypasses macOS file associations for text documents', async () => {
  27. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  28. await openNativeTextFile('/Users/test/settings.yaml', signal(), { platform: 'darwin', run })
  29. expect(run).toHaveBeenCalledWith('open', ['-t', '/Users/test/settings.yaml'], expect.any(AbortSignal), 'hidden')
  30. })
  31. it('uses the Linux desktop association for text documents', async () => {
  32. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  33. await openNativeTextFile('/tmp/settings.yaml', signal(), {
  34. platform: 'linux', osRelease: '6.8.0-generic', env: {}, run,
  35. })
  36. expect(run).toHaveBeenCalledWith('xdg-open', ['/tmp/settings.yaml'], expect.any(AbortSignal), 'hidden')
  37. })
  38. it.each([
  39. ['distribution marker', { WSL_DISTRO_NAME: 'Ubuntu' }, '6.8.0-generic'],
  40. ['interop marker', { WSL_INTEROP: '/run/WSL/123_interop' }, '6.8.0-generic'],
  41. ['kernel release', {}, '5.15.153.1-microsoft-standard-WSL2'],
  42. ])('hands WSL text documents to the Windows desktop from the %s', async (_label, env, osRelease) => {
  43. const requestSignal = signal()
  44. const run = vi.fn<PathOpenerRunner>(async command => command === 'wslpath'
  45. ? { stdout: '\\\\wsl.localhost\\Ubuntu\\home\\test user\\settings.yaml\r\n', stderr: '' }
  46. : { stdout: '', stderr: '' })
  47. await openNativeTextFile('/home/test user/settings.yaml', requestSignal, {
  48. platform: 'linux', osRelease, env, run,
  49. })
  50. expect(run.mock.calls).toEqual([
  51. ['wslpath', ['-w', '/home/test user/settings.yaml'], requestSignal, 'hidden'],
  52. ['explorer.exe', ['file://wsl.localhost/Ubuntu/home/test%20user/settings.yaml'], requestSignal, 'visible'],
  53. ])
  54. })
  55. it('rejects an empty WSL path translation before invoking Windows', async () => {
  56. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '\r\n', stderr: '' }))
  57. await expect(openNativeTextFile('/home/test/settings.yaml', signal(), {
  58. platform: 'linux', osRelease: '6.8.0-generic', env: { WSL_DISTRO_NAME: 'Ubuntu' }, run,
  59. })).rejects.toThrow('wslpath returned no Windows path')
  60. expect(run).toHaveBeenCalledOnce()
  61. })
  62. it('does not invoke Windows when the request aborts during WSL path translation', async () => {
  63. const abort = new AbortController()
  64. const run = vi.fn<PathOpenerRunner>(async () => {
  65. abort.abort(new Error('closed'))
  66. return { stdout: '\\\\wsl.localhost\\Ubuntu\\home\\test\\settings.yaml\n', stderr: '' }
  67. })
  68. await expect(openNativeTextFile('/home/test/settings.yaml', abort.signal, {
  69. platform: 'linux', osRelease: '6.8.0-generic', env: { WSL_DISTRO_NAME: 'Ubuntu' }, run,
  70. })).rejects.toThrow('closed')
  71. expect(run).toHaveBeenCalledOnce()
  72. })
  73. it.each([
  74. // Explorer parses its own command line and splits fields at commas and
  75. // equals signs, and libuv quotes an argument only when it holds a space, so
  76. // the encoded file URI is what keeps the whole path in one field. Only those
  77. // two separators are escaped on top of the URI's own encoding: Explorer
  78. // rejects percent-encoded non-ASCII and opens Documents instead, while it
  79. // resolves the literal characters, so `报告` stays literal here. UNC takes
  80. // the same encoding.
  81. ["C:\\work\\o'reilly, & 100%.txt", "file:///C:/work/o'reilly%2C%20&%20100%25.txt"],
  82. ['C:\\work\\plain.txt', 'file:///C:/work/plain.txt'],
  83. ['C:\\work\\my report.txt', 'file:///C:/work/my%20report.txt'],
  84. ['C:\\work\\key=value.txt', 'file:///C:/work/key%3Dvalue.txt'],
  85. ['C:\\my files\\报告,#%.txt', 'file:///C:/my%20files/报告%2C%23%25.txt'],
  86. ['C:\\目录\\a,b=c.txt', 'file:///C:/目录/a%2Cb%3Dc.txt'],
  87. ['C:\\工作\\报告 2026.txt', 'file:///C:/工作/报告%202026.txt'],
  88. ['\\\\server\\share\\a,b.txt', 'file://server/share/a%2Cb.txt'],
  89. // Node resolves the path before encoding it, so a verbatim prefix is not
  90. // part of the target: `\\?\` and `\\?\UNC\` arrive as the ordinary drive or
  91. // UNC URI. A device-namespace path takes that same UNC handling; it names a
  92. // device rather than a shell item, which this opener does not open.
  93. ['\\\\?\\C:\\work\\a,b.txt', 'file:///C:/work/a%2Cb.txt'],
  94. ['\\\\?\\UNC\\server\\share\\a,b.txt', 'file://server/share/a%2Cb.txt'],
  95. ['\\\\.\\C:\\work\\a,b.txt', 'file://./C:/work/a%2Cb.txt'],
  96. ['\\\\wsl$\\Ubuntu\\home\\t,est a.txt', 'file://wsl$/Ubuntu/home/t%2Cest%20a.txt'],
  97. ] as const)('opens %s through the one encoded Explorer target', async (path, target) => {
  98. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  99. await openNativePath(path, signal(), { platform: 'win32', run })
  100. expect(run).toHaveBeenCalledExactlyOnceWith('explorer.exe', [target], expect.any(AbortSignal), 'visible')
  101. })
  102. // Node restores a trailing separator against the host's `path.sep`, so a
  103. // separator-terminated Windows path encodes differently on the Windows host
  104. // this opener runs on than on the POSIX host a test run may use.
  105. it('encodes a separator-terminated drive root as the hosting platform resolves it', async () => {
  106. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  107. await openNativePath('C:\\', signal(), { platform: 'win32', run })
  108. expect(run).toHaveBeenCalledExactlyOnceWith(
  109. 'explorer.exe',
  110. [process.platform === 'win32' ? 'file:///C:/' : 'file:///C://'],
  111. expect.any(AbortSignal),
  112. 'visible',
  113. )
  114. })
  115. it('encodes a directory target the same way it encodes a file target', async () => {
  116. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  117. await openNativeAssociatedPath('C:\\work\\dir,comma', signal(), { platform: 'win32', run })
  118. expect(run).toHaveBeenCalledWith(
  119. 'explorer.exe',
  120. ['file:///C:/work/dir%2Ccomma'],
  121. expect.any(AbortSignal),
  122. 'visible',
  123. )
  124. })
  125. it('uses the Windows desktop association for text documents', async () => {
  126. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  127. await openNativeTextFile('C:\\work\\settings.yaml', signal(), { platform: 'win32', run })
  128. expect(run).toHaveBeenCalledWith(
  129. 'explorer.exe',
  130. ['file:///C:/work/settings.yaml'],
  131. expect.any(AbortSignal),
  132. 'visible',
  133. )
  134. })
  135. it('opens with Linux xdg-open', async () => {
  136. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  137. await openNativePath('/tmp/a.txt', signal(), {
  138. platform: 'linux', osRelease: '6.8.0-generic',
  139. env: { WSL_DISTRO_NAME: '', WSL_INTEROP: '' }, run,
  140. })
  141. expect(run).toHaveBeenCalledWith('xdg-open', ['/tmp/a.txt'], expect.any(AbortSignal), 'hidden')
  142. })
  143. it('rejects unsupported platforms', async () => {
  144. await expect(openNativePath('/x', signal(), { platform: 'freebsd' as NodeJS.Platform }))
  145. .rejects.toThrow('unsupported on freebsd')
  146. })
  147. it('uses the current process platform when no platform override is supplied', async () => {
  148. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  149. await openNativePath('/tmp/platform-default.txt', signal(), {
  150. osRelease: '6.8.0-generic', env: {}, run,
  151. })
  152. const expected = process.platform === 'win32'
  153. ? 'explorer.exe'
  154. : process.platform === 'linux'
  155. ? 'xdg-open'
  156. : 'open'
  157. expect(run.mock.calls[0]?.[0]).toBe(expected)
  158. })
  159. it('samples ambient WSL markers and kernel release when no fact overrides are supplied', async () => {
  160. const ambientWsl = [process.env.WSL_DISTRO_NAME, process.env.WSL_INTEROP]
  161. .some(value => value !== undefined && value !== '')
  162. || osRelease().toLowerCase().includes('microsoft')
  163. const run = vi.fn<PathOpenerRunner>(async command => command === 'wslpath'
  164. ? { stdout: 'C:\\settings.yaml\n', stderr: '' }
  165. : { stdout: '', stderr: '' })
  166. await openNativePath('/tmp/ambient-facts.yaml', signal(), { platform: 'linux', run })
  167. expect(run.mock.calls[0]?.[0]).toBe(ambientWsl ? 'wslpath' : 'xdg-open')
  168. })
  169. it.each([
  170. ['open', openNativePath],
  171. ['reveal', revealNativePath],
  172. ] as const)('keeps Explorer windows visible through the default %s adapter', async (_intent, open) => {
  173. execFileMock.mockImplementationOnce((_command, _args, _options, callback) => {
  174. callback(null, '', '')
  175. })
  176. await open('C:\\work\\report.txt', signal(), { platform: 'win32' })
  177. expect(execFileMock.mock.lastCall?.[0]).toBe('explorer.exe')
  178. expect(execFileMock.mock.lastCall?.[2].windowsHide).toBe(false)
  179. })
  180. it('runs the default command adapter without a shell and preserves command failures', async () => {
  181. execFileMock.mockImplementationOnce((_command, _args, _options, callback) => {
  182. callback(null, '', '')
  183. })
  184. await openNativePath('/tmp/default.txt', signal(), { platform: 'darwin' })
  185. const [command, args, options] = execFileMock.mock.calls[0]!
  186. expect(command).toBe('open')
  187. expect(args).toEqual(['/tmp/default.txt'])
  188. expect(options.encoding).toBe('utf8')
  189. expect(options.windowsHide).toBe(true)
  190. expect(options.signal).toBeInstanceOf(AbortSignal)
  191. const commandError = Object.assign(new Error('open failed'), { code: 1 })
  192. execFileMock.mockImplementationOnce((_command, _args, _options, callback) => {
  193. callback(commandError, 'partial output', 'failure details')
  194. })
  195. await expect(openNativePath('/tmp/missing.txt', signal(), { platform: 'darwin' })).rejects.toMatchObject({
  196. message: 'open failed', cause: commandError, code: 1,
  197. stdout: 'partial output', stderr: 'failure details',
  198. })
  199. })
  200. })
  201. describe('browser-renderable documents', () => {
  202. const LS_PLIST = `{
  203. LSHandlers = (
  204. {
  205. LSHandlerPreferredVersions = {
  206. LSHandlerRoleAll = "-";
  207. };
  208. LSHandlerRoleAll = "com.google.chrome";
  209. LSHandlerURLScheme = https;
  210. }
  211. );
  212. }`
  213. it('opens a page with the default browser rather than the .html handler on darwin', async () => {
  214. const calls: { command: string; args: readonly string[] }[] = []
  215. const run = async (command: string, args: readonly string[]) => {
  216. calls.push({ command, args })
  217. return { stdout: command === 'defaults' ? LS_PLIST : '', stderr: '' }
  218. }
  219. await openNativePath('/w/page.html', new AbortController().signal, { platform: 'darwin', run })
  220. // A developer who bound .html to an editor still gets a rendered page.
  221. expect(calls.map(c => [c.command, ...c.args])).toEqual([
  222. ['defaults', 'read', 'com.apple.LaunchServices/com.apple.launchservices.secure'],
  223. ['open', '-b', 'com.google.chrome', '/w/page.html'],
  224. ])
  225. })
  226. it('leaves every other document to the default application', async () => {
  227. const calls: string[][] = []
  228. const run = async (command: string, args: readonly string[]) => {
  229. calls.push([command, ...args])
  230. return { stdout: '', stderr: '' }
  231. }
  232. await openNativePath('/w/report.md', new AbortController().signal, { platform: 'darwin', run })
  233. // No LaunchServices read at all: markdown is not a browser document.
  234. expect(calls).toEqual([['open', '/w/report.md']])
  235. })
  236. it('falls back to the default application when no browser can be named', async () => {
  237. // LaunchServices has no https record (a fresh account), so the system's
  238. // own content-type choice is the best answer available.
  239. const calls: string[][] = []
  240. const run = async (command: string, args: readonly string[]) => {
  241. calls.push([command, ...args])
  242. if (command === 'defaults') throw new Error('domain not found')
  243. return { stdout: '', stderr: '' }
  244. }
  245. await openNativePath('/w/page.html', new AbortController().signal, { platform: 'darwin', run })
  246. expect(calls).toEqual([
  247. ['defaults', 'read', 'com.apple.LaunchServices/com.apple.launchservices.secure'],
  248. ['open', '/w/page.html'],
  249. ])
  250. // A record without an https handler is the same answer.
  251. const bare: string[][] = []
  252. await openNativePath('/w/page.html', new AbortController().signal, {
  253. platform: 'darwin',
  254. run: async (command, args) => {
  255. bare.push([command, ...args])
  256. return { stdout: '{ LSHandlers = ( ); }', stderr: '' }
  257. },
  258. })
  259. expect(bare[1]).toEqual(['open', '/w/page.html'])
  260. })
  261. it('honors $BROWSER on linux and leaves windows to its association', async () => {
  262. const linux: string[][] = []
  263. await openNativePath('/w/page.html', new AbortController().signal, {
  264. platform: 'linux',
  265. osRelease: '6.8.0-generic',
  266. env: { BROWSER: 'firefox' },
  267. run: async (command, args) => { linux.push([command, ...args]); return { stdout: '', stderr: '' } },
  268. })
  269. expect(linux).toEqual([['firefox', '/w/page.html']])
  270. // Unset $BROWSER: xdg-open's association is the fallback.
  271. const bare: string[][] = []
  272. await openNativePath('/w/page.html', new AbortController().signal, {
  273. platform: 'linux',
  274. osRelease: '6.8.0-generic',
  275. env: {},
  276. run: async (command, args) => { bare.push([command, ...args]); return { stdout: '', stderr: '' } },
  277. })
  278. expect(bare).toEqual([['xdg-open', '/w/page.html']])
  279. // Windows names no browser without the UserChoice registry.
  280. const win: string[][] = []
  281. await openNativePath('C:\\w\\page.html', new AbortController().signal, {
  282. platform: 'win32',
  283. run: async (command, args) => { win.push([command, ...args]); return { stdout: '', stderr: '' } },
  284. })
  285. expect(win[0]?.[0]).toBe('explorer.exe')
  286. })
  287. it('hands browser-renderable WSL paths to the Windows desktop', async () => {
  288. const calls: string[][] = []
  289. await openNativePath('/home/test/page.html', new AbortController().signal, {
  290. platform: 'linux',
  291. osRelease: '5.15.153.1-microsoft-standard-WSL2',
  292. env: { BROWSER: 'firefox' },
  293. run: async (command, args) => {
  294. calls.push([command, ...args])
  295. return {
  296. stdout: command === 'wslpath' ? 'C:\\workspace\\page.html\n' : '',
  297. stderr: '',
  298. }
  299. },
  300. })
  301. expect(calls).toEqual([
  302. ['wslpath', '-w', '/home/test/page.html'],
  303. ['explorer.exe', 'file:///C:/workspace/page.html'],
  304. ])
  305. })
  306. })
  307. describe('canOpenNativePath', () => {
  308. it('always answers yes where the desktop is part of the platform', () => {
  309. expect(canOpenNativePath({ platform: 'darwin', env: {} })).toBe(true)
  310. expect(canOpenNativePath({ platform: 'win32', env: {} })).toBe(true)
  311. })
  312. it('requires a display server or WSL interop on linux', () => {
  313. const linux = { platform: 'linux' as const, osRelease: '6.8.0-generic' }
  314. // Headless is the case the capability exists for: `xdg-open` would spawn
  315. // into nothing, so a surface should show the path as text instead.
  316. expect(canOpenNativePath({ ...linux, env: {} })).toBe(false)
  317. expect(canOpenNativePath({ ...linux, env: { DISPLAY: ':0' } })).toBe(true)
  318. expect(canOpenNativePath({ ...linux, env: { WAYLAND_DISPLAY: 'wayland-0' } })).toBe(true)
  319. expect(canOpenNativePath({
  320. platform: 'linux', osRelease: '5.15.153.1-microsoft-standard-WSL2', env: {},
  321. })).toBe(true)
  322. })
  323. it('answers no on a platform the opener does not support', () => {
  324. expect(canOpenNativePath({ platform: 'freebsd', env: {} })).toBe(false)
  325. })
  326. it('samples the ambient environment when no override is supplied', () => {
  327. const env = process.env
  328. const marked = (value: string | undefined): boolean => value !== undefined && value !== ''
  329. const expected = marked(env.WSL_DISTRO_NAME) || marked(env.WSL_INTEROP)
  330. || marked(env.DISPLAY) || marked(env.WAYLAND_DISPLAY)
  331. expect(canOpenNativePath({ platform: 'linux', osRelease: '6.8.0-generic' })).toBe(expected)
  332. })
  333. it('samples the ambient platform when none is named', () => {
  334. // The internals are a test seam; a deployment calls this with nothing and
  335. // must get the answer for the host it is actually running on.
  336. expect(canOpenNativePath()).toBe(canOpenNativePath({ platform: process.platform }))
  337. })
  338. })
  339. describe('native file manager', () => {
  340. it.each([
  341. ['darwin', 'finder', '/tmp/my report.txt', 'open', ['-R', '/tmp/my report.txt']],
  342. ['win32', 'explorer', 'C:\\work\\my report.txt', 'explorer.exe', ['/select,', 'file:///C:/work/my%20report.txt']],
  343. ['linux', 'directory', '/tmp/a $b; report.txt', 'xdg-open', ['/tmp']],
  344. ] as const)('reveals through %s without opening the file association', async (platform, manager, path, command, args) => {
  345. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  346. const internals = { platform, env: {}, osRelease: 'generic', run }
  347. expect(nativeFileManager(internals)).toBe(manager)
  348. await revealNativePath(path, signal(), internals)
  349. expect(run).toHaveBeenCalledExactlyOnceWith(command, args, expect.any(AbortSignal),
  350. platform === 'win32' ? 'visible' : 'hidden')
  351. })
  352. it('selects a translated WSL path in Explorer and never starts a Linux file manager', async () => {
  353. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: 'C:\\work\\报告.txt\r\n', stderr: '' }))
  354. const internals = { platform: 'linux' as const, env: { WSL_DISTRO_NAME: 'Ubuntu' }, run }
  355. expect(nativeFileManager(internals)).toBe('explorer')
  356. await revealNativePath('/mnt/c/work/报告.txt', signal(), internals)
  357. expect(run.mock.calls.map(([cmd, args]) => [cmd, args])).toEqual([
  358. ['wslpath', ['-w', '/mnt/c/work/报告.txt']], ['explorer.exe', ['/select,', 'file:///C:/work/报告.txt']],
  359. ])
  360. })
  361. it('refuses empty WSL translations and cancelled translation without launching Explorer', async () => {
  362. const abort = new AbortController()
  363. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: '', stderr: '' }))
  364. const internals = { platform: 'linux' as const, env: {}, osRelease: 'microsoft', run }
  365. await expect(revealNativePath('/file', signal(), internals)).rejects.toThrow('no Windows path')
  366. run.mockImplementationOnce(async () => { abort.abort(new Error('stopped')); return { stdout: 'C:\\file', stderr: '' } })
  367. await expect(revealNativePath('/file', abort.signal, internals)).rejects.toThrow('stopped')
  368. expect(run.mock.calls.every(([cmd]) => cmd === 'wslpath')).toBe(true)
  369. })
  370. it('rejects unsupported platforms, cancellation, and launcher errors', async () => {
  371. const run = vi.fn<PathOpenerRunner>().mockRejectedValue(new Error('desktop failed'))
  372. expect(nativeFileManager({ platform: 'aix' })).toBeNull()
  373. await expect(revealNativePath('/file', signal(), { platform: 'aix', run })).rejects.toThrow('unsupported')
  374. await expect(revealNativePath('/file', AbortSignal.abort(new Error('cancelled')), { run })).rejects.toThrow('cancelled')
  375. expect(run).not.toHaveBeenCalled()
  376. await expect(revealNativePath('/file', signal(), { platform: 'darwin', run })).rejects.toThrow('desktop failed')
  377. expect(nativeFileManager()).toBe(process.platform === 'darwin' ? 'finder' : process.platform === 'win32' ? 'explorer' : 'directory')
  378. })
  379. })
  380. it('uses the native runner for a file-manager handoff when none is injected', async () => {
  381. execFileMock.mockImplementation((_command, _args, _options, callback) => { callback(null, '', '') })
  382. await revealNativePath('/tmp/report.txt', signal())
  383. expect(execFileMock).toHaveBeenCalled()
  384. })
  385. it.each(['win32', 'linux'] as const)('accepts Explorer delegate exit 1 through the native runner on %s', async (platform) => {
  386. execFileMock.mockImplementation((command, _args, _options, callback) => {
  387. if (command === 'wslpath') callback(null, 'C:\\work\\report.txt', '')
  388. else callback(Object.assign(new Error('delegated'), { code: 1 }), '', '')
  389. })
  390. await expect(revealNativePath(platform === 'win32' ? 'C:\\work\\report.txt' : '/mnt/c/work/report.txt', signal(),
  391. { platform, env: { WSL_DISTRO_NAME: 'Ubuntu' } })).resolves.toBeUndefined()
  392. })
  393. it.each([2, 'ENOENT', undefined])('preserves Explorer failure %s', async (code) => {
  394. const failure = Object.assign(new Error('launch failed'), code === undefined ? {} : { code })
  395. execFileMock.mockImplementation((_command, _args, _options, callback) => { callback(failure, '', '') })
  396. await expect(revealNativePath('C:\\file.txt', signal(), { platform: 'win32' })).rejects.toMatchObject({ code })
  397. })
  398. it('preserves cancellation even when Explorer returns delegate exit 1', async () => {
  399. const abort = new AbortController()
  400. const reason = new Error('cancelled')
  401. const run = vi.fn<PathOpenerRunner>(async () => {
  402. abort.abort(reason)
  403. throw Object.assign(new Error('delegated'), { code: 1 })
  404. })
  405. await expect(revealNativePath('C:\\file.txt', abort.signal, { platform: 'win32', run })).rejects.toBe(reason)
  406. })
  407. it.each(['win32', 'linux'] as const)('accepts the Explorer delegate exit 1 when opening on %s', async (platform) => {
  408. // The settings sheet's open gesture must survive the same handoff reveal does.
  409. const run = vi.fn<PathOpenerRunner>(async (command) => {
  410. if (command === 'wslpath') return { stdout: 'C:\\work\\settings.yaml', stderr: '' }
  411. throw Object.assign(new Error('delegated'), { code: 1 })
  412. })
  413. await expect(openNativePath(
  414. platform === 'win32' ? 'C:\\work\\settings.yaml' : '/mnt/c/work/settings.yaml', signal(),
  415. { platform, env: { WSL_DISTRO_NAME: 'Ubuntu' }, run },
  416. )).resolves.toBeUndefined()
  417. })
  418. it('preserves a non-delegate Explorer failure when opening', async () => {
  419. const failure = Object.assign(new Error('launch failed'), { code: 2 })
  420. const run = vi.fn<PathOpenerRunner>().mockRejectedValue(failure)
  421. await expect(openNativePath('C:\\file.txt', signal(), { platform: 'win32', run })).rejects.toBe(failure)
  422. })
  423. it.each([
  424. ['C:\\my files\\报告,#%.txt', 'file:///C:/my%20files/报告%2C%23%25.txt'],
  425. ['\\\\server\\share\\a,b.txt', 'file://server/share/a%2Cb.txt'],
  426. ])('preserves special characters in the Explorer target %s', async (path, target) => {
  427. const run = vi.fn<PathOpenerRunner>().mockResolvedValue({ stdout: '', stderr: '' })
  428. await revealNativePath(path, signal(), { platform: 'win32', run })
  429. expect(run).toHaveBeenCalledWith('explorer.exe', ['/select,', target], expect.any(AbortSignal), 'visible')
  430. })
  431. it.each(['.html', '.svg'])('uses the file association for %s despite a configured browser', async (extension) => {
  432. const path = `/work/report${extension}`
  433. for (const platform of ['darwin', 'linux'] as const) {
  434. const run = vi.fn<PathOpenerRunner>(async () => ({ stdout: 'browser bundle', stderr: '' }))
  435. const lifetime = signal()
  436. await openNativeAssociatedPath(path, lifetime, {
  437. platform, osRelease: '6.8.0-generic', env: { BROWSER: 'custom-browser' }, run,
  438. })
  439. expect(run.mock.calls).toEqual([[platform === 'darwin' ? 'open' : 'xdg-open', [path], lifetime, 'hidden']])
  440. }
  441. })