Skip to content

The agent that grows with you

test(webapp): check Windows file URLs from the browser to the gateway

emozilla827490cf766c
diff --git a/apps/desktop/src/lib/browser-file-urls.test.ts b/apps/desktop/src/lib/browser-file-urls.test.ts
new file mode 100644
index 00000000000..14bf507bb58
--- /dev/null
+++ b/apps/desktop/src/lib/browser-file-urls.test.ts
@@ -0,0 +1,92 @@
+import { LOCAL_CONNECTION_ID } from '@hermes/shared'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'
+import { $connection } from '@/store/session'
+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'
+
+import { installBrowserDesktopBridge } from './browser-desktop-bridge'
+import { localPreviewTarget } from './local-preview'
+import { resolveMediaDisplaySrc, resolveMediaPlaybackSrc } from './media'
+
+// The Webapp asks its gateway for a Windows drive-letter or UNC file in the forms the gateway
+// resolves: reads by the native path, streams by the file: URL itself. The gateway half,
+// tests/hermes_cli/test_webapp_file_urls.py, answers these exact requests.
+const FILES = [
+ { dir: 'file:///C:/Users/me/renders', native: 'C:\\Users\\me\\renders' },
+ { dir: 'file://nas/share/renders', native: '\\\\nas\\share\\renders' }
+]
+
+const OWNER = { connectionId: LOCAL_CONNECTION_ID, profile: 'default' }
+const win = window
+let requests: { body: Record<string, unknown>; url: URL }[] = []
+
+beforeEach(() => {
+ requests = []
+ seedWebappSession('served-token')
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: URL, init?: RequestInit) => {
+ requests.push({ body: JSON.parse(String(init?.body ?? '{}')), url: input })
+
+ const answers: Record<string, unknown> = {
+ '/api/files/ticket': { ticket: 'stream-ticket' },
+ '/api/fs/read-data-url': { dataUrl: 'data:image/png;base64,UE5H' },
+ '/api/fs/read-text': { text: '<p>report</p>' }
+ }
+
+ return new Response(JSON.stringify(answers[input.pathname] ?? {}), { status: 200 })
+ })
+ )
+ expect(installBrowserDesktopBridge()).toBe(true)
+ setApiRequestConnection(LOCAL_CONNECTION_ID)
+ setApiRequestProfile('default')
+ $connection.set({ connectionId: LOCAL_CONNECTION_ID, mode: 'remote', profile: 'default' } as never)
+})
+
+afterEach(() => {
+ clearWebappSession()
+ Reflect.deleteProperty(win, 'hermesDesktop')
+ document.documentElement.removeAttribute('data-hermes-desktop-host')
+ setApiRequestConnection(null)
+ setApiRequestProfile(null)
+ $connection.set(null)
+ window.dispatchEvent(new Event('beforeunload'))
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+describe.each(FILES)('a Webapp file under $dir', ({ dir, native }) => {
+ it('reads an image by its native path', async () => {
+ await expect(resolveMediaDisplaySrc(`${dir}/shot%20one.png`, OWNER)).resolves.toBe('data:image/png;base64,UE5H')
+
+ const [read] = requests
+
+ expect(read.url.pathname).toBe('/api/fs/read-data-url')
+ expect(read.url.searchParams.get('path')).toBe(`${native}\\shot one.png`)
+ })
+
+ it('previews a page by its native path', async () => {
+ const target = localPreviewTarget(`${dir}/report%20%231.html`)
+
+ await expect(window.hermesDesktop.readFileText(target?.path ?? '')).resolves.toMatchObject({
+ text: '<p>report</p>'
+ })
+
+ const [read] = requests
+
+ expect(read.url.pathname).toBe('/api/fs/read-text')
+ expect(read.url.searchParams.get('path')).toBe(`${native}\\report #1.html`)
+ })
+
+ it('streams a clip by its file URL, ticketed for that URL', async () => {
+ const clip = `${dir}/clip%20one.mp4`
+ const src = new URL(await resolveMediaPlaybackSrc(clip, OWNER))
+ const [ticket] = requests
+
+ expect(ticket.url.pathname).toBe('/api/files/ticket')
+ expect(ticket.body).toEqual({ path: clip, profile: 'default', route: 'stream' })
+ expect(src.pathname).toBe('/api/files/stream')
+ expect(Object.fromEntries(src.searchParams)).toEqual({ path: clip, profile: 'default', ticket: 'stream-ticket' })
+ })
+})
diff --git a/tests/hermes_cli/test_webapp_file_urls.py b/tests/hermes_cli/test_webapp_file_urls.py
new file mode 100644
index 00000000000..82897c44f51
--- /dev/null
+++ b/tests/hermes_cli/test_webapp_file_urls.py
@@ -0,0 +1,82 @@
+"""The gateway resolves the Webapp's requests for a ``file:`` URL to the file the URL names.
+
+The Webapp asks in two forms (the renderer half is pinned in
+``apps/desktop/src/lib/browser-file-urls.test.ts``). Image and preview reads
+(``/api/fs/read-data-url``, ``/api/fs/read-text``) carry the native path the shared ``file:`` URL
+parser gives: ``C:\\...`` for a drive letter, ``\\\\host\\share\\...`` for a UNC host. Audio and video
+carry the ``file:`` URL itself, ticketed through ``POST /api/files/ticket``, and the gateway decodes it
+on its own OS. On Windows both forms reach drive-letter and UNC files.
+"""
+import base64
+import os
+from pathlib import Path
+
+import pytest
+from starlette.testclient import TestClient
+
+from hermes_cli import web_server
+
+PROFILE = "default"
+
+
+def webapp_client(monkeypatch, tmp_path):
+ """The loopback Webapp's API: the browser credential in the session header, no files root."""
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.delenv("HERMES_DASHBOARD_FILES_ROOT", raising=False)
+ monkeypatch.setenv("HOME", str(home))
+ for key, value in (("auth_required", False), ("bound_host", None)):
+ monkeypatch.setattr(web_server.app.state, key, value, raising=False)
+ client = TestClient(web_server.app)
+ client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
+ yield client
+ client.close()
+
+
[email protected](params=["local", "unc"])
+def files(request, tmp_path):
+ """A clip, an image and a page, named as the Webapp meets them: by their own path (a drive path on
+ Windows) or, on Windows, through a UNC host (the local administrative share, ``\\\\127.0.0.1\\C$``)."""
+ renders = tmp_path / "renders"
+ renders.mkdir()
+ (renders / "clip one.mp4").write_bytes(b"hello")
+ (renders / "shot one.png").write_bytes(b"\x89PNG\r\n\x1a\nimage")
+ (renders / "report #1.html").write_text("<p>report</p>", encoding="utf-8")
+ if request.param == "unc":
+ if os.name != "nt":
+ pytest.skip("UNC hosts are Windows paths")
+ drive, rest = os.path.splitdrive(str(renders))
+ renders = Path(f"\\\\127.0.0.1\\{drive[0]}${rest}")
+ if not renders.is_dir():
+ pytest.skip("the local administrative share is not reachable")
+ return renders
+
+
+def test_the_webapp_plays_a_file_url_through_its_stream_ticket(webapp_client, files):
+ url = (files / "clip one.mp4").as_uri()
+ minted = webapp_client.post("/api/files/ticket", json={"route": "stream", "path": url, "profile": PROFILE})
+ assert minted.status_code == 200, (url, minted.text)
+
+ # The <video> element sends only the ticketed URL, never the session header.
+ media_element = TestClient(web_server.app)
+ stream = media_element.get(
+ "/api/files/stream",
+ params={"path": url, "profile": PROFILE, "ticket": minted.json()["ticket"]},
+ headers={"Range": "bytes=1-3"},
+ )
+ media_element.close()
+ assert (stream.status_code, stream.content) == (206, b"ell"), (url, stream.text)
+
+
+def test_the_webapp_reads_images_and_previews_by_native_path(webapp_client, files):
+ # ``str(path)`` is what the shared parser gives for ``path.as_uri()`` (``apps/shared/src/file-url.ts``).
+ shot = files / "shot one.png"
+ read = webapp_client.get("/api/fs/read-data-url", params={"path": str(shot), "profile": PROFILE})
+ assert read.status_code == 200, (shot, read.text)
+ assert read.json()["dataUrl"] == "data:image/png;base64," + base64.b64encode(shot.read_bytes()).decode()
+
+ page = files / "report #1.html"
+ preview = webapp_client.get("/api/fs/read-text", params={"path": str(page), "profile": PROFILE})
+ assert preview.status_code == 200, (page, preview.text)
+ assert preview.json()["text"] == "<p>report</p>"