Skip to content

The agent that grows with you

refactor(desktop): exercise download and profile routing through real boundaries

ethernetf7622c4b6aab
diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.ts
index 72f52cf5b0e..02a576356a0 100644
--- a/apps/desktop/electron/connection-registry.ts
+++ b/apps/desktop/electron/connection-registry.ts
@@ -451,6 +451,41 @@ export function registrySourceOwnsPrimaryBackend(
return Boolean(id) && id === registry.primary && resolvedConnectionId(registry, descriptor) === id
}
+export interface ReuseMatchingPrimaryRemoteBackendOptions<T extends ResolvedConnectionDescriptor> {
+ connectionId: string
+ ensurePrimary: (profile: null | string | undefined) => Promise<T>
+ profile: null | string | undefined
+ registry: ConnectionRegistry
+ source: RegistryConnection
+}
+
+export interface SharedRegistryProfileScope {
+ connectionId: string
+ profile: string
+ sharedRemote: true
+}
+
+/** Reuse the live URL/cloud primary without losing the caller's REST profile scope. */
+export async function reuseMatchingPrimaryRemoteBackend<T extends ResolvedConnectionDescriptor>({
+ connectionId,
+ ensurePrimary,
+ profile,
+ registry,
+ source
+}: ReuseMatchingPrimaryRemoteBackendOptions<T>): Promise<(T & SharedRegistryProfileScope) | null> {
+ if (connectionId !== registry.primary || source.kind === 'local' || source.kind === 'ssh') {
+ return null
+ }
+
+ const descriptor: T = await ensurePrimary(profile)
+
+ if (!registrySourceOwnsPrimaryBackend(registry, connectionId, descriptor)) {
+ return null
+ }
+
+ return { ...descriptor, profile: String(profile ?? '').trim() || 'default', connectionId, sharedRemote: true }
+}
+
function normalizedSshTarget(route: { host?: unknown; port?: unknown; user?: unknown }): null | string {
const ssh = normalizeSshConfig({ ...route, mode: 'ssh' })
diff --git a/apps/desktop/electron/gateway-file-download-transport.test.ts b/apps/desktop/electron/gateway-file-download-transport.test.ts
index b245165cbf0..48e5ff4c74e 100644
--- a/apps/desktop/electron/gateway-file-download-transport.test.ts
+++ b/apps/desktop/electron/gateway-file-download-transport.test.ts
@@ -1,71 +1,386 @@
-/**
- * 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 { EventEmitter } from 'node:events'
import fs from 'node:fs'
+import http from 'node:http'
+import type { AddressInfo } from 'node:net'
+import os from 'node:os'
import path from 'node:path'
-import { fileURLToPath } from 'node:url'
+import { PassThrough } from 'node:stream'
-import { test } from 'vitest'
+import { afterEach, beforeEach, expect, test, vi } from 'vitest'
-const __dirname = path.dirname(fileURLToPath(import.meta.url))
-const source = fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8')
+import { downloadAgentFor } from './api-transport'
+import { pathForRegistryBackendRequest } from './connection-config'
+import type {
+ GatewayFileSaveContext,
+ GatewayFileSaveDeps,
+ GatewayFileSaveResult,
+ GatewaySaveDialogResult
+} from './gateway-file-download'
+import {
+ finalizeGatewayDownload,
+ fsPumpDeps,
+ gatewayFileRequestPaths,
+ saveGatewayDownload
+} from './gateway-file-download'
+import type {
+ GatewayDownloadOptions,
+ GatewayOauthDownloadDeps,
+ GatewayOauthDownloadRequest,
+ GatewayOauthRequestOptions
+} from './gateway-file-download-transport'
+import { downloadViaOauthSessionToFile, downloadViaTokenToFile } from './gateway-file-download-transport'
-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`)
+interface Deferred<T> {
+ promise: Promise<T>
+ resolve: (value: T) => void
+}
+
+function deferred<T>(): Deferred<T> {
+ let resolve: (value: T) => void = (): void => {
+ throw new Error('Promise not initialized')
+ }
- return source.slice(start, end)
+ const promise: Promise<T> = new Promise((done): void => {
+ resolve = done
+ })
+
+ return { promise, resolve }
}
-test('token transport streams to disk instead of buffering the whole body', () => {
- const fn = extract('function downloadViaTokenToFile', '\nfunction ')
+const context: GatewayFileSaveContext = { suggested: 'suggested.bin', fallbackName: 'fallback.bin' }
+let directory: string
+const servers: http.Server[] = []
- // 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\)/)
+beforeEach(async (): Promise<void> => {
+ directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'gateway-transport-'))
})
+afterEach(async (): Promise<void> => {
+ vi.useRealTimers()
-test('oauth transport streams to disk instead of buffering the whole body', () => {
- const fn = extract('function downloadViaOauthSessionToFile', '\nasync function finalizeGatewayDownload')
+ for (const server of servers.splice(0)) {
+ server.closeAllConnections()
+ await new Promise<void>((resolve, reject): void => {
+ server.close((error?: Error): void => {
+ if (error) {
+ reject(error)
+ } else {
+ resolve()
+ }
+ })
+ })
+ }
- assert.match(fn, /electronNet\.request/)
- assert.match(fn, /finalizeGatewayDownload\(/)
- assert.doesNotMatch(fn, /Buffer\.concat/)
- assert.doesNotMatch(fn, /chunks\.push/)
+ await fs.promises.rm(directory, { recursive: true, force: true })
})
-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\(/)
- // Production deps come from one place so the streaming save and the data-URL
- // fallback share the exclusive-create + rename contract (#96597).
- assert.match(fn, /fsPumpDeps\(\)/)
- assert.doesNotMatch(fn, /fs\.createWriteStream/)
- // HTTP errors carry their status so a 404 can trigger the fallback.
- assert.match(fn, /throw httpStatusError\(statusCode, /)
+async function serve(handler: (request: http.IncomingMessage, response: http.ServerResponse) => void): Promise<string> {
+ const server: http.Server = http.createServer(handler)
+ servers.push(server)
+ await new Promise<void>((resolve): void => {
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ // SAFETY: listen(0, '127.0.0.1') completed above, so this is a bound TCP address, not a pipe or closed server.
+ const address: AddressInfo = server.address() as AddressInfo
+
+ return `http://127.0.0.1:${address.port}`
+}
+
+function saveDialog(filePath: string): GatewayFileSaveDeps {
+ return { showSaveDialog: async (): Promise<GatewaySaveDialogResult> => ({ canceled: false, filePath }) }
+}
+
+interface AuthCase {
+ name: string
+ options: GatewayDownloadOptions
+ header: string
+ value: string
+}
+
+const authCases: AuthCase[] = [
+ { name: 'token', options: {}, header: 'x-hermes-session-token', value: 'session-token' },
+ { name: 'bearer', options: { bearer: 'native-token' }, header: 'authorization', value: 'Bearer native-token' }
+]
+
+test.each(authCases)(
+ '$name transport streams before EOF, only after the dialog, and drops the connection timeout',
+ async ({ options, header, value }: AuthCase): Promise<void> => {
+ const responseReady: Deferred<http.ServerResponse> = deferred<http.ServerResponse>()
+
+ const baseUrl: string = await serve((request: http.IncomingMessage, response: http.ServerResponse): void => {
+ expect(request.headers[header]).toBe(value)
+ expect(request.headers[header === 'authorization' ? 'x-hermes-session-token' : 'authorization']).toBeUndefined()
+ response.writeHead(200, { 'Content-Disposition': 'attachment; filename="server.bin"' })
+ response.flushHeaders()
+ responseReady.resolve(response)
+ })
+
+ const dialogEntered: Deferred<void> = deferred<void>()
+ const decision: Deferred<GatewaySaveDialogResult> = deferred<GatewaySaveDialogResult>()
+ const destination: string = path.join(directory, 'existing.bin')
+ await fs.promises.writeFile(destination, 'original')
+
+ const pending: Promise<GatewayFileSaveResult> = downloadViaTokenToFile(
+ `${baseUrl}/download`,
+ 'session-token',
+ context,
+ {
+ showSaveDialog: async (settings: { defaultPath: string; title: string }): Promise<GatewaySaveDialogResult> => {
+ expect(settings).toEqual({ defaultPath: 'server.bin', title: 'Save File' })
+ dialogEntered.resolve()
+
+ return decision.promise
+ }
+ },
+ { ...options, timeoutMs: 2000 }
+ )
+
+ const response: http.ServerResponse = await responseReady.promise
+ await dialogEntered.promise
+ expect(
+ Object.values(downloadAgentFor('http:').sockets)
+ .flat()
+ .some((socket): boolean => socket?.timeout === 0)
+ ).toBe(true)
+ response.write('first chunk')
+ expect(await fs.promises.readdir(directory)).toEqual(['existing.bin'])
+ decision.resolve({ canceled: false, filePath: destination })
+ await vi.waitFor(async (): Promise<void> => {
+ const part: string | undefined = (await fs.promises.readdir(directory)).find((name: string): boolean =>
+ name.endsWith('.part')
+ )
+
+ expect(part).toBeDefined()
+ expect(await fs.promises.readFile(path.join(directory, part!), 'utf8')).toBe('first chunk')
+ })
+ expect(await fs.promises.readFile(destination, 'utf8')).toBe('original')
+ response.end(' last chunk')
+ expect(await pending).toEqual({ saved: true, path: destination })
+ expect(await fs.promises.readFile(destination, 'utf8')).toBe('first chunk last chunk')
+ expect(await fs.promises.readdir(directory)).toEqual(['existing.bin'])
+ }
+)
+
+interface FixtureSession {
+ partition: string
+}
+
+class CookieRequest extends EventEmitter implements GatewayOauthDownloadRequest {
+ aborted: boolean = false
+ ended: boolean = false
+ abort(): void {
+ this.aborted = true
+ }
+ end(): void {
+ this.ended = true
+ }
+}
+
+test('cookie transport preserves the session, waits for the dialog without a deadline, and cancels without writing', async (): Promise<void> => {
+ vi.useFakeTimers()
+ const session: FixtureSession = { partition: 'persist:gateway-test' }
+ const request: CookieRequest = new CookieRequest()
+ const decision: Deferred<GatewaySaveDialogResult> = deferred<GatewaySaveDialogResult>()
+ const response = Object.assign(new PassThrough(), { statusCode: 200, headers: {} })
+
+ const deps: GatewayOauthDownloadDeps<FixtureSession> = {
+ getSession: (url: string): FixtureSession => {
+ expect(url).toBe('https://gateway.example/file')
+
+ return session
+ },
+ request: (options: GatewayOauthRequestOptions<FixtureSession>): GatewayOauthDownloadRequest => {
+ expect(options).toEqual({
+ method: 'GET',
+ url: 'https://gateway.example/file',
+ session,
+ useSessionCookies: true,
+ redirect: 'follow'
+ })
+ expect(options.session).toBe(session)
+
+ return request
+ },
+ showSaveDialog: (): Promise<GatewaySaveDialogResult> => decision.promise
+ }
+
+ const pending: Promise<GatewayFileSaveResult> = downloadViaOauthSessionToFile(
+ 'https://gateway.example/file',
+ context,
+ deps,
+ { timeoutMs: 2000 }
+ )
+
+ expect(request.ended).toBe(true)
+ request.emit('response', response)
+ await vi.advanceTimersByTimeAsync(10000)
+ expect(request.aborted).toBe(false)
+ expect(response.listenerCount('data')).toBe(0)
+ decision.resolve({ canceled: true })
+ expect(await pending).toEqual({ canceled: true, saved: false })
+ expect(request.aborted).toBe(true)
+ expect(await fs.promises.readdir(directory)).toEqual([])
+ response.destroy()
})
-test('data-URL fallback writes through the same failure-atomic primitive, never writeFile in place', () => {
- const fn = extract('async function saveGatewayFileViaDataUrl', '\n// Mint a single-use WS ticket')
+test('cookie connection timeout aborts before headers and never opens a dialog', async (): Promise<void> => {
+ vi.useFakeTimers()
+ const request: CookieRequest = new CookieRequest()
+
+ const pending: Promise<GatewayFileSaveResult> = downloadViaOauthSessionToFile(
+ 'https://gateway.example/file',
+ context,
+ {
+ getSession: (): FixtureSession => ({ partition: 'persist:gateway-test' }),
+ request: (): GatewayOauthDownloadRequest => request,
+ showSaveDialog: async (): Promise<GatewaySaveDialogResult> => {
+ throw new Error('unexpected dialog')
+ }
+ },
+ { timeoutMs: 2000 }
+ )
+
+ const rejected: Promise<void> = expect(pending).rejects.toThrow('Timed out connecting to Hermes backend after 2000ms')
+ await vi.advanceTimersByTimeAsync(2000)
+ await rejected
+ expect(request.aborted).toBe(true)
+ expect(await fs.promises.readdir(directory)).toEqual([])
+})
+
+test('cookie transport streams bytes after approval and preserves HTTP status on errors', async (): Promise<void> => {
+ for (const statusCode of [200, 404, 503]) {
+ const request: CookieRequest = new CookieRequest()
+ const destination: string = path.join(directory, 'cookie.bin')
+ const response = Object.assign(new PassThrough(), { statusCode, headers: {} })
+
+ const pending: Promise<GatewayFileSaveResult> = downloadViaOauthSessionToFile(
+ 'https://gateway.example/file',
+ context,
+ {
+ ...saveDialog(destination),
+ getSession: (): FixtureSession => ({ partition: 'persist:gateway-test' }),
+ request: (): GatewayOauthDownloadRequest => request
+ }
+ )
+
+ const rejection: Promise<void> | null =
+ statusCode >= 400
+ ? expect(pending).rejects.toMatchObject({ statusCode, message: `${statusCode}: cookie error` })
+ : null
+
+ request.emit('response', response)
+ response.end(statusCode === 200 ? 'cookie payload' : 'cookie error')
+
+ if (rejection) {
+ await rejection
+ } else {
+ expect(await pending).toEqual({ saved: true, path: destination })
+ }
+
+ expect(await fs.promises.readFile(destination, 'utf8')).toBe('cookie payload')
+ expect(await fs.promises.readdir(directory)).toEqual(['cookie.bin'])
+ }
+})
+
+test.each([404, 401, 403, 500])(
+ 'HTTP %i preserves status and permits only the scoped 404 fallback',
+ async (statusCode: number): Promise<void> => {
+ const baseUrl: string = await serve((_request: http.IncomingMessage, response: http.ServerResponse): void => {
+ response.writeHead(statusCode)
+ response.end('backend error')
+ })
+
+ const destination: string = path.join(directory, 'saved.bin')
+
+ const paths = gatewayFileRequestPaths(
+ '/remote/report.bin',
+ (requestPath: string): string => pathForRegistryBackendRequest(requestPath, 'acme', { sharedRemote: true }),
+ 'session-42'
+ )
+
+ const reads: string[] = []
+
+ const pending: Promise<GatewayFileSaveResult> = saveGatewayDownload(paths, context, {
+ ...saveDialog(destination),
+ download: (requestPath: string, ctx: GatewayFileSaveContext): Promise<GatewayFileSaveResult> =>
+ downloadViaTokenToFile(`${baseUrl}${requestPath}`, 'session-token', ctx, {
+ showSaveDialog: async (): Promise<GatewaySaveDialogResult> => {
+ throw new Error('HTTP errors must not open a dialog')
+ }
+ }),
+ readDataUrl: async (requestPath: string): Promise<string> => {
+ reads.push(requestPath)
+
+ return 'data:application/octet-stream;base64,aGVsbG8='
+ }
+ })
+
+ if (statusCode === 404) {
+ expect(await pending).toEqual({ saved: true, path: destination })
+ expect(reads).toEqual(['/api/fs/read-data-url?path=%2Fremote%2Freport.bin&session_id=session-42&profile=acme'])
+ expect(await fs.promises.readFile(destination, 'utf8')).toBe('hello')
+ } else {
+ await expect(pending).rejects.toMatchObject({ statusCode, message: `${statusCode}: backend error` })
+ expect(reads).toEqual([])
+ expect(await fs.promises.readdir(directory)).toEqual([])
+ }
+ }
+)
+
+test('dialog-time and mid-stream failures abort without clobbering an existing destination', async (): Promise<void> => {
+ const destination: string = path.join(directory, 'existing.bin')
+ await fs.promises.writeFile(destination, 'original')
+
+ for (const duringDialog of [true, false]) {
+ const response = Object.assign(new PassThrough(), { statusCode: 200, headers: {} })
+ const decision: Deferred<GatewaySaveDialogResult> = deferred<GatewaySaveDialogResult>()
+ let aborted: boolean = false
+
+ const pending: Promise<GatewayFileSaveResult> = finalizeGatewayDownload(
+ response,
+ context,
+ (): void => {
+ aborted = true
+ },
+ { showSaveDialog: (): Promise<GatewaySaveDialogResult> => decision.promise }
+ )
+
+ const rejected: Promise<void> = expect(pending).rejects.toThrow('socket failed')
+
+ if (!duringDialog) {
+ decision.resolve({ canceled: false, filePath: destination })
+ await vi.waitFor((): void => {
+ expect(response.listenerCount('data')).toBe(1)
+ })
+ response.write('partial')
+ }
+
+ response.destroy(new Error('socket failed'))
+ await new Promise<void>((resolve): void => {
+ response.once('close', resolve)
+ })
+ decision.resolve({ canceled: false, filePath: destination })
+ await rejected
+ expect(aborted).toBe(true)
+ expect(await fs.promises.readFile(destination, 'utf8')).toBe('original')
+ expect(await fs.promises.readdir(directory)).toEqual(['existing.bin'])
+ }
+})
- assert.match(fn, /dialog\.showSaveDialog/)
- assert.match(fn, /writeBufferToFile\(/)
- assert.match(fn, /fsPumpDeps\(\)/)
- // A direct writeFile truncates an existing destination before the write
- // completes; a mid-write failure would destroy it (#96597).
- assert.doesNotMatch(fn, /fs\.promises\.writeFile/)
+test('data-URL fallback keeps a pre-existing temp collision and destination intact', async (): Promise<void> => {
+ const destination: string = path.join(directory, 'existing.bin')
+ const temp: string = path.join(directory, 'collision.part')
+ await fs.promises.writeFile(destination, 'original')
+ await fs.promises.writeFile(temp, 'other download')
+ await expect(
+ saveGatewayDownload({ download: '/download', dataUrl: '/data-url' }, context, {
+ ...saveDialog(destination),
+ pump: { ...fsPumpDeps(), tempPathFor: (): string => temp },
+ download: async (): Promise<GatewayFileSaveResult> => {
+ throw Object.assign(new Error('not found'), { statusCode: 404 })
+ },
+ readDataUrl: async (): Promise<string> => 'data:,replacement'
+ })
+ ).rejects.toMatchObject({ code: 'EEXIST' })
+ expect(await fs.promises.readFile(destination, 'utf8')).toBe('original')
+ expect(await fs.promises.readFile(temp, 'utf8')).toBe('other download')
})
diff --git a/apps/desktop/electron/gateway-file-download-transport.ts b/apps/desktop/electron/gateway-file-download-transport.ts
new file mode 100644
index 00000000000..5676e2aea3c
--- /dev/null
+++ b/apps/desktop/electron/gateway-file-download-transport.ts
@@ -0,0 +1,161 @@
+import http from 'node:http'
+import https from 'node:https'
+
+import { downloadAgentFor } from './api-transport'
+import type {
+ GatewayDownloadResponse,
+ GatewayFileSaveContext,
+ GatewayFileSaveDeps,
+ GatewayFileSaveResult
+} from './gateway-file-download'
+import { finalizeGatewayDownload } from './gateway-file-download'
+import { DEFAULT_FETCH_TIMEOUT_MS, resolveTimeoutMs } from './hardening'
+
+export interface GatewayDownloadOptions {
+ bearer?: string
+ timeoutMs?: number
+}
+
+function downloadUrl(url: string): URL {
+ let parsed: URL
+
+ try {
+ parsed = new URL(url)
+ } catch (error) {
+ throw new Error(`Invalid URL: ${error instanceof Error ? error.message : String(error)}`)
+ }
+
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ throw new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`)
+ }
+
+ return parsed
+}
+
+export function downloadViaTokenToFile(
+ url: string,
+ token: null | string,
+ context: GatewayFileSaveContext,
+ deps: GatewayFileSaveDeps,
+ options: GatewayDownloadOptions = {}
+): Promise<GatewayFileSaveResult> {
+ return new Promise((resolve: (result: GatewayFileSaveResult) => void, reject: (error: Error) => void): void => {
+ const parsed: URL = downloadUrl(url)
+ const client: typeof http | typeof https = parsed.protocol === 'https:' ? https : http
+ const timeoutMs: number = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
+
+ const request: http.ClientRequest = client.request(
+ parsed,
+ {
+ agent: downloadAgentFor(parsed.protocol),
+ method: 'GET',
+ headers: options.bearer
+ ? { Authorization: `Bearer ${options.bearer}` }
+ : { 'X-Hermes-Session-Token': token ?? '' }
+ },
+ (response: http.IncomingMessage): void => {
+ // Headers end the connection deadline, not the user's save-dialog time.
+ request.setTimeout(0)
+ void finalizeGatewayDownload(
+ response,
+ context,
+ (): void => {
+ request.destroy()
+ },
+ deps
+ ).then(resolve, reject)
+ }
+ )
+
+ request.on('error', reject)
+ request.setTimeout(timeoutMs, (): void => {
+ request.destroy(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`))
+ })
+ request.end()
+ })
+}
+
+export interface GatewayOauthDownloadRequest {
+ on(event: 'response', listener: (response: GatewayDownloadResponse) => void): void
+ on(event: 'error', listener: (error: Error) => void): void
+ abort(): void
+ end(): void
+}
+
+export interface GatewayOauthRequestOptions<S> {
+ method: 'GET'
+ url: string
+ session: S
+ useSessionCookies: true
+ redirect: 'follow'
+}
+
+export interface GatewayOauthDownloadDeps<S> extends GatewayFileSaveDeps {
+ getSession: (url: string) => S | null
+ request: (options: GatewayOauthRequestOptions<S>) => GatewayOauthDownloadRequest
+}
+
+export function downloadViaOauthSessionToFile<S>(
+ url: string,
+ context: GatewayFileSaveContext,
+ deps: GatewayOauthDownloadDeps<S>,
+ options: GatewayDownloadOptions = {}
+): Promise<GatewayFileSaveResult> {
+ return new Promise((resolve: (result: GatewayFileSaveResult) => void, reject: (error: Error) => void): void => {
+ const session: S | null = deps.getSession(url)
+
+ if (!session) {
+ throw new Error('OAuth session partition is unavailable.')
+ }
+
+ downloadUrl(url)
+ const timeoutMs: number = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
+
+ const request: GatewayOauthDownloadRequest = deps.request({
+ method: 'GET',
+ url,
+ session,
+ useSessionCookies: true,
+ redirect: 'follow'
+ })
+
+ let settled: boolean = false
+
+ const timer: ReturnType<typeof setTimeout> = setTimeout((): void => {
+ if (settled) {
+ return
+ }
+
+ settled = true
+ request.abort()
+ reject(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`))
+ }, timeoutMs)
+
+ request.on('response', (response: GatewayDownloadResponse): void => {
+ if (settled) {
+ return
+ }
+
+ settled = true
+ clearTimeout(timer)
+ void finalizeGatewayDownload(
+ response,
+ context,
+ (): void => {
+ request.abort()
+ },
+ deps
+ ).then(resolve, reject)
+ })
+ request.on('error', (error: Error): void => {
+ if (settled) {
+ return
+ }
+
+ settled = true
+ clearTimeout(timer)
+ reject(error)
+ })
+ request.end()
+ })
+}
diff --git a/apps/desktop/electron/gateway-file-download.ts b/apps/desktop/electron/gateway-file-download.ts
index ac1ea430cde..b83d0d6fcad 100644
--- a/apps/desktop/electron/gateway-file-download.ts
+++ b/apps/desktop/electron/gateway-file-download.ts
@@ -2,9 +2,8 @@
// 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
+// The token / OAuth transports delegate to the shared finalizer here. It
+// waits for the save dialog before `pumpStreamToFile` streams the
// response into a sibling temp file with backpressure and renames it onto the
// user-selected destination only once the body has landed in full — so a large
// download never has to be buffered whole in the native process, and a failed
@@ -336,6 +335,144 @@ export function gatewayFilePath(rawPath: unknown): string {
return String(rawPath || '').trim()
}
+export interface GatewayFileSaveContext {
+ fallbackName: string
+ suggested: string
+}
+
+export interface GatewaySaveDialogResult {
+ canceled: boolean
+ filePath?: string
+}
+
+export interface GatewayFileSaveResult {
+ canceled?: boolean
+ path?: string
+ saved: boolean
+}
+
+export interface GatewaySaveDialogOptions {
+ defaultPath: string
+ title: string
+}
+
+export interface GatewayFileSaveDeps {
+ showSaveDialog: (options: GatewaySaveDialogOptions) => Promise<GatewaySaveDialogResult>
+ pump?: PumpDeps
+}
+
+export interface GatewayDownloadResponse extends ReadableLike {
+ statusCode?: number
+ headers: { [name: string]: string | string[] | undefined }
+}
+
+/** Keep the body unread until the user selects a destination. */
+export async function finalizeGatewayDownload(
+ response: GatewayDownloadResponse,
+ context: GatewayFileSaveContext,
+ abort: () => void,
+ deps: GatewayFileSaveDeps
+): Promise<GatewayFileSaveResult> {
+ const statusCode: number = response.statusCode || 500
+
+ if (statusCode >= 400) {
+ const message: string = await readGatewayErrorText(response)
+ throw Object.assign(new Error(`${statusCode}: ${message}`), { statusCode })
+ }
+
+ // A socket can fail while the native dialog is open, before the pump listens.
+ let responseError: Error | null = null
+ response.on('error', (error: Error): void => {
+ responseError = error
+ })
+
+ const disposition: string | string[] | undefined =
+ response.headers['content-disposition'] || response.headers['Content-Disposition']
+
+ const filename: string = filenameFromContentDisposition(disposition) || context.suggested || context.fallbackName
+
+ try {
+ const result: GatewaySaveDialogResult = await deps.showSaveDialog({ defaultPath: filename, title: 'Save File' })
+
+ if (result.canceled || !result.filePath) {
+ abort()
+
+ return { canceled: true, saved: false }
+ }
+
+ if (responseError) {
+ throw responseError
+ }
+
+ await pumpStreamToFile(response, result.filePath, deps.pump ?? fsPumpDeps())
+
+ return { path: result.filePath, saved: true }
+ } catch (error) {
+ abort()
+ throw error
+ }
+}
+
+function readGatewayErrorText(response: ReadableLike): Promise<string> {
+ return new Promise((resolve: (message: string) => void): void => {
+ const chunks: Buffer[] = []
+ let total: number = 0
+ response.on('data', (chunk: Buffer | Uint8Array | string): void => {
+ if (total >= 500) {
+ return
+ }
+
+ // Normalize text and binary stream chunks before retaining the bounded error prefix.
+ const bytes: Uint8Array = chunk instanceof Uint8Array ? chunk : Buffer.from(chunk, 'utf8')
+ const buffer: Buffer = Buffer.from(bytes.subarray(0, 500 - total))
+ total += buffer.length
+ chunks.push(buffer)
+ })
+
+ const finish: () => void = (): void => {
+ resolve(Buffer.concat(chunks).toString('utf8'))
+ }
+
+ response.on('end', finish)
+ response.on('error', finish)
+ })
+}
+
+export interface GatewayFileDownloadDeps extends GatewayFileSaveDeps {
+ download: (requestPath: string, context: GatewayFileSaveContext) => Promise<GatewayFileSaveResult>
+ readDataUrl: (requestPath: string) => Promise<string>
+}
+
+/** Only a missing streaming endpoint permits the older, capped data-URL route. */
+export async function saveGatewayDownload(
+ requestPaths: GatewayFileRequestPaths,
+ context: GatewayFileSaveContext,
+ deps: GatewayFileDownloadDeps
+): Promise<GatewayFileSaveResult> {
+ try {
+ return await deps.download(requestPaths.download, context)
+ } catch (error) {
+ if (!isNotFoundError(error)) {
+ throw error
+ }
+ }
+
+ const buffer: Buffer = parseDataUrlToBuffer(await deps.readDataUrl(requestPaths.dataUrl))
+
+ const result: GatewaySaveDialogResult = await deps.showSaveDialog({
+ defaultPath: context.suggested || context.fallbackName,
+ title: 'Save File'
+ })
+
+ if (result.canceled || !result.filePath) {
+ return { canceled: true, saved: false }
+ }
+
+ await writeBufferToFile(buffer, result.filePath, deps.pump ?? fsPumpDeps())
+
+ return { path: result.filePath, saved: true }
+}
+
// 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 {
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 7efb8925acb..ed63ca76544 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -30,9 +30,10 @@ import {
shell,
systemPreferences
} from 'electron'
+import type { Session } from 'electron'
import { type ActiveRuntimeState, classifyActiveRuntime } from './active-runtime-state'
-import { destroyKeepaliveAgents, downloadAgentFor, jsonAgentFor, withRetry } from './api-transport'
+import { destroyKeepaliveAgents, jsonAgentFor, withRetry } from './api-transport'
import { appIconCandidates, resolveAppIcon } from './app-icon'
import { stageAppInstallerFile } from './app-installer-file'
import { appVersionInfo, type AppVersionInfo, assertSourceUpdateChannel, packagedReleaseChannel } from './app-version'
@@ -147,15 +148,17 @@ import {
parseBackendScopeKey,
reconcileAppliedGlobalConnection,
reconcileRegistryDrift,
- registrySourceOwnsPrimaryBackend,
rememberSshEnumeration,
removeConnection,
+ type ResolvedConnectionDescriptor,
resolvedConnectionId,
resolveRegistryLocalRoute,
+ reuseMatchingPrimaryRemoteBackend,
reuseMatchingPrimarySshBackend,
setConnectionLaunchMode,
setLastUsedConnection,
setPrimaryConnection,
+ type SharedRegistryProfileScope,
shouldDeferLocalEnumeration,
shouldRetrySshInventory,
updateEligibility,
@@ -201,17 +204,20 @@ import {
} from './find-in-page'
import { createFirstRunSetupGate } from './first-run-setup-gate'
import { registerFsIpc } from './fs-ipc'
+import type {
+ GatewayFileSaveContext,
+ GatewayFileSaveDeps,
+ GatewayFileSaveResult,
+ GatewaySaveDialogOptions,
+ GatewaySaveDialogResult
+} from './gateway-file-download'
import {
- filenameFromContentDisposition,
- fsPumpDeps,
gatewayFilePath,
gatewayFileRequestPaths,
- isNotFoundError,
- parseDataUrlToBuffer,
- pumpStreamToFile,
resolveGatewayFileBackend,
- writeBufferToFile
+ saveGatewayDownload
} from './gateway-file-download'
+import { downloadViaOauthSessionToFile, downloadViaTokenToFile } from './gateway-file-download-transport'
import { stopGatewayBeforeUpdate } from './gateway-stop-before-update'
import { resolveGatewayVersion } from './gateway-version'
import { probeGatewayWebSocket } from './gateway-ws-probe'
@@ -272,6 +278,7 @@ import {
import { registerMcpOauthCallbackIpc } from './mcp-oauth-callback-ipc'
import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'
import { fetchLocalMedia } from './media-range'
+import type { GatedDownloadAuth } from './native-auth-decisions'
import {
oauthGuardMayHardFail,
oauthSessionIsLive,
@@ -4649,65 +4656,6 @@ function fetchJson(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. `options.bearer`
-// switches the header to Authorization (RFC 8252 native flow), matching fetchJson.
-function downloadViaTokenToFile(url, token, ctx, 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 agent = downloadAgentFor(parsed.protocol)
- const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
-
- const req = client.request(
- parsed,
- {
- agent,
- method: 'GET',
- headers: options.bearer ? { Authorization: `Bearer ${options.bearer}` } : { 'X-Hermes-Session-Token': token }
- },
- res => {
- // 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
- }
- }
- }).then(resolve, reject)
- }
- )
-
- 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
@@ -7164,166 +7112,12 @@ async function ensureNativeAccessToken(baseUrl: string): Promise<string | null>
}
}
-// 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 = getOauthSessionForUrl(url)
-
- 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 settled = false
-
- const timer = setTimeout(() => {
- if (settled) {
- return
- }
-
- settled = true
-
- try {
- request.abort()
- } catch {
- // already finished
- }
-
- reject(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`))
- }, timeoutMs)
-
- request.on('response', res => {
- if (settled) {
- 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
- }
- }
- }).then(resolve, reject)
- })
- request.on('error', error => {
- if (settled) {
- return
- }
-
- settled = true
- clearTimeout(timer)
- reject(error)
- })
- request.end()
- })
-}
-
-// 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
- }
-
- 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 {
- // Failure-atomic: exclusive temp create beside the destination, rename into
- // place only once the body is complete (#96597).
- await pumpStreamToFile(res, result.filePath, fsPumpDeps())
- } catch (error) {
- ctx.abort?.()
- throw error
- }
-
- return { path: result.filePath, saved: true }
-}
-
-// 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
-
- res.on('data', chunk => {
- if (total >= 500) {
- return
- }
-
- 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)))
- })
-}
-
interface GatewayFileConnection extends RegistryBackendRequestScope {
authMode?: 'oauth' | 'token'
baseUrl: string
token?: null | string
}
-interface GatewayFileSaveContext {
- fallbackName: string
- suggested: string
-}
-
interface GatewayFileSavePayload {
sessionId?: string
connectionId?: unknown
@@ -7332,7 +7126,7 @@ interface GatewayFileSavePayload {
suggestedName?: unknown
}
-async function gatedFileAuth(connection: GatewayFileConnection) {
+async function gatedFileAuth(connection: GatewayFileConnection): Promise<GatedDownloadAuth> {
const nativeAt =
connection.authMode === 'oauth' ? await ensureNativeAccessToken(connection.baseUrl).catch(() => null) : null
@@ -7344,13 +7138,13 @@ function gatewayFileRequestPath(
connectionId: null | string,
profile: null | string,
requestPath: string
-) {
+): string {
return connectionId
? pathForRegistryBackendRequest(requestPath, profile, connection)
: pathWithGlobalRemoteProfile(requestPath, profile, profileRouteOptions(profile))
}
-async function saveGatewayFile(payload: GatewayFileSavePayload = {}) {
+async function saveGatewayFile(payload: GatewayFileSavePayload = {}): Promise<GatewayFileSaveResult> {
const filePath = gatewayFilePath(payload.path)
if (!filePath) {
@@ -7364,7 +7158,7 @@ async function saveGatewayFile(payload: GatewayFileSavePayload = {}) {
const suggested = String(payload.suggestedName || '').trim()
const fallbackName = path.basename(filePath) || suggested || 'download'
- const ctx = { suggested, fallbackName }
+ const ctx: GatewayFileSaveContext = { suggested, fallbackName }
const requestPaths = gatewayFileRequestPaths(
filePath,
@@ -7372,41 +7166,38 @@ async function saveGatewayFile(payload: GatewayFileSavePayload = {}) {
payload.sessionId
)
- const url = `${connection.baseUrl}${requestPaths.download}`
-
- try {
- const auth = await gatedFileAuth(connection)
-
- if (auth.kind === 'bearer') {
- return await downloadViaTokenToFile(url, auth.token, ctx, { bearer: auth.token })
- }
+ const deps: GatewayFileSaveDeps = {
+ showSaveDialog: (options: GatewaySaveDialogOptions): Promise<GatewaySaveDialogResult> =>
+ dialog.showSaveDialog(mainWindow, options)
+ }
- if (auth.kind === 'cookie') {
- return await downloadViaOauthSessionToFile(url, ctx)
- }
+ return saveGatewayDownload(requestPaths, ctx, {
+ ...deps,
+ download: async (requestPath: string, context: GatewayFileSaveContext): Promise<GatewayFileSaveResult> => {
+ const url: string = `${connection.baseUrl}${requestPath}`
+ const auth: GatedDownloadAuth = await gatedFileAuth(connection)
- return await downloadViaTokenToFile(url, auth.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, requestPaths.dataUrl, ctx)
- }
+ if (auth.kind === 'cookie') {
+ return downloadViaOauthSessionToFile<Session>(url, context, {
+ ...deps,
+ getSession: getOauthSessionForUrl,
+ request: electronNet.request
+ })
+ }
- throw error
- }
+ return downloadViaTokenToFile(
+ url,
+ auth.token,
+ context,
+ deps,
+ auth.kind === 'bearer' ? { bearer: auth.token } : {}
+ )
+ },
+ readDataUrl: (requestPath: string): Promise<string> => readGatewayFileDataUrl(connection, requestPath)
+ })
}
-// 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: GatewayFileConnection,
- requestPath: string,
- ctx: GatewayFileSaveContext
-) {
+async function readGatewayFileDataUrl(connection: GatewayFileConnection, requestPath: string): Promise<string> {
const url = `${connection.baseUrl}${requestPath}`
const auth = await gatedFileAuth(connection)
let json: unknown
@@ -7426,23 +7217,7 @@ async function saveGatewayFileViaDataUrl(
throw new Error('Gateway returned no file data')
}
- const buffer = parseDataUrlToBuffer(dataUrl)
- const filename = ctx.suggested || ctx.fallbackName
-
- const result = await dialog.showSaveDialog(mainWindow, {
- defaultPath: filename,
- title: 'Save File'
- })
-
- if (result.canceled || !result.filePath) {
- return { canceled: true, saved: false }
- }
-
- // Same failure-atomic contract as the streaming path: a direct writeFile
- // truncates an existing destination before the write completes (#96597).
- await writeBufferToFile(buffer, result.filePath, fsPumpDeps())
-
- return { path: result.filePath, saved: true }
+ return dataUrl
}
// Mint a single-use WS ticket for a gated gateway. Returns the ticket string.
@@ -10759,23 +10534,17 @@ async function ensureRegistryBackend(
}
}
- // The v1 primary and the registry primary can describe the same remote
- // backend beyond the SSH-fingerprint path above (cloud/url remotes have no
- // ssh -G identity). Reuse the already-running primary when the registry
- // resolves its live descriptor back to this exact source id; otherwise one
- // Desktop window starts two isolated servers whose transient runtime ids
- // are not interchangeable.
- if (id === registry.primary && source.kind !== 'local' && source.kind !== 'ssh') {
- const primaryDescriptor = await ensureBackend(profile)
+ const sharedPrimary: (ResolvedConnectionDescriptor & SharedRegistryProfileScope) | null =
+ await reuseMatchingPrimaryRemoteBackend({
+ connectionId: id,
+ ensurePrimary: ensureBackend,
+ profile,
+ registry,
+ source
+ })
- if (registrySourceOwnsPrimaryBackend(registry, id, primaryDescriptor)) {
- return {
- ...primaryDescriptor,
- profile: profileKey,
- connectionId: id,
- sharedRemote: true
- }
- }
+ if (sharedPrimary) {
+ return sharedPrimary
}
if (source.kind === 'local') {
diff --git a/apps/desktop/electron/registry-primary-profile-scope.test.ts b/apps/desktop/electron/registry-primary-profile-scope.test.ts
index 36d60077c2d..bccca503b00 100644
--- a/apps/desktop/electron/registry-primary-profile-scope.test.ts
+++ b/apps/desktop/electron/registry-primary-profile-scope.test.ts
@@ -1,37 +1,137 @@
-import fs from 'node:fs'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
-
import { describe, expect, it } from 'vitest'
import { pathForRegistryBackendRequest } from './connection-config'
+import type { ConnectionRegistry, RegistryConnection, ResolvedConnectionDescriptor } from './connection-registry'
+import { reuseMatchingPrimaryRemoteBackend } from './connection-registry'
-const here = path.dirname(fileURLToPath(import.meta.url))
-const mainSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')
+interface LiveDescriptor extends ResolvedConnectionDescriptor {
+ baseUrl: string
+ wsUrl: string
+}
-describe('primary-remote descriptor reuse keeps profile scope', () => {
- it('scopes a shared-remote request with ?profile=<profile>', () => {
- expect(pathForRegistryBackendRequest('/api/skills', 'acme', { sharedRemote: true })).toBe(
- '/api/skills?profile=acme'
- )
- })
+function registryFor(source: RegistryConnection): ConnectionRegistry {
+ return {
+ version: 2,
+ primary: source.id,
+ launchMode: 'primary',
+ lastUsed: source.id,
+ connections: [{ id: 'local', kind: 'local', label: 'This device' }, source]
+ }
+}
- it('does not add a profile query when the backend is not shared-remote', () => {
- // An isolated backend owns one profile; the router must not invent a scope.
- expect(pathForRegistryBackendRequest('/api/skills', 'acme', { sharedRemote: false, remoteProfile: null })).toBe(
- '/api/skills'
- )
- })
+describe('primary-remote descriptor reuse keeps profile scope', (): void => {
+ it.each(['remote', 'cloud'] as const)(
+ 'reuses %s identity and routes each caller without mutating the primary',
+ async (kind: 'remote' | 'cloud'): Promise<void> => {
+ const source: RegistryConnection = {
+ id: 'shared',
+ kind,
+ label: 'Shared',
+ url: 'https://gateway.example',
+ authMode: 'token'
+ }
+
+ const registry: ConnectionRegistry = registryFor(source)
+
+ const descriptor: LiveDescriptor = {
+ mode: 'remote',
+ remoteKind: kind === 'remote' ? 'url' : 'cloud',
+ baseUrl: source.url!,
+ wsUrl: 'wss://gateway.example/ws?ticket=live',
+ authMode: 'token'
+ }
+
+ const profiles: Array<null | string | undefined> = []
+
+ for (const profile of ['acme', 'research', null]) {
+ const result = await reuseMatchingPrimaryRemoteBackend({
+ connectionId: source.id,
+ profile,
+ registry,
+ source,
+ ensurePrimary: async (requested: null | string | undefined): Promise<LiveDescriptor> => {
+ profiles.push(requested)
+
+ return descriptor
+ }
+ })
+
+ expect(result).toMatchObject({
+ ...descriptor,
+ profile: profile ?? 'default',
+ connectionId: source.id
+ })
+
+ if (!result) {
+ throw new Error('Expected a reused descriptor')
+ }
+
+ expect(pathForRegistryBackendRequest('/api/skills', result.profile, result)).toBe(
+ `/api/skills?profile=${profile ?? 'default'}`
+ )
+ expect(pathForRegistryBackendRequest('/api/skills?profile=explicit', result.profile, result)).toBe(
+ '/api/skills?profile=explicit'
+ )
+ }
+
+ expect(profiles).toEqual(['acme', 'research', null])
+ expect(descriptor).not.toHaveProperty('sharedRemote')
+ expect(descriptor).not.toHaveProperty('profile')
+ expect(pathForRegistryBackendRequest('/api/skills', 'acme', { sharedRemote: false, remoteProfile: null })).toBe(
+ '/api/skills'
+ )
+ }
+ )
+
+ it('does not boot ineligible primaries or reuse a different live identity', async (): Promise<void> => {
+ const source: RegistryConnection = {
+ id: 'shared',
+ kind: 'remote',
+ label: 'Shared',
+ url: 'https://gateway.example',
+ authMode: 'token',
+ token: 'right-account'
+ }
+
+ const registry: ConnectionRegistry = registryFor(source)
+ let calls: number = 0
+
+ const descriptor: LiveDescriptor = {
+ mode: 'remote',
+ remoteKind: 'url',
+ baseUrl: 'https://gateway.example',
+ wsUrl: 'wss://gateway.example/ws',
+ authMode: 'token',
+ token: 'wrong-account',
+ headers: {}
+ }
+
+ const ensurePrimary = async (): Promise<LiveDescriptor> => {
+ calls += 1
+
+ return descriptor
+ }
- it('marks the reused primary-remote descriptor sharedRemote so the router scopes it', () => {
- const branchStart = mainSource.indexOf("if (id === registry.primary && source.kind !== 'local'")
- expect(branchStart).toBeGreaterThan(-1)
- const branch = mainSource.slice(branchStart, branchStart + 800)
+ for (const candidate of [
+ { source, connectionId: 'secondary' },
+ { source: { ...source, kind: 'local' as const }, connectionId: source.id },
+ { source: { ...source, kind: 'ssh' as const }, connectionId: source.id }
+ ]) {
+ expect(
+ await reuseMatchingPrimaryRemoteBackend({ ...candidate, profile: 'acme', registry, ensurePrimary })
+ ).toBeNull()
+ }
- // The reuse branch must decorate the ambient primary descriptor with
- // sharedRemote: true, matching the explicit shared-remote connection path.
- expect(branch).toContain('const primaryDescriptor = await ensureBackend(profile, { passive })')
- expect(branch).toContain('registrySourceOwnsPrimaryBackend(registry, id, primaryDescriptor)')
- expect(branch).toContain('sharedRemote: true')
+ expect(calls).toBe(0)
+ expect(
+ await reuseMatchingPrimaryRemoteBackend({
+ source,
+ connectionId: source.id,
+ profile: 'acme',
+ registry,
+ ensurePrimary
+ })
+ ).toBeNull()
+ expect(calls).toBe(1)
})
})