The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): read file: URLs with one shared parser
Bear Huddleston072452f7f4bb
diff --git a/apps/desktop/electron/media-protocol.test.ts b/apps/desktop/electron/media-protocol.test.tsindex e10771b1e75..83da3062f2f 100644--- a/apps/desktop/electron/media-protocol.test.ts+++ b/apps/desktop/electron/media-protocol.test.ts@@ -40,8 +40,27 @@ describe('media protocol helpers', () => {expect(isStreamableMediaPath('/tmp/render.MP4')).toBe(true)expect(isStreamableMediaPath('/tmp/voice.flac')).toBe(true)expect(isStreamableMediaPath('/tmp/secrets.txt')).toBe(false)+ expect(isStreamableMediaPath('file:///tmp/render.MP4#t=30')).toBe(true)+ expect(isStreamableMediaPath('file://nas/share/voice.flac?download=1')).toBe(true)+ expect(isStreamableMediaPath('file:///tmp/secrets.txt?name=clip.mp4')).toBe(false)+ expect(isStreamableMediaPath('file://%invalid/clip.mp4')).toBe(false)})+ // Decoding an encoded separator would add a path segment the URL never had.+ it.each(['file:///tmp/..%2f..%2fetc/clip.mp4', 'file:///C:/media/..%5cclip.mp4', 'file://nas/share/..%5Cclip.mp4'])(+ 'refuses the encoded separator in %s',+ async url => {+ const deps = dependencies()++ expect(isStreamableMediaPath(url)).toBe(false)+ expect(() => remoteMediaEndpoint('https://gateway.test', url)).toThrow('Invalid media file URL')+ expect(+ (await createMediaProtocolHandler(deps)(request(`hermes-media://remote/${encodeURIComponent(url)}`))).status+ ).toBe(415)+ expect(deps.fetchRemote).not.toHaveBeenCalled()+ }+ )+it('forwards range/cache negotiation headers but strips renderer credentials', () => {const headers = mediaRequestHeaders(new Headers({@@ -147,7 +166,16 @@ describe('createMediaProtocolHandler', () => {expect(deps.resolveRemoteConnection).not.toHaveBeenCalled()})- it('proxies token-auth remote media without placing the token in the URL', async () => {+ it.each([+ ['/root/outputs/render.mp4', '/root/outputs/render.mp4'],+ ['file:///tmp/video%20clip.mp4', '/tmp/video clip.mp4'],+ ['file://localhost/tmp/video%20clip.mp4#t=30', '/tmp/video clip.mp4'],+ ['file:///tmp/video%20clip.mp4?download=1', '/tmp/video clip.mp4'],+ ['file:///C:/Users/Alice/video%20clip.mp4', 'file:///C:/Users/Alice/video%20clip.mp4'],+ ['file://nas/share/video%20clip.mp4', 'file://nas/share/video%20clip.mp4'],+ ['file:///C:/Users/Alice/video%20clip.mp4#t=30', 'file:///C:/Users/Alice/video%20clip.mp4#t=30'],+ ['file://nas/share/video%20clip.mp4?download=1', 'file://nas/share/video%20clip.mp4?download=1']+ ])('keeps old POSIX gateways working and preserves drive/UNC information for %s', async (file, expectedPath) => {const deps = dependencies({resolveRemoteConnection: vi.fn(async () => ({authMode: 'token' as const,@@ -158,7 +186,7 @@ describe('createMediaProtocolHandler', () => {})const response = await createMediaProtocolHandler(deps)(- request('hermes-media://remote/%2Froot%2Foutputs%2Frender.mp4?connectionId=work-ssh&profile=reviewer', {+ request(`hermes-media://remote/${encodeURIComponent(file)}?connectionId=work-ssh&profile=reviewer`, {Range: 'bytes=0-1023'}))@@ -169,7 +197,7 @@ describe('createMediaProtocolHandler', () => {const [rawUrl, headers] = vi.mocked(deps.fetchRemote).mock.calls[0]const url = new URL(rawUrl)expect(url.pathname).toBe('/hermes/api/files/stream')- expect(url.searchParams.get('path')).toBe('/root/outputs/render.mp4')+ expect(url.searchParams.get('path')).toBe(expectedPath)expect(url.searchParams.has('token')).toBe(false)expect(headers.get('x-hermes-session-token')).toBe('s e/cret')expect(headers.get('range')).toBe('bytes=0-1023')diff --git a/apps/desktop/electron/media-protocol.ts b/apps/desktop/electron/media-protocol.tsindex 7c8e1c7830a..a30e84048f5 100644--- a/apps/desktop/electron/media-protocol.ts+++ b/apps/desktop/electron/media-protocol.ts@@ -1,3 +1,5 @@+import { fileUrlToNativePath } from '../../shared/src/file-url'+import { httpStatusError, readStatusCode } from './api-transport'import { requestWithOauthFallback } from './oauth-rest-request'@@ -97,7 +99,13 @@ export function mediaProtocolDownloadName(rawUrl: string): null | string {}export function isStreamableMediaPath(filePath: string): boolean {- const lower = filePath.toLowerCase()+ const mediaPath = /^file:/i.test(filePath) ? fileUrlToNativePath(filePath) : filePath++ if (mediaPath === null) {+ return false+ }++ const lower = mediaPath.toLowerCase()return STREAMABLE_MEDIA_EXTENSIONS.some(extension => lower.endsWith(extension))}@@ -124,6 +132,21 @@ export function remoteMediaEndpoint(baseUrl: string, filePath: string, profile?:throw new Error(`Unsupported Hermes backend URL protocol: ${url.protocol}`)}+ if (/^file:/i.test(filePath)) {+ const nativePath = fileUrlToNativePath(filePath)++ if (nativePath === null) {+ throw new Error('Invalid media file URL')+ }++ // Older gateways accept native POSIX paths, not file URIs. Keep that+ // lossless contract, but leave drive letters and UNC hosts (a native path+ // not starting with `/`) to the gateway.+ if (nativePath.startsWith('/')) {+ filePath = nativePath+ }+ }+url.searchParams.set('path', filePath)if (profile) {diff --git a/apps/desktop/src/app/chat/right-rail/preview-file.tsx b/apps/desktop/src/app/chat/right-rail/preview-file.tsxindex d47e7fa4ad5..fa822fe19fe 100644--- a/apps/desktop/src/app/chat/right-rail/preview-file.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-file.tsx@@ -1,3 +1,4 @@+import { fileUrlToNativePath } from '@hermes/shared'import { useStore } from '@nanostores/react'import type * as React from 'react'import type {@@ -202,13 +203,7 @@ function filePathForTarget(target: PreviewTarget) {return target.path}- try {- const url = new URL(target.url)-- return url.protocol === 'file:' ? decodeURIComponent(url.pathname) : target.url- } catch {- return target.url- }+ return fileUrlToNativePath(target.url) ?? target.url}function formatBytes(bytes: number | undefined) {diff --git a/apps/desktop/src/lib/local-preview.test.ts b/apps/desktop/src/lib/local-preview.test.tsindex 36baae2cb02..d57719fe76d 100644--- a/apps/desktop/src/lib/local-preview.test.ts+++ b/apps/desktop/src/lib/local-preview.test.ts@@ -13,9 +13,11 @@ import {localPreviewTarget,normalizeOrLocalPreviewTarget,openPreviewTargetInBrowser,+ pathToFileUrl,remoteHtmlPreviewDocument,validatedRemoteHtmlDataUrl} from './local-preview'+import { previewArtifactKey } from './preview-targets'describe('isLoopbackPreviewUrl', () => {it.each(['http://localhost:5173', 'https://127.0.0.2:8443/app', 'http://0.0.0.0:3000', 'http://[::1]:4173'])(@@ -212,6 +214,63 @@ describe('remote HTML previews', () => {})})+describe('preview path resolution', () => {+ // Drive and UNC URLs read back as native Windows paths, so a UNC target+ // keeps its host when re-serialized instead of becoming `file:////server/...`.+ it.each([+ 'C:\\work tree\\résumé #1.py',+ '\\\\server\\share\\source.py',+ '/srv/source.py',+ '/srv/name\\with%20spaces.py',+ '//srv/share/source.py'+ ])('resolves the file URL of %s back to the same filesystem target', path => {+ const target = localPreviewTarget(pathToFileUrl(path), '/unrelated/cwd')++ expect(target?.path).toBe(path)+ expect(target?.url).toBe(pathToFileUrl(path))+ })++ it.each([+ ['file:///C:/work%20tree/source.py', 'C:\\work tree\\source.py', 'file:///C%3A/work%20tree/source.py'],+ ['file://server/share/source.py', '\\\\server\\share\\source.py', 'file://server/share/source.py']+ ])('reads %s as the Windows path %s', (url, path, fileUrl) => {+ expect(localPreviewTarget(url)).toMatchObject({ label: 'source.py', path, url: fileUrl })+ })++ // Decoding `..%2f` would add a segment the URL parser never normalized. Such+ // a URL keeps its text undecoded, as an unparseable one does, and the preview+ // artifact key leaves it raw too.+ it.each(['file:///srv/project/..%2f..%2fetc/passwd', 'file:///C:/work/..%5c..%5cWindows/win.ini'])(+ 'does not decode the encoded separators in %s into path segments',+ url => {+ expect(localPreviewTarget(url, '/unrelated/cwd')?.path).toBe(url.slice('file://'.length))+ expect(previewArtifactKey(url, '/unrelated/cwd')).toBe(url)+ }+ )++ it('keeps absolute filesystem targets independent of the working directory', async () => {+ window.hermesDesktop = { normalizePreviewTarget: vi.fn(async () => null) } as never+ const cwd = 'C:\\work tree'++ const absolutePaths = [+ 'C:\\work tree\\source.py',+ 'D:/other project/source.py',+ '\\\\server\\share\\source.py',+ '/srv/source.py',+ '//srv/share/source.py'+ ]++ for (const path of absolutePaths) {+ await expect(normalizeOrLocalPreviewTarget(path, cwd)).resolves.toMatchObject({ path })+ }++ // Relative targets join through the separator-normalizing resolver.+ await expect(normalizeOrLocalPreviewTarget('source.py', cwd)).resolves.toMatchObject({+ path: 'C:/work tree/source.py'+ })+ })+})+describe('PDF previews', () => {it('classifies PDF files as PDF previews', () => {expect(localPreviewTarget('/tmp/spec.pdf')).toMatchObject({diff --git a/apps/desktop/src/lib/local-preview.ts b/apps/desktop/src/lib/local-preview.tsindex f12a34f73e7..076426b9c6d 100644--- a/apps/desktop/src/lib/local-preview.ts+++ b/apps/desktop/src/lib/local-preview.ts@@ -1,3 +1,4 @@+import { fileUrlToNativePath } from '@hermes/shared'import DOMPurify from 'dompurify'import { isDesktopFsRemoteMode, readDesktopFileDataUrl, readDesktopFileText } from '@/lib/desktop-fs'@@ -241,11 +242,8 @@ export function localPreviewTarget(rawTarget: string, cwd?: string | null): Prevlet path = rawif (/^file:\/\//i.test(raw)) {- try {- path = decodeURIComponent(new URL(raw).pathname)- } catch {- path = raw.replace(/^file:\/\//i, '')- }+ // A URL that does not parse, or encodes a separator, keeps its text undecoded.+ path = fileUrlToNativePath(raw) ?? raw.replace(/^file:\/\//i, '')} else if (!raw.startsWith('/') && !isWindowsAbsolutePath(raw) && cwd) {path = joinPath(cwd, raw)}diff --git a/apps/desktop/src/lib/media.remote.test.ts b/apps/desktop/src/lib/media.remote.test.tsindex f4d158f6242..ddbe284237d 100644--- a/apps/desktop/src/lib/media.remote.test.ts+++ b/apps/desktop/src/lib/media.remote.test.ts@@ -22,6 +22,19 @@ describe('filePathFromMediaPath', () => {it('decodes a file:// URL with encoded characters', () => {expect(filePathFromMediaPath('file:///tmp/a%20b.png')).toBe('/tmp/a b.png')})++ // The URL's own `/C:/...` pathname opens nothing on Windows, and dropping a+ // UNC host named another file.+ it.each([+ ['file:///C:/Users/me/a%20b.png', 'C:\\Users\\me\\a b.png'],+ ['file://nas/share/a%20b.png', '\\\\nas\\share\\a b.png']+ ])('reads %s as the Windows path %s', (url, path) => {+ expect(filePathFromMediaPath(url)).toBe(path)+ })++ it.each(['file:///tmp/..%2f..%2fetc/a.png', 'file:///tmp/100%.png'])('keeps %s undecoded', url => {+ expect(filePathFromMediaPath(url)).toBe(url.slice('file://'.length))+ })})describe('mediaExternalUrl', () => {@@ -50,6 +63,15 @@ describe('mediaExternalUrl', () => {)})+ it('downloads a Windows gateway file URL by its native path', () => {+ $connection.set({ mode: 'remote', baseUrl: 'https://gw', token: 't' } as never)++ expect(new URL(mediaExternalUrl('file:///C:/Users/me/a%20b.png')).searchParams.get('path')).toBe(+ 'C:\\Users\\me\\a b.png'+ )+ expect(new URL(mediaExternalUrl('file://nas/share/a.png')).searchParams.get('path')).toBe('\\\\nas\\share\\a.png')+ })+it('falls back to file:// when remote connection lacks a token', () => {$connection.set({ mode: 'remote', baseUrl: 'https://gw' } as never)expect(mediaExternalUrl('/tmp/a.png')).toBe('file:///tmp/a.png')@@ -84,7 +106,19 @@ describe('mediaGatewayStreamUrl', () => {it('rewrites gateway-local media to the main-process remote stream proxy', () => {$connection.set({ mode: 'remote', baseUrl: 'https://gw', token: 's e/cret' } as never)- expect(mediaGatewayStreamUrl('file:///tmp/a b.mp4')).toBe('hermes-media://remote/%2Ftmp%2Fa%20b.mp4')++ for (const path of [+ '/tmp/a b.mp4',+ 'file:///tmp/a%20b.mp4',+ 'C:/Users/Alice/video.mp4',+ 'file:///C:/Users/Alice/video%20clip.mp4',+ 'file://nas/share/video%20clip.mp4'+ ]) {+ const url = new URL(mediaGatewayStreamUrl(path))+ expect(url.protocol).toBe('hermes-media:')+ expect(url.hostname).toBe('remote')+ expect.soft(decodeURIComponent(url.pathname.slice(1)), path).toBe(path)+ }})it('supports OAuth remotes with no renderer-visible token and scopes pool profiles', () => {@@ -166,6 +200,29 @@ describe('resolveMediaDisplaySrc', () => {)expect(readFileDataUrl).toHaveBeenCalledWith('/Users/me/project/a b.png')})++ it('reads Windows file URLs from the local desktop shell by their native path', async () => {+ const readFileDataUrl = vi.fn(async () => 'data:image/png;base64,bG9jYWw=')++ vi.stubGlobal('window', { hermesDesktop: { readFileDataUrl } })+ $connection.set({ mode: 'local' } as never)++ await resolveMediaDisplaySrc('file:///C:/Users/me/a%20b.png')+ await resolveMediaDisplaySrc('file://nas/share/a.png')+ expect(readFileDataUrl.mock.calls).toEqual([['C:\\Users\\me\\a b.png'], ['\\\\nas\\share\\a.png']])+ })++ it('reads an owner-pinned Windows file URL through the gateway by its native path', async () => {+ vi.stubGlobal('window', { hermesDesktop: { api } })+ $connection.set({ mode: 'remote' } as never)++ await resolveMediaDisplaySrc('file:///C:/Users/me/a%20b.png', { connectionId: 'win-gw', profile: 'work' })+ expect(api).toHaveBeenCalledWith({+ connectionId: 'win-gw',+ path: `/api/fs/read-data-url?path=${encodeURIComponent('C:\\Users\\me\\a b.png')}`,+ profile: 'work'+ })+ })})describe('resolveMediaPlaybackSrc', () => {@@ -199,6 +256,9 @@ describe('resolveMediaPlaybackSrc', () => {await expect(resolveMediaPlaybackSrc('C:\\renders\\demo.mp4')).resolves.toBe('hermes-media://stream/C%3A%5Crenders%5Cdemo.mp4')+ await expect(resolveMediaPlaybackSrc('file:///C:/renders/demo.mp4')).resolves.toBe(+ 'hermes-media://stream/C%3A%5Crenders%5Cdemo.mp4'+ )})})diff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.tsindex e235301920c..ccf10f0ec81 100644--- a/apps/desktop/src/lib/media.ts+++ b/apps/desktop/src/lib/media.ts@@ -1,4 +1,4 @@-import { LOCAL_CONNECTION_ID } from '@hermes/shared'+import { fileUrlToNativePath, LOCAL_CONNECTION_ID } from '@hermes/shared'import { capabilityScoped, hermesApi, type OwnerScope } from '@/api/client'import type { HermesConnection } from '@/global'@@ -292,7 +292,7 @@ export function mediaGatewayStreamUrl(path: string): string {const conn = $connection.get()if (isRemoteGateway()) {- const file = encodeURIComponent(filePathFromMediaPath(path))+ const file = encodeURIComponent(path)const scope = [conn?.connectionId ? `connectionId=${encodeURIComponent(conn.connectionId)}` : '',@@ -326,16 +326,16 @@ export function mediaPathFromMarkdownHref(href?: string): string | null {}}+// A drive or UNC URL becomes its Windows path (`C:\…`, `\\host\share\…`): the+// desktop fs bridge and the gateway's fs routes open those on Windows, while+// the URL's own `/C:/…` pathname opens nothing there. A URL that does not+// decode, or encodes a separator, keeps its text undecoded.export function filePathFromMediaPath(path: string): string {- if (!path.startsWith('file:')) {+ if (!/^file:/i.test(path)) {return path}- try {- return decodeURIComponent(new URL(path).pathname)- } catch {- return path.replace(/^file:\/\//, '')- }+ return fileUrlToNativePath(path) ?? path.replace(/^file:\/\//i, '')}// True when this desktop shell is wired to a remote gateway. Local media pathsdiff --git a/apps/desktop/src/lib/preview-targets.test.ts b/apps/desktop/src/lib/preview-targets.test.tsindex ac738f254de..cadfd8c8a98 100644--- a/apps/desktop/src/lib/preview-targets.test.ts+++ b/apps/desktop/src/lib/preview-targets.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'import {extractPreviewTargets,+ previewArtifactKey,previewName,previewTargetFromMarkdownHref,stripPreviewTargets@@ -18,6 +19,14 @@ describe('previewName', () => {])('labels %s by its file name', target => {expect(previewName(target)).toBe('report.html')})++ it.each([+ ['file:///C:/work%20tree/report%20%231.html', 'report #1.html'],+ ['file://server/share/report.html', 'report.html'],+ ['file:///srv/100%.txt', '100%.txt']+ ])('labels file URL %s by its file name', (url, name) => {+ expect(previewName(url)).toBe(name)+ })})describe('preview target detection', () => {@@ -43,3 +52,27 @@ describe('preview target detection', () => {expect(stripPreviewTargets('[Preview: demo.html](#preview:%2Ftmp%2Fdemo.html)\nopen it')).toBe('\nopen it')})})++describe('previewArtifactKey', () => {+ it.each([+ ['file:///srv/report%20%231.html', '/srv/report #1.html'],+ ['file:///C:/work%20tree/report.html', 'C:\\work tree\\report.html'],+ ['file:///C:/work%20tree/report.html', 'C:/work tree/report.html'],+ ['file://server/share/report.html', '\\\\server\\share\\report.html'],+ ['file:////srv/share/report.html', '//srv/share/report.html'],+ // `\` separates only in drive and UNC paths; a POSIX name may contain one.+ ['file:///srv/name%5Cdraft.html', '/srv/name\\draft.html']+ ])('keys %s as the same artifact as %s', (url, path) => {+ expect(previewArtifactKey(url, '/work')).toBe(previewArtifactKey(path, '/work'))+ })++ it.each([+ 'file:///srv/project/..%2f..%2fetc/passwd',+ 'file:///srv/project/..%2F..%2Fetc/passwd',+ 'file:///C:/work/..%5c..%5cWindows/win.ini',+ 'file://server/share/..%5Csecret.txt',+ 'file:///tmp/100%.txt'+ ])('leaves %s undecoded', url => {+ expect(previewArtifactKey(url, '/work')).toBe(url)+ })+})diff --git a/apps/desktop/src/lib/preview-targets.ts b/apps/desktop/src/lib/preview-targets.tsindex 8f472241aba..3dc01e8498c 100644--- a/apps/desktop/src/lib/preview-targets.ts+++ b/apps/desktop/src/lib/preview-targets.ts@@ -1,3 +1,5 @@+import { fileUrlToNativePath } from '@hermes/shared'+import { isWindowsAbsolutePath } from '@/lib/path-compare'const PREVIEW_MARKDOWN_RE = /\[Preview:[^\]]+\]\((?<href>#preview[:/][^)]+)\)/gi@@ -48,7 +50,8 @@ export function previewName(target: string): string {const url = new URL(target)if (url.protocol === 'file:') {- return decodeURIComponent(url.pathname).split(/[\\/]/).filter(Boolean).pop() || target+ // A URL that does not decode, or encodes a separator, is labelled by its raw path.+ return (fileUrlToNativePath(target) ?? url.pathname).split(/[\\/]/).filter(Boolean).pop() || target}const file = url.pathname.split('/').filter(Boolean).pop()@@ -68,24 +71,13 @@ export function previewArtifactKey(target: string, cwd: string): string {}if (/^file:\/\//i.test(path)) {- try {- const url = new URL(path)-- // Encoded separators are not legal file-URL path segments.- if (/%2f|%5c/i.test(url.pathname)) {- return path- }-- path = decodeURIComponent(url.pathname)-- if (url.hostname) {- path = `//${url.hostname}${path}`- } else if (/^\/[a-z]:\//i.test(path)) {- path = path.slice(1)- }- } catch {+ const filePath = fileUrlToNativePath(path)++ if (filePath === null) {return path}++ path = filePath}const windows = /^[a-z]:[\\/]/i.test(path) || path.startsWith('\\\\')diff --git a/apps/desktop/tsconfig.electron.json b/apps/desktop/tsconfig.electron.jsonindex 8f0a2964cb7..2fb7b323075 100644--- a/apps/desktop/tsconfig.electron.json+++ b/apps/desktop/tsconfig.electron.json@@ -17,6 +17,6 @@"rootDir": "..","outDir": "build/electron-types"},- "include": ["electron", "product-identity.cjs", "product-identity.d.cts", "update-feed.cjs", "update-feed.d.cts", "../shared/src/ansi.ts", "../shared/src/data-url-read-max.ts", "../shared/src/external-url.ts", "../shared/src/translucency.ts"],+ "include": ["electron", "product-identity.cjs", "product-identity.d.cts", "update-feed.cjs", "update-feed.d.cts", "../shared/src/ansi.ts", "../shared/src/data-url-read-max.ts", "../shared/src/external-url.ts", "../shared/src/file-url.ts", "../shared/src/translucency.ts"],"exclude": ["src", "electron/**/*.e2e.mts"]}diff --git a/apps/shared/src/file-url.test.ts b/apps/shared/src/file-url.test.tsnew file mode 100644index 00000000000..0869a08c06e--- /dev/null+++ b/apps/shared/src/file-url.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest'++import { fileUrlToNativePath } from './file-url'++describe('fileUrlToNativePath', () => {+ it.each([+ ['file:///srv/report.html', '/srv/report.html'],+ ['file:///srv/report%20%231%3F.html', '/srv/report #1?.html'],+ ['file:///srv/100%25.txt', '/srv/100%.txt'],+ ['file:///srv/r%C3%A9sum%C3%A9.md', '/srv/résumé.md'],+ ['file:///srv/clip.mp4?download=1#t=30', '/srv/clip.mp4'],+ ['file://localhost/srv/report.html', '/srv/report.html'],+ ['FILE:///srv/report.html', '/srv/report.html'],+ // No host: a POSIX double-slash path, not UNC.+ ['file:////srv/share/report.html', '//srv/share/report.html'],+ // `\` separates only in drive and UNC paths; a POSIX name may contain one.+ ['file:///srv/name%5Cdraft.html', '/srv/name\\draft.html']+ ])('reads POSIX URL %s as %s', (url, path) => {+ expect(fileUrlToNativePath(url)).toBe(path)+ })++ it.each([+ ['file:///C:/work%20tree/report.html', 'C:\\work tree\\report.html'],+ ['file:///c:/Users/me/100%25.txt', 'c:\\Users\\me\\100%.txt'],+ ['file://localhost/C:/work/report.html', 'C:\\work\\report.html'],+ ['file:///C|/work/report.html', 'C:\\work\\report.html'],+ // `pathToFileUrl` encodes the drive colon; the decoded path still names a drive.+ ['file:///C%3A/work/report.html', 'C:\\work\\report.html'],+ ['file:///D:/a/../b/report.html', 'D:\\b\\report.html']+ ])('reads drive URL %s as %s', (url, path) => {+ expect(fileUrlToNativePath(url)).toBe(path)+ })++ it.each([+ ['file://server/share/report%20%231.html', '\\\\server\\share\\report #1.html'],+ ['file://NAS.example/share/report.html', '\\\\nas.example\\share\\report.html'],+ ['file://10.0.0.5/share/report.html', '\\\\10.0.0.5\\share\\report.html']+ ])('reads UNC URL %s as %s', (url, path) => {+ expect(fileUrlToNativePath(url)).toBe(path)+ })++ it.each([+ 'file:///srv/project/..%2f..%2fetc/passwd',+ 'file:///srv/project/..%2F..%2Fetc/passwd',+ 'file:///C:/work/..%2f..%2fWindows/win.ini',+ 'file:///C:/work/..%5c..%5cWindows/win.ini',+ 'file:///C%3A%5CWindows/win.ini',+ 'file://server/share/..%5Csecret.txt'+ ])('refuses the encoded separator in %s', url => {+ expect(fileUrlToNativePath(url)).toBeNull()+ })++ it.each(['file:///tmp/100%.txt', 'file:///tmp/%E0%A4%A.txt', 'file://%invalid/clip.mp4', 'not a url', '', 'file'])(+ 'refuses malformed input %j',+ value => {+ expect(fileUrlToNativePath(value)).toBeNull()+ }+ )++ it.each(['https://example.com/report.html', 'blob:file:///srv/report.html', 'C:\\work\\report.html'])(+ 'refuses non-file URL %s',+ value => {+ expect(fileUrlToNativePath(value)).toBeNull()+ }+ )+})diff --git a/apps/shared/src/file-url.ts b/apps/shared/src/file-url.tsnew file mode 100644index 00000000000..8f04d850849--- /dev/null+++ b/apps/shared/src/file-url.ts@@ -0,0 +1,49 @@+/**+ * Reading a `file:` URL back into the path it names. Desktop meets these URLs+ * in agent output, preview targets and the media pipeline, in the renderer and+ * in Electron main; every surface decodes them with this one rule so a URL+ * names the same file everywhere.+ */++// Drive letter after the path's leading slash. Node's win32 `fileURLToPath`+// tests the decoded path too, so `/C%3A/...` is a drive path.+const DRIVE_PATH_RE = /^\/[a-z]:/i++/**+ * The native path a `file:` URL names, read the way Node's `fileURLToPath`+ * reads it on the OS the URL itself implies: a UNC host or a drive letter can+ * only be Windows (`\\host\share\...`, `C:\...`), anything else is POSIX.+ *+ * The URL decides, not the OS this code runs on: the file may live on a remote+ * gateway or a WSL backend, so a host-platform reading would refuse the POSIX+ * URLs a Windows desktop receives from them, and a key derived from the path+ * would differ by desktop OS.+ *+ * Null when the value is not a parseable `file:` URL, does not percent-decode,+ * or encodes a separator: `%2f` anywhere, `%5c` in a Windows path (a POSIX+ * name may hold a literal backslash).+ */+export function fileUrlToNativePath(value: string): null | string {+ try {+ const { hostname, pathname, protocol } = new URL(value)++ // Decoding an encoded separator would add a segment the URL parser never normalized.+ if (protocol !== 'file:' || /%2f/i.test(pathname)) {+ return null+ }++ const path = decodeURIComponent(pathname)++ if (!hostname && !DRIVE_PATH_RE.test(path)) {+ return path+ }++ if (/%5c/i.test(pathname)) {+ return null+ }++ return (hostname ? `//${hostname}${path}` : path.slice(1)).replace(/\//g, '\\')+ } catch {+ return null+ }+}diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.tsindex 87dc2408dc8..3e93f36fa73 100644--- a/apps/shared/src/index.ts+++ b/apps/shared/src/index.ts@@ -62,6 +62,7 @@ export {DATA_URL_READ_MIN_MAX_MB} from './data-url-read-max'export { type ExternalUrlTarget, externalUrlTarget } from './external-url'+export { fileUrlToNativePath } from './file-url'export { compactNumber } from './format'export { type FuzzyMatch, fuzzyRank, fuzzyScore, fuzzyScoreMulti, type RankedItem } from './fuzzy'export * from './gateway-events'