Skip to content

The agent that grows with you

fix(desktop): bound stalled token and cookie download bodies too

Teknium70ab54fe51ea
diff --git a/apps/desktop/electron/gateway-download-transport.ts b/apps/desktop/electron/gateway-download-transport.ts
index 2f250dd8359..35b225bc969 100644
--- a/apps/desktop/electron/gateway-download-transport.ts
+++ b/apps/desktop/electron/gateway-download-transport.ts
@@ -2,39 +2,10 @@ import http from 'node:http'
import https from 'node:https'
import { downloadAgentFor, withRetry } from './api-transport'
+import { destroyStalledBody } from './gateway-file-download'
import { DEFAULT_FETCH_TIMEOUT_MS, resolveTimeoutMs } from './hardening'
import { nativeGatewayHttpHeaders } from './local-gateway'
-// Bound a body that stops arriving once the consumer is reading it. The watchdog arms only
-// when a 'data'/'readable' consumer attaches, so the unread body waiting on the native save
-// dialog stays the user's time; it pauses under write backpressure and resets on every chunk.
-function destroyStalledBody(res: http.IncomingMessage, idleMs: number) {
- let timer: ReturnType<typeof setTimeout> | undefined
- let watching = false
- const stop = () => clearTimeout(timer)
-
- const arm = () => {
- stop()
- timer = setTimeout(() => res.destroy(new Error(`Hermes backend download stalled: no data for ${idleMs}ms`)), idleMs)
- }
-
- const watch = () => {
- if (watching || res.destroyed) { return }
- watching = true
- // Added after the consumer's own listener, so this never switches a reader's mode.
- res.on('data', arm)
- arm()
- }
-
- res.on('newListener', event => {
- if (event === 'data' || event === 'readable') { queueMicrotask(watch) }
- })
- res.on('pause', stop)
- res.on('resume', () => { if (watching) { arm() } })
- res.once('end', stop)
- res.once('close', stop)
-}
-
// Retry only the connection phase, never a save dialog or a partially saved body.
export async function downloadViaTokenToFile(url, token, ctx, finalizeGatewayDownload, options: any = {}) {
const parsed = new URL(url)
diff --git a/apps/desktop/electron/gateway-file-download-transport.test.ts b/apps/desktop/electron/gateway-file-download-transport.test.ts
index 1318debd38d..1f3dec96508 100644
--- a/apps/desktop/electron/gateway-file-download-transport.test.ts
+++ b/apps/desktop/electron/gateway-file-download-transport.test.ts
@@ -292,6 +292,61 @@ test('cookie transport streams bytes after approval and preserves HTTP status on
}
})
+test('a token or cookie body that stalls mid-read is destroyed after the idle deadline, never the dialog', async (): Promise<void> => {
+ // R4 for the non-native transports: headers drop the connect timeout, so without a body
+ // deadline a stalled stream hung the save forever. The open dialog (150 ms > 50 ms) is the
+ // user's time and is not counted.
+ const slowDialog = (destination: string): GatewayFileSaveDeps => ({
+ showSaveDialog: async (): Promise<GatewaySaveDialogResult> => {
+ await new Promise(resolve => setTimeout(resolve, 150))
+
+ return { canceled: false, filePath: destination }
+ }
+ })
+
+ const baseUrl: string = await serve((request: http.IncomingMessage, response: http.ServerResponse): void => {
+ response.writeHead(200, { 'Content-Type': 'application/octet-stream' })
+
+ if (request.url === '/whole') {
+ response.end('bytes')
+
+ return
+ }
+
+ response.write('head-')
+ })
+
+ const whole: string = path.join(directory, 'whole.bin')
+ await expect(
+ downloadViaTokenToFile(`${baseUrl}/whole`, 'tok', context, slowDialog(whole), { bodyIdleTimeoutMs: 50 })
+ ).resolves.toEqual({ saved: true, path: whole })
+ await expect(
+ downloadViaTokenToFile(`${baseUrl}/stall`, 'tok', context, slowDialog(path.join(directory, 'stall.bin')), {
+ bodyIdleTimeoutMs: 50
+ })
+ ).rejects.toThrow('stalled')
+
+ const request: CookieRequest = new CookieRequest()
+ const response = Object.assign(new PassThrough(), { statusCode: 200, headers: {} })
+
+ const pending: Promise<GatewayFileSaveResult> = downloadViaOauthSessionToFile(
+ 'https://gateway.example/file',
+ context,
+ {
+ ...slowDialog(path.join(directory, 'cookie.bin')),
+ getSession: (): FixtureSession => ({ partition: 'persist:gateway-test' }),
+ request: (): GatewayOauthDownloadRequest => request
+ },
+ { bodyIdleTimeoutMs: 50 }
+ )
+
+ request.emit('response', response)
+ response.write('head-')
+ await expect(pending).rejects.toThrow('stalled')
+ expect(request.aborted).toBe(true)
+ expect((await fs.promises.readdir(directory)).sort()).toEqual(['whole.bin'])
+}, 5_000)
+
test.each([404, 401, 403, 500])(
'HTTP %i preserves status and permits only the scoped 404 fallback',
async (statusCode: number): Promise<void> => {
diff --git a/apps/desktop/electron/gateway-file-download-transport.ts b/apps/desktop/electron/gateway-file-download-transport.ts
index 5676e2aea3c..4429cd9c74e 100644
--- a/apps/desktop/electron/gateway-file-download-transport.ts
+++ b/apps/desktop/electron/gateway-file-download-transport.ts
@@ -8,12 +8,18 @@ import type {
GatewayFileSaveDeps,
GatewayFileSaveResult
} from './gateway-file-download'
-import { finalizeGatewayDownload } from './gateway-file-download'
+import { destroyStalledBody, finalizeGatewayDownload, type StallWatchableBody } from './gateway-file-download'
import { DEFAULT_FETCH_TIMEOUT_MS, resolveTimeoutMs } from './hardening'
export interface GatewayDownloadOptions {
bearer?: string
timeoutMs?: number
+ /** Idle deadline for a body being read (reset per chunk); defaults to the fetch timeout. */
+ bodyIdleTimeoutMs?: number
+}
+
+function bodyIdleMs(options: GatewayDownloadOptions): number {
+ return resolveTimeoutMs(options.bodyIdleTimeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
}
function downloadUrl(url: string): URL {
@@ -54,8 +60,10 @@ export function downloadViaTokenToFile(
: { 'X-Hermes-Session-Token': token ?? '' }
},
(response: http.IncomingMessage): void => {
- // Headers end the connection deadline, not the user's save-dialog time.
+ // Headers end the connection deadline, not the user's save-dialog time;
+ // a body that then stops arriving mid-read is bounded by the idle deadline.
request.setTimeout(0)
+ destroyStalledBody(response, bodyIdleMs(options))
void finalizeGatewayDownload(
response,
context,
@@ -138,6 +146,12 @@ export function downloadViaOauthSessionToFile<S>(
settled = true
clearTimeout(timer)
+
+ // Electron net's IncomingMessage is a Readable: bound a stalled body the same way.
+ if (typeof (response as Partial<StallWatchableBody>).destroy === 'function') {
+ destroyStalledBody(response as unknown as StallWatchableBody, bodyIdleMs(options))
+ }
+
void finalizeGatewayDownload(
response,
context,
diff --git a/apps/desktop/electron/gateway-file-download.ts b/apps/desktop/electron/gateway-file-download.ts
index 4fcbd25f291..37a652d81db 100644
--- a/apps/desktop/electron/gateway-file-download.ts
+++ b/apps/desktop/electron/gateway-file-download.ts
@@ -405,6 +405,46 @@ export interface GatewayDownloadResponse extends ReadableLike {
headers: { [name: string]: string | string[] | undefined }
}
+/** The stream surface the body idle watchdog needs: Node's http.IncomingMessage
+ * and Electron net's IncomingMessage are both Readable EventEmitters. */
+export interface StallWatchableBody {
+ on(event: string, listener: (...args: any[]) => void): unknown
+ once(event: string, listener: (...args: any[]) => void): unknown
+ destroy(error?: Error): unknown
+ destroyed?: boolean
+}
+
+// Bound a body that stops arriving once the consumer is reading it. The watchdog arms only
+// when a 'data'/'readable' consumer attaches, so the unread body waiting on the native save
+// dialog stays the user's time; it pauses under write backpressure and resets on every chunk.
+// Shared by every download transport (native descriptor, token/bearer, OAuth cookie).
+export function destroyStalledBody(res: StallWatchableBody, idleMs: number): void {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ let watching = false
+ const stop = (): void => clearTimeout(timer)
+
+ const arm = (): void => {
+ stop()
+ timer = setTimeout(() => res.destroy(new Error(`Hermes backend download stalled: no data for ${idleMs}ms`)), idleMs)
+ }
+
+ const watch = (): void => {
+ if (watching || res.destroyed) { return }
+ watching = true
+ // Added after the consumer's own listener, so this never switches a reader's mode.
+ res.on('data', arm)
+ arm()
+ }
+
+ res.on('newListener', (event: string) => {
+ if (event === 'data' || event === 'readable') { queueMicrotask(watch) }
+ })
+ res.on('pause', stop)
+ res.on('resume', () => { if (watching) { arm() } })
+ res.once('end', stop)
+ res.once('close', stop)
+}
+
/** Keep the body unread until the user selects a destination. */
export async function finalizeGatewayDownload(
response: GatewayDownloadResponse,