The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { readDesktopFileDataUrl } = vi.hoisted(() => ({ readDesktopFileDataUrl: vi.fn() }))
vi.mock('@/lib/desktop-fs', () => ({
isDesktopFsRemoteMode: () => true,
readDesktopFileDataUrl,
readDesktopFileText: vi.fn()
}))
import {
isLoopbackPreviewUrl,
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'])(
'accepts loopback origin %s',
url => {
expect(isLoopbackPreviewUrl(url)).toBe(true)
}
)
// mDNS and LAN names are other devices (homeassistant.local), not the dev
// server the agent is building.
it.each(['https://x.com', 'https://localhost.example.com', 'http://homeassistant.local:8123', 'not a URL'])(
'rejects non-loopback or malformed origin %s',
url => {
expect(isLoopbackPreviewUrl(url)).toBe(false)
}
)
})
const remoteTarget = {
kind: 'file' as const,
label: 'report.html',
path: '/srv/report.html',
previewKind: 'html' as const,
source: '/srv/report.html',
url: 'file:///srv/report.html'
}
describe('remote HTML previews', () => {
beforeEach(() => {
vi.clearAllMocks()
window.hermesDesktop = {
normalizePreviewTarget: vi.fn(async () => remoteTarget)
} as never
})
it('loads bounded authenticated bytes while retaining the canonical file URL', async () => {
const dataUrl = `data:text/html;base64,${btoa('<h1>remote</h1>')}`
readDesktopFileDataUrl.mockResolvedValue(dataUrl)
await expect(normalizeOrLocalPreviewTarget('/srv/report.html')).resolves.toEqual({
...remoteTarget,
dataUrl
})
// No session scope: the read names none.
expect(readDesktopFileDataUrl).toHaveBeenCalledWith('/srv/report.html', undefined)
})
it('falls back to source mode when the transport is not canonical HTML', async () => {
readDesktopFileDataUrl.mockResolvedValue('data:text/plain;base64,SGVsbG8=')
await expect(normalizeOrLocalPreviewTarget('/srv/report.html')).resolves.toMatchObject({
renderMode: 'source',
transient: true,
url: 'file:///srv/report.html'
})
})
it('rejects malformed base64', () => {
expect(validatedRemoteHtmlDataUrl('data:text/html;base64,SGVsbG8=')).toBe('data:text/html;base64,SGVsbG8=')
expect(validatedRemoteHtmlDataUrl('data:text/html;base64,SGVsbG8')).toBeNull()
expect(validatedRemoteHtmlDataUrl('data:text/html;base64,SGVsbG8%3D')).toBeNull()
})
it('wraps remote HTML in a deny-by-default content policy', () => {
const html =
'<meta http-equiv="refresh" content="0;url=https://example.test"><a href="https://example.test">remote</a>'
const document = remoteHtmlPreviewDocument(`data:text/html;base64,${btoa(html)}`)
expect(document).toContain(`default-src 'none'`)
expect(document).toContain(`form-action 'none'`)
expect(document).toContain('<a>remote</a>')
expect(document).not.toContain('refresh')
expect(document).not.toContain('https://example.test')
})
it('strips scripts from remote HTML', () => {
const html =
'<p>safe</p><script>document.body.textContent = "SCRIPT-RAN"</script><template><script>TEMPLATE-SCRIPT</script></template>'
const document = remoteHtmlPreviewDocument(`data:text/html;base64,${btoa(html)}`)
expect(document).toContain('<p>safe</p>')
expect(document).not.toContain('<script')
expect(document).not.toContain('SCRIPT-RAN')
expect(document).not.toContain('TEMPLATE-SCRIPT')
})
it('does not create scripts when sanitized HTML is reparsed', () => {
const html = '<form><math><mtext></form><form><mglyph><style></math><script>MUTATION-SCRIPT</script>'
const sanitized = remoteHtmlPreviewDocument(`data:text/html;base64,${btoa(html)}`)
expect(sanitized).not.toContain('<script')
expect(new DOMParser().parseFromString(sanitized ?? '', 'text/html').querySelector('script')).toBeNull()
})
it('decodes remote HTML as UTF-8', () => {
const html = '<p>café 😀</p>'
const payload = btoa(String.fromCharCode(...new TextEncoder().encode(html)))
expect(remoteHtmlPreviewDocument(`data:text/html;base64,${payload}`)).toContain(html)
})
it('stages remote HTML before opening it in the system browser', async () => {
const dataUrl = `data:text/html;base64,${btoa('<h1>remote</h1>')}`
const saveImageBuffer = vi.fn(async (_data: ArrayBuffer | Uint8Array, _ext: string) => '/tmp/report #1?.html')
const openPreviewInBrowser = vi.fn(async () => undefined)
window.hermesDesktop = { openPreviewInBrowser, saveImageBuffer } as never
await openPreviewTargetInBrowser({ ...remoteTarget, dataUrl })
expect(new TextDecoder().decode(saveImageBuffer.mock.calls[0]?.[0])).toBe('<h1>remote</h1>')
expect(saveImageBuffer).toHaveBeenCalledWith(expect.any(Uint8Array), '.html')
expect(openPreviewInBrowser).toHaveBeenCalledWith('file:///tmp/report%20%231%3F.html')
})
it('passes browser blob staging URLs through unchanged', async () => {
const dataUrl = `data:text/html;base64,${btoa('<h1>remote</h1>')}`
const saveImageBuffer = vi.fn(async () => 'blob:http://127.0.0.1:9119/preview')
const openPreviewInBrowser = vi.fn(async () => undefined)
window.hermesDesktop = { openPreviewInBrowser, saveImageBuffer } as never
await openPreviewTargetInBrowser({ ...remoteTarget, dataUrl })
expect(openPreviewInBrowser).toHaveBeenCalledWith('blob:http://127.0.0.1:9119/preview')
})
it('serializes UNC staging paths as file URLs', async () => {
const dataUrl = `data:text/html;base64,${btoa('<h1>remote</h1>')}`
const saveImageBuffer = vi.fn(async () => '\\\\server\\share\\report #1.html')
const openPreviewInBrowser = vi.fn(async () => undefined)
window.hermesDesktop = { openPreviewInBrowser, saveImageBuffer } as never
await openPreviewTargetInBrowser({ ...remoteTarget, dataUrl })
expect(openPreviewInBrowser).toHaveBeenCalledWith('file://server/share/report%20%231.html')
})
it('preserves backslashes in POSIX local file paths', () => {
expect(localPreviewTarget('/tmp/report\\draft.html')?.url).toBe('file:///tmp/report%5Cdraft.html')
})
// #85132: a Windows absolute path is absolute; joining it onto cwd made
// `/repo/C:\\Users\\...` which no filesystem has.
it.each(['C:\\Users\\me\\report.html', 'C:/Users/me/report.html', '\\\\server\\share\\report.html'])(
'treats Windows absolute path %s as absolute instead of joining it onto cwd',
raw => {
expect(localPreviewTarget(raw, '/repo')).toMatchObject({ label: 'report.html', path: raw, previewKind: 'html' })
}
)
it('still joins relative paths onto cwd', () => {
expect(localPreviewTarget('out/report.html', '/repo')?.path).toBe('/repo/out/report.html')
})
it('preserves POSIX double-slash file paths', () => {
expect(localPreviewTarget('//srv/share/report #1?.html')?.url).toBe('file:////srv/share/report%20%231%3F.html')
})
it('opens ordinary targets without staging them', async () => {
const openPreviewInBrowser = vi.fn(async () => undefined)
const saveImageBuffer = vi.fn()
window.hermesDesktop = { openPreviewInBrowser, saveImageBuffer } as never
await openPreviewTargetInBrowser(remoteTarget)
expect(saveImageBuffer).not.toHaveBeenCalled()
expect(openPreviewInBrowser).toHaveBeenCalledWith(remoteTarget.url)
})
it('keeps local HTML source browser opens on their existing path', async () => {
const openPreviewInBrowser = vi.fn(async () => undefined)
window.hermesDesktop = { openPreviewInBrowser } as never
await openPreviewTargetInBrowser({
...remoteTarget,
renderMode: 'source',
source: '/tmp/local.html',
url: 'file:///tmp/local.html'
})
expect(openPreviewInBrowser).toHaveBeenCalledWith('file:///tmp/local.html')
})
it('does not send failed remote HTML paths to the local browser', async () => {
const openPreviewInBrowser = vi.fn(async () => undefined)
window.hermesDesktop = { openPreviewInBrowser } as never
await expect(
openPreviewTargetInBrowser({ ...remoteTarget, renderMode: 'source', transient: true })
).rejects.toThrow('Remote HTML preview could not be loaded')
expect(openPreviewInBrowser).not.toHaveBeenCalled()
})
})
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({
path: '/tmp/spec.pdf',
previewKind: 'pdf'
})
})
it('keeps ordinary text files on the source-preview path', () => {
expect(localPreviewTarget('/tmp/spec.md')).toMatchObject({
language: 'markdown',
previewKind: 'text'
})
})
it('does not UTF-8-enrich remote PDFs before loading their bytes', async () => {
vi.clearAllMocks()
window.hermesDesktop = {
normalizePreviewTarget: vi.fn(async () => null)
} as never
await expect(normalizeOrLocalPreviewTarget('/remote/spec.pdf')).resolves.toMatchObject({
path: '/remote/spec.pdf',
previewKind: 'pdf'
})
expect(readDesktopFileDataUrl).not.toHaveBeenCalled()
})
})