Skip to content

The agent that grows with you

refactor(desktop): move the save-dialog IPC out of electron/main.ts

Tekniumc635546de1ee
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 510d9ddfc37..b5a846f9cca 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -1,26 +1,12 @@
import { type ChildProcess, execFileSync, spawn } from 'node:child_process'
import type { GatewayEndpoint } from './local-gateway'
-import {
- configurePythonGatewayTicketClient,
- createLocalGatewayDials,
- createStaleGatewayRestarter,
- ensureLocalGateway,
- gatewayOwnerProfile,
- localGatewayDial,
- nativeGatewayHttpHeaders,
- redialLocalGateway,
- runGatewayEnsure
-} from './local-gateway'
+import { configurePythonGatewayTicketClient, createLocalGatewayDials, createStaleGatewayRestarter, ensureLocalGateway, gatewayOwnerProfile, localGatewayDial, nativeGatewayHttpHeaders, redialLocalGateway, runGatewayEnsure } from './local-gateway'
import { closeGatewayTicketBridges, createGatewayTicketResolver } from './local-gateway-python'
import { createPluginWsUrlHandler } from './plugin-ws-url'
const localGatewayDials = createLocalGatewayDials()
-configurePythonGatewayTicketClient(
- createGatewayTicketResolver(
- async () => ensureRuntime(await resolveHermesBackend([]), () => undefined),
- resolveHermesCwd
- )
-)
+configurePythonGatewayTicketClient(createGatewayTicketResolver(
+ async () => ensureRuntime(await resolveHermesBackend([]), () => undefined), resolveHermesCwd))
import crypto from 'node:crypto'
import fs from 'node:fs'
import http from 'node:http'
@@ -552,7 +538,7 @@ import { loadRendererLoadErrorPage } from './renderer-load-error-page'
import { attachRendererConsoleCapture, formatRendererBoundaryReport } from './renderer-log'
import { fetchRosterSourceData } from './roster-source-fetch'
import { rosterSourceStatus } from './roster-source-status'
-import { saveTextFileAs } from './save-text-file'
+import { registerSaveDialogIpc } from './save-text-file'
import {
classifyStoredSecret,
readSecretStoragePolicy,
@@ -5123,8 +5109,7 @@ async function resolveHermesBackend(backendArgs: string[]): Promise<ResolvedHerm
env: {},
kind: 'command',
shell: shellForProbe,
- local: 'installed',
- root: await launcherInstallRoot(hermesCommand) // ticket minting needs it (#138774)
+ local: 'installed', root: await launcherInstallRoot(hermesCommand) // ticket minting needs it (#138774)
}
}
@@ -5400,13 +5385,7 @@ function fetchJson(url, token, options: any = {}) {
async (requestState: any) => {
// Mint inside each retry: a grant authorizes exactly one HTTP request.
const nativeHeaders = options.gatewayDescriptor
- ? await nativeGatewayHttpHeaders(
- options.gatewayDescriptor,
- url,
- HERMES_HOME,
- options.method || 'GET',
- options.upload ? undefined : options.body
- )
+ ? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url, HERMES_HOME, options.method || 'GET', options.upload ? undefined : options.body)
: null
return new Promise((resolve, reject) => {
@@ -7815,13 +7794,8 @@ async function freshGatewayWsUrl(profile, webContentsId) {
const connection = await ensureBackend(profile)
if (connection.gatewayEndpoint) {
- return localGatewayDial({
- ensure: () => ensureBackend(profile),
- forget: () => forgetLocalGatewayDescriptor(profile),
- launchHome: HERMES_HOME,
- prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, webContentsId),
- profile: String(profile ?? '')
- })
+ return localGatewayDial({ ensure: () => ensureBackend(profile), forget: () => forgetLocalGatewayDescriptor(profile), launchHome: HERMES_HOME,
+ prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, webContentsId), profile: String(profile ?? '') })
}
if (connection.authMode === 'oauth') {
@@ -10735,13 +10709,14 @@ async function forgetRegistryLocalGatewayDescriptor(connectionId, profile) {
}
if (backendPool.delete(localRoute.poolKey)) {
- rememberLog(
- `[gateway] forgot stale canonical endpoint for connection "${String(connectionId || '').trim() || 'primary'}" profile "${profileKey}"; re-ensuring`
- )
+ rememberLog(`[gateway] forgot stale canonical endpoint for connection "${String(connectionId || '').trim() || 'primary'}" profile "${profileKey}"; re-ensuring`)
}
}
-async function ensureBackend(profile, opts: { passive?: boolean; request?: { method?: string; path?: string } } = {}) {
+async function ensureBackend(
+ profile,
+ opts: { passive?: boolean; request?: { method?: string; path?: string } } = {}
+) {
const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()
const passive = Boolean(opts.passive)
@@ -11670,47 +11645,41 @@ async function dialPoolBackend(profile, entry, opts: { forceLocal?: boolean; poo
directoryExists(path.join(HERMES_HOME, 'profiles', key))
)
- const connection = await ensureLocalGateway(
- async () => {
- const backend = await ensureRuntime(
- await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),
- () => assertPoolEntryStillOwned(poolKey, entry)
- )
+ const connection = await ensureLocalGateway(async () => {
+ const backend = await ensureRuntime(
+ await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),
+ () => assertPoolEntryStillOwned(poolKey, entry)
+ )
- profileDeletionGate.assertCanStart(profile)
- assertPoolEntryStillOwned(poolKey, entry)
+ profileDeletionGate.assertCanStart(profile)
+ assertPoolEntryStillOwned(poolKey, entry)
- // Never another profile's dotenv credentials from the Desktop env (#68367).
- return runGatewayEnsure(
- { ...backend, env: desktopBackendSpawnEnv(backend.env || {}) },
- resolveHermesCwd(),
- HERMES_HOME,
- profileBackendParentEnv({ hermesHome: HERMES_HOME, profile })
- )
- },
- async () => {
- // Same update mutual exclusion as the primary's waitForLocalStart (#73822);
- // a held update shows the window's blocked screen for this profile too.
- await waitForPoolUpdateClearance({
- profile,
- poolKey,
- gateDeps: updateGateDeps,
- signal: localBackendLifecycle.signal,
- isCancelled: (): boolean => backendPool.get(poolKey) !== entry,
- log: rememberLog,
- showHold: showUpdateHold,
- clearHold: clearUpdateHold,
- pollMs: UPDATE_WAIT_POLL_MS,
- timeoutMs: UPDATE_WAIT_TIMEOUT_MS
- })
- // Update waits yield: retirement or profile deletion may win in that gap.
- assertPoolEntryStillOwned(poolKey, entry)
- assertLocalProfileCanStart(profile, profileDeletionGate, key =>
- directoryExists(path.join(HERMES_HOME, 'profiles', key))
- )
- },
- restartStaleLocalGateway
- )
+ // Never another profile's dotenv credentials from the Desktop env (#68367).
+ return runGatewayEnsure(
+ { ...backend, env: desktopBackendSpawnEnv(backend.env || {}) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile })
+ )
+ }, async () => {
+ // Same update mutual exclusion as the primary's waitForLocalStart (#73822);
+ // a held update shows the window's blocked screen for this profile too.
+ await waitForPoolUpdateClearance({
+ profile,
+ poolKey,
+ gateDeps: updateGateDeps,
+ signal: localBackendLifecycle.signal,
+ isCancelled: (): boolean => backendPool.get(poolKey) !== entry,
+ log: rememberLog,
+ showHold: showUpdateHold,
+ clearHold: clearUpdateHold,
+ pollMs: UPDATE_WAIT_POLL_MS,
+ timeoutMs: UPDATE_WAIT_TIMEOUT_MS
+ })
+ // Update waits yield: retirement or profile deletion may win in that gap.
+ assertPoolEntryStillOwned(poolKey, entry)
+ assertLocalProfileCanStart(profile, profileDeletionGate, key => directoryExists(path.join(HERMES_HOME, 'profiles', key)))
+ }, restartStaleLocalGateway)
assertPoolEntryStillOwned(poolKey, entry)
@@ -11740,9 +11709,7 @@ async function restartLocalGatewayOwner(ownerProfile: string): Promise<void> {
)
const reason = `${result.stdout}\n${result.stderr}`.trim().split(/\r?\n/).filter(Boolean).pop()
- rememberLog(
- `[gateway] hermes --profile ${ownerProfile} gateway restart exited ${result.code}${reason ? `: ${reason}` : ''}`
- )
+ rememberLog(`[gateway] hermes --profile ${ownerProfile} gateway restart exited ${result.code}${reason ? `: ${reason}` : ''}`)
}
// A ready gateway whose boot commit differs from this Hermes (it outlived `hermes update`) is
@@ -11752,12 +11719,9 @@ const restartStaleLocalGateway = createStaleGatewayRestarter(restartLocalGateway
// Models-page "Restart Hermes": restart the local gateway behind `profile`'s cached descriptor.
// A remote/SSH descriptor has no gatewayEndpoint, so nothing local is touched for it.
async function restartAttachedLocalGateway(profile: string): Promise<void> {
- const pending =
- profile === primaryProfileKey()
- ? backendConnectionState.getPromise()
- : localProfilePoolKeys(profile)
- .map(key => backendPool.get(key)?.connectionPromise)
- .find(Boolean)
+ const pending = profile === primaryProfileKey()
+ ? backendConnectionState.getPromise()
+ : localProfilePoolKeys(profile).map(key => backendPool.get(key)?.connectionPromise).find(Boolean)
const connection = await pending?.catch(() => null)
const endpoint = connection?.gatewayEndpoint
@@ -12159,29 +12123,18 @@ async function startHermes(requestedProfile?: string) {
// Local WSL backend — paths are bridgeable.
setWslBridgeProfileState(primaryProfile, true)
- const connection = await ensureLocalGateway(
- () =>
- runGatewayEnsure(
- { ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}) },
- resolveHermesCwd(),
- HERMES_HOME,
- profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: primaryProfile })
- ),
- undefined,
- restartStaleLocalGateway
- )
+ const connection = await ensureLocalGateway(() => runGatewayEnsure(
+ { ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: primaryProfile })
+ ), undefined, restartStaleLocalGateway)
backendConnectionState.assertCurrentAttempt(connectionAttempt)
backendStartFailure = null
rememberLog('[backend] Hermes gateway is ready')
- updateBootProgress({
- phase: 'backend.ready',
- message: 'Hermes gateway is ready',
- progress: 94,
- running: true,
- error: null
- })
+ updateBootProgress({ phase: 'backend.ready', message: 'Hermes gateway is ready', progress: 94, running: true, error: null })
bootstrapRepairAttempt = 0
// The primary descriptor names its own profile: a profile-less descriptor
@@ -14333,10 +14286,7 @@ ipcMain.handle('hermes:connection:for', async (event, payload) => {
const registry = readDesktopConnectionsRegistry()
const id = registryDialConnectionId(connectionId, registry.primary)
- return connectDesktopProfileRoute(
- { connectionId: id, profile: String(profile ?? '').trim() || 'default' },
- event.sender
- )
+ return connectDesktopProfileRoute({ connectionId: id, profile: String(profile ?? '').trim() || 'default' }, event.sender)
})
const windowConnectionRoutes = new WindowConnectionRouteRegistry()
@@ -15326,27 +15276,17 @@ ipcMain.handle('hermes:gateway:ws-url-for', async (_event, payload) => {
const connection = await ensureRegistryBackend(payload?.connectionId, payload?.profile)
if (connection.gatewayEndpoint) {
- return localGatewayDial({
- ensure: () => ensureRegistryBackend(payload?.connectionId, payload?.profile),
- launchHome: HERMES_HOME,
- forget: () => forgetRegistryLocalGatewayDescriptor(payload?.connectionId, payload?.profile),
- profile: String(payload?.profile ?? ''),
- prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, _event.sender.id)
- })
+ return localGatewayDial({ ensure: () => ensureRegistryBackend(payload?.connectionId, payload?.profile), launchHome: HERMES_HOME,
+ forget: () => forgetRegistryLocalGatewayDescriptor(payload?.connectionId, payload?.profile), profile: String(payload?.profile ?? ''),
+ prepare: (baseUrl, ticket) => localGatewayDials.prepare(baseUrl, ticket, _event.sender.id) })
}
return registryGatewayWsUrlHandler(payload)
})
})
-const pluginWsUrl = createPluginWsUrlHandler({
- ensureBackend,
- ensureRegistryBackend,
- forgetLocalGatewayDescriptor,
- forgetRegistryLocalGatewayDescriptor,
- launchHome: HERMES_HOME,
- prepare: localGatewayDials.preparePlugin
-})
+const pluginWsUrl = createPluginWsUrlHandler({ ensureBackend, ensureRegistryBackend, forgetLocalGatewayDescriptor,
+ forgetRegistryLocalGatewayDescriptor, launchHome: HERMES_HOME, prepare: localGatewayDials.preparePlugin })
ipcMain.handle('hermes:plugin:ws-url', (event, payload) => pluginWsUrl(payload ?? {}, event.sender.id))
// Transactional update for a Desktop-managed SSH install. Unlike the generic
@@ -15509,12 +15449,7 @@ async function fetchJsonForBackend(
.filter(name => typeof name === 'string' && name)
const readProfile = (_profile, scoped) =>
- fetchJsonForBackend(descriptor, scoped, {
- method: opts.method,
- body: opts.body,
- timeoutMs: opts.timeoutMs,
- profileScoped: true
- })
+ fetchJsonForBackend(descriptor, scoped, { method: opts.method, body: opts.body, timeoutMs: opts.timeoutMs, profileScoped: true })
return sessions
? fetchAllProfilesSessionsPerProfile(path, profiles, readProfile)
@@ -16185,14 +16120,7 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles, registry
const getRegistryJson = (descriptor, path) => getJsonForBackend(descriptor, path, { timeoutMs: 10_000 })
// RT-42: count each backend (install_id) once; remote-override profiles are another backend.
const identity = { primaryBackendId: await primaryBackendInstallId(), unknownPrimaryProfiles: remoteProfiles }
- total += await mergeRegistrySessionRows(
- registrySources,
- remoteParams,
- getRegistryJson,
- merged,
- profileTotals,
- identity
- )
+ total += await mergeRegistrySessionRows(registrySources, remoteParams, getRegistryJson, merged, profileTotals, identity)
}
const recency = s => s?.[order] ?? s?.started_at ?? 0
@@ -16200,9 +16128,7 @@ async function mergeRemoteProfileSessions(searchParams, remoteProfiles, registry
const archivedOnly = searchParams.get('archived') === 'only'
- return composeUnifiedSessionResponse(base, merged, offset, limit, total, profileTotals, remoteErrors, {
- archivedOnly
- })
+ return composeUnifiedSessionResponse(base, merged, offset, limit, total, profileTotals, remoteErrors, { archivedOnly })
}
// Every CONNECTED registry gateway as a session source: resolved descriptors
@@ -16401,13 +16327,12 @@ async function handleHermesApiRequest(request) {
// Main's shared transport for every descriptor: configured headers, a native
// gateway grant per attempt, and the OAuth bearer→cookie fallback that
// survives refresh failures and login races (requestWithOauthFallback).
- const send = current =>
- fetchJsonForBackend(current, apiRoute.requestPath, {
- method: request?.method,
- body: request?.body,
- upload: request?.upload,
- timeoutMs
- })
+ const send = current => fetchJsonForBackend(current, apiRoute.requestPath, {
+ method: request?.method,
+ body: request?.body,
+ upload: request?.upload,
+ timeoutMs
+ })
response = connection.gatewayEndpoint
? await redialLocalGateway({
@@ -16711,20 +16636,10 @@ ipcMain.handle('hermes:writeClipboard', (_event, text) => {
return true
})
-// Native save-location picker (profile export etc.) — the write itself happens
-// elsewhere (the backend, for profile archives); this only picks the path.
-ipcMain.handle('hermes:selectSavePath', async (_event, options: any = {}) => {
- const result = await dialog.showSaveDialog(mainWindow, {
- title: options?.title || 'Save',
- defaultPath: options?.defaultPath ? String(options.defaultPath) : undefined,
- filters: Array.isArray(options?.filters) ? options.filters : undefined
- })
-
- if (result.canceled || !result.filePath) {
- return null
- }
-
- return result.filePath
+// Save dialogs: the path picker (profile export) and /save's main-process write (save-text-file.ts).
+registerSaveDialogIpc(ipcMain, {
+ defaultDir: () => app.getPath('documents'),
+ showSaveDialog: options => dialog.showSaveDialog(mainWindow, options)
})
// Paired reader for the GUI terminal's paste chord: the renderer's
@@ -16735,15 +16650,6 @@ ipcMain.handle('hermes:readClipboard', () => clipboard.readText())
ipcMain.handle('hermes:saveGatewayFile', (_event, payload) => saveGatewayFile(payload))
-// T11: /save writes here, not on the gateway (which may be remote): the renderer passes the content
-// the owner rendered (session.export) and the user picks the destination.
-ipcMain.handle('hermes:saveTextFileAs', (_event, request) =>
- saveTextFileAs(request || {}, {
- defaultDir: () => app.getPath('documents'),
- showSaveDialog: options => dialog.showSaveDialog(mainWindow, options)
- })
-)
-
ipcMain.handle('hermes:saveImageFromUrl', (_event, url) => saveImageFromUrl(String(url || '')))
// The custom context menu's edit verbs. They act on the SENDER's focused
@@ -18026,14 +17932,8 @@ ipcMain.handle('hermes:deep-link-ready', () => {
function registerDeepLinkProtocol() {
registerDeepLinkProtocolWith({
- app,
- protocol: HERMES_PROTOCOL,
- env: process.env,
- defaultApp: Boolean(process.defaultApp),
- argv: process.argv,
- execPath: process.execPath,
- resolve: entry => path.resolve(entry),
- log: rememberLog
+ app, protocol: HERMES_PROTOCOL, env: process.env, defaultApp: Boolean(process.defaultApp),
+ argv: process.argv, execPath: process.execPath, resolve: entry => path.resolve(entry), log: rememberLog
})
}
diff --git a/apps/desktop/electron/save-text-file.test.ts b/apps/desktop/electron/save-text-file.test.ts
index 0d2f3712fe1..ec7d2c3624b 100644
--- a/apps/desktop/electron/save-text-file.test.ts
+++ b/apps/desktop/electron/save-text-file.test.ts
@@ -4,7 +4,7 @@ import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
-import { SAVE_TEXT_FILE_MAX_BYTES, saveTextFileAs } from './save-text-file'
+import { registerSaveDialogIpc, SAVE_TEXT_FILE_MAX_BYTES, saveTextFileAs } from './save-text-file'
const scratch: string[] = []
@@ -85,3 +85,20 @@ describe('saveTextFileAs (Electron-side /save write)', () => {
expect(opened).toBe(false)
})
})
+
+describe('registerSaveDialogIpc', () => {
+ it('registers the path picker and the main-process write', async () => {
+ const handlers = new Map<string, (event: unknown, ...args: any[]) => unknown>()
+ const dir = tempDir()
+ const target = path.join(dir, 'out.json')
+ registerSaveDialogIpc(
+ { handle: (channel, listener) => void handlers.set(channel, listener) },
+ { defaultDir: () => dir, showSaveDialog: async () => ({ canceled: false, filePath: target }) }
+ )
+
+ expect([...handlers.keys()].sort()).toEqual(['hermes:saveTextFileAs', 'hermes:selectSavePath'])
+ expect(await handlers.get('hermes:selectSavePath')!(null, { title: 'Export' })).toBe(target)
+ expect(await handlers.get('hermes:saveTextFileAs')!(null, { content: '{}' })).toEqual({ saved: true, path: target })
+ expect(fs.readFileSync(target, 'utf8')).toBe('{}')
+ })
+})
diff --git a/apps/desktop/electron/save-text-file.ts b/apps/desktop/electron/save-text-file.ts
index e67534e1a0a..583785aba10 100644
--- a/apps/desktop/electron/save-text-file.ts
+++ b/apps/desktop/electron/save-text-file.ts
@@ -28,6 +28,10 @@ export interface SaveTextFileDeps {
writeFile?: (filePath: string, content: string) => Promise<void>
}
+interface IpcMainLike {
+ handle: (channel: string, listener: (event: unknown, ...args: any[]) => unknown) => void
+}
+
/** Rendered transcripts can be large; cap well above any realistic /save output. */
export const SAVE_TEXT_FILE_MAX_BYTES = 64 * 1024 * 1024
@@ -95,3 +99,20 @@ export async function saveTextFileAs(
return { saved: true, path: result.filePath }
}
+
+/** Native save-location picker (profile export etc.): only picks the path; the write happens elsewhere. */
+export async function selectSavePath(options: any, deps: SaveTextFileDeps): Promise<null | string> {
+ const result = await deps.showSaveDialog({
+ title: options?.title || 'Save',
+ defaultPath: options?.defaultPath ? String(options.defaultPath) : undefined,
+ filters: Array.isArray(options?.filters) ? options.filters : undefined
+ })
+
+ return result.canceled || !result.filePath ? null : result.filePath
+}
+
+/** `hermes:selectSavePath` (path only) and `hermes:saveTextFileAs` (dialog + main-process write). */
+export function registerSaveDialogIpc(ipcMain: IpcMainLike, deps: SaveTextFileDeps): void {
+ ipcMain.handle('hermes:selectSavePath', (_event, options = {}) => selectSavePath(options, deps))
+ ipcMain.handle('hermes:saveTextFileAs', (_event, request) => saveTextFileAs(request || {}, deps))
+}