Skip to content

The agent that grows with you

fix(desktop): save remote gateway files natively

Paul BlackSwand5a865882a8e
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 212641d92d3..1140a4e53e0 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -4646,6 +4646,62 @@ function fetchJson(url, token, options: any = {}) {
})
}
+function fetchBuffer(url, token, options: any = {}) {
+ return new Promise((resolve, reject) => {
+ let parsed
+
+ try {
+ parsed = new URL(url)
+ } catch (error) {
+ reject(new Error(`Invalid URL: ${error.message}`))
+
+ return
+ }
+
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ reject(new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`))
+
+ return
+ }
+
+ const client = parsed.protocol === 'https:' ? https : http
+ const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
+ const req = client.request(
+ parsed,
+ {
+ method: 'GET',
+ headers: {
+ 'X-Hermes-Session-Token': token
+ }
+ },
+ res => {
+ const chunks = []
+
+ res.on('error', reject)
+ res.on('data', chunk => chunks.push(Buffer.from(chunk)))
+ res.on('end', () => {
+ const buffer = Buffer.concat(chunks)
+ const statusCode = res.statusCode || 500
+
+ if (statusCode >= 400) {
+ reject(new Error(`${statusCode}: ${buffer.toString('utf8').slice(0, 500) || res.statusMessage || ''}`))
+
+ return
+ }
+
+ resolve({ buffer, headers: res.headers || {} })
+ })
+ }
+ )
+
+ req.on('error', reject)
+ req.setTimeout(timeoutMs, () => {
+ req.destroy(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`))
+ })
+ req.end()
+ })
+}
+
function fetchPublicJson(url, options: any = {}) {
// Credential-free JSON GET/POST for public gateway endpoints
// (``/api/status``, ``/api/auth/providers``). Unlike ``fetchJson`` it sends
@@ -6744,6 +6800,158 @@ async function ensureNativeAccessToken(baseUrl: string): Promise<string | null>
}
}
+function fetchBufferViaOauthSession(url, options: any = {}) {
+ return new Promise((resolve, reject) => {
+ const sess = getOauthSession()
+
+ if (!sess) {
+ reject(new Error('OAuth session partition is unavailable.'))
+
+ return
+ }
+
+ let parsed
+
+ try {
+ parsed = new URL(url)
+ } catch (error) {
+ reject(new Error(`Invalid URL: ${error.message}`))
+
+ return
+ }
+
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ reject(new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`))
+
+ return
+ }
+
+ const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
+ const request = electronNet.request({
+ method: 'GET',
+ url,
+ session: sess,
+ useSessionCookies: true,
+ redirect: 'follow'
+ } as any)
+ let timedOut = false
+
+ const timer = setTimeout(() => {
+ timedOut = true
+
+ try {
+ request.abort()
+ } catch {
+ // already finished
+ }
+
+ reject(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`))
+ }, timeoutMs)
+
+ request.on('response', res => {
+ const chunks = []
+
+ res.on('data', chunk => chunks.push(Buffer.from(chunk)))
+ res.on('end', () => {
+ if (timedOut) {
+ return
+ }
+
+ clearTimeout(timer)
+ const buffer = Buffer.concat(chunks)
+ const statusCode = res.statusCode || 500
+
+ if (statusCode >= 400) {
+ reject(new Error(`${statusCode}: ${buffer.toString('utf8').slice(0, 500) || res.statusMessage || ''}`))
+
+ return
+ }
+
+ resolve({ buffer, headers: res.headers || {} })
+ })
+ })
+ request.on('error', error => {
+ if (timedOut) {
+ return
+ }
+
+ clearTimeout(timer)
+ reject(error)
+ })
+ request.end()
+ })
+}
+
+function gatewayFilePath(rawPath) {
+ const value = String(rawPath || '').trim()
+
+ if (!value) {
+ return ''
+ }
+
+ if (!/^file:/i.test(value)) {
+ return value
+ }
+
+ try {
+ return decodeURIComponent(new URL(value).pathname)
+ } catch {
+ return value.replace(/^file:\/\//i, '')
+ }
+}
+
+function filenameFromContentDisposition(value) {
+ const text = String(value || '')
+ const encoded = text.match(/filename\*=(?:UTF-8'')?([^;]+)/i)?.[1]
+ const plain = text.match(/filename="?([^";]+)"?/i)?.[1]
+ const raw = encoded || plain || ''
+
+ if (!raw) {
+ return ''
+ }
+
+ try {
+ return path.basename(decodeURIComponent(raw.trim()))
+ } catch {
+ return path.basename(raw.trim())
+ }
+}
+
+async function saveGatewayFile(payload: any = {}) {
+ const filePath = gatewayFilePath(payload.path)
+
+ if (!filePath) {
+ throw new Error('Missing gateway file path')
+ }
+
+ const profile = payload.profile || null
+ const connection = await ensureBackend(profile)
+ const requestPath = pathWithGlobalRemoteProfile(`/api/fs/download?path=${encodeURIComponent(filePath)}`, profile, {
+ globalRemote: globalRemoteActive(),
+ profileRemoteOverride: profileHasRemoteOverride(profile)
+ })
+ const url = `${connection.baseUrl}${requestPath}`
+ const fetched = (
+ connection.authMode === 'oauth' ? await fetchBufferViaOauthSession(url) : await fetchBuffer(url, connection.token)
+ ) as any
+ const disposition = fetched.headers['content-disposition'] || fetched.headers['Content-Disposition']
+ const fallbackName = path.basename(filePath) || String(payload.suggestedName || '').trim() || 'download'
+ const filename =
+ filenameFromContentDisposition(disposition) || String(payload.suggestedName || '').trim() || fallbackName
+ const result = await dialog.showSaveDialog(mainWindow, {
+ defaultPath: filename,
+ title: 'Save File'
+ })
+
+ if (result.canceled || !result.filePath) {
+ return { canceled: true, saved: false }
+ }
+
+ await fs.promises.writeFile(result.filePath, fetched.buffer)
+
+ return { path: result.filePath, saved: true }
+}
+
// Mint a single-use WS ticket for a gated gateway. Returns the ticket string.
// Prefers a native bearer token (cookieless RFC 8252 flow) when present,
// falling back to the OAuth cookie partition otherwise.
@@ -12136,6 +12344,8 @@ ipcMain.handle('hermes:selectSavePath', async (_event, options: any = {}) => {
// canvas. The main process has no such gate.
ipcMain.handle('hermes:readClipboard', () => clipboard.readText())
+ipcMain.handle('hermes:saveGatewayFile', (_event, payload) => saveGatewayFile(payload))
+
ipcMain.handle('hermes:saveImageFromUrl', (_event, url) => saveImageFromUrl(String(url || '')))
ipcMain.handle('hermes:saveImageBuffer', async (_event, payload) => {
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index b6b592f2b42..86f61263877 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -164,6 +164,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
selectSavePath: options => ipcRenderer.invoke('hermes:selectSavePath', options),
writeClipboard: text => ipcRenderer.invoke('hermes:writeClipboard', text),
readClipboard: () => ipcRenderer.invoke('hermes:readClipboard'),
+ saveGatewayFile: payload => ipcRenderer.invoke('hermes:saveGatewayFile', payload),
saveImageFromUrl: url => ipcRenderer.invoke('hermes:saveImageFromUrl', url),
saveImageBuffer: (data, ext) => ipcRenderer.invoke('hermes:saveImageBuffer', { data, ext }),
saveClipboardImage: () => ipcRenderer.invoke('hermes:saveClipboardImage'),
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index b43fbc3a542..14f16b3eff8 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -182,6 +182,11 @@ declare global {
}) => Promise<null | string>
writeClipboard: (text: string) => Promise<boolean>
readClipboard: () => Promise<string>
+ saveGatewayFile?: (payload: { path: string; profile?: null | string; suggestedName?: string }) => Promise<{
+ canceled?: boolean
+ path?: string
+ saved: boolean
+ }>
saveImageFromUrl: (url: string) => Promise<boolean>
saveImageBuffer: (data: ArrayBuffer | Uint8Array, ext: string) => Promise<string>
saveClipboardImage: () => Promise<string>
diff --git a/apps/desktop/src/lib/media.remote.test.ts b/apps/desktop/src/lib/media.remote.test.ts
index c16835cd676..26abd4693fd 100644
--- a/apps/desktop/src/lib/media.remote.test.ts
+++ b/apps/desktop/src/lib/media.remote.test.ts
@@ -1,5 +1,3 @@
-// @vitest-environment jsdom
-// downloadGatewayMediaFile drives an <a download> click, so these need a DOM.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { $connection } from '@/store/session'
@@ -205,49 +203,37 @@ describe('gatewayMediaDataUrl', () => {
})
describe('downloadGatewayMediaFile', () => {
- const api = vi.fn(async ({ path }: { path: string }) => {
- if (path.startsWith('/api/fs/read-data-url?')) {
- return { dataUrl: 'data:text/markdown;base64,IyByZXBvcnQ=' }
- }
-
- throw new Error(`unexpected path ${path}`)
- })
-
- let clickSpy: ReturnType<typeof vi.spyOn>
+ const saveGatewayFile = vi.fn(async () => ({ path: '/Users/me/Downloads/report.md', saved: true }))
beforeEach(() => {
- api.mockClear()
- vi.stubGlobal('window', { hermesDesktop: { api }, setTimeout: vi.fn() })
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => ({ blob: async () => new Blob(['# report'], { type: 'text/markdown' }) }))
- )
- URL.createObjectURL = vi.fn(() => 'blob:remote-artifact')
- URL.revokeObjectURL = vi.fn()
- clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
- $connection.set({ mode: 'remote' } as never)
+ saveGatewayFile.mockClear()
+ vi.stubGlobal('window', { hermesDesktop: { saveGatewayFile } })
+ $connection.set({ mode: 'remote', profile: 'docker-gw' } as never)
})
afterEach(() => {
vi.unstubAllGlobals()
- vi.clearAllMocks()
- clickSpy.mockRestore()
$connection.set(null)
})
- it('downloads gateway files through the desktop fs bridge', async () => {
- await downloadGatewayMediaFile('file:///Users/me/project/report.md')
+ it('downloads gateway files through the native desktop save bridge', async () => {
+ await expect(downloadGatewayMediaFile('file:///Users/me/project/a%20b.md')).resolves.toEqual({
+ path: '/Users/me/Downloads/report.md',
+ saved: true
+ })
- expect(api).toHaveBeenCalledWith({
- path: '/api/fs/read-data-url?path=%2FUsers%2Fme%2Fproject%2Freport.md'
+ expect(saveGatewayFile).toHaveBeenCalledWith({
+ path: '/Users/me/project/a b.md',
+ profile: 'docker-gw',
+ suggestedName: 'a b.md'
})
- expect(clickSpy).toHaveBeenCalledOnce()
})
- it('rejects when the gateway refuses the file read', async () => {
- api.mockRejectedValueOnce(new Error('403 File is not readable'))
+ it('rejects when the desktop bridge is unavailable', async () => {
+ vi.stubGlobal('window', { hermesDesktop: {} })
- await expect(downloadGatewayMediaFile('/Users/me/project/report.md')).rejects.toThrow('403')
- expect(clickSpy).not.toHaveBeenCalled()
+ await expect(downloadGatewayMediaFile('/Users/me/project/report.md')).rejects.toThrow(
+ 'Desktop file download bridge'
+ )
})
})
diff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.ts
index 33bcfbd963f..90aaceffa28 100644
--- a/apps/desktop/src/lib/media.ts
+++ b/apps/desktop/src/lib/media.ts
@@ -165,25 +165,25 @@ export async function gatewayMediaDataUrl(path: string): Promise<string> {
}
// Remote-mode replacement for opening gateway-local file paths with file://.
-// The file lives on the gateway, so fetch it over the authenticated fs bridge
-// and hand the bytes to the local browser shell as a download.
-export async function downloadGatewayMediaFile(path: string): Promise<void> {
- const dataUrl = await readDesktopFileDataUrl(filePathFromMediaPath(path))
-
- if (!dataUrl) {
- throw new Error('Gateway returned no file data')
+// The file lives on the gateway, so ask the Electron main process to fetch the
+// bytes through the authenticated backend connection and save them locally. This
+// avoids browser/OS downloads losing OAuth cookies and avoids the data-URL cap
+// used by preview endpoints.
+export async function downloadGatewayMediaFile(
+ path: string
+): Promise<{ canceled?: boolean; path?: string; saved: boolean }> {
+ const file = filePathFromMediaPath(path)
+ const conn = $connection.get()
+
+ if (!window.hermesDesktop?.saveGatewayFile) {
+ throw new Error('Desktop file download bridge is unavailable')
}
- const response = await fetch(dataUrl)
- const blobUrl = URL.createObjectURL(await response.blob())
- const anchor = document.createElement('a')
- anchor.href = blobUrl
- anchor.download = mediaName(path)
- anchor.rel = 'noopener noreferrer'
- document.body.appendChild(anchor)
- anchor.click()
- anchor.remove()
- window.setTimeout(() => URL.revokeObjectURL(blobUrl), 30_000)
+ return window.hermesDesktop.saveGatewayFile({
+ path: file,
+ profile: conn?.profile,
+ suggestedName: mediaName(file)
+ })
}
export function mediaDisplayLabel(path: string): string {
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 01c5e9d77f8..08d3714b68b 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -2868,6 +2868,19 @@ async def fs_read_data_url(path: str):
return {"dataUrl": f"data:{_fs_mime_type(target)};base64,{encoded}"}
[email protected]("/api/fs/download")
+async def fs_download(path: str):
+ target, _st = _fs_regular_file(_fs_path(path))
+ if _is_sensitive_path(target):
+ raise HTTPException(status_code=403, detail="Access to sensitive files is not allowed")
+ return FileResponse(
+ path=str(target),
+ media_type=_fs_mime_type(target),
+ filename=target.name,
+ content_disposition_type="attachment",
+ )
+
+
@app.get("/api/fs/git-root")
async def fs_git_root(path: str):
target = _fs_path(path)
diff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.py
index 3cf33b18272..a7a0a37a203 100644
--- a/tests/hermes_cli/test_web_server_fs.py
+++ b/tests/hermes_cli/test_web_server_fs.py
@@ -55,6 +55,28 @@ def test_fs_read_data_url_rejects_over_cap(client, tmp_path, monkeypatch):
assert response.status_code == 413
+def test_fs_download_streams_file_without_data_url_cap(client, tmp_path, monkeypatch):
+ monkeypatch.setattr(web_server, "_FS_DATA_URL_MAX_BYTES", 3)
+ target = tmp_path / "report with spaces.pdf"
+ target.write_bytes(b"123456")
+
+ response = client.get("/api/fs/download", params={"path": str(target)})
+
+ assert response.status_code == 200
+ assert response.content == b"123456"
+ assert response.headers["content-type"].startswith("application/pdf")
+ assert "report%20with%20spaces.pdf" in response.headers["content-disposition"]
+
+
+def test_fs_download_rejects_sensitive_files(client, tmp_path):
+ target = tmp_path / ".env"
+ target.write_text("SECRET=1")
+
+ response = client.get("/api/fs/download", params={"path": str(target)})
+
+ assert response.status_code == 403
+
+
def test_fs_endpoints_require_auth(tmp_path):
client = TestClient(web_server.app)
target = tmp_path / "secret.txt"