The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stream native gateway downloads + 404 data-url fallback
Paul Armbruster27b003996a04
diff --git a/apps/desktop/electron/gateway-file-download-transport.test.ts b/apps/desktop/electron/gateway-file-download-transport.test.tsnew file mode 100644index 00000000000..2dae653b8b0--- /dev/null+++ b/apps/desktop/electron/gateway-file-download-transport.test.ts@@ -0,0 +1,70 @@+/**+ * Wiring coverage for the main.ts gateway download transports. These functions+ * pull in main-process singletons (https/http, electronNet, the OAuth session,+ * the save dialog), so we assert on their source shape — the same approach as+ * oauth-session-request.test.ts — while gateway-file-download.test.ts unit-tests+ * the extracted streaming/decoding logic behaviorally.+ */++import assert from 'node:assert/strict'+import fs from 'node:fs'+import path from 'node:path'+import test from 'node:test'+import { fileURLToPath } from 'node:url'++const __dirname = path.dirname(fileURLToPath(import.meta.url))+const source = fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8')++function extract(startMarker: string, endMarker: string): string {+ const start = source.indexOf(startMarker)+ assert.notEqual(start, -1, `${startMarker} should exist`)+ const end = source.indexOf(endMarker, start + startMarker.length)+ assert.notEqual(end, -1, `boundary after ${startMarker} should exist`)++ return source.slice(start, end)+}++test('token transport streams to disk instead of buffering the whole body', () => {+ const fn = extract('function downloadViaTokenToFile', '\nfunction ')++ // Delegates byte-moving to the streaming finalizer...+ assert.match(fn, /finalizeGatewayDownload\(/)+ // ...and must NOT accumulate the full response before writing.+ assert.doesNotMatch(fn, /Buffer\.concat/)+ assert.doesNotMatch(fn, /chunks\.push/)+ // Idle timeout is dropped once headers arrive so the dialog/stream isn't killed.+ assert.match(fn, /setTimeout\(0\)/)+})++test('oauth transport streams to disk instead of buffering the whole body', () => {+ const fn = extract('function downloadViaOauthSessionToFile', '\nasync function finalizeGatewayDownload')++ assert.match(fn, /electronNet\.request/)+ assert.match(fn, /finalizeGatewayDownload\(/)+ assert.doesNotMatch(fn, /Buffer\.concat/)+ assert.doesNotMatch(fn, /chunks\.push/)+})++test('finalizeGatewayDownload prompts a save dialog then streams the response', () => {+ const fn = extract('async function finalizeGatewayDownload', '\nfunction readGatewayErrorText')++ assert.match(fn, /dialog\.showSaveDialog/)+ assert.match(fn, /pumpStreamToFile\(/)+ // HTTP errors carry their status so a 404 can trigger the fallback.+ assert.match(fn, /error\.statusCode = statusCode/)+})++test('saveGatewayFile falls back to the data-url route only on 404', () => {+ const fn = extract('async function saveGatewayFile', '\nasync function saveGatewayFileViaDataUrl')++ assert.match(fn, /\/api\/fs\/download\?path=/)+ assert.match(fn, /isNotFoundError\(error\)/)+ assert.match(fn, /saveGatewayFileViaDataUrl\(/)+})++test('data-url fallback reads the capped route and decodes it', () => {+ const fn = extract('async function saveGatewayFileViaDataUrl', '// Mint a single-use WS ticket')++ assert.match(fn, /\/api\/fs\/read-data-url\?path=/)+ assert.match(fn, /parseDataUrlToBuffer\(/)+})diff --git a/apps/desktop/electron/gateway-file-download.test.ts b/apps/desktop/electron/gateway-file-download.test.tsnew file mode 100644index 00000000000..124cef4dfef--- /dev/null+++ b/apps/desktop/electron/gateway-file-download.test.ts@@ -0,0 +1,189 @@+import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'+import test from 'node:test'++import {+ filenameFromContentDisposition,+ gatewayFilePath,+ isNotFoundError,+ parseDataUrlToBuffer,+ pumpStreamToFile+} from './gateway-file-download'++// A Readable-like response driven manually in tests.+class FakeResponse extends EventEmitter {+ paused = false+ resumed = false+ destroyed = false++ pause() {+ this.paused = true+ }++ resume() {+ this.resumed = true+ }++ destroy() {+ this.destroyed = true+ }+}++// A write stream that records writes and lets tests control backpressure.+class FakeWriteStream extends EventEmitter {+ chunks: Buffer[] = []+ ended = false+ destroyed = false+ private writeReturns: boolean[]++ constructor(writeReturns: boolean[] = []) {+ super()+ this.writeReturns = writeReturns+ }++ write(chunk: Buffer): boolean {+ this.chunks.push(chunk)++ return this.writeReturns.length ? this.writeReturns.shift()! : true+ }++ end(cb: () => void) {+ this.ended = true+ cb()+ }++ destroy() {+ this.destroyed = true+ }+}++test('pumpStreamToFile streams chunks to the destination without buffering the whole body', async () => {+ const res = new FakeResponse()+ const ws = new FakeWriteStream()+ const unlinked: string[] = []++ const promise = pumpStreamToFile(res as never, '/tmp/out.bin', {+ createWriteStream: () => ws as never,+ unlink: async p => {+ unlinked.push(p)+ }+ })++ res.emit('data', Buffer.from('abc'))+ res.emit('data', Buffer.from('def'))+ res.emit('end')++ await promise++ assert.equal(Buffer.concat(ws.chunks).toString('utf8'), 'abcdef')+ assert.equal(ws.ended, true)+ assert.deepEqual(unlinked, []) // success -> no cleanup+})++test('pumpStreamToFile applies backpressure: pauses on a full buffer and resumes on drain', async () => {+ const res = new FakeResponse()+ const ws = new FakeWriteStream([false]) // first write signals "buffer full"++ const promise = pumpStreamToFile(res as never, '/tmp/out.bin', {+ createWriteStream: () => ws as never,+ unlink: async () => {}+ })++ res.emit('data', Buffer.from('big-chunk'))+ assert.equal(res.paused, true, 'source should be paused when write() returns false')+ assert.equal(res.resumed, false)++ ws.emit('drain')+ assert.equal(res.resumed, true, 'source should resume after the write stream drains')++ res.emit('end')+ await promise+})++test('pumpStreamToFile unlinks the partial file and rejects on a write error', async () => {+ const res = new FakeResponse()+ const ws = new FakeWriteStream()+ const unlinked: string[] = []++ const promise = pumpStreamToFile(res as never, '/tmp/partial.bin', {+ createWriteStream: () => ws as never,+ unlink: async p => {+ unlinked.push(p)+ }+ })++ res.emit('data', Buffer.from('abc'))+ ws.emit('error', new Error('ENOSPC: disk full'))++ await assert.rejects(promise, /disk full/)+ assert.deepEqual(unlinked, ['/tmp/partial.bin'])+ assert.equal(res.destroyed, true, 'source should be torn down on write failure')+})++test('pumpStreamToFile unlinks the partial file and rejects on a response error', async () => {+ const res = new FakeResponse()+ const ws = new FakeWriteStream()+ const unlinked: string[] = []++ const promise = pumpStreamToFile(res as never, '/tmp/partial.bin', {+ createWriteStream: () => ws as never,+ unlink: async p => {+ unlinked.push(p)+ }+ })++ res.emit('data', Buffer.from('abc'))+ res.emit('error', new Error('socket hang up'))++ await assert.rejects(promise, /socket hang up/)+ assert.deepEqual(unlinked, ['/tmp/partial.bin'])+})++test('parseDataUrlToBuffer decodes base64 payloads', () => {+ const buffer = parseDataUrlToBuffer('data:text/markdown;base64,IyByZXBvcnQ=')++ assert.equal(buffer.toString('utf8'), '# report')+})++test('parseDataUrlToBuffer decodes percent-encoded (non-base64) payloads', () => {+ const buffer = parseDataUrlToBuffer('data:text/plain,hello%20world')++ assert.equal(buffer.toString('utf8'), 'hello world')+})++test('parseDataUrlToBuffer throws on a malformed data URL', () => {+ assert.throws(() => parseDataUrlToBuffer('not-a-data-url'), /Malformed data URL/)+})++test('filenameFromContentDisposition prefers filename* and reduces to a basename', () => {+ assert.equal(+ filenameFromContentDisposition("attachment; filename*=UTF-8''report%20with%20spaces.pdf"),+ 'report with spaces.pdf'+ )+ assert.equal(filenameFromContentDisposition('attachment; filename="report.md"'), 'report.md')+ // A traversal attempt in the header cannot escape the chosen directory.+ assert.equal(filenameFromContentDisposition('attachment; filename="../../etc/passwd"'), 'passwd')+ assert.equal(filenameFromContentDisposition(''), '')+ assert.equal(filenameFromContentDisposition(undefined), '')+})++test('gatewayFilePath normalizes bare paths and file:// URLs', () => {+ assert.equal(gatewayFilePath('/Users/me/report.md'), '/Users/me/report.md')+ assert.equal(gatewayFilePath('file:///Users/me/a%20b.md'), '/Users/me/a b.md')+ assert.equal(gatewayFilePath(''), '')+ assert.equal(gatewayFilePath(null), '')+})++test('isNotFoundError matches only HTTP 404', () => {+ const notFound: any = new Error('404: missing')++ notFound.statusCode = 404+ assert.equal(isNotFoundError(notFound), true)++ const forbidden: any = new Error('403: nope')++ forbidden.statusCode = 403+ assert.equal(isNotFoundError(forbidden), false)+ assert.equal(isNotFoundError(new Error('plain')), false)+ assert.equal(isNotFoundError(null), false)+})diff --git a/apps/desktop/electron/gateway-file-download.ts b/apps/desktop/electron/gateway-file-download.tsnew file mode 100644index 00000000000..acdca9723c2--- /dev/null+++ b/apps/desktop/electron/gateway-file-download.ts@@ -0,0 +1,167 @@+// Helpers for saving a gateway-hosted file to the local disk from the Electron+// main process. Extracted from main.ts so the streaming, data-URL decoding, and+// filename derivation are unit-testable without spinning up Electron.+//+// The transport wrappers (token / OAuth) live in main.ts because they need+// main-process singletons (https/http, electronNet, the OAuth session). They+// delegate the byte-moving to `pumpStreamToFile` here, which streams the+// response to a user-selected destination with backpressure and cleans up a+// partial file on error — so a large download never has to be buffered whole in+// the native process.++import path from 'node:path'++// Minimal shape of the response objects we consume. Both Node's+// http.IncomingMessage and Electron net's IncomingMessage satisfy it.+export interface ReadableLike {+ on(event: 'data', listener: (chunk: Buffer | Uint8Array | string) => void): unknown+ on(event: 'end', listener: () => void): unknown+ on(event: 'error', listener: (err: Error) => void): unknown+ pause?: () => void+ resume?: () => void+ destroy?: (err?: Error) => void+}++export interface WriteStreamLike {+ write(chunk: Buffer): boolean+ end(cb: () => void): void+ destroy(err?: Error): void+ on(event: 'error', listener: (err: Error) => void): unknown+ once(event: 'drain', listener: () => void): unknown+}++export interface PumpDeps {+ createWriteStream: (destPath: string) => WriteStreamLike+ unlink: (destPath: string) => Promise<unknown>+}++// Stream `res` into `destPath`, honoring backpressure. On any read/write error+// the write stream is torn down and the (partial) destination file is removed+// before the returned promise rejects, so a failed download never leaves a+// truncated file behind.+export function pumpStreamToFile(res: ReadableLike, destPath: string, deps: PumpDeps): Promise<void> {+ return new Promise((resolve, reject) => {+ const ws = deps.createWriteStream(destPath)+ let failed = false++ const fail = (err: Error) => {+ if (failed) {+ return+ }++ failed = true++ try {+ res.destroy?.(err)+ } catch {+ // best effort — the socket may already be closed+ }++ try {+ ws.destroy()+ } catch {+ // best effort+ }++ Promise.resolve(deps.unlink(destPath))+ .catch(() => {})+ .then(() => reject(err))+ }++ ws.on('error', fail)+ res.on('error', fail)++ res.on('data', chunk => {+ if (failed) {+ return+ }++ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array)+ const ok = ws.write(buffer)++ // Backpressure: pause the source until the file stream drains so we never+ // accumulate the whole payload in memory.+ if (!ok && typeof res.pause === 'function') {+ res.pause()+ ws.once('drain', () => {+ if (!failed) {+ res.resume?.()+ }+ })+ }+ })++ res.on('end', () => {+ if (failed) {+ return+ }++ ws.end(() => resolve())+ })+ })+}++// Decode a `data:[<mime>][;base64],<payload>` URL into a Buffer. Used by the+// compatibility fallback that reads through the capped `/api/fs/read-data-url`+// route when the gateway predates `/api/fs/download`.+export function parseDataUrlToBuffer(dataUrl: string): Buffer {+ const match = /^data:([^,]*),([\s\S]*)$/.exec(String(dataUrl || ''))++ if (!match) {+ throw new Error('Malformed data URL')+ }++ const meta = match[1] || ''+ const payload = match[2] || ''++ if (/;base64/i.test(meta)) {+ return Buffer.from(payload, 'base64')+ }++ return Buffer.from(decodeURIComponent(payload), 'utf8')+}++// Extract a filename from a Content-Disposition header, preferring the RFC 5987+// `filename*` form. Returns '' when none is present. Always reduced to a+// basename so a malicious header can't redirect the save outside the picked dir.+export function filenameFromContentDisposition(value: unknown): string {+ 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())+ }+}++// Normalize a gateway file path that may arrive as a bare path or a file:// URL.+export function gatewayFilePath(rawPath: unknown): string {+ 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, '')+ }+}++// True when an error thrown by a transport wrapper represents an HTTP 404, used+// to trigger the data-URL compatibility fallback (and nothing else).+export function isNotFoundError(error: unknown): boolean {+ return Boolean(error) && (error as { statusCode?: number }).statusCode === 404+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 1140a4e53e0..601971ba536 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -117,6 +117,13 @@ import { findGitBash as _findGitBash } from './find-git-bash'import { installFoundInPageForwarder, performFind, stopFind } from './find-in-page'import { createFirstRunSetupGate } from './first-run-setup-gate'import { readDirForIpc } from './fs-read-dir'+import {+ filenameFromContentDisposition,+ gatewayFilePath,+ isNotFoundError,+ parseDataUrlToBuffer,+ pumpStreamToFile+} from './gateway-file-download'import { probeGatewayWebSocket } from './gateway-ws-probe'import { scanGitRepos } from './git-repo-scan'import {@@ -4646,7 +4653,11 @@ function fetchJson(url, token, options: any = {}) {})}-function fetchBuffer(url, token, options: any = {}) {+// Token-auth download that streams the response body straight to a+// user-selected destination (via finalizeGatewayDownload) instead of buffering+// the whole file in memory. The connect timeout is cleared once headers arrive+// so a slow save dialog or a large stream doesn't trip it.+function downloadViaTokenToFile(url, token, ctx, options: any = {}) {return new Promise((resolve, reject) => {let parsed@@ -4675,22 +4686,19 @@ function fetchBuffer(url, token, options: any = {}) {}},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+ // Headers arrived — the connection phase is done. Drop the idle timeout+ // so it can't abort mid-stream or while the save dialog is open.+ req.setTimeout(0)+ finalizeGatewayDownload(res, res.statusCode || 500, res.headers || {}, {+ ...ctx,+ abort: () => {+ try {+ req.destroy()+ } catch {+ // already finished+ }}-- resolve({ buffer, headers: res.headers || {} })- })+ }).then(resolve, reject)})@@ -6800,7 +6808,10 @@ async function ensureNativeAccessToken(baseUrl: string): Promise<string | null>}}-function fetchBufferViaOauthSession(url, options: any = {}) {+// OAuth-session download that streams the response body straight to a+// user-selected destination (via finalizeGatewayDownload). The connect timeout+// is cleared once the response headers arrive.+function downloadViaOauthSessionToFile(url, ctx, options: any = {}) {return new Promise((resolve, reject) => {const sess = getOauthSession()@@ -6834,10 +6845,14 @@ function fetchBufferViaOauthSession(url, options: any = {}) {useSessionCookies: true,redirect: 'follow'} as any)- let timedOut = false+ let settled = falseconst timer = setTimeout(() => {- timedOut = true+ if (settled) {+ return+ }++ settled = truetry {request.abort()@@ -6849,32 +6864,31 @@ function fetchBufferViaOauthSession(url, options: any = {}) {}, 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 || ''}`))+ if (settled) {+ return+ }- return+ // Response headers arrived — cancel the connect timeout so it can't abort+ // the stream while the save dialog is open or bytes are still flowing.+ settled = true+ clearTimeout(timer)+ finalizeGatewayDownload(res, res.statusCode || 500, res.headers || {}, {+ ...ctx,+ abort: () => {+ try {+ request.abort()+ } catch {+ // already finished+ }}-- resolve({ buffer, headers: res.headers || {} })- })+ }).then(resolve, reject)})request.on('error', error => {- if (timedOut) {+ if (settled) {return}+ settled = trueclearTimeout(timer)reject(error)})@@ -6882,39 +6896,63 @@ function fetchBufferViaOauthSession(url, options: any = {}) {})}-function gatewayFilePath(rawPath) {- const value = String(rawPath || '').trim()-- if (!value) {- return ''+// Shared tail for both transports: validate status, pick a filename, prompt the+// save dialog, then stream the (still-unconsumed) response body to the chosen+// destination. On an HTTP error the status code is attached so saveGatewayFile+// can trigger the 404-only compatibility fallback.+async function finalizeGatewayDownload(res, statusCode, headers, ctx: any = {}) {+ if (statusCode >= 400) {+ const message = await readGatewayErrorText(res)+ const error: any = new Error(`${statusCode}: ${message}`)+ error.statusCode = statusCode+ throw error}- if (!/^file:/i.test(value)) {- return value+ const disposition = headers['content-disposition'] || headers['Content-Disposition']+ const filename = filenameFromContentDisposition(disposition) || ctx.suggested || ctx.fallbackName+ const result = await dialog.showSaveDialog(mainWindow, {+ defaultPath: filename,+ title: 'Save File'+ })++ if (result.canceled || !result.filePath) {+ ctx.abort?.()++ return { canceled: true, saved: false }}try {- return decodeURIComponent(new URL(value).pathname)- } catch {- return value.replace(/^file:\/\//i, '')+ await pumpStreamToFile(res, result.filePath, {+ createWriteStream: (destPath: string) => fs.createWriteStream(destPath),+ unlink: (destPath: string) => fs.promises.unlink(destPath)+ })+ } catch (error) {+ ctx.abort?.()+ throw error}++ return { path: result.filePath, saved: true }}-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 || ''+// Read a bounded amount of an error response body for the thrown message.+function readGatewayErrorText(res): Promise<string> {+ return new Promise(resolve => {+ const chunks = []+ let total = 0- if (!raw) {- return ''- }+ res.on('data', chunk => {+ if (total >= 500) {+ return+ }- try {- return path.basename(decodeURIComponent(raw.trim()))- } catch {- return path.basename(raw.trim())- }+ const buffer = Buffer.from(chunk)++ total += buffer.length+ chunks.push(buffer)+ })+ res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8').slice(0, 500)))+ res.on('error', () => resolve(Buffer.concat(chunks).toString('utf8').slice(0, 500)))+ })}async function saveGatewayFile(payload: any = {}) {@@ -6926,18 +6964,56 @@ async function saveGatewayFile(payload: any = {}) {const profile = payload.profile || nullconst connection = await ensureBackend(profile)+ const suggested = String(payload.suggestedName || '').trim()+ const fallbackName = path.basename(filePath) || suggested || 'download'+ const ctx = { suggested, fallbackName }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)++ try {+ return await (connection.authMode === 'oauth'+ ? downloadViaOauthSessionToFile(url, ctx)+ : downloadViaTokenToFile(url, connection.token, ctx))+ } catch (error) {+ // Desktop and the remote gateway update independently. A gateway predating+ // /api/fs/download 404s here; fall back (ONLY on 404) to the older capped+ // data-URL route so downloads keep working against older backends.+ if (isNotFoundError(error)) {+ return await saveGatewayFileViaDataUrl(connection, profile, filePath, ctx)+ }++ throw error+ }+}++// Compatibility fallback: fetch the file through the capped+// `/api/fs/read-data-url` route, decode it, and save. Bounded by the gateway's+// data-URL cap, so it only serves smaller files — enough to keep older gateways+// working until they gain the streaming route.+async function saveGatewayFileViaDataUrl(connection, profile, filePath, ctx: any = {}) {+ const requestPath = pathWithGlobalRemoteProfile(+ `/api/fs/read-data-url?path=${encodeURIComponent(filePath)}`,+ profile,+ {+ globalRemote: globalRemoteActive(),+ profileRemoteOverride: profileHasRemoteOverride(profile)+ }+ )+ const url = `${connection.baseUrl}${requestPath}`+ const json = (+ connection.authMode === 'oauth' ? await fetchJsonViaOauthSession(url) : await fetchJson(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 dataUrl = json?.dataUrl++ if (!dataUrl) {+ throw new Error('Gateway returned no file data')+ }++ const buffer = parseDataUrlToBuffer(dataUrl)+ const filename = ctx.suggested || ctx.fallbackNameconst result = await dialog.showSaveDialog(mainWindow, {defaultPath: filename,title: 'Save File'@@ -6947,7 +7023,7 @@ async function saveGatewayFile(payload: any = {}) {return { canceled: true, saved: false }}- await fs.promises.writeFile(result.filePath, fetched.buffer)+ await fs.promises.writeFile(result.filePath, buffer)return { path: result.filePath, saved: true }}