import { type ChildProcess, execFileSync, spawn } from 'node:child_process' import crypto from 'node:crypto' import fs from 'node:fs' import http from 'node:http' import https from 'node:https' import os from 'node:os' import path from 'node:path' import tls from 'node:tls' import { pathToFileURL } from 'node:url' import { app, BrowserWindow, clipboard, crashReporter, dialog, net as electronNet, webContents as electronWebContents, globalShortcut, ipcMain, type IpcMainEvent, type IpcMainInvokeEvent, Menu, type MenuItemConstructorOptions, nativeTheme, powerMonitor, powerSaveBlocker, protocol, safeStorage, screen, session, shell, systemPreferences } from 'electron' import type { Session } from 'electron' import { type ActiveRuntimeState, classifyActiveRuntime } from './active-runtime-state' import { HERMES_API_EXPECTED_404 } from './api-expected-404' import { destroyKeepaliveAgents, htmlResponseError, httpStatusError, jsonAgentFor, readJsonErrorBody, readStatusCode, withRetry } from './api-transport' import { appIconCandidates, resolveAppIcon, shouldOverrideDockIcon } from './app-icon' import { stageAppInstallerFile } from './app-installer-file' import { appVersionInfo, type AppVersionInfo, assertSourceUpdateChannel, nativeAboutVersion, packagedReleaseChannel } from './app-version' import { runAppInstallerChecker } from './appinstaller-checker' import { installApplicationMenuAfterFirstWindow } from './application-menu-startup' import { stopBackendChild as stopBackendChildImpl, waitForBackendExit } from './backend-child' import { type BackendOutputTail, claimDecision, createBackendOutputTail, execText, formatBackendExitLine, isPidOnlyStartMarker, pidOnlyStartMarker, probeStartMarker, processStartMarker, REAP_PROBE_TIMEOUT_MS } from './backend-claim' import { dashboardFallbackArgs, serveBackendArgs } from './backend-command' import { createBackendConnectionState } from './backend-connection-state' import { BackendDialClaims } from './backend-dial-claim' import type { HostBackendRecord } from './backend-discovery' import { buildDesktopBackendEnv, pooledProfileBackendEnv, profileBackendParentEnv } from './backend-env' import { createBackendExitRecoveryLatch } from './backend-exit-recovery' import { isReauthRequiredError, waitForHermesReady } from './backend-health' import { backendCommandMatches, type BackendOwnershipEntry, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership' import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyHermesCli } from './backend-probes' import { waitForDashboardPortAnnouncement } from './backend-ready' import { recycleOwnedBackend } from './backend-recycle' import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate' import { createInstalledRuntimeGate } from './backend-resolution' import { createBackendServeSupportResolver } from './backend-serve-support' import { desktopBackendSpawnEnv } from './backend-spawn-env' import { isHostKeyChangedBootFailure, isRetryableRemoteBootFailure, isSshAuthFailedBootFailure, isSshClientFailedBootFailure, shouldHoldBootProgressForReauth, shouldLatchBackendStartFailure, shouldLatchHostKeyChangedFailure, shouldLatchRemoteReauthFailure, shouldLatchSshAuthFailure, shouldLatchSshClientFailure, sshClientFailedError } from './backend-start-failure' import { describeBootstrapFailure } from './bootstrap-failure-copy' import { detectRemoteDisplay, isWindowsBinaryPathInWsl, isWslEnvironment, resolveLinuxPasswordStore } from './bootstrap-platform' import { decideBootstrapRepair } from './bootstrap-repair-guard' import { runBootstrap } from './bootstrap-runner' import { bootstrapSnapshot } from './bootstrap-state' import { BROWSER_WINDOW_HEIGHT, BROWSER_WINDOW_MIN_HEIGHT, BROWSER_WINDOW_MIN_WIDTH, BROWSER_WINDOW_WIDTH, buildBrowserWindowUrl } from './browser-windows' import { createBundleSkewChecker } from './bundle-skew' import { BUNDLE_SWAP_RELAUNCH_FAILSAFE_MS, detectBundleSwap, readBundleSwapStamp, relaunchIntoSwappedBundle } from './bundle-swap' import { CHALLENGE_PARTITION } from './challenge-window' import { registerChallengeWindowIpc } from './challenge-window-ipc' import { provisionCliLinks } from './cli-provision' import { closeStopFailureMessage, finishWindowsCloseStop, type RuntimeLock } from './close-stop-kill' import { shouldAttemptCloudBootCascade } from './cloud-boot-cascade' import { discoverWithTeamFallback } from './cloud-discovery' import { createCloudSessionRecovery } from './cloud-session-recovery' import { installCommandScreenshot } from './command-screenshot' import { composerImageTimestamp } from './composer-image-name' import { writeComposerPaste } from './composer-paste' import { applyConnectionChange, teardownSshState } from './connection-apply' import { connectionInstallIds, evictConnectionCaches, rosterSourceErrors, sshInventoryAttemptedAt, sshRosterCache } from './connection-caches' import { apiRequestRegistryConnectionId, authModeFromStatus, buildGatewayWsUrl, buildGatewayWsUrlWithTicket, connectionScopeKey, cookiesHaveLiveSession, cookiesHaveSession, gatewayWsUrlIpcResult, hostLabelFromBaseUrl, isGatewayAuthRejection, localProfileEntry, modeIsRemoteLike, normalizeRemoteBaseUrl, normalizeRemoteHeaders, normalizeRemoteProfileName, normalizeSshConfig, normAuthMode, pathForRegistryBackendRequest, pathWithGlobalRemoteProfile, profileHasRemoteConnection, profileRemoteOverride, type ProfileRouteOptions, profileSshOverride, type RegistryBackendRequestScope, resolveAuthMode, resolveProfileApiRequest, resolveProfileBackendRoute, resolveRemoteSshDashboardProfile, resolveTestWsUrl, sanitizeRemoteHeaderValue, savedProfileSsh, tokenPreview, unscopableMutatingRequest, withTransientRetries } from './connection-config' import { applyConnectionConfigAtomically } from './connection-config-apply' import { backendScopeKey, backendScopePrefix, buildAgentRoster, connectionDialFieldsChanged, connectionIdForPendingLogin, mergeConnectionInput, migrateV1ToRegistry, normalizeConnectionInput, normalizeRegistry, parseBackendScopeKey, reconcileAppliedGlobalConnection, reconcileRegistryDrift, registryDialConnectionId, rememberSshEnumeration, removeConnection, type ResolvedConnectionDescriptor, resolvedConnectionId, resolveRegistryLocalRoute, reuseMatchingPrimaryRemoteBackend, reuseMatchingPrimarySshBackend, setConnectionLaunchMode, setLastUsedConnection, setPrimaryConnection, type SharedRegistryProfileScope, shouldDeferLocalEnumeration, shouldRetrySshInventory, updateEligibility, upsertConnection } from './connection-registry' import type { RegistryConnection } from './connection-registry' import type { RosterProfileMetadata } from './connection-registry' import { liveWindowState, overlayWindowState } from './connection-window-state' import { describeCrashReason, installCrashForensics } from './crash-forensics' import { adoptServedDashboardToken, isAttachedBackendTokenDrifted, resolveServedDashboardToken } from './dashboard-token' import { resolveDashboardWebDist } from './dashboard-web-dist' import { resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths' import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation' import { formatDesktopLogLine, formatLogStamp } from './desktop-log-line' import { createDesktopProfilePreferences, DESKTOP_PROFILE_NAME_RE, type DesktopProfileRoute, resolveDesktopConnectionRequest, resolveDesktopWindowLaunch } from './desktop-profile' import { registryPrimaryBootRoute, resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remote-route' import { type DesktopSharedMetrics, registerDesktopSharedMetrics } from './desktop-shared-metrics' import { buildPosixCleanupScript, buildWindowsCleanupScript, type DesktopUninstallResult, modeRemovesAgent, modeRemovesUserData, registerDesktopUninstallIpc, resolveRemovableAppPath, shouldRemoveAppBundle, uninstallArgsForMode, type UninstallSummaryDetails } from './desktop-uninstall' import { describeDevCdpDecision, resolveDevCdpPort } from './dev-cdp' import { preReadyDockLaunchSteps } from './dock-launch-order' import { embedHostOrigin } from './embed-host' import { installEmbedReferer } from './embed-referer' import { createAmbientClaimArbiter } from './event-dedupe' import { openExternalUrl as externalOpen, type ExternalOpenDeps, reportPreOpenStatFailure } from './external-open' import { buildTerminalScript, resolveTerminalLaunch, terminalScriptEnv, terminalScriptExtension, tuiResumeArgs } from './external-terminal' import { f12ShortcutDecision, toF12KeyboardEventPayload } from './f12-shortcut' import { resolveFeatureFlags } from './feature-flags' import { installFindShortcut, installFoundInPageForwarder, performFindAfterIndexingStarted, stopFind } 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 { gatewayFilePath, gatewayFileRequestPaths, resolveGatewayFileBackend, 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, spawnedBackendProbeOptions } from './gateway-ws-probe' import { windowsGitCandidates } from './git-binary-candidates' import { registerGitIpc } from './git-ipc' import { assertExistingPathForOpen, ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES, clampDataUrlReadMaxMb, DATA_URL_READ_DEFAULT_MAX_MB, dataUrlReadMaxBytesFromMb, DEFAULT_FETCH_TIMEOUT_MS, enableBasicPasswordStoreEncryption, encryptDesktopSecret as encryptDesktopSecretStrict, homeRelativeAttachmentCandidates, isMissingFileError, missingFileResult, readFileDataUrlForIpc, resolvePersistedRemoteToken, resolveReadableFileForIpc, resolveRemoteTokenPlainText, resolveRequestedPathForIpc, resolveTimeoutMs, SAFE_STORAGE_ENCODING, TEXT_PREVIEW_SOURCE_MAX_BYTES, tightenSecretFileMode, writeSecretFileAtomic } from './hardening' import { type AttachedBackend, attachOrReserveSpawn, checkoutHeadIdentity, HOST_SPAWN_GATE_STALE_MS, spawnLedgerPath, type SpawnReservation } from './host-backend-attach' import { assertNoSecondLocalBackend, assertNotPassiveSpawn } from './host-backend-singleton' import { lookupPublishedSessionToken } from './host-published-token' import { claimHostSpawnGate } from './host-spawn-gate' import { HERMES_HUB_FALLBACK_ORIGIN, HERMES_HUB_ORIGIN, isHermesHubClipboardWrite } from './hub-iframe-policy' import { requestHudClose } from './hud-close' import { cursorPointInWindow } from './hud-cursor' import { startHudGameOverlayWatch } from './hud-game-overlay' import { applyHudResetBounds, defaultHudBounds } from './hud-geometry' import { registerHudIpc } from './hud-ipc' import { installHudModifierTap } from './hud-modifier' import { applyHudElectronOverlay, promoteHudOverlay } from './hud-overlay' import { snapHudBounds } from './hud-snap' import { createHudSnapShortcut } from './hud-snap-shortcut' import { buildHudWindowUrl } from './hud-url' import { linuxOzoneBackend, resolveHudWindowing } from './hud-windowing' import { INSTALL_STAMP, installShape } from './install-stamp' import type { InstallStamp } from './install-stamp' import { applyLaunchProfileOverride } from './launch-profile' import { fetchLinkTitle, resolveFaviconCached } from './link-metadata' import { CHROMIUM_LOG_FILENAME, enableLinuxCrashDiagnostics, linuxCrashDiagnostics } from './linux-crash-diagnostics' import { decideLinuxGpuLaunch, disableGpuSwitchNeededForReason, LINUX_GPU_SILENT_RETRY_GRACE_S, linuxGpuChildDeathPath, linuxGpuFallbackMarker, linuxGpuMarkerAfterSuccessfulBoot, readLinuxGpuMarker, shouldEngageSilentGpuRetryFallback, writeLinuxGpuMarker } from './linux-gpu-fallback' import { notifyLauncherWindowRevealed } from './linux-launcher-ready' import { decideNvidiaEglFallback, nvidiaEglFallbackMarker, nvidiaEglMarkerAfterSuccessfulBoot, parseNvidiaDriverMajor, parseNvidiaDriverVersion, readNvidiaEglMarker, shouldRelaunchForNvidiaGpuDeath, writeNvidiaEglMarker } from './linux-nvidia-egl-fallback' import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle' import { resolveIpcFileReadPath, resolveMediaStreamFile, resolvePreviewTargetPath } from './local-read-path' import { localSkinProfileKey, readLocalSkinPayload } from './local-skin' import { ACTIVE_LOG_POLL_MS, planLogRotation, reclaimActiveLogIfOversized } from './log-rotation' import { registerMachineProfile } from './machine-profile' import { createMainProcessLagWatchdog } from './main-process-lag-watchdog' import { activateWindow, ensureMainWindow, shouldQuitOnLastChatClosed } from './main-window-lifecycle' import { assertManagedUpdatePreflightClear, executeManagedRemoteUpdate, fenceManagedSshBootstrapPublication, joinManagedUpdatesForApply, ManagedConnectionUpdateGate, managedSshDrainBlocker, managedSshRecoveryScopes, managedSshScopeRole, managedSshTokenPersistencePlan, managedSshUpdateAllRow, MAX_MANAGED_SSH_RECOVERY_ATTEMPTS, recoverManagedSshScopes, refusedManagedSshUpdate, type RemoteUpdateTarget, runManagedSshUpdate, validateCorrelationId, waitForManagedRemoteClearance, waitForManagedSshBootstrapFence, waitForManagedUpdateOperations } from './managed-ssh-update' import { registerMcpOauthCallbackIpc } from './mcp-oauth-callback-ipc' import { isMediaCapturePermission } from './media-capture-permission' import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol' import { fetchLocalMedia } from './media-range' import { createMinimizeToTray } from './minimize-to-tray' import { createNativeAccessTokenCoordinator, type NativeAccessTokenOptions, NativeAuthChangedError } from './native-access-token' import { oauthSessionIsLive, resolveJsonBody, resolveReadinessProbeAuth } from './native-auth-decisions' import { nativeRefreshUrl, type NativeTokenSet, parseTokenResponse, resolveLoginStrategy, tokenNeedsRefresh } from './native-oauth' import { runNativeLogin } from './native-oauth-login' import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } from './native-token-store' import { execGit, killTimedGitChildren, setNoConsoleGitRoots } from './no-console-git' import { registerNativeNotifications } from './notification-ipc' import { isExpectedOauthNavigationAbort } from './oauth-navigation' import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request' import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition' import { canShowInteractiveOauthLogin, mintGatewayWsTicket as mintOauthGatewayWsTicket, requestWithOauthFallback, retryCookie401WithLogin, withoutInteractiveOauthLogin } from './oauth-rest-request' import { wireOauthSessionResponse } from './oauth-session-response' import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap' import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity' import { bundledPayload, installIdForRoot, type PayloadInfo, payloadPythonPath } from './payload-backend' import { petOverlayClickThrough, shouldPopInOnOverlayClosed } from './pet-overlay' import { placePetOverlay, registerPetOverlayIpc } from './pet-overlay-ipc' import { buildRegistryProfileRoutes, isLocalEnumerationFailure, localRouteFallbackProfiles, undialedSshRouteSeeds } from './plugin-profile-routes' import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS } from './pool-limits' import { createPoolRetirer } from './pool-retire' import { createPoolRetirementClient } from './pool-retire-http' import { assertPoolEntryStillOwned, BackgroundSlotRetryBackoff, BackgroundSlotRetryDeferredError, isBackgroundSlotRetryDeferred, isBackgroundSlotWaitTimeout, LocalBackendSpawnCoordinator, type LocalBackendSpawnPriority, registerLocalBackendExitFinalizer, releaseLocalBackendSlot, releaseLocalBackendSlotAfterExit } from './pool-spawn-coordinator' import { createPoolStopper } from './pool-stop' import { poolTouchKeys } from './pool-touch-scope' import { createPortalSession, resolvePortalBaseUrl } from './portal-session' import { createKeepAwake, type KeepAwakeMode, keepAwakeWanted, parseKeepAwakeMode, readKeepAwakeMode } from './power-save' import { readPreUpdateBackupEnabled } from './pre-update-backup-config' import { capturePreviewContents } from './preview-capture' import { onPreviewWatchOwnerDestroyed, sendPreviewFileChangedToOwner } from './preview-file-watch' import { hasClosePreviewFlag, previewGuestInputAction } from './preview-guest-escape' import { commandFocusedGuest, notePreviewGuestHidden } from './preview-guest-offscreen' import { applyPreviewGuestAttachPrefs } from './preview-guest-throttle' import { PreviewReachRegistry } from './preview-reach' import { previewHttpUrlTarget } from './preview-url-target' import { createPrimaryRemoteConnection, FirstRunSetupResetError, runPrimaryBackendStartup } from './primary-backend-startup' import { rehomePrimaryConnection } from './primary-connection-rehome' import { PrimaryProfilePin, resolveLaunchProfile } from './primary-profile-pin' import { applyDesktopIdentity, PRODUCT_IDENTITY } from './product-identity' import { assertLocalProfileCanStart, decideProfileDeleteAction, dispatchConnectionScopedProfileDelete, localProfilePoolKeys, ProfileDeletionGate, profileNameFromDeleteRequest, resolveRouteProfile } from './profile-delete-routing' import { migrateActiveProfileIfMissing as migrateActiveProfileIfMissingPure } from './profile-migration' import { prepareProfileRenameLifecycle, profileRenameFromRequest } from './profile-rename-routing' import { applyRemoteProfileSessionOutcomes, assembleSidebarSessionSlices, buildSidebarSessionSliceParams, composeUnifiedSessionResponse, fetchPrimaryProfileSessions, fetchRegistrySessionRows, fetchRemoteProfileSessions, findRemoteOwnerProfileForSession, hasPinnedRegistrySessionSource, isAllProfilesSessionListRequest, pathWithRemoteOwnerScope, type RegistrySessionSource, remoteProfileQueryScope, settleRemoteProfileSessions, shouldIncludeLocalRegistrySessionSource, spliceRegistrySessionRows, tagRegistrySessionResponse, tagRemoteSessionRows } from './profile-session-routing' import { createQuickEntryShortcut, createQuickEntrySubmitRelay, quickEntryWindowBounds, sanitizeQuickEntrySettings } from './quick-entry' import { createQuitFinalization } from './quit-finalization' import { type ActiveWork, backendOwnedByApp, mergeActiveWork, normalizeActiveWork, quitPromptFor, shouldGuardWindowClose } from './quit-guard' import { backendQuitNeedsWait, backendTeardownOptions, createQuitTeardownCoordinator, type QuitTeardownTask } from './quit-teardown' import * as remoteLifecycle from './remote-lifecycle' import { attachPowerResumeRemoteRevalidation, ensureHealthyPooledRemoteBackendForDispatch, REMOTE_POOLED_LIVENESS_FAILURE_WINDOW_MS, RemoteLivenessTracker, RemoteRevalidationCoordinator, revalidatePooledRemoteBackends, revalidateRemoteConnection, revalidateSuspectPooledRemoteBackends } from './remote-liveness' import { resolveRemoteOauthTicket, rosterSourceEnumerationTimeoutMs } from './remote-oauth-ticket' import { createRemoteOwnerCache } from './remote-owner-cache' import { remoteSessionCookies } from './remote-session-cookies' import { attachRemoteRequestHeaderListener, collectRemoteHeaderSources, createRegistryGatewayWsUrlHandler, createRemoteWsHeaderStore, oauthLoginLoadUrlOptions, resolveRemoteRequestHeaders } from './remote-ws-headers' import { enableRendererAccessibility } from './renderer-accessibility' import { missingRendererAssets, presentRendererIndexes } from './renderer-bundle' import { planLaunchSwitches, readDesktopLaunchConfig } from './renderer-heap-flags' 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 { classifyStoredSecret, readSecretStoragePolicy, SECRET_STORAGE_POLICY_FILE, type SecretStoragePolicy, writeSecretStoragePolicy } from './secret-storage-policy' import { selectPathsDialogProperties } from './select-paths-dialog' import { selectRunnableBinary } from './select-runnable-binary' import { buildInstanceWindowUrl, buildSessionWindowUrl, chatWindowWebPreferences, createSessionWindowRegistry, instanceWindowBounds, SESSION_WINDOW_MIN_HEIGHT, SESSION_WINDOW_MIN_WIDTH } from './session-windows' import { ensureLoginShellPath } from './shell-path' import { removeStaleSingletonLock } from './singleton-lock' import { createSourcePythonBackend, resolveSourceInstallationBackend, type SourceBackend } from './source-backend' import { resolveSourcePython } from './source-python' import { resolveSshBinary } from './ssh-binary' import { createBootstrapCoordinator, sshConfigFingerprint } from './ssh-bootstrap-coordinator' import { collectSshConfigHosts, parseSshGOutput } from './ssh-config' import { createSshProbeConnection, pickLocalPort, redactSecrets, SshConnection } from './ssh-connection' import { createSshIsolatedKeepaliveRegistry } from './ssh-isolated-keepalive' import { createSshTeardownTracker } from './ssh-teardown' import { createStreamThrottle } from './stream-throttle' import { installSystemCaTrust } from './system-ca' import { registerTerminalIpc } from './terminal-ipc' import { nativeOverlayWidth as computeNativeOverlayWidth, titleBarOverlayOptions } from './titlebar-overlay-width' import { backgroundMaterialFor, defaultTranslucencyState, glassActive, glassSupportedOn, normalizeState as normalizeTranslucency, opacityNeedsSetting, translucencySupportedOn, vibrancyFor as vibrancyForTranslucency, windowBackgroundMaterialOptions, windowBackingOptions, windowOpacityFor, windowOpacityOptions } from './translucency' import { UPDATE_HANDOFF_DWELL_MS, UPDATE_WAIT_POLL_MS, UPDATE_WAIT_TIMEOUT_MS, waitForUpdateClearance } from './update-gate' import { parkedRunReport } from './update-handoff-report' import type { UpdateHoldWire } from './update-hold-types' import { createUpdateHoldScreen, type MarkerGateCallbacks, markerGateProbe, registerUpdateHoldIpc, waitForPoolUpdateClearance } from './update-hold-wiring' import { describeSkippedPrewrite, readLiveUpdateMarker, updateHandoffConflict, writeUpdateMarker } from './update-marker' import { heldWaitMessage, holdTicker } from './update-marker-gate' import { updateConnectionsBeforeLocal } from './update-order' import { resolveUpdaterMechanism, type UpdaterApplyResultWire, type UpdaterStatusWire, type UpdaterStrategy } from './updater' import { observeUpdaterHandoff, repairMacUpdaterHelper, resolveInstallationLauncher, resolveStagedUpdaterBinary, resolveVenvDir, spawnUpdaterProcess, stagedUpdaterSupportsPrewrittenMarker, userLauncherInstallRoot } from './updater-process' import { AppInstallerStrategy } from './updater/app-installer' import { createChannelAppInstallerStrategy } from './updater/app-installer' import { ChannelResolver, type ChannelTarget } from './updater/channel' import { inspectRunningChannelApp } from './updater/channel-native' import { ChannelStrategy } from './updater/channel-strategy' import { verifyPreparedChannelInstaller } from './updater/channel-windows-host' import { type CheckoutStrategy, createCheckoutStrategy } from './updater/checkout' import { readSourceUpdate, sourceChannelName, type SourceUpdate } from './updater/checkout-source' import { ExternalStrategy } from './updater/external' import { readUpdatesFeedBaseFromConfig, resolveFeedBaseUrl } from './updater/feed-config' import { createChannelMacStrategy, createMacStrategy } from './updater/mac-client' import { UpdateOperation } from './updater/operation' import { type ConsumedRelaunch, consumePendingRelaunch, registerUpdateRelaunch, type RelaunchRegistration } from './updater/relaunch' import { startUpdateRelaunchWaiter } from './updater/relaunch-waiter' import { preflightStateDb } from './updater/state-db-preflight' import { createStoreStrategy } from './updater/store-client' import { isExternalVenvHolder, isHermesOwnedVenvDaemon } from './venv-holder-select' import { fetchMarketplaceThemes, searchMarketplaceThemes } from './vscode-marketplace' import { createWakeIndicatorWindowController } from './wake-indicator-window' import { guardedWatch } from './watch-storm-breaker' import { windowAcceleratorAction } from './window-accelerator' import { enumerateWindowsFrontToBack, enumerationFailed, readWindowBelow } from './window-below' import { bindWindowChromeEvents } from './window-chrome-events' import { appliedPrimaryWindowRoute, registrySshPoolScopeByConnectionId, registrySshScopeForWindowRoute, WindowConnectionRouteRegistry } from './window-connection-route' import { registerWindowControlIpc, windowControlState } from './window-controls' import { revealAction, shouldFocusToTakeKeyboard } from './window-focus-policy' import { isAppSized, registerWindowSizing } from './window-growth' import { windowMenuTemplate } from './window-menu' import { createWindowOpenHandler } from './window-open-policy' import { installWindowRendererLifecycle } from './window-renderer-lifecycle' import { wireWindowReveal } from './window-reveal' import { bindGeometryPersistence, computeWindowOptions, debounce, sanitizeWindowState, MIN_HEIGHT as WINDOW_MIN_HEIGHT, MIN_WIDTH as WINDOW_MIN_WIDTH, windowSize } from './window-state' import { hiddenWindowsChildOptions, windowsShellCommand } from './windows-child-options' import { buildPathExtCandidates, chooseUpdaterArgs, resolveVenvHermesCommand } from './windows-hermes-path' import { connectWindowsRemote, detectRemotePlatform, helper, probeWindowsRemote, terminateOwnedWindowsDashboardForUpdate } from './windows-remote-lifecycle' import { alreadyHasNoSandbox, buildNoSandboxRelaunchArgs, decideWindowsSandboxLaunch, fallbackMarker, grantAllApplicationPackagesAcl, markerAfterSuccessfulBoot, readSandboxMarker, type SandboxFallbackReason, shouldAttemptAclRepair, shouldRelaunchForGpuSandboxCrash, shouldRelaunchForRendererSandboxCrashLoop, writeSandboxMarker } from './windows-sandbox-fallback' import { alreadyHasDisableGpu, buildDisableGpuRelaunchArgs, decideWindowsGpuStackCookieLaunch, gpuStackCookieFallbackMarker, isHermesDesktopGpuOverrideOff, markerAfterSuccessfulGpuStackCookieBoot, readGpuStackCookieMarker, shouldRelaunchForRendererStackCookieCrashLoop, shouldSurfaceErrorForRendererStackCookieCrashLoop, writeGpuStackCookieMarker } from './windows-stack-cookie-fallback' import { readWindowsUserEnvVar } from './windows-user-env' import { isPackagedInstallPath as isPackagedInstallPathUnderRoots } from './workspace-cwd' import { readWslWindowsClipboardImage } from './wsl-clipboard-image' import { resolvePickerDefaultPath, setActiveGatewayProfile, setWslBridgeProfileState } from './wsl-path-bridge' const IDENTITY_APP_NAME: string | null = applyDesktopIdentity(app) const USER_DATA_OVERRIDE: string | undefined = process.env.HERMES_DESKTOP_USER_DATA_DIR if (USER_DATA_OVERRIDE || process.env.HERMES_DATA_DIR_SUFFIX) { const resolvedUserData: string = resolveDesktopUserData(app.getPath('userData')) fs.mkdirSync(resolvedUserData, { recursive: true }) app.setPath('userData', resolvedUserData) } const DEV_SERVER = process.env.HERMES_DESKTOP_DEV_SERVER const IS_PACKAGED = app.isPackaged || Boolean(process.env.HERMES_DESKTOP_IS_PACKAGED) const IS_MAC = process.platform === 'darwin' const IS_WINDOWS = process.platform === 'win32' const IS_WSL = isWslEnvironment() // Truthful macOS kernel major (Tahoe = 25). Product version lies (16 vs 26) per // build SDK, so gate Tahoe workarounds on Darwin instead. const DARWIN_MAJOR = IS_MAC ? Number.parseInt(os.release(), 10) || 0 : 0 // Glass: macOS vibrancy, or Windows 11 22H2+ system backdrop. Computed once // so the renderer, the persisted default, and every chat window agree. const GLASS_SUPPORTED = glassSupportedOn(process.platform, os.release()) // Clear rides setOpacity, a documented no-op on Linux, so neither mode works // there and Settings drops the row entirely. const TRANSLUCENCY_SUPPORTED = translucencySupportedOn(process.platform) const APP_ROOT = app.getAppPath() // Device-local preference: block F12 from opening DevTools. // Set dynamically via IPC from the renderer Settings → Advanced. let f12Blocked = false // Preload must be plain JS — Electron's sandbox can't run .ts, and tsx's // ESM loader is broken on Electron 40's Node (ERR_INVALID_RETURN_PROPERTY_VALUE). // Dev (`npm run dev`) and prod both load the esbuild output from dist/. const PRELOAD_PATH = path.join(APP_ROOT, 'dist', 'electron-preload.js') const PREVIEW_GUEST_PRELOAD_PATH = path.join(APP_ROOT, 'dist', 'preview-guest-preload.js') // Remote displays (SSH X11 forwarding, VNC, RDP) make Chromium's GPU // compositor flicker — accelerated layers can't be presented cleanly over the // wire, so the window flashes during scroll/streaming/animation. Local // Windows/macOS (and WSLg, which renders locally via vGPU) composite on the // GPU and never see it. Fall back to software rendering when a remote display // is detected; it's rock-steady over the wire and the CPU cost is negligible // next to the connection's latency. Must run before app `ready` — these // switches only apply pre-launch. Override with HERMES_DESKTOP_DISABLE_GPU // (1/true → always disable, 0/false → keep GPU on). const REMOTE_DISPLAY_REASON = detectRemoteDisplay() if (REMOTE_DISPLAY_REASON) { app.disableHardwareAcceleration() // Belt-and-suspenders for X11/VNC, where the Viz compositor can still glitch // with only --disable-gpu: force compositing onto the CPU too. app.commandLine.appendSwitch('disable-gpu-compositing') // #97616: disableHardwareAcceleration() alone does NOT stop a GPU child // from spawning (it then dies error_code=1002 on AMD/Mesa). For the explicit // HERMES_DESKTOP_DISABLE_GPU override, fully spawn-block it. Remote-display // detections keep their long-standing compositing-only behavior. if (disableGpuSwitchNeededForReason(REMOTE_DISPLAY_REASON)) { app.commandLine.appendSwitch('disable-gpu') } console.log( `[hermes] remote display detected (${REMOTE_DISPLAY_REASON}); disabling GPU hardware acceleration to prevent flicker` ) } // #108047: a local Windows renderer crash loop with STATUS_STACK_BUFFER_OVERRUN // (0xC0000409) is recovered by disabling GPU — NOT by dropping the sandbox // (that path stays owned by STATUS_BREAKPOINT / #38216). Must run before app // `ready`. Skip applying switches when the remote-display block above already // did; still honor a sticky per-version marker so Start Menu launches recover. let windowsGpuStackCookieFallbackActive = false let windowsGpuStackCookieFallbackSticky = false let windowsGpuStackCookieRelaunchAttempted = false if (IS_WINDOWS) { const windowsGpuUserData = app.getPath('userData') const gpuStackCookieDecision = decideWindowsGpuStackCookieLaunch({ argv: process.argv, marker: readGpuStackCookieMarker(windowsGpuUserData), env: process.env, appVersion: app.getVersion() }) windowsGpuStackCookieFallbackActive = gpuStackCookieDecision.enable windowsGpuStackCookieFallbackSticky = gpuStackCookieDecision.nextMarker.state === 'fallback' try { writeGpuStackCookieMarker(windowsGpuUserData, gpuStackCookieDecision.nextMarker) } catch { void 0 } if (gpuStackCookieDecision.enable && !REMOTE_DISPLAY_REASON) { app.disableHardwareAcceleration() app.commandLine.appendSwitch('disable-gpu-compositing') console.log( `[hermes] Windows GPU stack-cookie fallback enabled (${gpuStackCookieDecision.reason}); disabling GPU hardware acceleration (0xC0000409 / #108047)` ) } } // Renderer debugging port. On for dev-server runs (`hgui` / `npm run dev`) so // the CDP tooling in scripts/ can attach; never for a packaged build — see // electron/dev-cdp.ts. Must run before app `ready` like the switches above; // Chromium binds it at launch. const DEV_CDP = resolveDevCdpPort({ env: process.env, isPackaged: IS_PACKAGED, devServer: DEV_SERVER }) if (DEV_CDP.port) { app.commandLine.appendSwitch('remote-debugging-port', String(DEV_CDP.port)) // Loopback only. Chromium already defaults to 127.0.0.1, but say it out loud // so a future edit can't widen it by omission. app.commandLine.appendSwitch('remote-debugging-address', '127.0.0.1') console.log( `[hermes] renderer debugging on http://127.0.0.1:${DEV_CDP.port} — anything that can reach it ` + 'can run code in the renderer. HERMES_DESKTOP_CDP_PORT=off to disable.' ) } else { const why = describeDevCdpDecision(DEV_CDP) if (why) { console.warn(`[hermes] ${why}`) } } // WSLg: Chromium blocklists the Mesa vGPU → software compositing → typing lag. // /dev/dxg means a real GPU is available; un-blocklist it. Skipped when a remote // display already forced software (SSH'd-into-WSL), and on Wayland ozone: WSL has // no DRM render node, so forced GPU compositing segfaults the GPU process there. if ( IS_WSL && !REMOTE_DISPLAY_REASON && fs.existsSync('/dev/dxg') && linuxOzoneBackend(process.env, process.argv) !== 'wayland' ) { app.commandLine.appendSwitch('ignore-gpu-blocklist') app.commandLine.appendSwitch('enable-gpu-rasterization') app.commandLine.appendSwitch('enable-zero-copy') console.log('[hermes] WSL GPU passthrough (/dev/dxg) detected; enabling GPU acceleration') } // #40077 / #124255: NVIDIA driver 580.x breaks ANGLE's EGL probing (Invalid // visual ID), killing the GPU process at startup. Route ANGLE through its // SwiftShader backend when the breakage is WITNESSED, not assumed: the same // point release breaks hosts where NVIDIA drives the display and renders fine // on hybrid hosts whose session EGL lands on the iGPU, so a driver-series gate // burns 4-9 CPU cores on healthy hosts (#124255). The gate is now behavioral — // boot with hardware GL and a marker; a GPU-process death before the first // window flips the marker sticky (per app + full driver version) and relaunches // once with SwiftShader. Deliberately NOT disableHardwareAcceleration(): on // 580.173.02 + Electron 40 that SIGKILLs the renderer (see the closed #40119). // Must run before app `ready` — the switch only applies pre-launch. Override // with HERMES_DESKTOP_NVIDIA_SWIFTSHADER (1/true → force on, 0/false → never). const NVIDIA_PROC_VERSION = (() => { try { return fs.readFileSync('/proc/driver/nvidia/version', 'utf8') } catch { return '' } })() const NVIDIA_DRIVER_MAJOR = parseNvidiaDriverMajor(NVIDIA_PROC_VERSION) const NVIDIA_DRIVER_VERSION = parseNvidiaDriverVersion(NVIDIA_PROC_VERSION) let nvidiaEglFallbackActive = false let nvidiaEglRelaunchAttempted = false const NVIDIA_EGL_FALLBACK = decideNvidiaEglFallback({ driverMajor: NVIDIA_DRIVER_MAJOR, driverVersion: NVIDIA_DRIVER_VERSION, marker: readNvidiaEglMarker(app.getPath('userData')), appVersion: app.getVersion(), env: process.env, platform: process.platform, isWsl: IS_WSL, remoteDisplayReason: REMOTE_DISPLAY_REASON }) nvidiaEglFallbackActive = NVIDIA_EGL_FALLBACK.enable // Persist the launch decision before GPU children start: a `booting` marker // left behind by a launch that never reached first paint is itself evidence // of a GPU death (the "GPU process isn't usable" FATAL abort wins the race // against our relaunch handler), and the next launch engages from it. if (NVIDIA_DRIVER_MAJOR !== null) { try { writeNvidiaEglMarker(app.getPath('userData'), NVIDIA_EGL_FALLBACK.nextMarker) } catch { void 0 } } if (NVIDIA_EGL_FALLBACK.enable) { app.commandLine.appendSwitch('use-angle', 'swiftshader') console.log( `[hermes] NVIDIA EGL fallback enabled (${NVIDIA_EGL_FALLBACK.reason}); routing ANGLE ` + 'through SwiftShader. Witnessed GPU-process death probe (#40077, #124255); an app or ' + 'driver update re-probes hardware GL once. HERMES_DESKTOP_NVIDIA_SWIFTSHADER=0 to opt out.' ) } // The behavioral half of the gate: a GPU-process death on a Linux NVIDIA host // that booted with hardware GL is the #40077 signature. Catch it before // Chromium's "GPU process isn't usable" FATAL abort ends the process, flip the // marker sticky, and relaunch once with SwiftShader. `killed` counts (the // #40077 GPU process died to Chromium's health-check SIGTERM, exit_code=15). if (NVIDIA_DRIVER_MAJOR !== null && process.platform === 'linux') { app.on('child-process-gone', (_event, details) => { if ( !shouldRelaunchForNvidiaGpuDeath({ details, fallbackActive: nvidiaEglFallbackActive, relaunchAttempted: nvidiaEglRelaunchAttempted }) ) { return } nvidiaEglRelaunchAttempted = true try { writeNvidiaEglMarker( app.getPath('userData'), nvidiaEglFallbackMarker(app.getVersion(), NVIDIA_DRIVER_VERSION ?? String(NVIDIA_DRIVER_MAJOR)) ) } catch { void 0 } console.warn( `[hermes] NVIDIA GPU process died (reason=${details?.reason}, exit=${details?.exitCode}); ` + 'relaunching once with --use-angle=swiftshader (#40077, #124255)' ) try { app.relaunch({ args: [...process.argv.slice(1), '--use-angle=swiftshader'] }) void exitAfterBackendShutdown(0) } catch (error) { console.error(`[hermes] NVIDIA SwiftShader relaunch failed: ${error?.message || error}`) } }) } // #124843: on Mesa/Wayland the Chromium GPU child can fail init // (error_code=1002) and retry inside a sub-zygote forever — ~350% CPU, no // gpu-process, no crash. Bound it: one relaunch into software rendering, // then a sticky per-version marker so the next boot goes straight there. // Reactive only — healthy Mesa/Wayland stacks keep full acceleration. Must // run before app `ready`. Override with HERMES_DESKTOP_DISABLE_GPU // (1/true → always software, 0/false → keep GPU on). let linuxGpuFallbackActive = false let linuxGpuFallbackSticky = false let linuxGpuRelaunchAttempted = false const LINUX_GPU_SOFTWARE_ACTIVE = Boolean(REMOTE_DISPLAY_REASON) || NVIDIA_EGL_FALLBACK.enable || alreadyHasDisableGpu(process.argv, process.env) if (process.platform === 'linux') { const linuxGpuUserData = app.getPath('userData') const linuxGpuDecision = decideLinuxGpuLaunch({ argv: process.argv, env: process.env, marker: readLinuxGpuMarker(linuxGpuUserData), appVersion: app.getVersion(), remoteDisplayReason: REMOTE_DISPLAY_REASON, nvidiaFallbackActive: NVIDIA_EGL_FALLBACK.enable }) linuxGpuFallbackActive = linuxGpuDecision.enable linuxGpuFallbackSticky = linuxGpuDecision.nextMarker.state === 'fallback' try { writeLinuxGpuMarker(linuxGpuUserData, linuxGpuDecision.nextMarker) } catch { void 0 } if (linuxGpuDecision.enable && linuxGpuDecision.reason !== 'already-enabled' && !LINUX_GPU_SOFTWARE_ACTIVE) { app.disableHardwareAcceleration() app.commandLine.appendSwitch('disable-gpu-compositing') console.log( `[hermes] Linux GPU software fallback enabled (${linuxGpuDecision.reason}); disabling GPU ` + 'hardware acceleration after a GPU-child init failure (#124843). HERMES_DESKTOP_DISABLE_GPU=0 to opt out.' ) } } // Linux: point Chromium at the session's keychain backend so safeStorage can // encrypt remote gateway tokens (hardening.ts refuses to persist them without // it). The value arrives via HERMES_DESKTOP_PASSWORD_STORE, bridged by the // `hermes desktop` launcher from detection or `desktop.password_store` in // config.yaml. Must run before app `ready` — the switch only applies pre-launch. const PASSWORD_STORE = resolveLinuxPasswordStore() if (PASSWORD_STORE.warning) { console.warn(`[hermes] ${PASSWORD_STORE.warning}`) } if (PASSWORD_STORE.store) { app.commandLine.appendSwitch('password-store', PASSWORD_STORE.store) console.log(`[hermes] using password-store backend: ${PASSWORD_STORE.store}`) } // Windows sandbox / GPU breakpoint crash recovery (#38216). // // Some hosts (AMD RX 6000 drivers, orphan AppContainer SIDs under %LOCALAPPDATA%, // missing S-1-15-2-2 ACEs) kill Chromium's sandboxed GPU/renderer children with // 0x80000003. After enough GPU deaths the browser process FATAL-exits before the // UI is usable. Must run before app `ready` so `--no-sandbox` applies to child // processes. The sticky marker recovers Start Menu / shortcut launches that // never go through `hermes desktop`; it is version-scoped so an app update // re-probes the sandbox instead of degrading forever. // // `windowsSandboxFallbackActive` = this process runs without the Chromium // sandbox (any cause, including a manual --no-sandbox flag) — guards the // relaunch handlers. `windowsSandboxFallbackSticky` = the fallback machinery // engaged and the marker must stay `fallback` after a successful boot; a // manual flag alone is honored but never made sticky. let windowsSandboxFallbackActive = false let windowsSandboxFallbackSticky = false let windowsSandboxFallbackReason: SandboxFallbackReason = 'boot-loop' let windowsNoSandboxRelaunchAttempted = false // #121954: the two-strike boot-abort ladder now also covers Linux. On Linux // hosts where the sandboxed GPU child cannot start (dies pre-main on an // FD-ownership violation), Chromium prints "GPU process isn't usable. // Goodbye." and aborts — a 100% crash loop; the host isolation matrix in // #121954 shows only `--no-sandbox` reaches the UI. Same sticky per-version // recovery as #38216: two consecutive mid-boot aborts engage `--no-sandbox`, // an app update re-probes the sandbox once. Windows-only extras (ACL repair, // renderer crash-loop relaunch) stay inside the IS_WINDOWS branch. if (IS_WINDOWS || process.platform === 'linux') { const windowsUserData = app.getPath('userData') const priorMarker = readSandboxMarker(windowsUserData) // Best-effort ACL repair, only when the last boot aborted or the fallback is // engaged — icacls /T recurses the whole install tree, so healthy launches // skip it (the installer already granted the ACE at install time). Repair // targets the install dir only: granting AppContainer read on userData would // expose Hermes sessions/config to every packaged app on the machine. if (shouldAttemptAclRepair(priorMarker)) { const exeDir = path.dirname(process.execPath) const acl = grantAllApplicationPackagesAcl(exeDir, { execFileSync }) if (acl.ok) { console.log(`[hermes] granted ALL APPLICATION PACKAGES RX on ${exeDir} (#38216)`) } else if (acl.error && acl.error !== 'missing-target-or-exec') { console.warn(`[hermes] AppContainer ACL grant failed on ${exeDir}: ${acl.error}`) } } const sandboxDecision = decideWindowsSandboxLaunch({ argv: process.argv, env: process.env, marker: priorMarker, appVersion: app.getVersion() }) windowsSandboxFallbackActive = sandboxDecision.enable windowsSandboxFallbackSticky = sandboxDecision.nextMarker.state === 'fallback' if (sandboxDecision.nextMarker.state === 'fallback' && sandboxDecision.nextMarker.reason) { windowsSandboxFallbackReason = sandboxDecision.nextMarker.reason } if (sandboxDecision.enable && sandboxDecision.reason !== 'already-enabled') { app.commandLine.appendSwitch('no-sandbox') process.env.ELECTRON_DISABLE_SANDBOX = '1' console.log( `[hermes] sandbox fallback enabled (${sandboxDecision.reason}); launching with --no-sandbox (#38216, #121954)` ) } writeSandboxMarker(windowsUserData, sandboxDecision.nextMarker) // One coalesced Linux GPU-child recovery (#86073, #124843, #121954): the // sandbox signature is tried first (that host's matrix shows --disable-gpu // still crashes), then the software ladder — including the relapse after a // --no-sandbox boot died again. One death, one bounded relaunch; Windows // keeps its breakpoint-signature fast path unchanged. app.on('child-process-gone', (_event, details) => { if (IS_WINDOWS) { if ( !shouldRelaunchForGpuSandboxCrash({ details, alreadyNoSandbox: windowsSandboxFallbackActive || alreadyHasNoSandbox(process.argv, process.env), relaunchAttempted: windowsNoSandboxRelaunchAttempted }) ) { return } windowsNoSandboxRelaunchAttempted = true windowsSandboxFallbackActive = true windowsSandboxFallbackSticky = true windowsSandboxFallbackReason = 'gpu-breakpoint' try { writeSandboxMarker(app.getPath('userData'), fallbackMarker('gpu-breakpoint', app.getVersion())) } catch { void 0 } console.warn( `[hermes] GPU child died with the sandbox signature (exit=${details?.exitCode}); relaunching once with --no-sandbox (#38216)` ) try { app.relaunch({ args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) }) void exitAfterBackendShutdown(0) } catch (error) { console.error(`[hermes] --no-sandbox relaunch failed: ${error?.message || error}`) } return } const alreadySoftware = LINUX_GPU_SOFTWARE_ACTIVE || linuxGpuFallbackActive || alreadyHasDisableGpu(process.argv, process.env) const path = linuxGpuChildDeathPath({ details, alreadyNoSandbox: windowsSandboxFallbackActive || alreadyHasNoSandbox(process.argv, process.env), alreadySoftware, sandboxRelaunchAttempted: windowsNoSandboxRelaunchAttempted, softwareRelaunchAttempted: linuxGpuRelaunchAttempted }) if (path === 'no-sandbox') { windowsNoSandboxRelaunchAttempted = true windowsSandboxFallbackActive = true windowsSandboxFallbackSticky = true windowsSandboxFallbackReason = 'gpu-breakpoint' try { writeSandboxMarker(app.getPath('userData'), fallbackMarker('gpu-breakpoint', app.getVersion())) } catch { void 0 } console.warn( `[hermes] Linux GPU child died with the sandbox signature (exit=${details?.exitCode}); relaunching once with --no-sandbox (#121954)` ) try { app.relaunch({ args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) }) void exitAfterBackendShutdown(0) } catch (error) { console.error(`[hermes] --no-sandbox relaunch failed: ${error?.message || error}`) } return } if (path === 'disable-gpu') { linuxGpuRelaunchAttempted = true linuxGpuFallbackActive = true linuxGpuFallbackSticky = true const reason = String(details?.reason || '').toLowerCase() === 'launch-failure' ? 'gpu-launch-failure' : 'gpu-crash' try { writeLinuxGpuMarker(app.getPath('userData'), linuxGpuFallbackMarker(reason, app.getVersion())) } catch { void 0 } console.warn( `[hermes] Linux GPU child gone (reason=${details?.reason}); relaunching once with --disable-gpu (#124843)` ) try { app.relaunch({ args: buildDisableGpuRelaunchArgs(process.argv.slice(1)) }) void exitAfterBackendShutdown(0) } catch (error) { console.error(`[hermes] --disable-gpu relaunch failed: ${error?.message || error}`) } } }) } ipcMain.handle('hermes:get-remote-display-reason', () => REMOTE_DISPLAY_REASON) ipcMain.handle('hermes:embed-host:origin', () => embedHostOrigin()) // Keep the renderer's PROCESS priority normal while its windows are hidden — // a deprioritized renderer streams a live answer visibly slower once the // window is minimized. This switch only affects scheduling priority; it does // not exempt timers from throttling and costs nothing at idle. // // The timer/rAF throttling story is deliberately NOT handled here anymore. // The old process-wide `disable-background-timer-throttling` / // `disable-backgrounding-occluded-windows` switches (plus a static // `backgroundThrottling: false` on every chat window) pinned every renderer's // `document.visibilityState` to 'visible' forever — which silently turned all // the renderer's visibility-gated backstop polls and clock ticks into // always-on timers. A completely idle, minimized Hermes burned ~20% CPU // around the clock. Throttling is now a runtime dial scoped to streaming: // see createStreamThrottle() — chat windows are unthrottled while any turn is // in flight (so a live answer keeps painting while blurred, occluded, or // minimized, exactly as before) and return to Chromium's default throttling // once the work settles. app.commandLine.appendSwitch('disable-renderer-backgrounding') const SOURCE_REPO_ROOT = path.resolve(APP_ROOT, '../..') // Runtime identity comes only from the baked artifact stamp. Dev runs have none. if (INSTALL_STAMP) { console.log( `[hermes] install stamp: ${INSTALL_STAMP.commit ? INSTALL_STAMP.commit.slice(0, 12) : 'no-commit'}${INSTALL_STAMP.branch ? ` (${INSTALL_STAMP.branch})` : ''}${INSTALL_STAMP.dirty ? ' [DIRTY]' : ''} from ${INSTALL_STAMP.source || 'unknown'}` ) } else if (IS_PACKAGED) { // Dev builds without a stamp are normal; packaged builds without one // mean the bootstrap won't know what to clone. Surface clearly. console.error( '[hermes] WARNING: no install-stamp.json found in packaged build. First-launch bootstrap will not have a pinned ref to install.' ) } const DESKTOP_PROFILE_CONFIG_PATH: string = path.join(app.getPath('userData'), 'active-profile.json') // Only the lock-owning destination may adopt a workspace or start a backend. // #78101: on Linux/X11 a zombie/defunct Electron process leaves the // SingletonLock symlink behind with a PID that still answers kill(pid, 0), // so Chromium's own liveness probe keeps refusing every later launch and the // app silently exits. Clear a provably-dead owner and retry once; always log // when the lock is legitimately lost so the exit is diagnosable. function acquireSingleInstanceLock(): boolean { if (app.requestSingleInstanceLock()) { return true } const stalePid = removeStaleSingletonLock(app.getPath('userData')) if (stalePid !== null) { console.error(`[hermes] removed stale SingletonLock (owner ${stalePid} dead); retrying launch`) return app.requestSingleInstanceLock() } return false } const isPrimaryInstance: boolean = acquireSingleInstanceLock() if (!isPrimaryInstance) { console.error('[hermes] another Hermes Desktop instance holds the single-instance lock; exiting') app.exit(0) } // `hermes desktop` shortens TMPDIR only so the lock above can bind its socket (#124688). The // backend and every other child get the real one (the profile scratch dir) back. if (process.env.HERMES_DESKTOP_TMPDIR) { process.env.TMPDIR = process.env.HERMES_DESKTOP_TMPDIR delete process.env.HERMES_DESKTOP_TMPDIR } const HERMES_HOME: string = resolveDesktopHermesHome({ home: app.getPath('home'), directoryExists, readWindowsHome: (): string | null => readWindowsUserEnvVar('HERMES_HOME') }) // #77311: `desktop.electron_flags` and the renderer heap ceiling // (`desktop.renderer_max_old_space_mb`) used to reach Chromium only through // the `hermes desktop` launcher's argv, so a packaged app opened from its // Start-menu / .desktop entry ran with no `--js-flags` at all. Apply them here // from config.yaml, before `ready` — Chromium copies `js-flags` to renderer // processes only from the browser's pre-launch command line. // `desktop.ssh_path` (#103288) rides the same pre-window read: an explicit // Windows ssh client for when the in-box OpenSSH is missing or broken. let desktopSshPathOverride = '' { let desktopLaunchYaml: string = '' try { desktopLaunchYaml = fs.readFileSync(path.join(HERMES_HOME, 'config.yaml'), 'utf8') } catch { void 0 // first run: no config yet → Chromium defaults } const desktopLaunchConfig = readDesktopLaunchConfig(desktopLaunchYaml) desktopSshPathOverride = desktopLaunchConfig.sshPath || '' // `desktop.renderer_accessibility: false` must reach packaged launches too, // not only the `hermes desktop` launcher's env bridge (#118271). if ( desktopLaunchConfig.rendererAccessibility === false && process.env.HERMES_DESKTOP_RENDERER_ACCESSIBILITY === undefined ) { process.env.HERMES_DESKTOP_RENDERER_ACCESSIBILITY = '0' } for (const planned of planLaunchSwitches(desktopLaunchConfig, process.argv.slice(1))) { if (planned.value === undefined) { app.commandLine.appendSwitch(planned.name) } else { app.commandLine.appendSwitch(planned.name, planned.value) } console.log( `[hermes] desktop launch switch from config.yaml: --${planned.name}${planned.value === undefined ? '' : `=${planned.value}`}` ) } } // ACTIVE_HERMES_ROOT — the canonical mutable Hermes install. Same path // install.ps1 / install.sh use, so a desktop-only user and a CLI-only user end // up with identical layouts and can share one install. const ACTIVE_HERMES_ROOT = path.join(HERMES_HOME, 'hermes-agent') setNoConsoleGitRoots([!IS_PACKAGED ? SOURCE_REPO_ROOT : null, ACTIVE_HERMES_ROOT]) // VENV_ROOT — venv lives inside the repo, exactly like install.ps1 does it. const VENV_ROOT = path.join(ACTIVE_HERMES_ROOT, 'venv') // BOOTSTRAP_COMPLETE_MARKER — written by the first-launch bootstrap runner // (Phase 1D) after install.ps1 has completed all stages and the user has // finished initial configuration. Presence of this marker means the install // is in a known-good state and we can skip the bootstrap flow on subsequent // boots, going straight to `resolveHermesBackend()`. Missing or stale marker // means we re-run the bootstrap; install.ps1's stages are idempotent so a // re-run on an already-good install just discovers everything in place. // // We deliberately put the marker INSIDE ACTIVE_HERMES_ROOT (not alongside) // so that deleting the checkout to start fresh also deletes the marker -- // avoids the confusing "marker exists but checkout is gone" state. const BOOTSTRAP_COMPLETE_MARKER = path.join(ACTIVE_HERMES_ROOT, '.hermes-bootstrap-complete') const BOOTSTRAP_MARKER_SCHEMA_VERSION = 1 const DESKTOP_CONNECTION_CONFIG_PATH = path.join(app.getPath('userData'), 'connection.json') // v2 multi-connection registry (named agent sources). Lives BESIDE // connection.json — v1 stays on disk untouched so older builds sharing the // profile keep working; the registry imports from it once and then owns its // own file. Same secret posture as connection.json (encrypted tokens, 0600). const DESKTOP_CONNECTIONS_REGISTRY_PATH = path.join(app.getPath('userData'), 'connections.json') const DESKTOP_INSTALLATION_PATH = path.join(app.getPath('userData'), 'desktop-installation.json') const DESKTOP_UPDATE_CONFIG_PATH = path.join(app.getPath('userData'), 'updates.json') const DESKTOP_WINDOW_STATE_PATH = path.join(app.getPath('userData'), 'window-state.json') const DESKTOP_BACKEND_OWNERSHIP_PATH = path.join(app.getPath('userData'), 'backend-ownership.json') const DESKTOP_MANAGED_SSH_RECOVERY_PATH = path.join(app.getPath('userData'), 'managed-ssh-update-recovery.json') // active-profile.json records which Hermes profile the desktop launches its // local backend as. When set, startHermes() passes `hermes --profile // dashboard …`, which deterministically pins HERMES_HOME (see // _apply_profile_override in hermes_cli/main.py) and bypasses the sticky // ~/.hermes/active_profile file. Unset (null) preserves the legacy behavior: // no --profile flag, so the backend honors active_profile / default. // Mirrors hermes_cli.profiles._PROFILE_ID_RE so we never hand the backend a // value its profile resolver would reject and exit on. const PROFILE_NAME_RE = DESKTOP_PROFILE_NAME_RE // Branch we track for self-update. The GUI work has merged to main, so this // tracks main. User can also override at runtime via // hermesDesktop.updates.setBranch(). const DEFAULT_UPDATE_BRANCH = 'main' // desktop.log lives under HERMES_HOME/logs/ so it sits next to agent.log, // errors.log, gateway.log produced by hermes_logging.setup_logging — one log // directory per user, regardless of which UI surface produced the line. const DESKTOP_LOG_PATH = path.join(HERMES_HOME, 'logs', 'desktop.log') const DESKTOP_LOG_FLUSH_MS = 120 const DESKTOP_LOG_BUFFER_MAX_CHARS = 64 * 1024 // Bound desktop.log on disk. It is an append-only forensic log, so a boot loop // (version-skew crash -> backend exits instantly -> renderer keeps hitting // Retry) appends the full bootstrap transcript every attempt and grows without // bound — we have seen it reach ~326 GB and exhaust the disk, which then breaks // update/install (no room for git/venv/npm temp files). The cap, the cascade // and the discard ceiling live in log-rotation.ts, shared with the Chromium // log below. // #100573: keep the FATAL line and a local minidump for the next Linux SIGTRAP. // Both must be wired before `app` is ready; the log-file switch is inherited by // every child process, so a zygote or GPU CHECK lands in the same file. // Chromium opens an explicit --log-file with APPEND_TO_OLD_LOG_FILE, so this // one accumulates across launches exactly like desktop.log: bound it the same // way, and never let optional diagnostics fail the shell's startup. const CRASH_DIAGNOSTICS_LOGS_DIR = path.dirname(DESKTOP_LOG_PATH) const CRASH_DIAGNOSTICS = linuxCrashDiagnostics(CRASH_DIAGNOSTICS_LOGS_DIR) const CHROMIUM_LOG_PATH = path.join(CRASH_DIAGNOSTICS_LOGS_DIR, CHROMIUM_LOG_FILENAME) enableLinuxCrashDiagnostics(CRASH_DIAGNOSTICS, CRASH_DIAGNOSTICS_LOGS_DIR, { ensureLogsDir: dir => fs.mkdirSync(dir, { recursive: true }), reclaimChromiumLog: file => rotateLogIfNeededSync(file), appendSwitch: (name, value) => app.commandLine.appendSwitch(name, value), startCrashReporter: options => crashReporter.start(options) }) const BOOT_FAKE_MODE = process.env.HERMES_DESKTOP_BOOT_FAKE === '1' const BOOT_FAKE_ERROR = process.env.HERMES_DESKTOP_BOOT_FAKE_ERROR || '' // Automated teardown (Playwright's app.close(), harness scripts) quits with // nobody to answer a modal, so the active-work confirmation would hang the // caller instead of letting the process exit. Force quits set this. const SKIP_QUIT_CONFIRM = process.env.HERMES_DESKTOP_SKIP_QUIT_CONFIRM === '1' const BOOT_FAKE_STEP_MS = (() => { const raw = Number.parseInt(String(process.env.HERMES_DESKTOP_BOOT_FAKE_STEP_MS || ''), 10) if (!Number.isFinite(raw) || raw <= 0) { return 650 } return Math.max(120, raw) })() const APP_NAME: string = IDENTITY_APP_NAME || process.env.HERMES_DESKTOP_APP_NAME || 'Hermes' const HUD_WINDOW_TITLE = `${APP_NAME} HUD` const TITLEBAR_HEIGHT = 34 const MACOS_TRAFFIC_LIGHTS_HEIGHT = 14 const WINDOW_BUTTON_POSITION = { x: 24, y: TITLEBAR_HEIGHT / 2 - MACOS_TRAFFIC_LIGHTS_HEIGHT / 2 } // Right-edge window-control reservation lives in titlebar-overlay-width.ts // (pure + unit-testable); computeNativeOverlayWidth() applies it per platform. // It's only the pre-layout fallback — the renderer measures the exact overlay // width live via the Window Controls Overlay API. // The apple-touch PNG bakes in the macOS-style ~10% margin, which is correct // for the dock but renders visibly smaller than neighboring taskbar icons on // Windows, where icons are full-bleed. Windows prefers the full-bleed // assets/icon.ico (shipped to resources/ via extraResources) and only falls // back to the padded PNG if the ico is missing. // The ladder is BUILT once here but each window factory RE-RESOLVES through // resolveAppIcon (decoding probe): existence alone is not proof the bytes // decode, and an undecodable icon must never take the main process down. const APP_ICON_PATHS = appIconCandidates({ isWindows: IS_WINDOWS, appRoot: APP_ROOT, resourcesPath: process.resourcesPath, unpackedPathFor }) let rendererTitleBarTheme = null // Force the NATIVE window appearance (vibrancy material, titlebar, the // pre-first-paint window background) to follow the APP theme instead of the // OS appearance. With `vibrancy` set, macOS paints an NSVisualEffectView that // tracks the window's effective appearance and ignores `backgroundColor` — // so a dark-themed app on a light-mode Mac flashes a white material on every // new window until the renderer covers it. The renderer reports its mode via // 'hermes:native-theme' ('dark' | 'light' | 'system'); we pin // nativeTheme.themeSource to it and persist the value so cold launches paint // correctly before the renderer has even loaded. const NATIVE_THEME_CONFIG_PATH = path.join(app.getPath('userData'), 'native-theme.json') const THEME_SOURCES = new Set(['dark', 'light', 'system']) function readPersistedThemeSource() { try { const parsed = JSON.parse(fs.readFileSync(NATIVE_THEME_CONFIG_PATH, 'utf8')) if (parsed && THEME_SOURCES.has(parsed.themeSource)) { return parsed.themeSource } } catch { // Missing / malformed → follow the OS like a fresh install. } return 'system' } function writePersistedThemeSource(mode) { try { fs.mkdirSync(path.dirname(NATIVE_THEME_CONFIG_PATH), { recursive: true }) fs.writeFileSync(NATIVE_THEME_CONFIG_PATH, JSON.stringify({ themeSource: mode }, null, 2), 'utf8') } catch (error) { rememberLog(`[theme] write native theme failed: ${error.message}`) } } nativeTheme.themeSource = readPersistedThemeSource() // Window translucency (see-through window). One lever, 0–100; 0 = off (the // default). Two modes share the lever (see electron/translucency.ts and // store/translucency): 'clear' maps it to the native window opacity so the // desktop shows through the whole window; 'glass' keeps the window opaque // and lets the renderer thin its surfaces over a platform material instead // — a matte blur with full-contrast text. macOS uses vibrancy; Windows 11 // uses DWM acrylic/mica/tabbed. Persisted so a cold launch applies it at // window creation, before the renderer reports its value. // macOS + Windows only; `setOpacity` is a no-op on Linux. const TRANSLUCENCY_CONFIG_PATH = path.join(app.getPath('userData'), 'translucency.json') function readPersistedTranslucency() { try { return normalizeTranslucency(JSON.parse(fs.readFileSync(TRANSLUCENCY_CONFIG_PATH, 'utf8')), GLASS_SUPPORTED) } catch { // Nothing persisted yet — a first launch. Glass ships on, so the FIRST // window has to be created with the glass backing already: a window born // opaque cannot reliably be swapped to glass afterwards (see // windowBackingOptions). nativeTheme is the only appearance signal main // has this early; the renderer's first resolved send corrects it. return defaultTranslucencyState(nativeTheme.shouldUseDarkColors ? 'dark' : 'light', GLASS_SUPPORTED, IS_WINDOWS) } } function writePersistedTranslucency(state) { try { fs.mkdirSync(path.dirname(TRANSLUCENCY_CONFIG_PATH), { recursive: true }) fs.writeFileSync(TRANSLUCENCY_CONFIG_PATH, JSON.stringify(state, null, 2), 'utf8') } catch (error) { rememberLog(`[translucency] write failed: ${error.message}`) } } let translucencyState = readPersistedTranslucency() // Chat windows whose webContents backing follows translucency (primary, // instance peers, session windows). The HUD / pet overlay / quick entry / // wake indicator are `transparent: true` windows that own their backgrounds — // painting a themed backing onto them would turn them into opaque rectangles. const translucencyBackedWindows = new WeakSet() // Set a live window's native opacity, but only when the state asks it to fade // — or when the window is already faded and is on its way back to opaque. The // window's own opacity is the record of whether that door was ever opened; see // opacityNeedsSetting for why it matters that it stays shut. function applyWindowOpacity(win) { const opacity = windowOpacityFor(translucencyState) if (typeof win.setOpacity === 'function' && opacityNeedsSetting(opacity, win.getOpacity?.() ?? 1)) { win.setOpacity(opacity) } } // Re-apply translucency to a live window (runtime toggle, no recreation). // Opacity goes through applyWindowOpacity, which knows when the call is worth // making at all. The backing swap is the glass half: Chromium composites the // page against the window backing BEFORE the OS composites the window, so // glass needs the backing dropped for the platform material to reach it, and // every other state needs the opaque themed backing (anti-flash, and it is // what makes clear mode fade to the desktop instead of to black). // // `changed` says which native properties actually need touching. Dragging the // intensity slider emits ~100 updates, and in glass mode NONE of them change // anything native — the tint is painted by the renderer and windowOpacityFor // answers off `fade`, not `intensity`, there. Re-issuing setVibrancy on every // tick restarts its 150ms animation before macOS can settle the material, // which reads as jank and flattens the frost levels into each other. Windows // setBackgroundMaterial is instantaneous but still skipped on tint-only ticks. // The glass Fade lever is the one glass drag that does reach main, and it // costs exactly what a Clear drag costs: one setOpacity. // // CAUTION (measured, macOS 26 / Electron 40): a runtime // setBackgroundColor('#00000000') is silently LOST on a window whose // compositor hasn't been up for a few seconds — including calls from // 'ready-to-show' and 'did-finish-load'. Cold launches therefore must not // rely on this path: windows are BORN with the right backing // (windowBackingOptions at each creation site). This path only has to cover // live toggles from Settings, where the window is long settled. function applyWindowTranslucency(win, changed = { backing: true, material: true, opacity: true }) { if (!win || win.isDestroyed()) { return } try { // Backing swap + material are scoped to registered chat windows (see // translucencyBackedWindows above). if (translucencyBackedWindows.has(win)) { if (changed.backing && typeof win.setBackgroundColor === 'function') { win.setBackgroundColor(glassActive(translucencyState) ? '#00000000' : getWindowBackgroundColor()) } if (changed.material) { // Glass frost level = the platform material. Animate the macOS hop so // a deliberate frost switch feels continuous — which only works if we // don't re-issue it on unrelated updates. Windows has no equivalent // animation option; setBackgroundMaterial is instantaneous. if (IS_MAC && typeof win.setVibrancy === 'function') { win.setVibrancy(vibrancyForTranslucency(translucencyState), { animationDuration: 150 }) } if (IS_WINDOWS && GLASS_SUPPORTED && typeof win.setBackgroundMaterial === 'function') { win.setBackgroundMaterial(backgroundMaterialFor(translucencyState)) } } } if (changed.opacity) { applyWindowOpacity(win) } } catch (error) { rememberLog(`[translucency] apply failed: ${error.message}`) } } // Constructor options every chat window shares for its translucency surface: // the platform material, the webContents backing, and a native opacity only if // the state actually fades — all under the CURRENT state. Glass omits // backgroundColor so the material shows from the first frame (Electron hands a // translucent window a transparent default backing, and runtime swaps are lost // early in a window's life — see applyWindowTranslucency); otherwise the opaque // themed anti-flash backing. // // Call sites also register the window in translucencyBackedWindows so a live // toggle can re-apply. The HUD, pet overlay, quick entry and wake indicator // are `transparent: true` windows that own their backgrounds and are // deliberately not chat windows. function chatWindowSurfaceOptions() { return { vibrancy: IS_MAC ? vibrancyForTranslucency(translucencyState) : undefined, // Pin the material to its ACTIVE appearance: several NSVisualEffectView // materials collapse to a shared inactive look when the window blurs // (measured on macOS 26: sidebar, popover and under-window composited // pixel-identically once unfocused), which would quietly erase the // user's frost choice whenever they click elsewhere. Only observable // under glass — everywhere else the page buries the material. visualEffectState: IS_MAC ? ('active' as const) : undefined, // NOT `transparent: true` on Windows. The backdrop material already makes // the window translucent on its own: `IsTranslucent` answers yes off // `background_material_` alone, which is what gives the page its transparent // default backing, and `SetBackgroundMaterial` flips widget translucency // live, so a Clear→Glass toggle needs no recreate either way. Its one gate // is a frameless window, and `titleBarStyle: 'hidden'` already makes // `has_frame()` false here. // // What `transparent` adds on top is permanent and unwanted: it pins the // widget to kTranslucent for the window's whole life, so even glass-OFF // windows pay a DirectComposition redraw per frame (electron#39895), and it // opts into the documented transparent-window limits — including that a // RESIZABLE transparent window is unsupported and breaks (electron#48421). // Every chat window is resizable. ...windowBackgroundMaterialOptions(translucencyState, IS_WINDOWS, GLASS_SUPPORTED), ...windowOpacityOptions(translucencyState), ...windowBackingOptions(translucencyState, getWindowBackgroundColor()) } } function isHexColor(value) { return typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value) } // Background color to paint a window with BEFORE its renderer loads, so a new // (or reopened) window doesn't flash white/light in dark mode. Prefer the theme // the renderer last reported; fall back to the OS preference on first launch. function getWindowBackgroundColor() { if (rendererTitleBarTheme && isHexColor(rendererTitleBarTheme.background)) { return rendererTitleBarTheme.background } return nativeTheme.shouldUseDarkColors ? '#111111' : '#f7f7f7' } // Transparent WCO — renderer chrome shows through. rgba(0,0,0,0) can fall back // to GetFrameColor() on some Electron builds; rgba(1,0,0,0) is the escape hatch. const TITLEBAR_OVERLAY_COLOR = 'rgba(1, 0, 0, 0)' // WSLg returns false: the RDP host paints nothing for a frameless window and // Electron's own overlay drifts its hit-region under RAIL, so the renderer // paints its own min/max/close (wslg-window-controls.tsx) over the // hermes:window-control IPC channel. See titleBarOverlayOptions. function getTitleBarOverlayOptions(win?) { return titleBarOverlayOptions({ platform: IS_MAC ? 'mac' : IS_WINDOWS ? 'windows' : IS_WSL ? 'wslg' : 'linux', darwinMajor: DARWIN_MAJOR, titlebarHeight: TITLEBAR_HEIGHT, color: TITLEBAR_OVERLAY_COLOR, foreground: rendererTitleBarTheme && isHexColor(rendererTitleBarTheme.foreground) ? rendererTitleBarTheme.foreground : null, dark: nativeTheme.shouldUseDarkColors, // The native WCO buttons don't scale with the page; scale the overlay so // its height tracks the zoomed renderer titlebar (#81086). zoomFactor: win?.webContents?.getZoomFactor?.() }) } // Push refreshed overlay options to a live window after a theme/appearance // change. No-op only on plain (non-WSL) Linux, where getTitleBarOverlayOptions() // returns false; the try/catch additionally guards builds where // setTitleBarOverlay isn't supported. function applyTitleBarOverlay(win) { const options = getTitleBarOverlayOptions(win) if (!options || typeof options !== 'object') { return } try { win?.setTitleBarOverlay?.(options) } catch { // Overlay not supported on this platform/build — leave the frameless // titlebar as-is. } } const MEDIA_MIME_TYPES = { '.avi': 'video/x-msvideo', '.bmp': 'image/bmp', '.flac': 'audio/flac', '.gif': 'image/gif', '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.m4a': 'audio/mp4', '.mkv': 'video/x-matroska', '.mov': 'video/quicktime', '.mp3': 'audio/mpeg', '.mp4': 'video/mp4', '.ogg': 'audio/ogg', '.opus': 'audio/ogg; codecs=opus', '.pdf': 'application/pdf', '.png': 'image/png', '.svg': 'image/svg+xml', '.wav': 'audio/wav', '.webm': 'video/webm', '.webp': 'image/webp' } const PREVIEW_HTML_EXTENSIONS = new Set(['.html', '.htm']) const PREVIEW_PDF_EXTENSIONS = new Set(['.pdf']) const PREVIEW_WATCH_DEBOUNCE_MS = 120 const TEXT_PREVIEW_MAX_BYTES = 512 * 1024 const PREVIEW_LANGUAGE_BY_EXT = { '.c': 'c', '.conf': 'ini', '.cpp': 'cpp', '.css': 'css', '.csv': 'csv', '.go': 'go', '.graphql': 'graphql', '.h': 'c', '.hpp': 'cpp', '.html': 'html', '.java': 'java', '.js': 'javascript', '.json': 'json', '.jsx': 'jsx', '.kt': 'kotlin', '.lua': 'lua', '.md': 'markdown', '.mjs': 'javascript', '.py': 'python', '.rb': 'ruby', '.rs': 'rust', '.sh': 'shell', '.sql': 'sql', '.svg': 'xml', '.toml': 'toml', '.ts': 'typescript', '.tsx': 'tsx', '.txt': 'text', '.xml': 'xml', '.yaml': 'yaml', '.yml': 'yaml', '.zsh': 'shell' } function looksBinary(buffer) { if (!buffer.length) { return false } let suspicious = 0 for (const byte of buffer) { if (byte === 0) { return true } // Allow common whitespace controls: tab, LF, CR. if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) { suspicious += 1 } } return suspicious / buffer.length > 0.12 } function previewFileMetadata(filePath, mimeType) { let byteSize = 0 let binary = false try { const stat = fs.statSync(filePath) byteSize = stat.size if (!mimeType.startsWith('image/')) { const fd = fs.openSync(filePath, 'r') try { const sample = Buffer.alloc(Math.min(byteSize, 4096)) const bytesRead = fs.readSync(fd, sample, 0, sample.length, 0) binary = looksBinary(sample.subarray(0, bytesRead)) } finally { fs.closeSync(fd) } } } catch { // Metadata is best-effort; the read handlers surface hard errors later. } return { binary, byteSize, large: byteSize > TEXT_PREVIEW_MAX_BYTES } } app.setName(APP_NAME) // No application menu until the first window exists. Electron would otherwise // install its default menu at `will-finish-launching` (before `ready`), and a // key equivalent routed through that menu's delegate with no window open // segfaults the macOS shell — the updater relaunch races the user's keystroke // (#115332). Must run at module scope: on macOS a later `null` never removes // an installed menu. The real menu lands in installApplicationMenuAfterFirstWindow. Menu.setApplicationMenu(null) // Windows toast notifications silently no-op unless an AppUserModelID is set: // `new Notification().show()` returns without error and nothing appears. The // AUMID must match the installed Start Menu shortcut's AUMID, which // electron-builder derives from the build `appId` (com.nousresearch.hermes) — // keep this string in sync with package.json `build.appId`. macOS/Linux don't // need this, so gate it on Windows. (Fixes: desktop approval/turn notifications // never firing on Windows.) if (IS_WINDOWS) { app.setAppUserModelId(IDENTITY_APP_NAME ? PRODUCT_IDENTITY.appId : 'com.nousresearch.hermes') } // Seed the native About panel with the best-known Hermes version. This is // refreshed on every open via showAboutPanelFresh, so an in-place // `hermes update` mid-session is reflected without an app restart; the seed // covers the first open and any non-menu invocation path. Never seed empty: // an empty applicationVersion falls back to the bundle version, which is the // 0.0.0 placeholder on local builds (#124581). app.setAboutPanelOptions({ applicationName: APP_NAME, applicationVersion: nativeAboutVersion(appVersionInfo(INSTALL_STAMP, '', app.getVersion())), copyright: 'Copyright © 2026 Nous Research' }) // Custom scheme for streaming audio/video into the renderer. Local paths read // from this machine; remote paths are proxied through the configured gateway // with main-process authentication. This avoids whole-file data URLs and keeps // playback seekable and Range-aware. Must be registered before app readiness. protocol.registerSchemesAsPrivileged([ { scheme: MEDIA_PROTOCOL, privileges: { secure: true, standard: true, stream: true, supportFetchAPI: true } } ]) function registerMediaProtocol(): void { const handler: ReturnType = createMediaProtocolHandler({ ensureRemoteBearer: (baseUrl: string): Promise => ensureNativeAccessToken(baseUrl), // Electron's file:// loader ignores Range, which prevents video seeking. fetchLocal: fetchLocalMedia, fetchRemote: (url, headers, method) => electronNet.fetch(url, { bypassCustomProtocolHandlers: true, credentials: 'omit', headers, method }), fetchRemoteWithCookies: (url, headers, method) => { const oauthSession = getOauthSessionForUrl(url) if (!oauthSession) { throw new Error('OAuth session partition is unavailable.') } return oauthSession.fetch(url, { bypassCustomProtocolHandlers: true, credentials: 'include', headers, method }) }, resolveLocalFile: async filePath => { // On a Windows host with a WSL backend the media path arrives as a // WSL/POSIX path (`/home/...`, `/mnt/c/...`) the Windows fs can't open // as-is; bridge it to a UNC/drive form first, same as directory reads. // The protocol handler already percent-decoded the pathname, so this // boundary bridges only — re-decoding/stripping would corrupt the path. const { resolvedPath } = await resolveReadableFileForIpc(resolveMediaStreamFile(filePath), { purpose: 'Media stream' }) return resolvedPath }, // Claim-guarded (#90812): a media stream load can race a renderer's own // reconnect dial for the same (connectionId, profile) scope; coalescing // here avoids bootstrapping a second SSH tunnel / remote dashboard. resolveRemoteConnection: ({ connectionId, profile }) => backendDialClaims.run(backendScopeKey(connectionId, profile), () => connectionId ? ensureRegistryBackend(connectionId, profile) : ensureBackend(profile) ) }) protocol.handle(MEDIA_PROTOCOL, handler) } let mainWindow = null const backendConnectionState = createBackendConnectionState, any>() const localBackendLifecycle = createLocalBackendLifecycle({ stopChild: (child: ChildProcess): void => { if (child.exitCode === null && child.signalCode === null) { stopBackendChildImpl(child, { forceKillProcessTree, isWindows: IS_WINDOWS }) } }, waitForExit: (child: ChildProcess): Promise => waitForBackendExit(child, { forceKillProcessTree, isWindows: IS_WINDOWS }), cancelSetup: (): void => { firstRunSetupGate?.resetForRetry() bootstrapAbortController?.abort() } }) function spawnOwnedBackend(...args: Parameters): ChildProcess { const child = localBackendLifecycle.spawn((): ChildProcess => spawn(...args)) child.once('exit', (): boolean => localBackendLifecycle.release(child)) child.once('error', (): void => { if (!child.pid) { localBackendLifecycle.release(child) } }) return child } const remoteLiveness = new RemoteLivenessTracker() // Pooled remotes are probed on the renderer reconnect cadence (minutes apart), // not the primary's sub-minute retry loop, so they need a failure window wider // than that cadence or a dead pooled descriptor's streak resets on every tick // and it is never dropped (#94381). const pooledRemoteLiveness = new RemoteLivenessTracker(undefined, REMOTE_POOLED_LIVENESS_FAILURE_WINDOW_MS) const remoteRevalidation = new RemoteRevalidationCoordinator() const registryDispatchRevalidation = new RemoteRevalidationCoordinator() // Single-owner reconnect/dial claim (#90812): reconnectGateway()'s in-flight // lock is per-renderer, so two windows racing one wake can both invoke the // backend ensure IPC and double-dial a pooled SSH backend. Main owns backend // lifecycles, so concurrent dials for one (connectionId, profile) scope // coalesce here — the second caller awaits the first spawn's result. const backendDialClaims = new BackendDialClaims() // True while connection-config:apply soft-rehomes the primary — suppresses the // backend-exit toast so an intentional kill doesn't look like a crash. let softRehomeInProgress = false // Primary-slot bookkeeping for the exit supervisor (#112344). `primaryStartsInFlight` // counts startHermes() calls that have not settled; `primaryRecoverySuppressed` // is set by every intentional invalidate of the slot and cleared by the next // startHermes(), so the dying child's stale exit never respawns behind a // re-home, a quit, or a latched boot failure. let primaryStartsInFlight = 0 let primaryRecoverySuppressed = false const primaryExitRecovery = createBackendExitRecoveryLatch() // Additional per-profile backends, keyed by profile name. The PRIMARY backend // (the desktop's launch profile) stays managed by backendConnectionState + // startHermes(); this pool only holds EXTRA profile // backends spawned lazily when a session belongs to a different profile. A user // with no named profiles never populates this map, so their experience is // byte-for-byte the single-backend behavior. const backendPool = new Map() // profile -> { process, port, token, connectionPromise, lastActiveAt } const profileDeletionGate = new ProfileDeletionGate() // Keep the pool light: cap concurrent profile backends (LRU eviction) and reap // idle ones. A user idles at exactly the primary backend; pool backends only // exist while a non-primary profile is actively being chatted through. // Pool sizing is a device preference (Settings → Advanced → pool rows), not a // launch constant: mutable at runtime, persisted in userData, applied live. // The legacy HERMES_DESKTOP_POOL_* env vars remain the initial-value fallback // for scripted/headless setups; after launch the stored preference wins. const POOL_LIMITS_PATH = path.join(app.getPath('userData'), 'pool-limits.json') function readPersistedPoolLimits() { try { const limits = parsePoolLimits(fs.readFileSync(POOL_LIMITS_PATH, 'utf8')) rememberLog( `[pool-limits] loaded from ${POOL_LIMITS_PATH}: maxBackends=${limits.maxBackends}, idleMs=${limits.idleMs}` ) return limits } catch { // No persisted file yet — fall back to the legacy env vars so scripted // setups keep working. Log which source won: a silently-ignored env var // here costs a scripted-setup user a debugging session. const fromEnv = clampPoolLimits({ maxBackends: Number(process.env.HERMES_DESKTOP_POOL_MAX) || undefined, idleMs: Number(process.env.HERMES_DESKTOP_POOL_IDLE_MS) || undefined }) if (fromEnv.maxBackends !== POOL_LIMITS_DEFAULTS.maxBackends || fromEnv.idleMs !== POOL_LIMITS_DEFAULTS.idleMs) { rememberLog( `[pool-limits] no saved file; using env-var overrides: maxBackends=${fromEnv.maxBackends}, idleMs=${fromEnv.idleMs}` ) } else { rememberLog('[pool-limits] no saved file and no env overrides; using defaults') } return fromEnv } } function persistPoolLimits(limits) { try { fs.mkdirSync(path.dirname(POOL_LIMITS_PATH), { recursive: true }) // Atomic write: write to a temp file in the same directory, then rename. // A crash mid-write would otherwise leave truncated JSON and silently // lose the user's saved sizing. const tmpPath = `${POOL_LIMITS_PATH}.tmp` fs.writeFileSync(tmpPath, JSON.stringify(limits, null, 2), 'utf8') fs.renameSync(tmpPath, POOL_LIMITS_PATH) } catch (error) { rememberLog(`[pool-limits] write failed: ${error.message}`) } } // rememberLog() state. Declared here, before the top-level // readPersistedPoolLimits() call below, because that call logs during module // evaluation; declaring these later crashed launch with `undefined.push` in // the packaged build (esbuild lowers the TDZ to undefined instead of throwing). const hermesLog: string[] = [] let desktopLogBuffer = '' let desktopLogFlushTimer = null let desktopLogFlushPromise = Promise.resolve() let poolLimits = readPersistedPoolLimits() // Hard cap on local backends that are starting OR running (the LRU eviction // above is soft — it spares keepalive-fresh entries). Follows the live // preference: setPoolLimits() pushes a new max into the coordinator. const localBackendSpawnCoordinator = new LocalBackendSpawnCoordinator(poolLimits.maxBackends) const backgroundSlotRetryBackoff = new BackgroundSlotRetryBackoff() // How long a spawn may wait for a free local slot. Must stay under the // renderer's BACKEND_BOOT_WAIT_TIMEOUT_MS (45s, src/lib/with-timeout.ts) so // the queued ticket fails before the renderer does and the user sees why. const POOL_SLOT_WAIT_MS = 30_000 function spawnPriorityFrom(value: unknown): LocalBackendSpawnPriority { return value === 'foreground' ? 'foreground' : 'background' } // Foreground intent for a dial whose pool entry does not exist yet: a user // click that joins an in-flight backendDialClaims claim never re-enters // ensureBackend(), and the claim owner may still be awaiting poolStopper / // registry resolution before backendPool.set(). The local spawn takes the mark // right before its slot request; the IPC handler that set it clears it once // the claim settles, so a dial that never reaches a slot request (primary // route, remote scope, a guard rejection) cannot leave it for a later // hydration spawn of the same key to pick up. const pendingForegroundSpawns = new Set() function takeForegroundSpawn(...poolKeys: string[]): boolean { let marked = false for (const poolKey of poolKeys) { marked = pendingForegroundSpawns.delete(poolKey) || marked } return marked } // Upgrade a pooled entry (running, spawning, or queued for a slot) to // foreground so a queued slot wait can take the reserved foreground slot. function promotePoolEntry(entry: any): void { entry.spawnPriority = 'foreground' entry.localBackendSpawnRequest?.promote?.('foreground') } // Background hydration backs off after a slot timeout. Foreground opens bypass the cooldown. function logPoolSpawnFailure(label: string, error: unknown): void { if (isBackgroundSlotRetryDeferred(error)) { return } if (isBackgroundSlotWaitTimeout(error)) { rememberLog(`Profile backend ${label} slot wait timed out (background); retry is backing off`) } else { rememberLog( `Hermes backend for profile ${label} failed to start: ${error instanceof Error ? error.message : String(error)}` ) } } // Apply foreground intent to the dial claim for `scopeKey`: an entry already // in the pool is promoted directly, otherwise the intent is marked for the // spawn the claim owner is about to start. Returns the cleanup that clears a // mark the dial never consumed. function applySpawnPriority(scopeKey: string, spawnPriority: LocalBackendSpawnPriority): () => void { // The renderer's socket-close event may beat its parking IPC. Main owns // this fence too, so that race cannot resurrect the retired generation. for (const key of poolTouchKeys(scopeKey)) { poolRetirer.assertCanOpen(key, spawnPriority) } if (spawnPriority !== 'foreground') { return () => undefined } const existing = backendPool.get(scopeKey) if (existing) { promotePoolEntry(existing) } else { pendingForegroundSpawns.add(scopeKey) } return () => void pendingForegroundSpawns.delete(scopeKey) } function poolMaxBackends() { return poolLimits.maxBackends } function poolIdleMs() { return poolLimits.idleMs } /** * Apply new limits live: persist, then converge the running pool — evict * LRU backends down to the new max, and let the (already running) idle * reaper handle a shortened idle window on its next tick. Returns the * limits actually in force (post-clamp). */ function setPoolLimits(raw) { poolLimits = clampPoolLimits(raw) persistPoolLimits(poolLimits) localBackendSpawnCoordinator.setLimit(poolLimits.maxBackends) void evictLruPoolBackends(poolMaxBackends()).catch((error: Error): void => rememberLog(`Pool LRU eviction failed: ${String(error)}`) ) startPoolIdleReaper() return { ...poolLimits } } // A backend touched within this window has a live renderer socket (the keepalive // pings every 60s for every open profile). LRU eviction must spare these — a // concurrent multi-profile session keeps several backends "fresh" at once, and // killing one to honor the soft cap would abort a running agent. // // The window is intentionally MUCH wider than the 60s ping cadence: // * 1 missed ping = +60s of apparent silence // * WSL2 IPC stall = the renderer's `hermes:backend:touch` roundtrips // through 9p; a single brief 9p hiccup can stretch a // ping to ~30s of observed silence (#95189: gateways // exited every ~2 min on WSL2 because the previous // 90s window left no headroom — one delayed ping // pushed a live backend past the threshold and the // cap-driven eviction killed the active profile's // backend mid-session, re-minting runtime ids and // re-allocating pooled gateway secondaries ~700×/day). // * 3× ping + 60s headroom = ~4 min, comfortable margin for two missed // pings + WSL2 IPC stall. The hard ceiling for the cap-eligible set is // pool idle window above (default 10 min) — this constant only governs the // "is this backend plausibly still alive" question for LRU eviction, // not when the idle reaper definitively tears a backend down. const POOL_KEEPALIVE_FRESH_MS = Math.max( 120_000, Number(process.env.HERMES_DESKTOP_POOL_KEEPALIVE_FRESH_MS) || 4 * 60_000 ) let poolIdleReaper = null let backendOrphanReapPromise = null // Auto-reload budget for renderer crashes, shared by EVERY window (primary, // secondary session, instance) so a crash loop anywhere is suppressed after // the same budget instead of reloading per-window forever. A deterministic // startup crash would otherwise loop forever (reload → crash → reload), // pinning CPU and spamming logs. Allow a few reloads per rolling window, then // stop and leave the dead window so the user can read the error / quit. const RENDERER_RELOAD_WINDOW_MS = 60_000 const RENDERER_RELOAD_MAX = 3 const rendererReloadTimesRef: { current: number[] } = { current: [] } // Latched bootstrap failure: when the first-launch install fails, we hold // onto the error so subsequent startHermes() calls (e.g. the renderer's // ensureGatewayOpen retrying after the WS won't open) return the same error // instead of re-running install.ps1 in a hot loop. Cleared explicitly by // the renderer's "Reload and retry" path or by quitting the app. let bootstrapFailure = null // Latched non-bootstrap backend spawn failure — stops getConnection() from // respawning hermes serve backend children in a tight loop while boot is broken. let backendStartFailure = null // Latched CONFIRMED remote reauth failure. Remote failures deliberately do not // latch via backendStartFailure (they're usually transient and must stay // retryable), but a rejected session cannot self-heal — and the non-latching // path actively breaks recovery: each retry re-emits running:true and hides // the boot-failure overlay, so the "Sign in" button flickers away before it // can be clicked. Cleared on every recovery path and on a confirmed sign-in. let remoteReauthFailure = null // Active first-launch install, so the renderer's Cancel button (and app quit) // can abort the in-flight install.sh/ps1 instead of leaving it running. let bootstrapAbortController = null // Explicit "the user asked for a repair" flag. Repair used to signal intent by // deleting the bootstrap marker, which stranded healthy installs whose only // problem was a transient backend error (#72166). Intent now lives here, so // repair can force the installer without destroying provenance about how the // install was created. Cleared once the reinstall is under way. let bootstrapRepairRequested = false // Counter for in-flight repair attempts. Reset on a clean boot completion // (see runBootstrap -> ensureRuntime resolve path). Each successive repair // in the same failure episode increments this; once it crosses // MAX_BOOTSTRAP_REPAIR_SOFT_ATTEMPTS the guard escalates from "soft restart" // to "hard reinstall" so a transient backend stall (issue #74874) stops // looping the user through a destructive venv reinstall. let bootstrapRepairAttempt = 0 const MAX_BOOTSTRAP_REPAIR_SOFT_ATTEMPTS = 3 let connectionConfigCache = null let connectionConfigCacheMtime = null let connectionRegistryCache = null let connectionRegistryCacheMtime = null const remoteHeaderSessions = new WeakSet() const remoteWsHeaderStore = createRemoteWsHeaderStore() const previewWatchers = new Map() let previewShortcutActive = false const f12ShortcutActiveWindows = new Set() let nativeThemeListenerInstalled = false let bootProgressState = { error: null, fakeMode: BOOT_FAKE_MODE, isCloudBackendDown: false, message: 'Waiting to start Hermes backend', phase: 'idle', progress: 0, retryable: false, running: false, statusCode: null, timestamp: Date.now(), // The blocked boot screen (R8 D3): set while an update hold keeps the local // backend from starting, null otherwise. updateHold: null as UpdateHoldWire | null } // Chromium owns its --log-file for the life of the process, so the startup // reclaim above cannot bound a shell that stays up for days writing errors. // Poll and truncate in place; renaming would leave Chromium appending to the // renamed inode. Unref'd so it never holds the process open. function startChromiumLogWatcher(file) { const io = { size: f => { try { return fs.statSync(f).size } catch { return null // Not created yet — nothing has been logged. } }, truncate: f => fs.truncateSync(f, 0) } const timer = setInterval(() => { try { if (reclaimActiveLogIfOversized(file, io)) { rememberLog(`[diagnostics] truncated oversized Chromium log ${file}`) } } catch { // Best-effort — an unbounded log beats a crashed shell. } }, ACTIVE_LOG_POLL_MS) timer.unref?.() } function rotateLogIfNeededSync(base) { let size try { size = fs.statSync(base).size } catch { return // No live file yet — the append (re)creates it. } for (const [op, src, dst] of planLogRotation(size, base)) { try { if (op === 'rm') { fs.rmSync(src, { force: true }) } else { fs.renameSync(src, dst) } } catch { // Best-effort — logging must never block startup/shutdown. } } } async function rotateDesktopLogIfNeededAsync() { let size try { size = (await fs.promises.stat(DESKTOP_LOG_PATH)).size } catch { return // No live file yet — the append (re)creates it. } for (const [op, src, dst] of planLogRotation(size, DESKTOP_LOG_PATH)) { try { if (op === 'rm') { await fs.promises.rm(src, { force: true }) } else { await fs.promises.rename(src, dst) } } catch { // Best-effort — logging must never crash the shell. } } } function flushDesktopLogBufferSync() { if (!desktopLogBuffer) { return } const chunk = desktopLogBuffer desktopLogBuffer = '' try { fs.mkdirSync(path.dirname(DESKTOP_LOG_PATH), { recursive: true }) rotateLogIfNeededSync(DESKTOP_LOG_PATH) fs.appendFileSync(DESKTOP_LOG_PATH, chunk) } catch { // Logging must never block app startup/shutdown. } } function flushDesktopLogBufferAsync() { if (!desktopLogBuffer) { return desktopLogFlushPromise } const chunk = desktopLogBuffer desktopLogBuffer = '' desktopLogFlushPromise = desktopLogFlushPromise .then(async () => { await fs.promises.mkdir(path.dirname(DESKTOP_LOG_PATH), { recursive: true }) await rotateDesktopLogIfNeededAsync() await fs.promises.appendFile(DESKTOP_LOG_PATH, chunk) }) .catch(() => { // Logging must never crash the desktop shell. }) return desktopLogFlushPromise } function scheduleDesktopLogFlush() { if (desktopLogFlushTimer) { return } desktopLogFlushTimer = setTimeout(() => { desktopLogFlushTimer = null void flushDesktopLogBufferAsync() }, DESKTOP_LOG_FLUSH_MS) } function rememberLog(chunk) { const text = String(chunk || '').trim() if (!text) { return } // One timestamp per chunk: lines arriving in the same event happened // at the same moment. Local time, same shape as agent.log/gui.log. const stamp = formatLogStamp(new Date()) const lines = text.split(/\r?\n/).map(line => formatDesktopLogLine(line, stamp)) hermesLog.push(...lines) if (hermesLog.length > 300) { hermesLog.splice(0, hermesLog.length - 300) } desktopLogBuffer += `${lines.join('\n')}\n` if (desktopLogBuffer.length >= DESKTOP_LOG_BUFFER_MAX_CHARS) { if (desktopLogFlushTimer) { clearTimeout(desktopLogFlushTimer) desktopLogFlushTimer = null } void flushDesktopLogBufferAsync() return } scheduleDesktopLogFlush() } // Main-process stalls leave renderer-scoped lifecycle logging unable to run. // When the loop resumes, retain the delayed timer's timing in desktop.log so a // Windows AppHang report can be correlated without changing tray semantics. const mainProcessLagWatchdog = createMainProcessLagWatchdog({ cadenceMs: 1_000, thresholdMs: 2_000, now: Date.now, log: rememberLog, setInterval, clearInterval }) installCrashForensics({ flush: flushDesktopLogBufferSync, log: rememberLog }) // A rejected loadURL leaves a blank window and, unhandled, no trace anywhere // the user can send us. `label` names the surface so the log says which one. function loadWindowUrl(win, url, label) { win.loadURL(url).catch(error => rememberLog(`${label} failed to load: ${describeCrashReason(error)}`)) } const EXTERNAL_OPEN_DEPS: ExternalOpenDeps = { isWsl: IS_WSL, spawn: (cmd, args, opts) => spawn(cmd, args, opts), openExternal: url => shell.openExternal(url), openFile: openExternalFile, openLocalPath: openLocalFilesystemPath, notifyFailure: broadcastOpenFailed, log: rememberLog } // Deps for the pre-open stat guard (see openExternalFile): a miss is // broadcast with the 'missing-file' code so the dialog shows file-not-found // copy; other stat failures only log. const GUARD_REPORT_DEPS = { log: rememberLog, reportMissing: (rawUrl: string, message: string) => broadcastOpenFailed(rawUrl, message, 'missing-file') } // The single route every external URL open funnels through (external-open.ts). // main.ts only binds the electron deps; all open/fallback logic lives in the // module so it unit-tests without loading electron. function openExternalUrl(rawUrl: string) { return externalOpen(String(rawUrl || '').trim(), EXTERNAL_OPEN_DEPS) } async function openPreviewInBrowser(rawUrl: string) { const result = await externalOpen(String(rawUrl || '').trim(), EXTERNAL_OPEN_DEPS) // Only an invalid/unsupported URL is a hard "no" for the caller; an open // failure already raised the fallback modal with the URL. return !(result.ok === false && result.reason === 'invalid') } // `file://` URLs come from the artifacts panel (the renderer can't open them // itself because Chromium blocks that navigation). Reveal the file in the // system file manager instead of dispatching to the OS file association: // on Windows, archive artifacts (.gz/.tar) have no usable association, and // handing the path back to the OS shell bounces the open through the default // (Chromium) handler, which re-downloads the file — an infinite download loop // (issue #53170). Reveal-in-folder never re-opens the file, so it can't loop. // // A short per-path dedupe window additionally absorbs renderer-side double // clicks and retry storms so repeated open requests can't pile up windows. const FILE_REVEAL_DEDUPE_MS = 1_500 const recentFileReveals = new Map() export function _resetFileRevealDedupeForTest() { recentFileReveals.clear() } async function openExternalFile(rawUrl: string) { let localPath: string try { localPath = resolveRequestedPathForIpc(rawUrl, { purpose: 'Open external file' }) } catch { return } // A missing file must never reach the reveal fallback: on macOS revealing a // non-existent path is silently a no-op, so the click would do nothing at // all. Say "missing" before the OS is asked. Only ENOENT/ENOTDIR count as // missing — any other stat failure (EACCES on a locked volume, ELOOP) is // logged and still reaches the OS below, so an existing-but-locked file // keeps its real error instead of a fabricated miss. Classification lives // in external-open.ts so it unit-tests without electron. Misses are // reported here and not rethrown: external-open.ts documents that openFile // handles its own reporting, and rethrowing would stack a second dialog. try { assertExistingPathForOpen(localPath, 'Open external file') } catch (error) { if (reportPreOpenStatFailure(error, rawUrl, GUARD_REPORT_DEPS)) { return } } const now = Date.now() const lastReveal = recentFileReveals.get(localPath) if (lastReveal !== undefined && now - lastReveal < FILE_REVEAL_DEDUPE_MS) { rememberLog(`[file] duplicate reveal request within ${FILE_REVEAL_DEDUPE_MS}ms; ignored: ${localPath}`) return } recentFileReveals.set(localPath, now) // Prune stale entries so the map can't grow without bound over a long session. for (const [path, ts] of recentFileReveals) { if (now - ts >= FILE_REVEAL_DEDUPE_MS && path !== localPath) { recentFileReveals.delete(path) } } try { shell.showItemInFolder(localPath) } catch (error) { rememberLog(`[file] reveal in folder failed: ${error instanceof Error ? error.message : String(error)}`) } } // The `hermes:openExternal` route for a BARE local filesystem path — a chat // media link, a markdown href, or an artifacts-panel value carrying // `C:\…`, `~/…`, `/…` or a UNC path instead of a `file://` URL. `new URL()` // cannot express those (hermes-agent 80946): resolve through the same audited // `resolveRequestedPathForIpc` the file route uses, then OPEN with the OS // handler and fall back to reveal-in-folder, mirroring openExternalFile's // missing-file guard so a dead path reports "File not found" instead of a // silent no-op. Resolves false only when the path could not be resolved at // all; open failures are logged (with the path, so "Failed to open path" is // diagnosable) and still count as handled. async function openLocalFilesystemPath(rawPath: string): Promise { let localPath: string try { localPath = resolveRequestedPathForIpc(String(rawPath || ''), { purpose: 'Open external file' }) } catch { return false } try { assertExistingPathForOpen(localPath, 'Open external file') } catch (error) { if (reportPreOpenStatFailure(error, rawPath, GUARD_REPORT_DEPS)) { return true } } try { const errorMessage = await shell.openPath(localPath) if (!errorMessage) { return true } // Include the path so "Failed to open path" is diagnosable (hermes-agent // 84361), then reveal: on Windows archive artifacts have no usable // association, and the reveal never re-opens so it can't loop (#53170). rememberLog(`[file] openPath failed: ${errorMessage}; path=${localPath}; revealing in folder instead`) try { shell.showItemInFolder(localPath) } catch (revealError) { rememberLog( `[file] showItemInFolder failed: ${revealError instanceof Error ? revealError.message : String(revealError)}; path=${localPath}` ) } return true } catch (error) { rememberLog( `[file] openPath rejected: ${error instanceof Error ? error.message : String(error)}; path=${localPath}` ) return true } } // An open failure is surfaced to the renderer as a modal carrying the URL, so // a dead system-browser click (e.g. no https handler registered on Linux) is // never silent. `code` tags the failure class (e.g. 'missing-file') so the // dialog can show accurate localized copy instead of the generic one. // Broadcast to every window — the trigger has no single sender. function broadcastOpenFailed(url: string, message: string, code?: 'missing-file') { rememberLog(`[open-failed] ${url}: ${message}`) for (const win of BrowserWindow.getAllWindows()) { win.webContents.send('hermes:external-open-failed', { url, message, ...(code ? { code } : {}) }) } } function ensureWslWindowsFonts() { if (!IS_WSL) { return } const fontsDir = ['/mnt/c/Windows/Fonts', '/mnt/c/windows/fonts'].find(candidate => { try { return fs.statSync(candidate).isDirectory() } catch { return false } }) if (!fontsDir) { return } try { const confDir = path.join(app.getPath('home'), '.config', 'fontconfig', 'conf.d') const confPath = path.join(confDir, '99-hermes-wsl-windows-fonts.conf') let existing = '' try { existing = fs.readFileSync(confPath, 'utf8') } catch { existing = '' } if (existing.includes(fontsDir)) { return } fs.mkdirSync(confDir, { recursive: true }) fs.writeFileSync( confPath, `\n\n\n ${fontsDir}\n\n` ) rememberLog(`[fonts] wired WSL Windows fonts for renderer: ${fontsDir}`) const cache = spawn('fc-cache', ['-f', fontsDir], { detached: true, stdio: 'ignore' }) cache.on('error', () => undefined) cache.unref() } catch (error) { rememberLog(`[fonts] WSL font setup skipped: ${error.message}`) } } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } function clampBootProgress(value) { const numeric = Number(value) if (!Number.isFinite(numeric)) { return 0 } return Math.max(0, Math.min(100, Math.round(numeric))) } function broadcastBootProgress() { if (!mainWindow || mainWindow.isDestroyed()) { return } const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } webContents.send('hermes:boot-progress', bootProgressState) } // Bootstrap-event broadcast channel + state. The bootstrap runner emits a // stream of events (manifest, stage, log, complete, failed) that the renderer // install overlay subscribes to. We also keep a running snapshot: // - manifest: the stage list (rendered as a checklist in the overlay) // - stages: per-stage state ('pending' | 'running' | 'succeeded' | // 'skipped' | 'failed') keyed by stage name // - active: true while a bootstrap is in flight; false otherwise // - error: last 'failed' event's error message // - log: bounded ring buffer of the last 200 log lines for the // "Show details" affordance in the overlay // // The snapshot is queryable via the hermes:bootstrap:get IPC handler so a // reloaded renderer (e.g. devtools reload during dev) recovers state. // Bootstrap log ring: bounded buffer so a long install (npm + playwright // downloads can emit thousands of lines) doesn't grow unbounded in memory // AND so the renderer's getBootstrapState() reply stays a reasonable size. // We keep enough to cover an entire failed stage's transcript so the // 'Copy output' button gives the user actually-actionable context, not // just the last few lines. const BOOTSTRAP_LOG_RING_MAX = 500 let bootstrapState = { active: false, manifest: null, stages: {}, error: null, log: [], startedAt: null, completedAt: null, setupChoice: null, unsupportedPlatform: null } let firstRunSetupGate = null function broadcastBootstrapEvent(ev) { if (ev.type === 'manifest') { bootstrapState.manifest = ev bootstrapState.active = true bootstrapState.setupChoice = null bootstrapState.startedAt = bootstrapState.startedAt || Date.now() bootstrapState.stages = {} for (const stage of ev.stages || []) { bootstrapState.stages[stage.name] = { state: 'pending', json: null, durationMs: null, error: null } } } else if (ev.type === 'stage') { bootstrapState.stages[ev.name] = { state: ev.state, durationMs: ev.durationMs ?? null, json: ev.json ?? null, error: ev.error ?? null } } else if (ev.type === 'log') { bootstrapState.log.push({ ts: Date.now(), stage: ev.stage || null, line: ev.line, stream: ev.stream || 'stdout' }) if (bootstrapState.log.length > BOOTSTRAP_LOG_RING_MAX) { bootstrapState.log.splice(0, bootstrapState.log.length - BOOTSTRAP_LOG_RING_MAX) } } else if (ev.type === 'complete') { bootstrapState.active = false bootstrapState.completedAt = Date.now() bootstrapState.error = null bootstrapState.unsupportedPlatform = null } else if (ev.type === 'failed') { bootstrapState.active = false bootstrapState.error = ev.error || 'unknown error' bootstrapState.setupChoice = null } else if (ev.type === 'unsupported-platform') { bootstrapState.active = false bootstrapState.setupChoice = null bootstrapState.unsupportedPlatform = { platform: ev.platform, activeRoot: ev.activeRoot, installCommand: ev.installCommand, docsUrl: ev.docsUrl } } else if (ev.type === 'setup-choice') { bootstrapState.active = false bootstrapState.error = null bootstrapState.manifest = null bootstrapState.stages = {} bootstrapState.setupChoice = ev.active ? { platform: ev.platform, activeRoot: ev.activeRoot, local: ev.local || 'none', bundled: installShape() === 'bundled' } : null bootstrapState.unsupportedPlatform = null } else if (ev.type === 'dismissed') { resetBootstrapSnapshot() } if (!mainWindow || mainWindow.isDestroyed()) { return } const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } webContents.send('hermes:bootstrap:event', ev) } function getBootstrapState() { return bootstrapSnapshot(bootstrapState) } function resetBootstrapSnapshot(): void { bootstrapState = { active: false, manifest: null, stages: {}, error: null, log: [], startedAt: null, completedAt: null, setupChoice: null, unsupportedPlatform: null } } function promptFirstRunSetupChoice(backend) { broadcastBootstrapEvent({ type: 'setup-choice', active: true, platform: backend.platform || process.platform, activeRoot: backend.activeRoot || ACTIVE_HERMES_ROOT, local: backend.local || 'none', bundled: installShape() === 'bundled' }) } function hideFirstRunSetupChoice() { if (bootstrapState.setupChoice) { broadcastBootstrapEvent({ type: 'setup-choice', active: false }) } } function getFirstRunSetupGate() { if (!firstRunSetupGate) { firstRunSetupGate = createFirstRunSetupGate({ hideChoice: hideFirstRunSetupChoice, log: rememberLog, onStuck: (_backend, stuckAfterMs) => { updateBootProgress( { error: null, message: `Still waiting for first-run setup choice after ${Math.round(stuckAfterMs / 1000)} seconds`, phase: 'bootstrap.choice', progress: 12, running: true }, { allowDecrease: true } ) }, promptChoice: promptFirstRunSetupChoice }) } return firstRunSetupGate } async function waitForFirstRunSetupChoice(backend) { const gate = getFirstRunSetupGate() if (!gate.shouldGate(backend)) { return 'continue-local' } updateBootProgress( { error: null, message: 'Waiting for first-run setup choice', phase: 'bootstrap.choice', progress: 12, running: true }, { allowDecrease: true } ) return gate.wait(backend) } function continueFirstRunLocalBootstrap() { getFirstRunSetupGate().continueLocal() } function abandonFirstRunSetupChoiceForRemoteApply() { const gate = getFirstRunSetupGate() if (!gate.hasWaiter()) { return false } const resumedGatedConnection = gate.abandonForRemoteApply() if (resumedGatedConnection) { broadcastBootstrapEvent({ type: 'dismissed' }) } return resumedGatedConnection } // The latched reauth failure whose hold has already been logged, so a burst of // dropped updates from one in-flight sibling attempt logs once, not per event. let bootProgressHeldFor: Error | null = null function updateBootProgress(update, options: { allowDecrease?: boolean } = {}) { // A latched CONFIRMED reauth rejection owns the boot surface until a // recovery path clears it. Updates that are not a re-emit of that failure — // a running:true phase or cleared error from an attempt already in flight // when the latch closed, or an unrelated sibling failure that would flip // retryable back on — must not reach the renderer, or the overlay's Sign in // button flickers away again (#95701). if (shouldHoldBootProgressForReauth(remoteReauthFailure ? remoteReauthFailure.message : null, update)) { if (bootProgressHeldFor !== remoteReauthFailure) { bootProgressHeldFor = remoteReauthFailure rememberLog('[boot] remote reauth latched: holding the recovery overlay against a stale boot-progress update') } return } bootProgressHeldFor = null const nextProgressRaw = typeof update.progress === 'number' ? clampBootProgress(update.progress) : bootProgressState.progress const nextProgress = options.allowDecrease ? nextProgressRaw : Math.max(bootProgressState.progress, nextProgressRaw) bootProgressState = { ...bootProgressState, ...update, error: update.error === undefined ? bootProgressState.error : update.error, fakeMode: BOOT_FAKE_MODE || Boolean(update.fakeMode), progress: nextProgress, // `retryable` rides with `error`: it survives updates that preserve the // error and resets alongside a new/cleared error unless explicitly set. retryable: update.retryable === undefined ? update.error === undefined && Boolean(bootProgressState.retryable) : Boolean(update.retryable), timestamp: Date.now() } if (update.message) { rememberLog(`[boot] ${update.message}`) } broadcastBootProgress() } async function advanceBootProgress(phase, message, progress) { updateBootProgress({ phase, message, progress, running: true, error: null }) if (BOOT_FAKE_MODE) { await sleep(BOOT_FAKE_STEP_MS) } } function fileExists(filePath) { try { return fs.statSync(filePath).isFile() } catch { return false } } function isGitCheckout(root: string): boolean { return fs.existsSync(path.join(root, '.git')) } function directoryExists(filePath) { try { return fs.statSync(filePath).isDirectory() } catch { return false } } // --- in-app update mutual exclusion (#50238) ------------------------------- // The Tauri updater writes HERMES_HOME/.hermes-update-in-progress for the whole // duration of an `--update` run (see update.rs UpdateMarkerGuard). If the user // relaunches the desktop mid-update — because the window vanished with no // progress and looks crashed — a fresh instance must NOT spawn its own local // backend: that backend re-locks the venv shim, the updater's straggler cleanup // (`force_kill_other_hermes`, taskkill /IM hermes.exe) kills it, the launch // fails with the 45s "backend didn't come up" error, and the relaunch/kill // cycle loops. Instead the fresh instance parks until the update finishes, then // brings the backend up itself (it is the surviving instance — the updater's // own relaunch hits our single-instance lock and quits). Marker parsing + // staleness self-heal live in update-marker.ts (unit-tested). // Gate deps shared by the primary-window boot path and the pool-backend // spawn path. Consulting the on-disk marker, the in-process updateInFlight // flag, AND the successful detached hand-off state is load-bearing (#73822): // applyUpdates stops its own backend before committing the update hand-off. // A marker-only gate lets the renderer's reconnect respawn a backend during // that critical section, racing the update and leaving a live process on the // runtime being replaced. // The hand-off state closes the later Windows `cmd start` wrapper gap: the // wrapper exits 0 before the real PowerShell script claims the marker, and // `finally` clears updateInFlight immediately after the hand-off is accepted. function updateGateDeps(callbacks: MarkerGateCallbacks = {}) { return { hasLiveMarker: markerGateProbe( { hermesHome: HERMES_HOME, isWindows: IS_WINDOWS, log: rememberLog, updateRoot: resolveUpdateRoot }, callbacks ), isUpdateInFlight: () => updateInFlight, isHandoffActive: () => isQuittingForHandoff } } // The blocked boot screen (R8 D3) every update wait publishes its hold on. const updateHoldScreen = createUpdateHoldScreen({ hermesHome: HERMES_HOME, log: rememberLog, bootHold: () => bootProgressState.updateHold, updateBootProgress }) const clearUpdateHold = updateHoldScreen.clear const showUpdateHold = updateHoldScreen.show // Block until no live update is in progress (or we hit the wait timeout). // Emits a boot-progress phase so the renderer shows "Update in progress…" // rather than a frozen splash. Returns true if it parked at all. async function waitForUpdateToFinish() { let announced = false let longWaitAnnounced = false const parkedRun = parkedRunReport() // A dead marker whose checkout a leftover process still holds (R6), or whose // ownership the helper could not establish (the blocked screen, R8 D3). const hold = holdTicker({ show: state => showUpdateHold(state), clear: () => clearUpdateHold() }) // The wait ended because the user chose Start anyway, not because the // update finished (R8 m7): no bundle-swap relaunch mid-hold. let overridden = false const gateDeps = updateGateDeps({ onLiveMarker: marker => { parkedRun.park(marker) overridden = false }, onHeld: hold.onHeld, onOverride: () => { overridden = true } }) const outcome = await waitForUpdateClearance(gateDeps, { signal: localBackendLifecycle.signal, onWaitTick: async (reason, waitedMs) => { if (!announced) { announced = true rememberLog(`[updates] update in progress (${reason}); deferring backend start until it finishes`) } // Never a timeout (R8 D3): past the grace the boot shows the blocked // screen and stays parked until the hold ends, the user quits, or the // user confirms Start anyway (registerUpdateHoldIpc). const { held: heldNow, shown } = hold.tick(reason) if (shown) { return } if (reason === 'marker' && heldNow) { await advanceBootProgress('backend.update-wait', heldWaitMessage(heldNow), 12) return } // A live update owner is waited out, never aged out (C1 rule 3): booting // a backend into a half-replaced runtime is the failure this gate exists // for. Past the old ceiling, say so instead of silently counting down. if (reason === 'marker' && waitedMs >= UPDATE_WAIT_TIMEOUT_MS) { if (!longWaitAnnounced) { longWaitAnnounced = true rememberLog('[updates] update still running past 20 minutes; its owner is alive, so the boot keeps waiting') } await advanceBootProgress( 'backend.update-wait', 'An update is still running — Hermes will start automatically when it finishes. Its progress is in logs/update.log.', 12 ) return } await advanceBootProgress( 'backend.update-wait', 'An update is finishing — Hermes will start automatically when it completes…', 12 ) }, pollMs: UPDATE_WAIT_POLL_MS, timeoutMs: UPDATE_WAIT_TIMEOUT_MS }) clearUpdateHold() // A detached update's result file is the only way the user learns it // failed: consumed once, here, where boot passes the update gate. parkedRun.report({ hermesHome: HERMES_HOME, log: rememberLog, dialog, shell, openUpdates: sendOpenUpdatesRequested }) if (outcome === 'cancelled') { localBackendLifecycle.assertCanStart() } if (outcome === 'clear') { return false } if (outcome === 'timeout') { rememberLog('[updates] update still in progress after wait timeout; starting backend anyway') } else if (overridden) { rememberLog('[updates] proceeding with backend start over a held update (user chose Start anyway); no relaunch') } else if ( relaunchIntoSwappedBundle({ isPackaged: IS_PACKAGED, argv: process.argv, running: INSTALL_STAMP, resourcesPath: process.resourcesPath, relaunch: extraArgs => app.relaunch({ args: [...buildNoSandboxRelaunchArgs(process.argv.slice(1)), ...extraArgs] }), exit: () => void exitAfterBackendShutdown(0), log: rememberLog }) ) { await advanceBootProgress('backend.update-restart', 'Restarting Hermes to load the updated app…', 14) // Park while the scheduled exit lands so this stale build never starts a // backend; the failsafe below only runs if the exit somehow does not. await new Promise(resolve => setTimeout(resolve, BUNDLE_SWAP_RELAUNCH_FAILSAFE_MS)) rememberLog( `[updates] relaunch did not land within ${BUNDLE_SWAP_RELAUNCH_FAILSAFE_MS}ms; continuing with the current build` ) } else { rememberLog('[updates] update finished; proceeding with backend start') } return true } function unpackedPathFor(filePath) { return filePath.replace(/app\.asar(?=$|[\\/])/, 'app.asar.unpacked') } function findOnPath(command) { if (!command) { return null } if (path.isAbsolute(command) || command.includes(path.sep) || (IS_WINDOWS && command.includes('/'))) { if (!fileExists(command)) { return null } if (isWindowsBinaryPathInWsl(command, { isWsl: IS_WSL })) { return null } return command } const pathEntries = String(process.env.PATH || '') .split(path.delimiter) .filter(Boolean) // On Windows, try PATHEXT extensions BEFORE the bare (empty-extension) name. // A real command must resolve via its .exe/.cmd (Windows command-resolution // semantics consult PATHEXT); an extensionless file — e.g. a Git-Bash // shell-script shim named `hermes` — must not shadow `hermes.cmd`/`hermes.exe`. // The empty entry is kept LAST so callers that already include the extension // (py.exe, pwsh.exe, powershell.exe) still resolve. const extensions = buildPathExtCandidates(process.env.PATHEXT, IS_WINDOWS) for (const entry of pathEntries) { for (const extension of extensions) { const candidate = path.join(entry, `${command}${extension}`) if (fileExists(candidate)) { return candidate } } } return null } function isCommandScript(command) { return IS_WINDOWS && /\.(cmd|bat)$/i.test(command || '') } async function unwrapWindowsVenvHermesCommand(command, backendArgs) { return resolveVenvHermesCommand(command, backendArgs, { isWindows: IS_WINDOWS, isCommandScript, fileExists, directoryExists, canImportHermesCli, getVenvPython, buildDesktopBackendEnv, resolvePath: (...segments) => path.resolve(...segments), dirname: p => path.dirname(p), basename: p => path.basename(p), rememberLog }) } // Does the resolved runtime understand the `serve` subcommand? The desktop // spawns `hermes serve`; runtimes older than serve only have `dashboard`. We // detect support so getBackendArgsForRuntime() can route old runtimes through // the legacy `dashboard --no-open` form instead of crashing on an unknown // subcommand (would brick every user mid-upgrade — #54568 follow-up). // Fast-path / probe / cache strategy: see backend-serve-support.ts header. const backendSupportsServe = createBackendServeSupportResolver(HERMES_HOME, rememberLog) // Given a resolved backend whose args target `serve`, return the args the // runtime actually understands: unchanged when `serve` is supported, or // rewritten to `dashboard --no-open` for older runtimes. async function getBackendArgsForRuntime(backend) { return (await backendSupportsServe(backend)) ? backend.args : dashboardFallbackArgs(backend.args) } function normalizeExecutablePathForCompare(commandPath) { if (!commandPath) { return null } let resolved = path.resolve(String(commandPath)) try { resolved = fs.realpathSync.native ? fs.realpathSync.native(resolved) : fs.realpathSync(resolved) } catch { // Fallback to path.resolve() above. } return IS_WINDOWS ? resolved.toLowerCase() : resolved } function looksLikeDesktopAppBinary(commandPath) { if (!IS_WINDOWS || !commandPath) { return false } const normalizedCandidate = normalizeExecutablePathForCompare(commandPath) const normalizedCurrentExec = normalizeExecutablePathForCompare(process.execPath) if (normalizedCandidate && normalizedCurrentExec && normalizedCandidate === normalizedCurrentExec) { return true } let resolved = path.resolve(String(commandPath)) try { resolved = fs.realpathSync.native ? fs.realpathSync.native(resolved) : fs.realpathSync(resolved) } catch { // Keep resolved path fallback. } const resourcesDir = path.join(path.dirname(resolved), 'resources') // existsSync for the archive: Electron's asar shim stats app.asar itself as a directory (so // fileExists was always false) and constructs the deprecated fs.Stats doing it (#96857). return ( fs.existsSync(path.join(resourcesDir, 'app.asar')) || directoryExists(path.join(resourcesDir, 'app.asar.unpacked')) ) } function isHermesSourceRoot(root) { return directoryExists(root) && fileExists(path.join(root, 'hermes_cli', 'main.py')) } async function findPythonForRoot(root: string): Promise { return resolveSourcePython(root, { override: process.env.HERMES_DESKTOP_PYTHON, isWindows: IS_WINDOWS, fileExists }) } async function findSystemPython() { if (!IS_WINDOWS) { // POSIX systems: PATH lookup is safe. for (const command of ['python3', 'python']) { const candidate = findOnPath(command) if (candidate) { return candidate } } return null } // Windows: PATH-based detection has TWO landmines we have to dodge. // // (1) The Microsoft Store "Python stub" lives at // %LOCALAPPDATA%\Microsoft\WindowsApps\python.exe and is on PATH // by default on modern Windows. It's a redirector that opens the // Store window if no Store Python is installed. Running it for // `-m venv` would either succeed (real Store install — fine) or // pop the Store dialog (bad UX during boot). // (2) `py.exe` (Python launcher) is missing from per-user installs // that didn't check the launcher option, so PATH-only checks // miss real Python 3.13 installs (user-reported case). // // We also restrict ourselves to Python 3.11–3.13. 3.14 is the latest // CPython but several Hermes deps (notably pywinpty's Rust-built // windows_x86_64_msvc crate) don't yet publish 3.14 wheels, and // `pip install -e .` falls back to source-build, which fails without // a Rust toolchain. install.ps1 sidesteps this by pinning to 3.11 // via uv; until we add the same uv-managed Python pathway here, the // simplest fix is to refuse 3.14 detection and let the NSIS prereq // page offer to install 3.11 alongside. // // Strategy: probe in three passes, in order from most-precise to // least-precise, and ONLY use PATH lookup as a last resort after // confirming the candidate isn't the WindowsApps redirector. // // Pass 1: PEP 514 registry — every standards-compliant Python // installer registers itself at SOFTWARE\Python\PythonCore. // The MS Store stub does NOT register here, so a hit means // a real Python install. Versions are explicit so we // inherently filter 3.14 out. // Pass 2: Filesystem probe of standard install locations // (Program Files, LocalAppData\Programs\Python). Same // version filtering by directory name. // Pass 3: PATH lookup of `py.exe` (the launcher itself never // triggers the Store) — but call it with a version flag so // we resolve to a SPECIFIC supported version, not whatever // py.exe's default is (which on a 3.14-only box would be // 3.14). const SUPPORTED_VERSIONS = ['3.11', '3.12', '3.13'] const SUPPORTED_VERSIONS_NO_DOT = ['311', '312', '313'] // Pass 1: registry. Use `reg query` since main process doesn't have // a reliable in-process registry API across all electron versions. for (const hive of ['HKLM', 'HKCU']) { for (const version of SUPPORTED_VERSIONS) { try { const out = await execText( 'reg', ['query', `${hive}\\SOFTWARE\\Python\\PythonCore\\${version}\\InstallPath`, '/ve', '/reg:64'], { timeout: 5_000 } ) // Output format: " (Default) REG_SZ C:\Path\To\Python\" const match = out.match(/REG_SZ\s+(.+?)\s*$/m) if (match) { const installPath = match[1].trim() const pythonExe = path.join(installPath, 'python.exe') if (fileExists(pythonExe)) { return pythonExe } } } catch { // Key not present — try next. } } } // Pass 2: filesystem probe of standard locations. const programFiles = process.env['ProgramFiles'] || 'C:\\Program Files' const localAppData = process.env.LOCALAPPDATA || '' for (const versionDir of SUPPORTED_VERSIONS_NO_DOT) { const systemWide = path.join(programFiles, `Python${versionDir}`, 'python.exe') if (fileExists(systemWide)) { return systemWide } if (localAppData) { const perUser = path.join(localAppData, 'Programs', 'Python', `Python${versionDir}`, 'python.exe') if (fileExists(perUser)) { return perUser } } } // Pass 3: py.exe with explicit version flag. The launcher itself is // safe to invoke (no Store popup) and `py -3.13 -c "import sys; // print(sys.executable)"` resolves to the actual python.exe path of // the requested version. We try in version-priority order so the // first hit wins. const pyExe = findOnPath('py.exe') if (pyExe) { for (const version of SUPPORTED_VERSIONS) { try { const out = await execText(pyExe, [`-${version}`, '-c', 'import sys; print(sys.executable)'], { timeout: PROBE_TIMEOUT_MS }) const candidate = out.trim() if (candidate && fileExists(candidate)) { return candidate } } catch { // py couldn't find that version — try next. } } } // We deliberately do NOT fall back to plain `python.exe` on PATH. // Without a way to verify the version safely (running `python -V` // risks the Microsoft Store popup), accepting whatever's there // could land us on 3.14 and trigger the Rust-build-from-source // failure. Better to return null and let the NSIS prereq page // offer to install a known-good 3.11 via winget. return null } function getVenvPython(venvRoot) { return path.join(venvRoot, IS_WINDOWS ? path.join('Scripts', 'python.exe') : path.join('bin', 'python')) } // Windows console-window flashes are governed by the *parent's* console, not by // each child spawn. A GUI-subsystem parent (pythonw.exe) has no console, so every // console-subsystem child it spawns (git, gh, cmd, ...) must allocate its own — // which flashes a window. A console-subsystem parent (python.exe) instead owns a // single console that all of its children inherit, so none of them flash. // // Note this change adds no new creationflag: the backend spawn is ALREADY wrapped // in hiddenWindowsChildOptions() (windowsHide: true), but that setting is INERT // against pythonw.exe — a GUI-subsystem process has no console for it to act on. // Switching the backend to the venv's console python.exe is what makes the // existing wrapper load-bearing: with windowsHide the process comes up owning a // *windowless* console (verified at runtime — it has an attachable console whose // window handle is NULL), and its children inherit that one windowless console // instead of each allocating a visible one. // // This makes "no flashing windows" a property of the one backend launch rather // than a flag that has to be remembered at every descendant spawn site. Restoring // console python also restores stdout, so the backend announces its port on the // normal HERMES_DASHBOARD_READY stdout line and no ready-file side channel is // needed. function makeDashboardReadyFile() { const dir = path.join(app.getPath('userData'), 'backend-ready') fs.mkdirSync(dir, { recursive: true }) return path.join(dir, `dashboard-${process.pid}-${Date.now()}-${crypto.randomBytes(6).toString('hex')}.json`) } // resolveGitBinary — locate git.exe on Windows. A fresh installer-driven // install only has PortableGit under %LOCALAPPDATA%\hermes\git (never on // PATH), so a bare spawn('git') ENOENTs and self-update checks fail with // "Couldn't check for updates". PortableGit first, then UGit's bundled copy // (see ./git-binary-candidates), then standard Git-for-Windows locations, // then PATH. Cached after first probe. let _gitBinaryCache = null // A binary can exist on disk and still be unlaunchable — on macOS an // Intel-only build ahead on PATH (e.g. a pre-Rosetta-removal Homebrew) // fails at spawn time with errno -86 (EBADARCH), which callers then report // as an update-server/network problem. Probing `git --version` before // committing to a candidate skips such entries; the existence-only // fallback keeps behaviour unchanged where the probe itself cannot run. function binaryRuns(candidate) { try { execFileSync(candidate, ['--version'], { stdio: 'ignore', timeout: 5000, windowsHide: true }) return true } catch { return false } } function findPathCandidates(command) { const pathEntries = String(process.env.PATH || '') .split(path.delimiter) .filter(Boolean) const candidates = [] for (const entry of pathEntries) { const candidate = path.join(entry, command) if (fileExists(candidate)) { candidates.push(candidate) } } return candidates } function resolveGitBinary() { if (_gitBinaryCache) { return _gitBinaryCache } if (!IS_WINDOWS) { // Every PATH hit, probed — the first entry that merely exists can be // unlaunchable while a working system git sits later on the same PATH. const selected = selectRunnableBinary({ candidates: findPathCandidates('git'), fileExists, binaryRuns }) _gitBinaryCache = selected || 'git' return _gitBinaryCache } const localAppData = process.env.LOCALAPPDATA || '' // Fixed candidates + the UGit-bundled glob (a UGit install moves with every // app-* version, so it can only be found by enumerating the dir). UGit's // git.exe is usually on PATH, but an Explorer-launched Electron inherits the // login-time environment block and can miss it (#61494). const candidates = windowsGitCandidates( { localAppData, programFiles: process.env['ProgramFiles'] || 'C:\\Program Files', programFilesX86: process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)' }, { existsSync: fileExists, readdirSync: dir => fs.readdirSync(dir) } ) _gitBinaryCache = candidates.find(fileExists) || findOnPath('git') || 'git' return _gitBinaryCache } // resolveGhBinary — locate the GitHub CLI. GUI-launched apps get a minimal PATH // that omits Homebrew (/opt/homebrew/bin, /usr/local/bin) where `gh` usually // lives, so a bare spawn('gh') ENOENTs even though `gh` works in the user's // terminal. Check the common install locations first, then PATH. Cached. let _ghBinaryCache = null function resolveGhBinary() { if (_ghBinaryCache) { return _ghBinaryCache } const candidates = [] if (IS_WINDOWS) { candidates.push(path.join(process.env['ProgramFiles'] || 'C:\\Program Files', 'GitHub CLI', 'gh.exe')) if (process.env.LOCALAPPDATA) { candidates.push(path.join(process.env.LOCALAPPDATA, 'Microsoft', 'WinGet', 'Links', 'gh.exe')) } } else { const home = app.getPath('home') candidates.push('/opt/homebrew/bin/gh', '/usr/local/bin/gh', '/usr/bin/gh', path.join(home, '.local', 'bin', 'gh')) // PATH hits go through the same probe: a bare findOnPath fallback would // re-select an unlaunchable first hit when none of the fixed locations exist. candidates.push(...findPathCandidates('gh')) } // Same selection rule as git: an existing-but-unlaunchable candidate (e.g. // an Intel-only build from a stale Homebrew) must not shadow a working one // further down the list, and PATH is only consulted when none of the // explicit candidates is usable. const selected = selectRunnableBinary({ candidates, fileExists, binaryRuns }) _ghBinaryCache = selected || findOnPath('gh') || 'gh' return _ghBinaryCache } function recentHermesLog() { return hermesLog.slice(-20).join('\n') } // ─── Self-update (git-pull against the running backend's hermes root) ────── function readDesktopUpdateConfig(): { branch: string; branchExplicit: boolean } { try { const parsed: { branch?: unknown } | null = JSON.parse(fs.readFileSync(DESKTOP_UPDATE_CONFIG_PATH, 'utf8')) const branch: string = typeof parsed?.branch === 'string' ? parsed.branch.trim() : '' return { branch: branch || DEFAULT_UPDATE_BRANCH, branchExplicit: branch.length > 0 } } catch { return { branch: DEFAULT_UPDATE_BRANCH, branchExplicit: false } } } // Atomic file write: temp + rename (atomic on all platforms). Prevents // partial writes on crash/power loss that corrupt JSON config files. function writeFileAtomic(targetPath, data, encoding?: BufferEncoding) { const tmp = targetPath + '.tmp' fs.writeFileSync(tmp, data, encoding) fs.renameSync(tmp, targetPath) } // ─── Main-window geometry persistence (window-state.json) ────────────────── function readWindowState() { try { return sanitizeWindowState(JSON.parse(fs.readFileSync(DESKTOP_WINDOW_STATE_PATH, 'utf8'))) } catch { return null } } // Persist the window's restored (non-maximized) bounds plus its maximized flag. // getNormalBounds() keeps the pre-maximize size, so un-maximizing next session // lands back where the user actually sized the window. While fullscreen, // getNormalBounds() reports the fullscreen bounds with isMaximized=false — the // broken transition behind #94319 — so record that provenance and let recovery // on the next launch recognize the snapshot instead of guessing from geometry. function persistWindowState() { if (!mainWindow || mainWindow.isDestroyed() || mainWindow.isMinimized() || isAppSized(mainWindow)) { return } try { const { x, y, width, height } = mainWindow.getNormalBounds() fs.mkdirSync(path.dirname(DESKTOP_WINDOW_STATE_PATH), { recursive: true }) writeFileAtomic( DESKTOP_WINDOW_STATE_PATH, JSON.stringify( { x, y, width, height, isMaximized: mainWindow.isMaximized(), boundsCapturedFullScreen: mainWindow.isFullScreen() }, null, 2 ) ) } catch (err) { rememberLog(`[window-state] persist failed: ${err?.message || err}`) } } // move/resize fire many times mid-drag; debounce to one write. const schedulePersistWindowState = debounce(persistWindowState, 250) // Zoom's primary store is a main-process JSON file. The renderer localStorage // mirror lives under Electron's cache/storage folders, which crash recovery // can move or recreate — wiping the zoom setting exactly when the user just // recovered from a crash (#56726). JSON survives; localStorage is kept as a // secondary mirror so pre-JSON installs migrate transparently on first read. const DESKTOP_ZOOM_STATE_PATH = path.join(app.getPath('userData'), 'zoom-state.json') function readZoomState() { try { const raw = JSON.parse(fs.readFileSync(DESKTOP_ZOOM_STATE_PATH, 'utf8')) const level = Number(raw?.zoomLevel) return Number.isFinite(level) ? level : null } catch { return null } } function writeZoomState(zoomLevel) { try { fs.mkdirSync(path.dirname(DESKTOP_ZOOM_STATE_PATH), { recursive: true }) writeFileAtomic(DESKTOP_ZOOM_STATE_PATH, JSON.stringify({ zoomLevel }, null, 2)) } catch (error) { rememberLog(`[zoom] json persist failed: ${error?.message || error}`) } } // Match the backend's source resolution but bias toward a real git checkout. // Dev → SOURCE_REPO_ROOT. Packaged/CLI install → ACTIVE_HERMES_ROOT. // HERMES_DESKTOP_HERMES_ROOT always wins so devs can pin a worktree. function resolveUpdateRoot() { const candidates = [ process.env.HERMES_DESKTOP_HERMES_ROOT && path.resolve(process.env.HERMES_DESKTOP_HERMES_ROOT), !IS_PACKAGED && isHermesSourceRoot(SOURCE_REPO_ROOT) ? SOURCE_REPO_ROOT : null, isHermesSourceRoot(ACTIVE_HERMES_ROOT) ? ACTIVE_HERMES_ROOT : null ].filter(Boolean) return candidates.find(isGitCheckout) || candidates[0] || ACTIVE_HERMES_ROOT } function emitUpdateProgress(payload) { const merged = { stage: 'idle', message: '', percent: null, error: null, ...payload, at: Date.now() } rememberLog(`[updates] ${merged.stage}: ${merged.message || merged.error || ''}`) desktopMetrics.noteUpdateProgress(merged.stage) for (const window of BrowserWindow.getAllWindows()) { window.webContents.send('hermes:updates:progress', merged) } } async function checkUpdates(opts: { force?: boolean } = {}): Promise { // A packaged install delegates to the update owner named by its stamp. let strategy: UpdaterStrategy | null = null try { strategy = await resolvePackagedUpdateStrategy() if (strategy) { return await strategy.check(opts) } } catch (error) { return { supported: true, mechanism: strategy?.mechanism, error: 'check-failed', message: error instanceof Error ? error.message : String(error), fetchedAt: Date.now() } } // Checkout install: dispatch through the strategy layer — one mechanism, // one stamp, no direct body path. The flow lives in updater/checkout.ts; // this is the only production door to the checkout arms. return resolveCheckoutUpdateStrategy().check(opts) } let updateInFlight = false // ── bundled / App Installer helpers ───────────────────────────────────────── /** * Keep the native updater instance alive across check, download and install. * Its identity comes from the packaged app, not its optional Python payload. */ const updateOperation: UpdateOperation = new UpdateOperation(createPackagedUpdateStrategy) const desktopMetrics: DesktopSharedMetrics = registerDesktopSharedMetrics() function resolvePackagedUpdateStrategy(): Promise { return updateOperation.resolve() } async function createPackagedUpdateStrategy(): Promise { const mechanism = resolveUpdaterMechanism({ platform: process.platform, updateMechanism: INSTALL_STAMP?.updateMechanism, source: INSTALL_STAMP?.source }) if (mechanism === 'windows-handoff' || mechanism === 'posix-handoff') { return null } if (INSTALL_STAMP?.channelBuild && (mechanism === 'electron-updater' || mechanism === 'app-installer')) { const build = INSTALL_STAMP.channelBuild const installed = await inspectRunningChannelApp(build) // Platform/arch/signing are the channel's own preconditions. The Python // payload is not: electron-updater swaps the .app without it, and the // darwin Light channel build ships none (write-build-stamp.mjs). The // strategy that consumes the payload (app-installer) demands it itself. if ( (process.platform !== 'darwin' && process.platform !== 'win32') || (process.arch !== 'arm64' && process.arch !== 'x64') ) { throw new Error('Channel updates require a supported packaged application') } return new ChannelStrategy({ build, mechanism, resolver: new ChannelResolver({ build, platform: process.platform, arch: process.arch, signer: installed.signer }), nativeFactory: (target: ChannelTarget): UpdaterStrategy => createNativePackagedStrategy(mechanism, target) }) } return createNativePackagedStrategy(mechanism) } function createNativePackagedStrategy( mechanism: UpdaterStrategy['mechanism'], target?: ChannelTarget ): UpdaterStrategy { if (mechanism === 'electron-updater') { const deps: Parameters[0] = { channel: resolveUpdaterChannelFromStamp(), light: isLightVariant(), feedBaseUrl: resolveDesktopFeedBaseUrl(), appVersion: app.getVersion(), log: rememberLog, emitProgress: emitUpdateProgress, beforeInstall: teardownBundledBackend, onInstallFailure: restoreBundledBackend } return target ? createChannelMacStrategy(deps, target) : createMacStrategy(deps) } if (mechanism === 'app-installer') { const payload: PayloadInfo = requireBundledPayload(mechanism) const deps: ConstructorParameters[0] = { python: payload.storePython, // The checker is bundled core code, run with the payload python. module: 'hermes_cli.windows_appinstaller_update', run: (python, module) => runAppInstallerChecker(python, module, { env: { ...process.env, PYTHONPATH: payloadPythonPath(payload) }, onStderr: stderr => console.error(`[app-installer] checker stderr: ${stderr.slice(0, 400)}`) }), channel: resolveUpdaterChannelFromStamp(), light: isLightVariant(), feedBaseUrl: resolveDesktopFeedBaseUrl(), installer: { prepare: url => stageAppInstallerFile(url, path.join(app.getPath('userData'), 'updates')), open: file => shell.openPath(file) }, teardownBundledBackend, restoreBundledBackend, emitUpdateProgress, appVersion: INSTALL_STAMP?.channelBuild?.windowsVersion ?? app.getVersion(), quit: () => app.quit(), registerPendingRelaunch: (fromVersion: string): Promise => registerUpdateRelaunch(app, fromVersion, { // The relaunch mechanism: a detached waiter, external to the dying // process. It snapshots the OLD package, signals the handshake, // waits for this process to exit and for the OS to swap the // installed package version, then activates the NEW package. // Electron's app.relaunch would re-execute the OLD package's // binary and can hold the swap open, so it is not used. The // script is staged to a temp dir and resolved absolutely so // nothing inherited from the package holds the swap open. relaunch: () => startUpdateRelaunchWaiter(PRODUCT_IDENTITY.msixAppIdWithOrg, process.resourcesPath, rememberLog) }) } return target ? createChannelAppInstallerStrategy(deps, target, verifyPreparedChannelInstaller) : new AppInstallerStrategy(deps) } if (mechanism === 'microsoft-store') { const payload: PayloadInfo = requireBundledPayload(mechanism) return createStoreStrategy({ python: payload.storePython, module: 'hermes_cli.windows_store_update', pythonPath: payloadPythonPath(payload), env: process.env, windowHandle: () => (BrowserWindow.getFocusedWindow() ?? mainWindow)?.getNativeWindowHandle() ?? null, appVersion: app.getVersion(), teardown: teardownBundledBackend, restore: restoreBundledBackend, emitProgress: emitUpdateProgress, quit: () => app.quit(), registerPendingRelaunch: (fromVersion: string): Promise => registerUpdateRelaunch(app, fromVersion, { relaunch: () => startUpdateRelaunchWaiter( PRODUCT_IDENTITY.storeMsix!.identityName, process.resourcesPath, rememberLog, 1860 ) }) }) } return new ExternalStrategy(INSTALL_STAMP) } /** * The bundled Python payload for a strategy whose update check runs inside * it. A stamp that names such a mechanism without a payload is a broken * install; say so instead of failing on `payload.storePython`. */ function requireBundledPayload(mechanism: UpdaterStrategy['mechanism']): PayloadInfo { const payload: PayloadInfo | null = bundledPayload(process.resourcesPath) if (!payload) { throw new Error(`${mechanism} updates require the bundled application payload, which this install has none of`) } return payload } /** * The checkout updater strategy (windows-handoff / posix-handoff). The flow * lives in updater/checkout.ts; this is the composition root that hands it * the app shell's impure edges. The public checkUpdates/applyUpdates * entrypoints dispatch only through this strategy — there is no other * production path to the checkout arms. */ function resolveCheckoutUpdateStrategy(): CheckoutStrategy { return createCheckoutStrategy({ hermesHome: HERMES_HOME, isWindows: IS_WINDOWS, isMac: IS_MAC, defaultUpdateBranch: DEFAULT_UPDATE_BRANCH, updateHandoffDwellMs: UPDATE_HANDOFF_DWELL_MS, readSourceUpdate: async ( updateRoot: string, opts: { force?: boolean; setChannel?: 'main' | 'stable' } ): Promise => readSourceUpdate({ python: await findPythonForRoot(updateRoot), git: resolveGitBinary(), updateRoot, hermesHome: HERMES_HOME, branchConfigPath: DESKTOP_UPDATE_CONFIG_PATH, force: opts.force, setChannel: opts.setChannel }), resolveUpdateRoot, resolveUpdaterBinary, remoteGatewayActive: globalRemoteActive, emitUpdateProgress, rememberLog, startHermes, stopBackendsForUpdate, repairMacUpdaterHelper: updater => repairMacUpdaterHelper(updater, { isMac: IS_MAC, log: rememberLog }), preflightStateDb: async (home: string, log: (message: string) => void): Promise => { const root: string = resolveUpdateRoot() // `updates.pre_update_backup: off` is the CLI's opt-out for the whole // pre-update backup family; the Desktop's emergency snapshot honours it // too (4de06d1dbf7b). An unreadable answer keeps the snapshot. if ( !(await readPreUpdateBackupEnabled( resolveHermesBackend(['config', 'get', 'updates.pre_update_backup', '--json']), home )) ) { log('[updates] emergency state.db backup disabled by updates.pre_update_backup') return } // PM-managed checkouts carry no venv of their own: the installation // launcher owns interpreter and generation selection there — same // contract as readSourceUpdate and the hand-off script. const managed: boolean = directoryExists(path.join(root, 'pm')) const launcher: string | null = managed ? resolveInstallationLauncher(root, IS_WINDOWS, HERMES_HOME) : null if (managed && !launcher) { const message = `state.db pre-flight failed: the installation launcher under ${root} is missing. ` + 'Update cancelled before backend shutdown. Repair this installation before retrying.' log(`[updates] ${message}`) throw new Error(message) } preflightStateDb({ python: managed ? null : await findPythonForRoot(root), launcher, script: path.join(root, 'hermes_cli', 'backup_sqlite.py'), home, log }) }, runningAppBundle, markQuittingForHandoff: () => { isQuittingForHandoff = true }, quit: () => app.quit() }) } /** * The App Installer feed base URL for a bundled MSIX install: config.yaml's * `updates.desktop_feed_base_url`, else Windows' registered App Installer * source. */ function resolveDesktopFeedBaseUrl(): string { return resolveFeedBaseUrl(readUpdatesFeedBaseFromConfig(path.join(HERMES_HOME, 'config.yaml'))) } /** The updater channel from the baked install stamp ('canary' vs 'stable'). */ function resolveUpdaterChannelFromStamp(): string { return packagedReleaseChannel(INSTALL_STAMP) ?? 'stable' } /** True when this artifact is the light (remote-only) variant. */ function isLightVariant(): boolean { return INSTALL_STAMP?.payload === 'light' } /** Invalidate connections and wait for every owned backend before the swap. */ async function teardownBundledBackend(): Promise { isQuittingForHandoff = true const results = await Promise.allSettled([ teardownPrimaryBackendAndWait(backendTeardownOptions('reconnect')), stopAllPoolBackends() ]) const errors = results.filter(result => result.status === 'rejected').map(result => result.reason) if (errors.length) { // An incomplete shutdown blocks replacement until a retry proves exit. backendStartFailure = new AggregateError(errors, 'Backend shutdown failed') throw backendStartFailure } } async function restoreBundledBackend(): Promise { try { // A failed stop retains its process handle. Retry before enabling a new start. await teardownBundledBackend() } finally { isQuittingForHandoff = false updateInFlight = false } backendStartFailure = null await startHermes() } // Set to true when the desktop is about to quit so a detached swap/install/ // uninstall script can take over. On macOS, app.quit() closes windows but // window-all-closed deliberately keeps the process alive (standard Electron // macOS convention). Without this flag the process never exits — the detached // hand-off script spins its PID-wait for the full timeout, and the user sees a // blank app with no window (and an uninstall that appears to do nothing). When // set, window-all-closed calls app.quit() on every platform so the process // actually dies and the hand-off script can proceed immediately. let isQuittingForHandoff = false // Quit-guard latches: one while the confirmation is on screen (a second // Cmd-Q must not stack dialogs), one after the user has said "quit anyway" // (the app.quit() that follows re-enters before-quit and must pass through). let quitPromptOpen = false let quitConfirmedWithActiveWork = false // Resolve the staged updater binary the desktop may hand an update to. On // Windows that binary owns ALL repo mutation — running `hermes update` + // rebuilding the desktop — so the desktop never touches its own bits while // running. macOS/Linux stage the same binary but deliberately do not use it; // see resolveStagedUpdaterBinary for the policy and for #74836. Returns null // whenever no hand-off applies; callers degrade gracefully. function resolveUpdaterBinary() { return resolveStagedUpdaterBinary(HERMES_HOME, { fileExists, isWindows: IS_WINDOWS }) } // Path to the venv shim whose lock decides whether `hermes update` can write // fresh entry points. On Windows this is the file the running backend // `hermes.exe` holds open; on POSIX it's never mandatory-locked. function venvHermesShimPath(updateRoot) { const venvDir = resolveVenvDir(updateRoot) return IS_WINDOWS ? path.join(venvDir, 'Scripts', 'hermes.exe') : path.join(venvDir, 'bin', 'hermes') } // Best-effort lock probe mirroring the Rust updater's is_locked(): a running // .exe on Windows refuses an O_RDWR open with a sharing violation. On POSIX // this practically always succeeds (no mandatory locking), so it returns false // — correct, since the shim-contention brick is Windows-only. function isShimLocked(shimPath) { if (!IS_WINDOWS) { return false } let fd try { fd = fs.openSync(shimPath, 'r+') return false } catch (err) { // ENOENT ⇒ not there ⇒ nothing locking it. Anything else (EBUSY/EPERM/ // EACCES) on Windows means a live handle holds it. return err && err.code !== 'ENOENT' } finally { if (fd !== undefined) { try { fs.closeSync(fd) } catch { void 0 } } } } // Kill only Hermes-OWNED venv daemons (the memory plugin's hindsight daemon: // exe under venv\Scripts AND cmdline referencing hindsight_api.main). The // daemon is spawned DETACHED, so it outlives the backend tree-kill and keeps // venv files mapped. External holders (a user terminal running `hermes`, // unrelated scripts) are NOT killed. The uninstall lock probe refuses a // held installation. Selection lives in the pure // venv-holder-select module (ordinal path-prefix, no PowerShell -like // wildcard hazards) so it's testable without Electron. function scanWindowsProcesses(): Array<{ ProcessId?: unknown; ExecutablePath?: string; CommandLine?: string }> { const out = execFileSync( 'powershell', [ '-NoProfile', '-Command', 'Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.CommandLine } | Select-Object ProcessId, ExecutablePath, CommandLine | ConvertTo-Json -Compress' ], hiddenWindowsChildOptions({ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15_000 }) ) const parsed = JSON.parse(String(out || '[]')) return Array.isArray(parsed) ? parsed : [parsed] } function killHermesOwnedVenvDaemons(updateRoot) { if (!IS_WINDOWS) { return } const scriptsDir = path.join(resolveVenvDir(updateRoot), 'Scripts') let holders = [] try { holders = scanWindowsProcesses().filter(p => isHermesOwnedVenvDaemon(p?.ExecutablePath, p?.CommandLine, scriptsDir)) } catch { // Best-effort: the uninstall lock probe remains the backstop. return } for (const holder of holders) { const pid = Number(holder?.ProcessId) if (Number.isInteger(pid) && pid > 0) { rememberLog(`[updates] stopping Hermes-owned venv daemon (hindsight) PID ${pid} before hand-off`) try { forceKillProcessTree(pid) } catch (error) { // Update hand-off only. Close/stop must not swallow this; see // windowsCloseStopOwnedBackends. rememberLog(`[updates] taskkill PID ${pid} failed: ${error instanceof Error ? error.message : String(error)}`) } } } } // Kill EXTERNAL Hermes processes that hold this install's venv shim (#62311): // the gateway Startup item and dashboard Scheduled Task are launched outside // this app (Task Scheduler / autostart), so the backend teardown above never // sees them — yet they map venv files and made every update hand-off abort // with "venv shim still locked". Selection is deliberately narrow // (isExternalVenvHolder: exe under venv\Scripts AND unambiguously a Hermes // program) — unrelated processes that merely mention the install root or use // the venv interpreter for their own scripts are never killed; the shim-lock // probe still aborts the hand-off for those. Called before the release gate // AND inside each gate pass, so a respawning autostart holder is re-killed // instead of winning the 15s race. function killExternalVenvHolders(updateRoot) { if (!IS_WINDOWS) { return } const scriptsDir = path.join(resolveVenvDir(updateRoot), 'Scripts') let holders = [] try { holders = scanWindowsProcesses().filter(p => isExternalVenvHolder(p?.ExecutablePath, p?.CommandLine, scriptsDir)) } catch { // Best-effort: the shim-lock probe remains the backstop. return } for (const holder of holders) { const pid = Number(holder?.ProcessId) if (Number.isInteger(pid) && pid > 0) { rememberLog( `[updates] stopping external Hermes venv holder (autostart gateway/dashboard) PID ${pid} before hand-off` ) try { forceKillProcessTree(pid) } catch (error) { rememberLog(`[updates] taskkill PID ${pid} failed: ${error instanceof Error ? error.message : String(error)}`) } } } } // Force-kill the entire process TREE rooted at each PID. Node's child.kill() // only signals the direct child, so on Windows a backend `hermes.exe` that // spawned its own grandchildren (a `hermes` REPL, a pty terminal session, the // gateway) would survive and keep the venv shim locked. taskkill /T /F reaps // the whole tree synchronously. The command is not widened: one owned PID, // /T /F, nothing else. Failures propagate — close/stop must not discard them. // Windows-only: this is called solely from the Windows shim-unlock and // close/stop paths, and the backend is NOT spawned detached (so it's not a // process-group leader — a POSIX negative-pgid kill would be meaningless // here anyway). POSIX teardown stays with the existing before-quit SIGTERM. function forceKillProcessTree(pid) { if (!IS_WINDOWS) { return } if (!Number.isInteger(pid) || pid <= 0) { return } execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], hiddenWindowsChildOptions({ stdio: 'ignore' })) } function holderPidsFromLockFile(lockPath: string): Pick { try { const raw = fs.readFileSync(lockPath, 'utf8').trim() if (!raw) { return { holderPids: [] } } let pid = Number(raw) if (!Number.isInteger(pid)) { const parsed = JSON.parse(raw) as { pid?: unknown } pid = Number(typeof parsed === 'object' && parsed ? parsed.pid : parsed) } return Number.isInteger(pid) && pid > 0 ? { holderPids: [pid] } : { holderPids: [] } } catch (error) { const code = (error as NodeJS.ErrnoException | null)?.code // Can't read the file: a live holder may be why. Do not clear it. if (code === 'EBUSY' || code === 'EPERM' || code === 'EACCES') { return { holderPids: [], held: true } } return { holderPids: [] } } } function collectCloseStopLocks(): RuntimeLock[] { const roots = [HERMES_HOME] const profilesRoot = path.join(HERMES_HOME, 'profiles') try { for (const name of fs.readdirSync(profilesRoot)) { roots.push(path.join(profilesRoot, name)) } } catch { // No profiles directory — the default home lock is enough. } const locks: RuntimeLock[] = [] for (const root of roots) { const lockPath = path.join(root, 'gateway.lock') try { if (!fs.statSync(lockPath).isFile()) { continue } } catch { continue } locks.push({ path: lockPath, ...holderPidsFromLockFile(lockPath) }) } return locks } // Captured before teardown drops the handles. Node keeps each process handle // open until exit is observed, so a PID read from a still-running child here // cannot have been reused by an unrelated process. function collectOwnedBackendChildren(): ChildProcess[] { const children = [backendConnectionState.getProcess(), ...[...backendPool.values()].map(entry => entry?.process)] return children.filter( (child): child is ChildProcess => Boolean(child) && Number.isInteger(child.pid) && child.pid > 0 ) } // Close/stop, after the graceful teardown, pool stop and straggler reap: the // same tree-kill for any owned child that is still running, an inventory of // those PIDs, and a clear of only the locks no live holder owns. Never throws; // returns the failure for the caller to surface once cleanup is done. function windowsCloseStopOwnedBackends(children: ChildProcess[]): Error | null { if (!IS_WINDOWS) { return null } try { const running = children.filter(child => child.exitCode === null && child.signalCode === null) const result = finishWindowsCloseStop( running.map(child => child.pid as number), collectCloseStopLocks(), { killTree: forceKillProcessTree, isPidAlive: isPidAliveWindows, clearLock: lockPath => { fs.rmSync(lockPath, { force: true }) } } ) for (const failure of result.taskkillFailures) { rememberLog(`[close-stop] taskkill PID ${failure.pid} failed: ${failure.error}`) } for (const failure of result.lockErrors) { rememberLog(`[close-stop] could not clear unheld lock ${failure.path}: ${failure.error}`) } if (result.clearedLocks.length) { rememberLog(`[close-stop] cleared unheld lock(s): ${result.clearedLocks.join(', ')}`) } return result.liveFailure ? new Error(closeStopFailureMessage(result)) : null } catch (error) { return error instanceof Error ? error : new Error(String(error)) } } function writeBackendOwnership(contents) { fs.mkdirSync(path.dirname(DESKTOP_BACKEND_OWNERSHIP_PATH), { recursive: true }) const tempPath = `${DESKTOP_BACKEND_OWNERSHIP_PATH}.${process.pid}.tmp` try { fs.writeFileSync(tempPath, contents, { encoding: 'utf8', mode: 0o600 }) fs.renameSync(tempPath, DESKTOP_BACKEND_OWNERSHIP_PATH) } finally { try { fs.rmSync(tempPath, { force: true }) } catch { void 0 } } } // execText and processStartMarker moved to backend-claim.ts (#93608) so the // claim/probe policy is testable — including on Windows CI with real // PowerShell — without booting Electron. main.ts calls through the module. async function backendCommandForPid(pid) { try { const command = IS_WINDOWS ? 'powershell.exe' : 'ps' const args = IS_WINDOWS ? [ '-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').CommandLine` ] : ['-p', String(pid), '-o', 'command='] return (await execText(command, args)) || null } catch { return null } } async function processIdentityMatches(identity, timeoutMs: number = 30_000) { // Degraded PID-only identity (#93608): the start-marker probe failed while // the child was verifiably alive, so only PID liveness can be checked here. // backendIdentityMatches layers the command-line check on top before // anything destructive relies on the answer. if (isPidOnlyStartMarker(identity.startMarker)) { try { process.kill(identity.pid, 0) return true } catch (error) { const code = (error as NodeJS.ErrnoException | null)?.code return code === 'ESRCH' || code === 'ENOENT' ? false : code === 'EPERM' ? true : undefined } } try { return (await processStartMarker(identity.pid, timeoutMs)) === identity.startMarker } catch (error) { return error?.code === 'ENOENT' || error?.code === 'ESRCH' ? false : undefined } } async function backendIdentityMatches(identity) { const processMatches = await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS) if (processMatches !== true) { return processMatches } const command = await backendCommandForPid(identity.pid) return command === null ? undefined : backendCommandMatches(command) } // True when the recorded parent Electron is still running (same PID AND start // marker); false when it is gone or its PID was reused; undefined when the // ownership record predates parent tracking. Undefined deliberately falls back // to the pre-parent reap behaviour so legacy orphan cleanup keeps working. async function backendParentMatches(entry) { if (!Number.isInteger(entry.parentPid) || typeof entry.parentStartMarker !== 'string' || !entry.parentStartMarker) { return undefined } try { return (await processStartMarker(entry.parentPid, REAP_PROBE_TIMEOUT_MS)) === entry.parentStartMarker } catch (error) { return error?.code === 'ENOENT' || error?.code === 'ESRCH' ? false : undefined } } async function stopOwnedBackend(identity) { const matches = await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS) if (matches === false) { return } if (matches !== true) { // Identity probe failed (not confirmed gone): preserve the record so a // later launch retries the stop instead of dropping it and leaking the // backend. reapOrphans keeps the entry when stop() throws. throw new Error(`Could not verify backend PID ${identity.pid} before stopping it.`) } if (IS_WINDOWS) { try { forceKillProcessTree(identity.pid) } catch (error) { const detail = error instanceof Error ? error.message : String(error) const stillThere = await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS) if (stillThere !== false) { throw new Error(`taskkill failed for backend PID ${identity.pid}: ${detail}`) } rememberLog(`taskkill reported failure for already-gone backend PID ${identity.pid}: ${detail}`) } } else { try { process.kill(-identity.pid, 'SIGTERM') } catch { try { process.kill(identity.pid, 'SIGTERM') } catch { return } } const deadline = Date.now() + 1500 while (Date.now() < deadline) { if ((await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS)) !== true) { return } await new Promise(resolve => setTimeout(resolve, 50)) } // Revalidate immediately before escalation so PID reuse cannot target a // replacement process. if ((await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS)) === true) { try { process.kill(-identity.pid, 'SIGKILL') } catch { process.kill(identity.pid, 'SIGKILL') } } } await new Promise(resolve => setTimeout(resolve, 50)) const remaining = await processIdentityMatches(identity, REAP_PROBE_TIMEOUT_MS) if (remaining !== false) { throw new Error(`Backend PID ${identity.pid} did not stop cleanly.`) } } const backendOwnership = createBackendOwnership({ matchesIdentity: backendIdentityMatches, matchesParent: backendParentMatches, stop: stopOwnedBackend, store: { read: () => { try { return fs.readFileSync(DESKTOP_BACKEND_OWNERSHIP_PATH, 'utf8') } catch { return null } }, write: writeBackendOwnership, // A corrupt ownership file is moved aside instead of being rewritten // away by the reap sweep — its records are the only pointer to any // still-running backends it described (#89298). quarantine: () => { const parked = `${DESKTOP_BACKEND_OWNERSHIP_PATH}.corrupt` try { fs.renameSync(DESKTOP_BACKEND_OWNERSHIP_PATH, parked) rememberLog(`Backend ownership file was unreadable; moved to ${parked}`) } catch { // Nothing to move (or no permission) — the sweep already skipped. } } } }) const desktopParentStartMarker = createParentStartMarkerResolver({ load: () => processStartMarker(process.pid), onError: error => { const detail = error instanceof Error ? error.message : String(error) rememberLog( `Could not resolve the Desktop process start marker; starting the backend with PID-only parent tracking: ${detail}` ) } }) async function claimBackendChild( child: ChildProcess & { hermesBackendIdentity?: BackendOwnershipEntry }, command: string, profile: string, nonce: string, outputTail: BackendOutputTail | null = null ): Promise { // Probe/claim policy lives in backend-claim.ts (#93608): a marker probe // that fails against a LIVE child degrades to PID-only identity — matching // createParentStartMarkerResolver — instead of killing a healthy backend // over a flaky Get-Process (PS 5.1 cold starts, #87169). Only a child that // actually died keeps the fail-closed throw, now carrying its stderr tail. const probe = await probeStartMarker(child.pid) const decision = claimDecision(child.exitCode === null && !child.killed, probe) if (decision.action === 'fail') { await localBackendLifecycle.stop(child) throw new Error( `Hermes backend (PID ${child.pid}) died before its identity could be recorded: ${decision.reason}${outputTail?.describe() ?? ''}` ) } let startMarker if (decision.action === 'degrade') { startMarker = pidOnlyStartMarker(child.pid) rememberLog( `WARNING: process start marker probe failed for live Hermes backend PID ${child.pid}; ` + `claiming with PID-only identity instead of stopping it: ${decision.reason}` ) } else { startMarker = decision.startMarker } try { const identity = await backendOwnership.claim({ command, nonce, pid: child.pid, profile, startMarker, // Record the spawning Electron so reapOrphans can tell an orphaned // backend (parent gone) from one owned by a live instance — a live // parent's backend is never reaped (#87295). parentPid: process.pid, parentStartMarker: await desktopParentStartMarker() }) child.hermesBackendIdentity = identity return identity } catch (error) { await localBackendLifecycle.stop(child) throw new Error( `Could not persist ownership for the Hermes backend: ${error.message}${outputTail?.describe() ?? ''}` ) } } function releaseBackendChild(child) { const identity = child?.hermesBackendIdentity if (!identity) { return } try { backendOwnership.release(identity) } catch (error) { rememberLog(`Could not release backend ownership for PID ${identity.pid}: ${error.message}`) } } function reapOrphanedBackendsOnce() { if (!backendOrphanReapPromise) { backendOrphanReapPromise = backendOwnership .reapOrphans() .then(pids => { if (pids.length) { rememberLog(`Reaped orphaned desktop backend PID(s): ${pids.join(', ')}`) } }) .catch(error => { backendOrphanReapPromise = null throw error }) } return backendOrphanReapPromise } // Stop app-owned Windows backends before replacing application outputs. // PM generations can retain live readers. Gateway draining/restart belongs to // `hermes update`; neither venv scans nor a second fleet stop belong here. async function stopBackendsForUpdate(): Promise { if (IS_WINDOWS) { await Promise.all([teardownPrimaryBackendAndWait(backendTeardownOptions('reconnect')), stopAllPoolBackends()]) } } // Uninstall still deletes the installation and its historical venv. Unlike // generation updates, deletion must wait for those old files to be released. async function releaseBackendLock(updateRoot: string, tag: string): Promise<{ unlocked: boolean }> { if (!IS_WINDOWS) { return { unlocked: true } } const hermesProcess = backendConnectionState.getProcess() // Seed the release gate with every PID we are about to signal: the // supervised primary backend and all pool backends. The gate waits for // these to actually LEAVE the process table, not just for the shim to // unlock — the shim probe only covers venv\Scripts\hermes.exe, but the // backend is `python.exe -m hermes_cli.main serve`, which need not hold // the shim at all (#74805 first-attempt race). const initialPids = [] if (hermesProcess && Number.isInteger(hermesProcess.pid)) { initialPids.push(hermesProcess.pid) } for (const entry of backendPool.values()) { if (entry.process && Number.isInteger(entry.process.pid)) { initialPids.push(entry.process.pid) } } // No backend comes back after an uninstall: stay silent, like a quit. await Promise.all([teardownPrimaryBackendAndWait(backendTeardownOptions('quit')), stopAllPoolBackends()]) // Uninstall deletes the whole runtime. Drain separately-running gateways // through the CLI, rather than targeting a gateway worker by PID. stopGatewayBeforeUpdate(venvHermesShimPath(updateRoot), HERMES_HOME) // Reap Hermes-OWNED venv daemons the tree-kill above cannot reach: the // memory plugin's hindsight daemon is spawned DETACHED (it outlives the // backend) yet runs off venv\Scripts\pythonw.exe, keeping venv files // mapped past the backend teardown (#75477/#75478). Narrowly scoped // (venv-holder-select) — external holders are never killed here. killHermesOwnedVenvDaemons(updateRoot) // External autostart Hermes processes (gateway Startup item, dashboard // Scheduled Task) also hold the venv shim and are invisible to the backend // teardown (#62311). Kill them before the gate AND re-scan inside each gate // pass, so a respawning holder loses the race instead of the update. killExternalVenvHolders(updateRoot) const shim = venvHermesShimPath(updateRoot) const gate = await waitForBackendRelease( initialPids, { isShimLocked: () => Boolean(isShimLocked(shim)), isPidAlive: isPidAliveWindows, collectStragglerPids: () => { // Re-kill resurgent external holders (autostart gateway/dashboard) on // every pass — #62311 — before collecting the desktop-owned stragglers. killExternalVenvHolders(updateRoot) const stragglers = [] const currentHermesProcess = backendConnectionState.getProcess() if (currentHermesProcess && Number.isInteger(currentHermesProcess.pid)) { stragglers.push(currentHermesProcess.pid) } for (const entry of backendPool.values()) { if (entry.process && Number.isInteger(entry.process.pid)) { stragglers.push(entry.process.pid) } } return stragglers }, killProcessTree: pid => { try { forceKillProcessTree(pid) } catch (error) { rememberLog(`[${tag}] taskkill PID ${pid} failed: ${error instanceof Error ? error.message : String(error)}`) } }, sleep: (ms: number) => new Promise(r => setTimeout(r, ms)), now: () => Date.now(), log: rememberLog }, tag ) if (gate.unlocked) { return { unlocked: true } } // Do NOT proceed past a held lock: handing off to the updater while another // process (a second desktop window, a user terminal, an unkillable child) // still maps the venv's files guarantees a half-updated venv — the updater's // dependency sync dies on access-denied partway through uninstalls, leaving // imports broken (the July 2026 brotlicffi/_sodium.pyd incidents). Failing // the update loudly and keeping the app running is strictly better than a // bricked install that needs manual venv surgery. rememberLog( `[${tag}] venv shim still locked after 15s; aborting hand-off (something outside this app holds the venv)` ) return { unlocked: false } } // applyUpdates — hand off to the installer's --update flow, then exit. // // The desktop is a pure consumer: it does NOT git pull / pip install / rebuild // itself (the old open-coded git dance lived here and drifted from // `hermes update`). Instead we spawn the staged Hermes-Setup binary with // --update and quit, so it can run `hermes update` (which refuses while we // hold the venv shim) and rebuild the desktop with our exe already gone. // // Detection (checkUpdates / commit changelog / "N behind") stays in the UI; // only this apply action changed. async function applyUpdates(): Promise { return updateOperation.apply(async (): Promise => { updateInFlight = true let handedOff: boolean = false try { // The local handoff asks the window to exit and the update scripts only // wait so long for that PID — never start that deadline while quit would // still be gated on a managed SSH update or its recovery transaction // (before-quit joins the same operations; the updater must not race them). // Bounded (review H3): a refusal leaves the remote operations running. const managedBusy = await joinManagedUpdatesForApply( () => [...managedConnectionUpdates.values(), ...managedConnectionRecoveries.values()], rememberLog ) if (managedBusy) { return managedBusy } const packaged: UpdaterStrategy | null = await resolvePackagedUpdateStrategy() const strategy: UpdaterStrategy = packaged ?? resolveCheckoutUpdateStrategy() const result: UpdaterApplyResultWire = await desktopMetrics.trackUpdateApply(packaged, strategy) handedOff = result.handedOff === true return result } finally { if (!handedOff) { updateInFlight = false } } }) } async function handOffWindowsBootstrapRecovery(reason) { if (!IS_WINDOWS || !IS_PACKAGED) { return false } // A bundled install does not own %LOCALAPPDATA%\hermes — the updater // would try to heal a tree the app never created. The payload IS the // runtime; recovery means reinstalling the app, not spawning the // updater. (ensureRuntime's bundled guard also short-circuits before // this call; this is the belt-and-suspenders check.) if (installShape() === 'bundled') { rememberLog('[bootstrap] refusing updater recovery hand-off on a bundled install; reinstall the app') return false } const updater = resolveUpdaterBinary() if (!updater) { return false } const handoffConflict = await updateHandoffConflict(HERMES_HOME) if (handoffConflict) { // Same hazard as applyUpdates (#75778): a live foreign updater already // owns the marker. Spawning another here would overwrite its claim and // race a second updater over the same install tree. The live updater // is already working on this exact install and will restart us when // it finishes, so treat this the same as a successful hand-off instead // of clobbering it with our own. rememberLog(`[bootstrap] refusing recovery hand-off: ${handoffConflict.message}`) isQuittingForHandoff = true setTimeout(() => { app.quit() }, UPDATE_HANDOFF_DWELL_MS) return true } const updateRoot = resolveUpdateRoot() const { branch: configuredBranch } = readDesktopUpdateConfig() // Recovery can run without Python. Keep the chosen branch; do not guess a replacement. const branch: string = configuredBranch || DEFAULT_UPDATE_BRANCH const updaterArgs: string[] = chooseUpdaterArgs({ runtimeUsable: await isSourceRuntimeUsable(updateRoot) }, branch) await stopBackendsForUpdate() const child = spawnUpdaterProcess(updater, updaterArgs, { cwd: HERMES_HOME, env: { ...process.env, HERMES_HOME, HERMES_INSTALL_ROOT: updateRoot }, detached: true, stdio: 'ignore' }) // Same marker pre-write as applyUpdates — see comment there. The recovery // hand-off has the same window where the renderer can respawn a backend // before the updater writes its own marker, and the same stale-updater // exclusion: a pre-#74782 binary would refuse its own pre-written claim and // strand the very recovery meant to heal the install. // // Exclusive create only (A7 rule 3): over any existing marker the pre-write // is skipped — the staged updater claims (and reclaims) for itself. if (Number.isInteger(child.pid) && stagedUpdaterSupportsPrewrittenMarker(updater)) { const prewrite = await writeUpdateMarker(HERMES_HOME, child.pid) if (!prewrite.ok) { rememberLog(`[bootstrap] skipping marker pre-write: ${describeSkippedPrewrite(prewrite)}`) } } else if (Number.isInteger(child.pid)) { rememberLog( `[bootstrap] skipping marker pre-write: staged updater predates self-adopt (${updater}); it would refuse its own claim` ) } rememberLog( `[bootstrap] handed off ${reason} recovery to updater: ${updater} ${updaterArgs.join(' ')}; exiting desktop to release app.asar` ) // Same dwell as the in-app update hand-off (#50419): give the updater's // window time to appear before we vanish, so the recovery doesn't look like // a crash and provoke a mid-recovery relaunch. The dwell doubles as the // hand-off settle window (#66753): a spawn error or early updater death // returns false so the caller falls through to its next recovery path // instead of quitting into nothing. const dwellStartedAt = Date.now() const handoffOutcome = await observeUpdaterHandoff(child, UPDATE_HANDOFF_DWELL_MS) if (!handoffOutcome.ok) { rememberLog(`[bootstrap] recovery hand-off not viable, staying alive: ${handoffOutcome.message}`) return false } isQuittingForHandoff = true setTimeout( () => { app.quit() }, Math.max(0, UPDATE_HANDOFF_DWELL_MS - (Date.now() - dwellStartedAt)) ) return true } // The running app's .app bundle (packaged macOS): execPath is // .app/Contents/MacOS/; climb three levels to the bundle root. function runningAppBundle() { if (!IS_MAC) { return null } let dir = path.dirname(app.getPath('exe')) // .../Contents/MacOS for (let i = 0; i < 2; i++) { dir = path.dirname(dir) } // -> .../X.app return dir.endsWith('.app') ? dir : null } // macOS/Linux update hand-off: spawn the repo-owned posix orchestrator // (scripts/desktop-update/posix.sh) detached and QUIT. The script waits us // out, runs `hermes update`, swaps/relaunches the app bundle, and writes // .hermes-update-result.json for the relaunched Desktop to surface. It shows // its own tiny shim window (or nothing, headless) — this process only needs // to leave. Checkouts that predate the script get the manual card once. function readJson(filePath) { try { return JSON.parse(fs.readFileSync(filePath, 'utf8')) } catch { return null } } // Bootstrap-complete marker helpers. The marker is written by whichever // installer ran: install.ps1, install.sh, the Rust bootstrap installer, or the // first-launch bootstrap runner. It is provenance ("a bootstrap finished // here"), NOT the launch gate -- activeRuntimeState() decides that, because a // healthy runtime can predate the marker or outlive a repair that cleared it. // // Marker schema (version 1): // { // schemaVersion: 1, // pinnedCommit: "<40-char SHA>", // what install.ps1 was driven against // pinnedBranch: "" | null, // completedAt: "", // desktopVersion: "" // for forensics // } function readBootstrapMarker() { return readJson(BOOTSTRAP_COMPLETE_MARKER) } // Marker-independent: is the canonical install at ACTIVE_HERMES_ROOT actually // runnable right now? A complete CLI install (`install.sh --include-desktop`) // or a DMG launch over a prior CLI install satisfies this WITHOUT the desktop // ever having written the bootstrap marker -- so we must be able to recognise // "already installed" off the filesystem alone, not just the marker. async function isSourceRuntimeUsable(root: string): Promise { return (await resolveSourceInstallationBackend(root, [], { hermesHome: HERMES_HOME })) !== null } function activeRuntimeState(backend: SourceBackend | null): ActiveRuntimeState { // We DELIBERATELY do NOT verify that the checkout is currently at the // pinned commit -- users update via the in-app update path or `hermes // update`, which moves HEAD legitimately. The marker only attests "a // desktop-managed bootstrap ran here at least once"; runtime usability is // what decides whether we can actually launch. const state: ActiveRuntimeState = classifyActiveRuntime( readBootstrapMarker(), BOOTSTRAP_MARKER_SCHEMA_VERSION, backend !== null ) // The canonical install stamp (written next to the runtime by the bootstrap) // tells the UI where this runtime came from. Prefer it over the marker so // the Runtime row reflects the actual install provenance. state.canonicalInstallStamp = readCanonicalInstallStamp() return state } /** Read the checkout-owned install stamp in the canonical runtime root * (`ACTIVE_HERMES_ROOT/install-stamp.json`), written by the Python * completion tail. Returns null when absent or unreadable. */ function readCanonicalInstallStamp() { try { const raw = fs.readFileSync(path.join(ACTIVE_HERMES_ROOT, 'install-stamp.json'), 'utf8') const parsed = JSON.parse(raw) if (parsed && typeof parsed === 'object' && typeof parsed.source === 'string') { return parsed } return null } catch { return null } } function writeBootstrapMarker(payload) { fs.mkdirSync(path.dirname(BOOTSTRAP_COMPLETE_MARKER), { recursive: true }) const merged = { schemaVersion: BOOTSTRAP_MARKER_SCHEMA_VERSION, pinnedCommit: payload.pinnedCommit || null, pinnedBranch: payload.pinnedBranch || null, completedAt: new Date().toISOString(), desktopVersion: app.getVersion() } writeFileAtomic(BOOTSTRAP_COMPLETE_MARKER, JSON.stringify(merged, null, 2) + '\n', 'utf8') // The checkout's own install stamp is written by the Python completion tail // (hermes_cli/source_completion.py) during the products stage, from the // checkout itself. The desktop never synthesizes it: the checkout is the // authority for its runtime identity, and a desktop-written copy would // clobber the completion tail's richer provenance. return merged } function resolveWebDist() { const override = process.env.HERMES_DESKTOP_WEB_DIST if (override && directoryExists(path.resolve(override))) { return path.resolve(override) } const unpackedDist = path.join(unpackedPathFor(APP_ROOT), 'dist') if (directoryExists(unpackedDist)) { return unpackedDist } // Final fallback: APP_ROOT/dist. When packaged with asar:true this lives // INSIDE app.asar — not a servable filesystem directory — so the embedded // dashboard backend 404s on static routes (see #41327, #39472). The durable // fix is unpacking dist/ (PR #41411 adds dist/** to asarUnpack so the tier-2 // unpackedDist above resolves). If we still land here while packaged, log it // so the cause isn't silent. const fallback = path.join(APP_ROOT, 'dist') // existsSync, not directoryExists: a stat inside app.asar constructs the deprecated fs.Stats (#96857). if (IS_PACKAGED && /app\.asar(?=$|[\\/])/.test(fallback) && !fs.existsSync(fallback)) { rememberLog( `[web-dist] dashboard frontend dir resolved to an asar-internal path that ` + `is not a real directory: ${fallback}. Static routes will 404. ` + `Ensure dist/** is unpacked (asarUnpack) or set HERMES_DESKTOP_WEB_DIST.` ) } return fallback } // Same resolution as resolveRendererIndex, but also hands back the missing // asset list already computed for the copy it chose. The primary-window path // needs BOTH, and re-deriving the list means walking the whole renderer // generation a second time: missingRendererAssets follows index.html's // modulepreload refs and then every chunk's inline __vite__mapDeps table, so // on a release build it reads ~28 MiB across ~160 files synchronously on the // main thread — measured ~49 ms per walk, twice before loadWindowUrl(). // Callers that only need the path keep using resolveRendererIndex below. function resolveRendererIndexWithMissing(): { index: string; missing: string[] } { const asarIndex = path.join(APP_ROOT, 'dist', 'index.html') const webDistIndex = path.join(resolveWebDist(), 'index.html') // A packaged build ships dist/ twice: inside app.asar AND — because // asarUnpack lists dist/** — beside it in app.asar.unpacked. Prefer the // unpacked tree, matching the resolveWebDist()/unpackedPathFor precedent: // it is the copy the embedded dashboard serves and the copy a repair // rewrites, while pointing the window at the asar-internal index.html is // exactly how lazy chunks end up fetched from a path that cannot serve // them (#93479). Every window loader shares this resolver (main, overlay, // quick), so the ordering fix covers all of them. Dev is unchanged: // unpackedPathFor is a no-op outside an asar, so both candidates collapse // to APP_ROOT/dist and the original order is preserved. const candidates = IS_PACKAGED ? [webDistIndex, asarIndex] : [asarIndex, webDistIndex] const present = presentRendererIndexes(candidates) // index.html and the hashed chunks it names are one generation. An update // that replaces only one of the two shipped copies (app.asar vs // app.asar.unpacked) leaves a TORN copy: the window loads, then dies on the // first lazy import with "Failed to fetch dynamically imported module" and // every restart reloads the same torn copy. Prefer a copy whose modules are // all present, so the intact generation heals the boot by itself. // Remember the FIRST candidate's list: if every copy turns out to be torn we // load present[0], and its list is already in hand — recomputing it there // would reintroduce the very second walk this function exists to avoid. let firstMissing: string[] | null = null for (const candidate of present) { const missing = missingRendererAssets(candidate) if (missing.length === 0) { return { index: candidate, missing: [] } } if (firstMissing === null) { firstMissing = missing } rememberLog( `[renderer] skipping torn renderer bundle at ${candidate}: ` + `${missing.length} module file(s) named by index.html are missing ` + `(${missing.slice(0, 3).join(', ')}${missing.length > 3 ? ', …' : ''})` ) } if (present.length > 0) { // Every copy is torn. Load the first one anyway — the boundary's error is // still better than a blank window — but say what is wrong and how to fix // it, because no amount of restarting repairs a torn bundle. rememberLog( `[renderer] every renderer bundle is incomplete (${present.join(', ')}). ` + `The last update replaced the app while its files were locked. ` + `Repair with: hermes desktop --force-build` ) // present[0]'s own list, captured on the first loop iteration — never the // last candidate's, which would describe a bundle we are not loading. return { index: present[0], missing: firstMissing ?? [] } } // Nothing on disk. A packaged build with no renderer bundle blank-pages with // a bare ERR_FILE_NOT_FOUND and no clue why (see #39484). Surface the cause // and the fix before Electron loads the missing file. rememberLog( `[renderer] index.html not found — the desktop app was packaged without a ` + `renderer bundle. Tried: ${candidates.join(', ')}. ` + `Rebuild with: hermes desktop --force-build` ) return { index: candidates[0], missing: [] } } // Path-only accessor: unchanged behaviour for the window loaders that do not // need the torn-asset list. function resolveRendererIndex() { return resolveRendererIndexWithMissing().index } // True when `dir` lives inside the packaged app bundle / install tree. // Packaged Electron's process.cwd() (and npm's INIT_CWD when dev tooling // leaked into a release build) often resolve here — e.g. win-unpacked on // Windows — which is exactly where PR #37536 item 16 said we must NOT run. function isPackagedInstallPath(dir) { return isPackagedInstallPathUnderRoots(dir, { isPackaged: IS_PACKAGED, installRoots: [ APP_ROOT, path.dirname(process.execPath), resolveRemovableAppPath(process.execPath, process.platform, process.env) ] }) } function resolveHermesCwd() { // In a packaged build, `process.cwd()` resolves to the install root (e.g. // `…/win-unpacked` on Windows or `/Applications/Hermes.app/Contents/...` // on macOS). Sessions spawned there leave files inside the app bundle // and bewilder users when "where did my files go?" is the install dir. // The user-configurable default project directory wins over everything, // followed by env hints (only honored when packaged if they point at a // real directory), then the home dir. const candidates = [ readDefaultProjectDir(), process.env.HERMES_DESKTOP_CWD, IS_PACKAGED ? null : process.env.INIT_CWD, IS_PACKAGED ? null : process.cwd(), !IS_PACKAGED ? SOURCE_REPO_ROOT : null, app.getPath('home') ] for (const candidate of candidates) { if (!candidate) { continue } const resolved = path.resolve(String(candidate)) if (isPackagedInstallPath(resolved)) { continue } if (directoryExists(resolved)) { return resolved } } return app.getPath('home') } function sanitizeWorkspaceCwd(cwd) { const trimmed = typeof cwd === 'string' ? cwd.trim() : '' if (!trimmed || isPackagedInstallPath(trimmed)) { return { cwd: resolveHermesCwd(), sanitized: Boolean(trimmed) } } try { const resolved = path.resolve(trimmed) if (directoryExists(resolved)) { return { cwd: resolved, sanitized: false } } } catch { // Fall through to the resolved default. } return { cwd: resolveHermesCwd(), sanitized: Boolean(trimmed) } } // Persisted "Default project directory" — surfaced as a setting in the // renderer (see app/settings/sessions-settings.tsx). Stored as JSON in // userData so it survives self-updates without bleeding into the new // install. `null` means "no preference, fall back to the usual chain". const DEFAULT_PROJECT_DIR_CONFIG_FILENAME = 'project-dir.json' function defaultProjectDirConfigPath() { return path.join(app.getPath('userData'), DEFAULT_PROJECT_DIR_CONFIG_FILENAME) } function readDefaultProjectDir() { try { const raw = fs.readFileSync(defaultProjectDirConfigPath(), 'utf8') const parsed = JSON.parse(raw) if (parsed && typeof parsed.dir === 'string' && parsed.dir.trim()) { const resolved = path.resolve(parsed.dir) if (directoryExists(resolved)) { return resolved } } } catch { // Missing / unreadable / malformed → fall through to the rest of the // candidate chain. } return null } function writeDefaultProjectDir(dir) { const target = defaultProjectDirConfigPath() const payload = dir ? JSON.stringify({ dir: path.resolve(dir) }, null, 2) : JSON.stringify({}, null, 2) try { fs.mkdirSync(path.dirname(target), { recursive: true }) fs.writeFileSync(target, payload, 'utf8') } catch (error) { rememberLog(`[settings] write default project dir failed: ${error.message}`) } } const installedRuntimeGate = createInstalledRuntimeGate(process.env, rememberLog) async function resolveHermesBackend(backendArgs: string[]): Promise { const payload = bundledPayload(process.resourcesPath) if (payload) { if (!IS_WINDOWS) { provisionCliLinks(payload.commands, path.join(os.homedir(), '.local', 'bin'), rememberLog) } return { kind: 'python', label: `bundled payload at ${payload.root}`, command: payload.shim, args: [...backendArgs], env: { ...buildDesktopBackendEnv(), HERMES_RUNTIME_DIR: payload.toolsDir }, root: payload.repoDir, bootstrap: false, shell: false, local: 'bundled' } } // 1. Explicit override -- HERMES_DESKTOP_HERMES_ROOT points at a developer // checkout. Honour it as-is (no bootstrap; the user is driving). const overrideRoot: string | undefined = process.env.HERMES_DESKTOP_HERMES_ROOT && path.resolve(process.env.HERMES_DESKTOP_HERMES_ROOT) if (overrideRoot && isHermesSourceRoot(overrideRoot)) { const backend: SourceBackend | null = createSourcePythonBackend( overrideRoot, await findPythonForRoot(overrideRoot), backendArgs ) if (backend) { return backend } } // 2. Development source -- when running `npm run dev` from a checkout, the // cloned repo at SOURCE_REPO_ROOT takes precedence over ACTIVE and any // installed `hermes` on PATH so local Python edits are actually exercised. // (In dev with no checkout, SOURCE_REPO_ROOT won't pass isHermesSourceRoot.) if (!IS_PACKAGED && isHermesSourceRoot(SOURCE_REPO_ROOT)) { const backend: SourceBackend | null = createSourcePythonBackend( SOURCE_REPO_ROOT, await findPythonForRoot(SOURCE_REPO_ROOT), backendArgs ) if (backend) { return backend } } // 3. HERMES_DESKTOP_HERMES — an explicit deployment override (used by the // Nix wrapper), not a discovered PATH candidate. The pinned backend is // the only valid runtime there. Resolve it before any mutable install, // which may belong to an older release or a different Python environment. const hermesOverride: string | undefined = process.env.HERMES_DESKTOP_HERMES let hermesCommand: string | null = null if (hermesOverride) { const resolvedOverride: string | null = findOnPath(hermesOverride) if (resolvedOverride) { hermesCommand = resolvedOverride } else if (!isWindowsBinaryPathInWsl(hermesOverride, { isWsl: IS_WSL })) { hermesCommand = hermesOverride } else { rememberLog(`Ignoring Windows Hermes override under WSL: ${hermesOverride}`) } if (hermesCommand) { if (looksLikeDesktopAppBinary(hermesCommand)) { rememberLog(`Ignoring desktop app executable on PATH while resolving Hermes CLI: ${hermesCommand}`) hermesCommand = null } else { const unwrapped: Awaited> = await unwrapWindowsVenvHermesCommand(hermesCommand, backendArgs) if (unwrapped) { return unwrapped } const shellForProbe: boolean = isCommandScript(hermesCommand) if ( shouldTrustHermesOverride(hermesOverride) || (await verifyHermesCli(hermesCommand, { shell: shellForProbe })) ) { return { label: `existing Hermes CLI at ${hermesCommand}`, command: hermesCommand, args: backendArgs, bootstrap: false, env: {}, kind: 'command', shell: shellForProbe, local: 'installed' } } rememberLog( `Ignoring existing Hermes CLI at ${hermesCommand}: --version probe failed; falling through to bootstrap.` ) } } } // 4. ACTIVE_HERMES_ROOT — the canonical install at // %LOCALAPPDATA%\\hermes\\hermes-agent (Windows) or ~/.hermes/hermes-agent. // A valid bootstrap marker proves Desktop finished the first-run install // flow, but marker provenance is NOT the same thing as runtime usability: // the CLI can publish the same installation launcher, and older desktop // builds could leave a healthy install behind without the marker. If the // active runtime is usable, launch it directly; only fall through to // bootstrap when the runtime itself is unusable. // HERMES_DESKTOP_IGNORE_EXISTING=1 skips this rung (see backend-resolution). const activeBackend: SourceBackend | null = await installedRuntimeGate.resolve(ACTIVE_HERMES_ROOT, () => resolveSourceInstallationBackend(ACTIVE_HERMES_ROOT, backendArgs, { hermesHome: HERMES_HOME }) ) const activeRuntime: ActiveRuntimeState = activeRuntimeState(activeBackend) if (activeBackend && !bootstrapRepairRequested) { if (!activeRuntime.hasValidMarker) { rememberLog( `[bootstrap] Active Hermes runtime at ${ACTIVE_HERMES_ROOT} is usable but the bootstrap marker is missing or stale; skipping first-run bootstrap.` ) } return activeBackend } if (bootstrapRepairRequested) { rememberLog('[bootstrap] repair requested; bypassing the usable active runtime to re-run the installer') } else { // 5. A source install outside ACTIVE_HERMES_ROOT (install.sh --dir, a // setup-hermes.sh clone), found through the launcher it published at a // fixed user-bin location: a Finder/Dock launch inherits a PATH without // ~/.local/bin. The reported root is then resolved and probed like any // installed runtime; HERMES_DESKTOP_IGNORE_EXISTING=1 skips it too. const userInstall: ReturnType = userLauncherInstallRoot(IS_WINDOWS, HERMES_HOME) if (userInstall) { const userBackend: SourceBackend | null = await installedRuntimeGate.resolve(userInstall.root, () => resolveSourceInstallationBackend(userInstall.root, backendArgs, { hermesHome: HERMES_HOME }) ) if (userBackend) { rememberLog(`[boot] Using Hermes install at ${userInstall.root} (published launcher ${userInstall.launcher})`) return userBackend } rememberLog(`[bootstrap] Hermes install at ${userInstall.root} (from ${userInstall.launcher}) is not usable`) } else { rememberLog(`[bootstrap] no usable Hermes install at ${ACTIVE_HERMES_ROOT} and no published user-bin launcher`) } } // 6. Nothing usable yet -- signal the bootstrap runner that we need to // clone+install. Phase 1D's bootstrap-runner consumes this sentinel // and drives install.ps1 stages with a progress UI. Until 1D lands, // callers see the sentinel and surface it as a user-facing error // explaining what's missing. // // We deliberately do NOT throw here -- throwing inside // resolveHermesBackend was the old "no payload" path and forced the // user into a dead end. With the bootstrap protocol, "no install yet" // is a recoverable state the GUI can drive through. return { kind: 'bootstrap-needed', label: 'Hermes Agent not installed yet; bootstrap required', command: null, args: backendArgs, bootstrap: true, env: {}, shell: false, // Hints for the bootstrap runner / UI layer: activeRoot: ACTIVE_HERMES_ROOT, installStamp: INSTALL_STAMP, // may be null in dev isPackaged: IS_PACKAGED, platform: process.platform, local: 'none' } } interface ResolvedHermesBackend { kind: string label: string command: string | null args: string[] env: NodeJS.ProcessEnv bootstrap: boolean shell: boolean local?: string root?: string installStamp?: Readonly | null activeRoot?: string isPackaged?: boolean platform?: NodeJS.Platform readyFile?: boolean } async function ensureRuntime( backend: ResolvedHermesBackend, assertStillOwned: () => void ): Promise { localBackendLifecycle.assertCanStart() assertStillOwned() if (!backend.bootstrap) { await advanceBootProgress('runtime.external', `Using ${backend.label}`, 32) return backend } // backend.kind === 'bootstrap-needed' means resolveHermesBackend couldn't // find anything to spawn. Hand off to the bootstrap runner which drives the // platform installer, writes the bootstrap-complete marker on success, then // we re-resolve to get the now-installed backend. // // Phase 1D status: bootstrap runs but events go to desktop.log only // (renderer window isn't created until later in startBackend). Phase 1E // will rewire startup to spawn the window first and route bootstrap events // to a renderer-side install overlay. // // The artifact kind forbids bootstrap even when a caller requests repair. if (backend.kind === 'bootstrap-needed' && installShape() === 'bundled') { rememberLog('[bootstrap] REFUSING installer on a bundled install; payload missing or damaged — reinstall the app') const bundledError: Error & { isBootstrapFailure?: boolean } = new Error( 'This app bundles its own Hermes runtime, but the runtime files are missing or damaged. Reinstall Hermes Desktop to restore it.' ) bundledError.isBootstrapFailure = true bootstrapFailure = bundledError throw bundledError } if (backend.kind === 'bootstrap-needed') { rememberLog('[bootstrap] no Hermes install found; starting first-launch bootstrap') if (await handOffWindowsBootstrapRecovery('bootstrap-needed')) { const handoffError: Error & { isBootstrapFailure?: boolean; bootstrapHandedOff?: boolean } = new Error( 'Hermes recovery was handed off to Hermes Setup. The desktop will restart when recovery completes.' ) handoffError.isBootstrapFailure = true handoffError.bootstrapHandedOff = true bootstrapFailure = handoffError throw handoffError } // Eagerly flip the bootstrap UI state to 'active' so the renderer // shows the install overlay BEFORE the runner finishes fetching the // manifest (which on slow networks can take tens of seconds and would // otherwise leave the user staring at the generic 'Preparing' splash). // We emit a synthetic manifest with an empty stages list -- the real // manifest event will overwrite it once install.ps1 -Manifest returns. try { broadcastBootstrapEvent({ type: 'manifest', stages: [], protocolVersion: null }) } catch { void 0 } localBackendLifecycle.assertCanStart() bootstrapAbortController = new AbortController() // The repair request has been honoured by reaching the installer; clear it // so a later boot isn't forced through bootstrap again. bootstrapRepairRequested = false bootstrapRepairAttempt = 0 const bootstrapResult = await runBootstrap({ installStamp: backend.installStamp, activeRoot: backend.activeRoot, sourceRepoRoot: SOURCE_REPO_ROOT, hermesHome: HERMES_HOME, logRoot: path.join(HERMES_HOME, 'logs'), abortSignal: bootstrapAbortController.signal, onEvent: ev => { // Tee every bootstrap event to (a) the desktop log for forensics // and (b) the renderer for live progress UI. Either may be absent; // tolerate both gracefully so a renderer crash doesn't stall the // bootstrap and a log-write failure doesn't suppress the UI signal. try { rememberLog(`[bootstrap] ${JSON.stringify(ev)}`) } catch { void 0 } try { broadcastBootstrapEvent(ev) } catch { void 0 } }, writeMarker: writeBootstrapMarker, gitBinary: resolveGitBinary() }) bootstrapAbortController = null if (bootstrapResult.cancelled) { const cancelledError = new Error('Hermes install was cancelled.') as any cancelledError.isBootstrapFailure = true cancelledError.bootstrapCancelled = true bootstrapFailure = cancelledError throw cancelledError } if (!bootstrapResult.ok) { // Plain lead sentence + trailing "Details:" line; the install overlay // shows this verbatim and offers Reload and retry / Open logs itself. const bootstrapError = new Error( describeBootstrapFailure(bootstrapResult.failedStage, bootstrapResult.error) ) as any bootstrapError.isBootstrapFailure = true bootstrapError.failedStage = bootstrapResult.failedStage || null // Latch the failure so subsequent startHermes() calls return this // same error without re-running install.ps1. Cleared by the // hermes:bootstrap:reset IPC (renderer's "Reload and retry"). bootstrapFailure = bootstrapError throw bootstrapError } rememberLog('[bootstrap] bootstrap complete; marker written. Re-resolving backend.') // Resolve the newly published launcher after the installer completes. return ensureRuntime( await installedRuntimeGate.afterInstall(() => resolveHermesBackend(backend.args)), assertStillOwned ) } throw new Error(`Unexpected bootstrap backend: ${backend.kind}`) } // Assemble a single-file multipart/form-data body (FastAPI `UploadFile` // endpoints, e.g. kanban attachments). Hand-rolled because node's http has no // FormData and the payload is one file — a dependency would be overkill. function multipartBody(upload) { const boundary = `----hermes-${crypto.randomBytes(12).toString('hex')}` const filename = String(upload.filename || 'file').replace(/["\r\n]/g, '_') const body = Buffer.concat([ Buffer.from( `--${boundary}\r\n` + `Content-Disposition: form-data; name="file"; filename="${filename}"\r\n` + `Content-Type: ${upload.contentType || 'application/octet-stream'}\r\n\r\n` ), Buffer.from(upload.bytes), Buffer.from(`\r\n--${boundary}--\r\n`) ]) return { body, contentType: `multipart/form-data; boundary=${boundary}` } } function fetchJson(url, token, options: any = {}) { // Retry policy lives in api-transport.ts: idempotent verbs retry on any // transient transport error; POST/PUT/DELETE only when the request provably // never reached the server (see shouldRetryRequest) — never double-submit. return withRetry( (requestState: any) => new Promise((resolve, reject) => { const { body, contentType } = options.upload ? multipartBody(options.upload) : { body: options.body === undefined ? undefined : Buffer.from(JSON.stringify(options.body)), contentType: 'application/json' } const parsed = new URL(url) const client = parsed.protocol === 'https:' ? https : http const agent = jsonAgentFor(parsed.protocol) const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS) if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { reject(new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`)) return } const req = client.request( parsed, { agent, method: options.method || 'GET', headers: { ...headersForRemoteRequest(url), ...(options.headers || {}), 'Content-Type': contentType, 'X-Hermes-Session-Token': token, // RFC 8252 native flow authenticates the gated gateway with a bearer // token instead of the loopback session-token header. When // ``options.bearer`` is set we send Authorization: Bearer ; // the gateway's OAuth gate verifies it via the provider stack with // no cookie involved. ...(options.bearer ? { Authorization: `Bearer ${options.bearer}` } : {}), ...(body ? { 'Content-Length': String(body.length) } : {}) } }, res => { const chunks = [] res.on('error', reject) res.on('data', chunk => chunks.push(chunk)) res.on('end', () => { const text = Buffer.concat(chunks).toString('utf8') if ((res.statusCode || 500) >= 400) { reject(httpStatusError(res.statusCode, text, res.statusMessage)) return } // http.request never follows redirects, so any 3xx -- with an HTML // login page, an empty body, whatever -- is the request bouncing // off a proxy or a scheme/slash mismatch, never JSON. if (res.statusCode >= 300) { reject(htmlResponseError(url, res.statusCode, res.headers.location)) return } if (!text) { resolve(null) return } // A 2xx response whose body is HTML means the request fell through // to the SPA index.html (e.g. an unregistered /api path). JSON.parse // would throw an opaque `Unexpected token '<'` here, so surface a // clear diagnostic with the offending URL instead. const looksHtml = /^\s*<(?:!doctype|html)/i.test(text) const contentType = String(res.headers['content-type'] || '') if (looksHtml || contentType.includes('text/html')) { reject(htmlResponseError(url, res.statusCode)) return } try { resolve(JSON.parse(text)) } catch { reject(new Error(`Invalid JSON from ${url} (status ${res.statusCode}): ${text.slice(0, 200)}`)) } }) } ) req.on('error', reject) req.setTimeout(timeoutMs, () => { req.destroy(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`)) }) // From here the request goes on the wire: a later transport error can no // longer prove the server didn't process it, so non-idempotent verbs must // not be retried past this point. requestState.bodySent = true if (body) { req.write(body) } req.end() }), { method: options.method || 'GET' } ) } function fetchPublicJson(url, options: any = {}) { // Credential-free JSON GET/POST for public gateway endpoints // (``/api/status``, ``/api/auth/providers``). Unlike ``fetchJson`` it sends // NO ``X-Hermes-Session-Token`` header — used by the auth-mode probe before // any credentials exist, and any time we must not leak a token to an // endpoint that doesn't need one. return withRetry( (requestState: any) => new Promise((resolve, reject) => { const body = options.body === undefined ? undefined : Buffer.from(JSON.stringify(options.body)) let parsed try { parsed = new URL(url) } catch (error) { reject(new Error(`Invalid URL: ${error.message}`)) return } const client = parsed.protocol === 'https:' ? https : http const agent = jsonAgentFor(parsed.protocol) const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS) if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { reject(new Error(`Unsupported Hermes backend URL protocol: ${parsed.protocol}`)) return } const req = client.request( parsed, { agent, method: options.method || 'GET', headers: { ...headersForRemoteRequest(url), ...(options.headers || {}), 'Content-Type': 'application/json', ...(body ? { 'Content-Length': String(body.length) } : {}) } }, res => { const chunks = [] res.on('data', chunk => chunks.push(chunk)) res.on('end', () => { const text = Buffer.concat(chunks).toString('utf8') if ((res.statusCode || 500) >= 400) { reject(httpStatusError(res.statusCode, text, res.statusMessage)) return } if (res.statusCode >= 300) { reject(htmlResponseError(url, res.statusCode, res.headers.location)) return } if (!text) { resolve(null) return } const looksHtml = /^\s*<(?:!doctype|html)/i.test(text) const contentType = String(res.headers['content-type'] || '') if (looksHtml || contentType.includes('text/html')) { reject(htmlResponseError(url, res.statusCode)) return } try { resolve(JSON.parse(text)) } catch { reject(new Error(`Invalid JSON from ${url} (status ${res.statusCode}): ${text.slice(0, 200)}`)) } }) } ) req.on('error', reject) req.setTimeout(timeoutMs, () => { req.destroy(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`)) }) // Past this point the request is on the wire — see fetchJson. requestState.bodySent = true if (body) { req.write(body) } req.end() }), { method: options.method || 'GET' } ) } function mimeTypeForPath(filePath) { const ext = path.extname(filePath || '').toLowerCase() return MEDIA_MIME_TYPES[ext] || 'application/octet-stream' } function extensionForMimeType(mimeType) { const type = String(mimeType || '') .split(';')[0] .trim() .toLowerCase() if (type === 'image/png') { return '.png' } if (type === 'image/jpeg') { return '.jpg' } if (type === 'image/gif') { return '.gif' } if (type === 'image/webp') { return '.webp' } if (type === 'image/bmp') { return '.bmp' } if (type === 'image/svg+xml') { return '.svg' } return '' } function filenameFromUrl(rawUrl, fallback = 'image') { try { const parsed = new URL(rawUrl) const base = path.basename(decodeURIComponent(parsed.pathname || '')) return base && base.includes('.') ? base : fallback } catch { return fallback } } async function resourceBufferFromUrl(rawUrl) { if (!rawUrl) { throw new Error('Missing URL') } if (rawUrl.startsWith('data:')) { const match = rawUrl.match(/^data:([^;,]+)?(;base64)?,(.*)$/s) if (!match) { throw new Error('Invalid data URL') } const mimeType = match[1] || 'application/octet-stream' const encoded = match[3] || '' const buffer = match[2] ? Buffer.from(encoded, 'base64') : Buffer.from(decodeURIComponent(encoded), 'utf8') return { buffer, mimeType } } if (/^file:/i.test(rawUrl)) { const { resolvedPath } = await resolveReadableFileForIpc(rawUrl, { purpose: 'Image file' }) const buffer = await fs.promises.readFile(resolvedPath) return { buffer, mimeType: mimeTypeForPath(resolvedPath) } } const parsed = new URL(rawUrl) const client = parsed.protocol === 'https:' ? https : http return new Promise((resolve, reject) => { const req = client.get(parsed, res => { if ((res.statusCode || 500) >= 400) { reject(new Error(`Failed to fetch ${rawUrl}: ${res.statusCode}`)) res.resume() return } const chunks = [] res.on('error', reject) res.on('data', chunk => chunks.push(chunk)) res.on('end', () => { resolve({ buffer: Buffer.concat(chunks), mimeType: res.headers['content-type'] || 'application/octet-stream' }) }) }) req.on('error', reject) }) } async function saveImageFromUrl(rawUrl) { const { buffer, mimeType } = (await resourceBufferFromUrl(rawUrl)) as any const extension = extensionForMimeType(mimeType) || '.png' // Generated-image URLs (fal.media etc.) usually end in an extensionless // content hash. Keep the name but always guarantee an extension — without // one Windows saves an unopenable "All Files" blob (#image18 report). const baseName = filenameFromUrl(rawUrl, `image${extension}`) const fallbackName = path.extname(baseName) ? baseName : `${baseName}${extension}` let downloadsDir = '' try { downloadsDir = app.getPath('downloads') } catch { // Leave the dialog at its last-used location when the OS has no // Downloads directory to offer. } const result = await dialog.showSaveDialog(mainWindow, { title: 'Save Image', defaultPath: downloadsDir ? path.join(downloadsDir, fallbackName) : fallbackName, filters: [ { name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'] }, { name: 'All Files', extensions: ['*'] } ] }) if (result.canceled || !result.filePath) { return false } await fs.promises.writeFile(result.filePath, buffer) return true } async function writeComposerImage(buffer, ext = '.png', name = '') { const rawExt = String(ext || '.png') .trim() .toLowerCase() const normalizedExt = rawExt.startsWith('.') ? rawExt : `.${rawExt}` const safeExt = /^\.[a-z0-9]{1,5}$/.test(normalizedExt) ? normalizedExt : '.png' const dir = path.join(app.getPath('userData'), 'composer-images') await fs.promises.mkdir(dir, { recursive: true }) const stamp = composerImageTimestamp() const random = crypto.randomBytes(3).toString('hex') const baseName = String(name || '') .split(/[\\/]/) .pop() ?.replace(/\.[^.]+$/, '') const safeName = (baseName || '') .replace(/[^\p{L}\p{N}._-]+/gu, '_') .replace(/^[._-]+|[._-]+$/g, '') .slice(0, 80) const fileName = safeName ? `${safeName}_${random}${safeExt}` : `composer_${stamp}_${random}${safeExt}` const filePath = path.join(dir, fileName) await fs.promises.writeFile(filePath, buffer) return filePath } function expandUserPath(filePath) { const value = String(filePath || '').trim() if (value === '~') { return app.getPath('home') } if (value.startsWith(`~${path.sep}`) || value.startsWith('~/')) { return path.join(app.getPath('home'), value.slice(2)) } return value } /** Markdown hrefs must percent-encode spaces (`/my%20notes/x.md`), but the * on-disk path is the decoded form. When the raw path misses, retry decoded * so chat links to paths with spaces still open in the preview rail. */ function decodedPathIfMissing(resolvedPath) { if (!/%[0-9a-fA-F]{2}/.test(resolvedPath)) { return null } let decoded try { decoded = decodeURIComponent(resolvedPath) } catch { return null } return decoded !== resolvedPath ? decoded : null } async function previewFileTarget(rawTarget, baseDir) { const raw = String(rawTarget || '').trim() const base = baseDir ? path.resolve(expandUserPath(baseDir)) : resolveHermesCwd() // A plain backend target is a WSL/POSIX path; bridge it to a Windows- // accessible form before resolving so the existence checks below (and the // final read) hit the real file rather than a drive-relative C:\home\... miss. let resolved = resolveRequestedPathForIpc(resolvePreviewTargetPath(raw, expandUserPath), { baseDir: base, purpose: 'Preview target' }) // Attachment references stored in chat history are frequently HOME-relative // (e.g. "AppData/Local/hermes/attachments/foo.xlsx" on Windows, or // ".hermes/attachments/foo.xlsx" elsewhere) rather than relative to the // agent's working directory. The primary resolution above only tries // `base` (the working dir), so such a ref never exists there and the // preview/download 404s even though the file is present on disk (#115609). if (!fileExists(resolved) && !directoryExists(resolved)) { for (const candidate of homeRelativeAttachmentCandidates(raw, app.getPath('home'), HERMES_HOME)) { if (fileExists(candidate)) { resolved = candidate break } } } // Markdown hrefs must percent-encode spaces (`/my%20notes/x.md`), but the // on-disk path is the decoded form. When the encoded path misses, retry the // decoded form so chat links to paths with spaces still open in the preview // rail (#102782) — before the directory/missing classification below, so a // decoded target is typed by what it actually is. if (!fileExists(resolved) && !directoryExists(resolved)) { const decoded = decodedPathIfMissing(resolved) if (decoded && (fileExists(decoded) || directoryExists(decoded))) { resolved = decoded } } // A directory is not a preview (#101683). Overloading it as // `/index.html` made a directory without one classify as missing, and // the renderer's blind fallback then fabricated a broken text-preview tab. // Answer with a typed non-previewable result so the card can offer the // native folder action, and a typed `missing` result so a dead link reports // instead of previewing. if (directoryExists(resolved)) { return { kind: 'file', label: path.basename(resolved) || resolved, path: resolved, previewKind: 'directory', source: raw, url: pathToFileURL(resolved).toString() } } if (!fileExists(resolved)) { return { kind: 'file', label: path.basename(resolved) || raw, path: resolved, previewKind: 'missing', source: raw, url: pathToFileURL(resolved).toString() } } const ext = path.extname(resolved).toLowerCase() ;({ resolvedPath: resolved } = await resolveReadableFileForIpc(resolved, { purpose: 'Preview target' })) const mimeType = mimeTypeForPath(resolved) const metadata = previewFileMetadata(resolved, mimeType) const isHtml = PREVIEW_HTML_EXTENSIONS.has(ext) const isImage = mimeType.startsWith('image/') const isPdf = PREVIEW_PDF_EXTENSIONS.has(ext) || mimeType === 'application/pdf' const previewKind = isHtml ? 'html' : isImage ? 'image' : isPdf ? 'pdf' : metadata.binary ? 'binary' : 'text' return { binary: metadata.binary, byteSize: metadata.byteSize, kind: 'file', large: metadata.large, label: path.basename(resolved), language: PREVIEW_LANGUAGE_BY_EXT[ext] || 'text', mimeType, path: resolved, previewKind, source: raw, url: pathToFileURL(resolved).toString() } } async function normalizePreviewTarget(rawTarget, baseDir) { const raw = String(rawTarget || '').trim() if (!raw) { return null } try { if (/^https?:\/\//i.test(raw)) { return previewHttpUrlTarget(raw) } return await previewFileTarget(raw, baseDir) } catch { return null } } async function filePathFromPreviewUrl(rawUrl) { const { resolvedPath } = await resolveReadableFileForIpc(String(rawUrl || ''), { purpose: 'Preview file' }) return resolvedPath } async function watchPreviewFile(owner, rawUrl) { let filePath try { filePath = await filePathFromPreviewUrl(rawUrl) } catch (error) { // A restored tab probing a file that is gone is an expected outcome — // answer it like the read handlers do instead of rejecting (Electron logs // every rejected handler as a stack trace at startup). if (isMissingFileError(error)) { return missingFileResult(rawUrl, error) } throw error } const watchDir = path.dirname(filePath) const targetName = path.basename(filePath) const id = crypto.randomBytes(12).toString('base64url') let timer = null // Proactive teardown: the watch must not outlive the window that asked for // it by whole quit-cycles waiting on a change event that never comes. const offOwnerDestroyed = onPreviewWatchOwnerDestroyed(owner, () => stopPreviewFileWatch(id)) const emit = () => { if (!fileExists(filePath)) { return } sendPreviewFileChangedToOwner(owner, { id, path: filePath, url: pathToFileURL(filePath).toString() }, () => stopPreviewFileWatch(id) ) } // guardedWatch: a win32 event storm closes the raw fs.watch and falls back // to a slow stat poll instead of pinning the main thread (#118974). const watcher = guardedWatch({ platform: process.platform, watch: listener => fs.watch(watchDir, listener), onEvent: (_eventType, filename) => { const changedName = filename ? path.basename(String(filename)) : '' if (changedName && changedName !== targetName) { return } if (timer) { clearTimeout(timer) } timer = setTimeout(() => { timer = null emit() }, PREVIEW_WATCH_DEBOUNCE_MS) }, snapshot: () => { const stat = fs.statSync(filePath) return `${stat.mtimeMs}:${stat.size}` }, onPollChange: emit, onTrip: ({ events, windowMs }) => console.warn(`[hermes] fs.watch storm on ${watchDir} (${events} events within ${windowMs}ms); polling instead`) }) previewWatchers.set(id, { owner, close: () => { offOwnerDestroyed() if (timer) { clearTimeout(timer) } watcher.close() } }) return { id, path: filePath } } function stopPreviewFileWatch(id) { const watcher = previewWatchers.get(id) if (!watcher) { return false } watcher.close() previewWatchers.delete(id) return true } function closePreviewWatchers() { for (const id of previewWatchers.keys()) { stopPreviewFileWatch(id) } } function requestOptionsWithHeaders(options: any = {}, headers = {}) { return { ...options, headers: { ...headers, ...(options.headers || {}) } } } /** Watch a DIRECTORY for entry churn (folders appearing/vanishing) — the * disk-plugin door's "new plugin folder" signal, replacing the renderer's 5s * readdir poll. Same registry + change channel as the preview file watchers * (the renderer reconciles on any tick; per-file edits stay on their own * watches), so stopPreviewFileWatch/closePreviewWatchers manage these too. */ function watchDirectory(owner, rawDir) { const watchDir = path.resolve(String(rawDir || '')) if (!fs.existsSync(watchDir) || !fs.statSync(watchDir).isDirectory()) { throw new Error(`Not a directory: ${watchDir}`) } const id = crypto.randomBytes(12).toString('base64url') let timer = null // Same proactive teardown as a file watch: a closed window's directory // watch must not keep polling the disk-plugin door until quit. const offOwnerDestroyed = onPreviewWatchOwnerDestroyed(owner, () => stopPreviewFileWatch(id)) const emit = () => { sendPreviewFileChangedToOwner(owner, { id, path: watchDir, url: pathToFileURL(watchDir).toString() }, () => stopPreviewFileWatch(id) ) } // A win32 event storm here pinned a core at 100% (#118974): the breaker // closes the raw watch and falls back to the readdir poll it replaced. const watcher = guardedWatch({ platform: process.platform, watch: listener => fs.watch(watchDir, listener), onEvent: () => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { timer = null emit() }, PREVIEW_WATCH_DEBOUNCE_MS) }, snapshot: () => fs.readdirSync(watchDir).sort().join('\0'), onPollChange: emit, onTrip: ({ events, windowMs }) => console.warn(`[hermes] fs.watch storm on ${watchDir} (${events} events within ${windowMs}ms); polling instead`) }) previewWatchers.set(id, { owner, close: () => { offOwnerDestroyed() if (timer) { clearTimeout(timer) } watcher.close() } }) return { id, path: watchDir } } // Best-effort read of a gateway's advertised auth providers, cached per base // URL for the life of the process. Used by the oauth pre-flight guard to tell // a password-provider gateway (which cannot satisfy the bearer/cookie checks // by design) from a real OAuth one. Any failure returns [] so callers keep the // strict guard — backends predating /api/auth/providers are unaffected. const gatewayAuthProvidersCache = new Map() async function gatewayAuthProviders(baseUrl, headers = {}) { const cached = gatewayAuthProvidersCache.get(baseUrl) if (cached) { return cached } let providers = [] try { const body = (await fetchPublicJson( `${baseUrl}/api/auth/providers`, requestOptionsWithHeaders({ timeoutMs: 8_000 }, headers) )) as any if (Array.isArray(body?.providers)) { providers = body.providers .filter(p => p && typeof p === 'object') .map(p => ({ name: String(p.name || ''), supportsPassword: Boolean(p.supports_password) })) .filter(p => p.name) } gatewayAuthProvidersCache.set(baseUrl, providers) } catch { // Optional metadata — an unreadable list keeps the strict guard. } return providers } // Build the readiness probe for a connection's auth mode. A gated gateway // must be probed with the SAME credentials the rest of the connection uses: // an anonymous probe 401s forever against a live session, and it can never // see the 404 that identifies a backend predating /api/health (the auth gate // answers before the SPA catch-all). `probeIsCredentialed` tells // waitForHermesReady how to read a 401 — rejected session vs gated route. async function buildReadinessHealthProbe(baseUrl, authMode, token) { if (authMode === 'oauth') { return { // fetchJson takes the bearer via `options.bearer` — a raw `headers` // option is ignored, so passing one here would silently probe // uncredentialed and reintroduce the 401 loop. probeHealth: (url: string, options: any = {}) => requestWithOauthFallback(baseUrl, { ensureNativeAccessToken, requestWithBearer: (bearer: string) => fetchJson(url, null, { ...options, bearer }), requestWithCookie: () => fetchJsonViaOauthSession(url, options) }), probeIsCredentialed: true } } const probeAuth = resolveReadinessProbeAuth(authMode, null, token) if (probeAuth.kind === 'token' && probeAuth.token) { return { probeHealth: (url, options: any = {}) => fetchJson(url, probeAuth.token, options), probeIsCredentialed: true } } return { probeHealth: fetchPublicJson, probeIsCredentialed: false } } // Boot-time readiness for a remote connection object. For a Hermes Cloud agent // whose own session cookie has expired, `waitForHermes` ends in the terminal // reauth error even though the portal session that can silently re-mint that // cookie is still live: the per-agent cascade (`cloudAgentSilentSignIn`) was // only ever driven by the settings UI, never by boot, so every relaunch needed // a manual "Use gateway" click. Run the cascade once and retry once; anything // that is not that exact case surfaces unchanged. async function waitForRemoteHermes(remote) { try { await waitForHermes(remote.baseUrl, remote.token, undefined, remote.authMode, remote.headers) } catch (error) { if (!shouldAttemptCloudBootCascade(remote, error)) { throw error } if (!(await hasLivePortalSession())) { throw error } rememberLog('[cloud] boot: agent session rejected but portal session is live, running silent sign-in') try { await cloudAgentSilentSignIn(remote.baseUrl) } catch (cascadeError) { rememberLog(`[cloud] boot: silent sign-in did not complete: ${cascadeError?.message || cascadeError}`) throw error } await waitForHermes(remote.baseUrl, remote.token, undefined, remote.authMode, remote.headers) } } async function waitForHermes( baseUrl: string, token: string | null | undefined, signal?: AbortSignal, authMode?: string | null, headers: Record = {}, { alreadyBound = false }: { alreadyBound?: boolean } = {} ): Promise { const { probeHealth, probeIsCredentialed } = await buildReadinessHealthProbe(baseUrl, authMode, token) return waitForHermesReady(baseUrl, { token, signal, fetchPublicJson, fetchJson: probeIsCredentialed ? (url, _token, options = {}) => probeHealth(url, requestOptionsWithHeaders(options, headers)) : fetchJson, probeHealth: (url, options = {}) => probeHealth(url, requestOptionsWithHeaders(options, headers)), probeIsCredentialed, alreadyBound }) } function getWindowButtonPosition(win = mainWindow) { if (!IS_MAC) { return null } // Fullscreen hides the traffic lights — treat as no left-side controls so the // renderer drops the traffic-light dodge inset and Y nudge. if (win?.isFullScreen?.()) { return null } return win?.getWindowButtonPosition?.() || WINDOW_BUTTON_POSITION } function getNativeOverlayWidth() { return computeNativeOverlayWidth({ isWindows: IS_WINDOWS, isWsl: IS_WSL, isMac: IS_MAC }) } function getWindowState(win = mainWindow) { return { isFullscreen: Boolean(win?.isFullScreen?.()), isMinimized: Boolean(win?.isMinimized?.()), isVisible: Boolean(win?.isVisible?.()), nativeOverlayWidth: getNativeOverlayWidth(), windowButtonPosition: getWindowButtonPosition(win), darwinMajor: IS_MAC ? DARWIN_MAJOR : 0, ...windowControlState(win, !IS_WINDOWS && IS_WSL) } } function sendBackendExit(payload) { // Intentional soft re-home (gateway mode apply) kills the child on purpose — // don't surface the "backend stopped" error toast / boot-failure path. if (softRehomeInProgress) { return } if (!mainWindow || mainWindow.isDestroyed()) { return } const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } webContents.send('hermes:backend-exit', payload) } function sendClosePreviewRequested() { if (!mainWindow || mainWindow.isDestroyed()) { return } const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } webContents.send('hermes:close-preview-requested') } /** * Ask the renderer to run a browser-navigation gesture on its focused preview * pane. `reload` also has an app-level fallback (reload the window); `back` and * `forward` mean nothing outside the browser, so the renderer just ignores them. */ function sendPreviewNavCommand(command: 'back' | 'forward' | 'reload') { // The user is inside the page itself — main is the only party that can see // that, so act here and never round-trip. if (commandFocusedGuest(command, electronWebContents.getFocusedWebContents())) { return } if (!mainWindow || mainWindow.isDestroyed()) { return } const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } webContents.send('hermes:preview-nav', command) } /** * The native back/forward gestures, which never reach the renderer on their own. * * - macOS: a two/three-finger swipe. Chromium's own overscroll navigation is * off in an Electron window, so the OS gesture surfaces as this event and * nothing consumes it. Requires "Swipe between pages" in System Settings. * - Windows/Linux: the dedicated back/forward buttons on a mouse, delivered as * `WM_APPCOMMAND`. */ function installBrowserNavGestures(window) { window.on('swipe', (_event, direction) => { if (direction === 'left' || direction === 'right') { // Swipe LEFT moves the page left, revealing what's behind it — that's // back. Matches Safari, Chrome, and Finder. sendPreviewNavCommand(direction === 'left' ? 'back' : 'forward') } }) window.on('app-command', (event, command) => { if (command !== 'browser-backward' && command !== 'browser-forward') { return } // Claim it either way: unhandled, Chromium walks the HOST document's // history, which would navigate the app shell itself. event.preventDefault() sendPreviewNavCommand(command === 'browser-backward' ? 'back' : 'forward') }) } function sendOpenFolderRequested() { if (!mainWindow || mainWindow.isDestroyed()) { return } const webContents = mainWindow.webContents if (!webContents || webContents.isDestroyed()) { return } webContents.send('hermes:open-folder-requested') } // Tell the renderer the machine just woke. Sleep silently drops the // renderer's WebSocket to the local backend; the renderer reconnects on this // signal so the chat composer doesn't stay stuck on "Starting Hermes...". function sendPowerResume() { if (!mainWindow || mainWindow.isDestroyed()) { return } const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } webContents.send('hermes:power-resume') } let powerResumeRegistered = false // Mirror of powerMonitor's AC/battery state, broadcast to every window so // renderer backstop polls can slow down on battery (see store/power.ts). // `null` until the first powerMonitor read after app ready. let onBatteryPower: boolean | null = null // Renderer-side battery gating seeds from this and stays current via the // 'hermes:power-battery' push below. ipcMain.handle('hermes:power-battery:get', () => onBatteryPower === true) function broadcastBatteryState(next: boolean) { if (onBatteryPower === next) { return } onBatteryPower = next for (const win of BrowserWindow.getAllWindows()) { const { webContents } = win if (webContents && !webContents.isDestroyed()) { webContents.send('hermes:power-battery', next) } } } function registerPowerResumeListeners() { if (powerResumeRegistered) { return } powerResumeRegistered = true try { // 'resume' covers sleep/wake; 'unlock-screen' covers lock/unlock without a // full suspend. Either can drop an idle socket. powerMonitor.on('resume', sendPowerResume) powerMonitor.on('unlock-screen', sendPowerResume) powerMonitor.on('on-battery', () => broadcastBatteryState(true)) powerMonitor.on('on-ac', () => broadcastBatteryState(false)) onBatteryPower = powerMonitor.isOnBatteryPower() // Pooled remote/SSH backends are also suspect after a wake (#93910): the // renderer nudge above only re-drives the PRIMARY socket, while pooled // tunnels have no renderer loop of their own. Bounded + coalesced inside; // never a hot loop. attachPowerResumeRemoteRevalidation({ log: rememberLog, powerMonitor, revalidate: () => revalidateSuspectPoolAfterResume() }) } catch { // powerMonitor is unavailable before app 'ready' on some platforms; the // caller registers after 'ready', so this should not normally throw. } } function getAppIconPath() { // Fail-soft: skip candidates that exist but don't decode (truncated PNG in a // packaged app.asar previously crashed createWindow mid-session). Missing // every candidate is fine — the window then uses the platform default icon. try { return resolveAppIcon(APP_ICON_PATHS) } catch { return undefined } } function sendOpenUpdatesRequested() { // The renderer mounts its open-updates listener in the same effect pass that // signals deep-link readiness. Before that (e.g. a boot-time dialog answered // before the window is up) queue the request; 'hermes:deep-link-ready' flushes it. if (!_rendererReadyForDeepLink || !mainWindow || mainWindow.isDestroyed()) { _pendingOpenUpdates = true return } const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } webContents.send('hermes:open-updates') // #83998: never pump the Windows foreground from an ambient surface — // showInactive + a guarded focus keep the raise from dismissing another // app's native dialog. if (!mainWindow.isVisible()) { mainWindow.showInactive() } if (shouldFocusToTakeKeyboard(mainWindow)) { mainWindow.focus() } } // Push titlebar/fullscreen chrome state to a window's renderer. Defaults to the // primary, but any full chat window (primary or a secondary "instance" peer) // passes itself so its own fullscreen toggle drives its own traffic-light inset. function sendWindowStateChanged(nextIsFullscreen?: boolean, target = mainWindow) { if (!target || target.isDestroyed()) { return } const { webContents } = target if (!webContents || webContents.isDestroyed()) { return } const state = getWindowState(target) if (typeof nextIsFullscreen === 'boolean') { state.isFullscreen = nextIsFullscreen } webContents.send('hermes:window-state-changed', state) } function buildApplicationMenu() { const template: MenuItemConstructorOptions[] = [] const checkForUpdatesItem = { label: 'Check for Updates…', click: () => sendOpenUpdatesRequested() } if (IS_MAC) { template.push({ label: APP_NAME, submenu: [ { label: `About ${APP_NAME}`, click: () => showAboutPanelFresh() }, checkForUpdatesItem, { type: 'separator' }, { role: 'services' }, { type: 'separator' }, { role: 'hide' }, { role: 'hideOthers' }, { role: 'unhide' }, { type: 'separator' }, { role: 'quit' } ] }) } template.push({ label: 'File', submenu: [ // No accelerator: ⌘⇧N is a rebindable renderer keybind (session.newWindow); // a menu accelerator would fight the rebind panel and (on macOS) be // swallowed before the renderer sees it. Here purely for discoverability. { click: () => createInstanceWindow(), label: 'New Window' }, // Same no-accelerator rationale: ⌘O is the rebindable renderer keybind // (workspace.openFolder). Clicking runs the same open-folder-as-project // flow through the renderer. { click: () => sendOpenFolderRequested(), label: 'Open Folder…' }, { type: 'separator' }, IS_MAC ? { // NO accelerator: on macOS a registered ⌘W is consumed by the OS // menu before the web contents ever sees it (and registerAccelerator // false is a no-op on mac — electron#18295). Leaving it off lets the // `before-input-event` handler below intercept ⌘W and route it to the // renderer's close-active-tab. Clicking the item still closes the tab // (or window) via the same request. click: () => sendClosePreviewRequested(), label: 'Close' } : { role: 'quit' } ] }) template.push({ label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, // ⌘⇧V is only wired up by this item existing: an accelerator with no menu // entry is never translated into an editor command, so the chord was a // no-op in every input in the app. The composer inserts plain text on // every paste anyway, so this is the same result as ⌘V there — it's the // terminal, preview, and other editable surfaces that need the strip. { role: 'pasteAndMatchStyle' }, { role: 'delete' }, { role: 'selectAll' }, ...(IS_MAC ? ([ { type: 'separator' }, { label: 'Substitutions', submenu: [{ role: 'showSubstitutions' }, { type: 'separator' }, { role: 'toggleTextReplacement' }] } ] satisfies MenuItemConstructorOptions[]) : []) ] }) template.push({ label: 'View', submenu: [ // Not `role: 'reload'`: that hard-reloads the RENDERER (every pane, the // whole shell) and a focused in-app browser needs ⌘R to mean "reload // this page", the way it does in every other browser. ⇧⌘R // (`forceReload`) below stays the unconditional escape hatch. // // No accelerator: ⌘R is claimed in `installPreviewShortcut`, which works // on every platform (this menu exists only on macOS). Declaring it here // too would fire the item and the input hook for one keypress. { click: () => sendPreviewNavCommand('reload'), label: 'Reload' }, { role: 'forceReload' }, { label: 'Toggle Developer Tools', accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Ctrl+Shift+I', click: (_menuItem, browserWindow) => toggleDevTools(browserWindow || mainWindow) }, { type: 'separator' }, { label: 'Actual Size', accelerator: 'CommandOrControl+0', click: () => { setAndPersistZoomLevel(mainWindow, DEFAULT_ZOOM_LEVEL) } }, { label: 'Zoom In', accelerator: 'CommandOrControl+Plus', click: () => { if (mainWindow && !mainWindow.isDestroyed()) { setAndPersistZoomLevel(mainWindow, mainWindow.webContents.getZoomLevel() + ZOOM_STEP) } } }, { label: 'Zoom Out', accelerator: 'CommandOrControl+-', click: () => { if (mainWindow && !mainWindow.isDestroyed()) { setAndPersistZoomLevel(mainWindow, mainWindow.webContents.getZoomLevel() - ZOOM_STEP) } } }, { type: 'separator' }, { role: 'togglefullscreen' } ] }) template.push(windowMenuTemplate(IS_MAC)) template.push({ label: 'Help', role: 'help', submenu: [checkForUpdatesItem] }) return Menu.buildFromTemplate(template) } function toggleDevTools(window) { // DevTools is enabled in packaged builds so users can diagnose renderer // issues without needing a dev build. Trade-off: tiny attack surface // increase versus a much better support story when WS connection or // CSP issues surface in the field. const { webContents } = window if (webContents.isDevToolsOpened()) { webContents.closeDevTools() } else { webContents.openDevTools({ mode: 'detach' }) } } function installDevToolsShortcut(window) { // Only Ctrl+Shift+I (or Cmd+Opt+I on Mac) opens DevTools. // F12 is explicitly blocked so Chromium's built-in handler doesn't open it. window.webContents.on('before-input-event', (event, input) => { if (input.type !== 'keyDown') { return } const key = input.key.toLowerCase() // A renderer binding gets first refusal. Chromium otherwise claims F12 // before the renderer can capture or dispatch it. if (input.key === 'F12') { const decision = f12ShortcutDecision(input, f12ShortcutActiveWindows.has(window.webContents.id), f12Blocked) if (decision === 'forward') { event.preventDefault() window.webContents.send('hermes:f12-shortcut', toF12KeyboardEventPayload(input)) return } if (decision === 'block') { event.preventDefault() return } // Not blocked — fall through to open DevTools. } const isInspectShortcut = input.key === 'F12' || (IS_MAC && input.meta && input.alt && key === 'i') || (!IS_MAC && input.control && input.shift && key === 'i') if (!isInspectShortcut) { return } event.preventDefault() toggleDevTools(window) }) } function installPreviewShortcut(window) { let focusedAt = 0 window.on('focus', () => { focusedAt = Date.now() }) window.webContents.on('before-input-event', (event, input) => { const action = windowAcceleratorAction(input, IS_MAC, Date.now() - focusedAt) // A ⌘W/⌘R that auto-repeats or lands right as focus arrives belongs to // the app that just lost focus (#105498). Claim it so the renderer's // keybind doesn't act on it either, and do nothing. if (action === 'swallow') { event.preventDefault() return } // Always claim ⌘W here (the File>Close item deliberately has no // accelerator, so nothing else does). The renderer decides tab-vs-window // — no `previewShortcutActive` gate, so it works for every closeable tab. // keyUp is not a claim: a chord that started in another app can deliver // its leftover keyup when this window inherits focus (#105498). if (action === 'close-tab') { event.preventDefault() // ⌘W in the HUD is "leave HUD mode", not "close a tab in the app // window". Routing it to the main renderer closed the app's tab out // from under the user while the HUD stayed put; routing it through the // HUD's own close path hands the session back like the exit button. // Keep a closing (or superseded) HUD from sending a second ⌘W to the // hidden main window while its 1.5s close grace is still running. if (hudWindows.has(window)) { if (window === hudWindow && !window.isDestroyed()) { closeHudWindow() } return } sendClosePreviewRequested() return } // ⌘R rides here rather than on the View menu item for the same reason: // the application menu only exists on macOS (it is set to null elsewhere, // see #77845), so a menu accelerator would leave Windows and Linux with no // way to reload a page at all. ⇧⌘R is left alone — that is `forceReload`, // the unconditional whole-window escape hatch. if (action === 'reload') { event.preventDefault() sendPreviewNavCommand('reload') } }) } // Zoom level is persisted in the renderer's own localStorage (per-origin, // survives reloads/restarts) rather than a main-process JSON file. The main // process owns setZoomLevel, so we mirror each change into localStorage and // read it back on did-finish-load to re-apply after reloads or crash recovery. import { applyZoomLevel, DEFAULT_ZOOM_LEVEL, installZoomReassertOnNavigation, installZoomReassertOnWindowEvents, percentToZoomLevel, ZOOM_STEP, ZOOM_STORAGE_KEY, zoomLevelToPercent, zoomWiringForWindowKind } from './zoom' function setAndPersistZoomLevel(window, zoomLevel) { if (!window || window.isDestroyed()) { return } // Apply + notify in one funnel so the settings UI stays in sync, including // changes made via the keyboard shortcuts or the View menu. const next = applyZoomLevel(window.webContents, zoomLevel) // The native window-controls overlay doesn't scale with the page; re-apply // it at the new zoom so its height tracks the zoomed titlebar (#81086). applyTitleBarOverlay(window) // Primary store: main-process JSON (survives crash recovery — #56726). writeZoomState(next) // Secondary mirror: renderer localStorage (legacy store; kept in sync so a // downgrade or JSON read failure still finds a sane value). window.webContents .executeJavaScript( `try { localStorage.setItem(${JSON.stringify(ZOOM_STORAGE_KEY)}, ${JSON.stringify(String(next))}) } catch { void 0 }` ) .catch(error => rememberLog(`[zoom] persist failed: ${error?.message || error}`)) } function restorePersistedZoomLevel(window) { if (!window || window.isDestroyed()) { return } // Prefer the JSON file — it survives crash recovery wiping Electron's // cache/storage folders (#56726). applyZoomLevel notifies the renderer so // the Appearance UI Scale control stays in sync. const saved = readZoomState() if (saved != null) { // Drift-guard: skip when this window already shows the persisted level. // Blindly re-applying on every resize/move would race the compositor's // surface reconfigure during a Wayland resize storm (Cosmic tiled mode // fires one whenever a new session window opens — #84818) and keep the // renderer notification stream churning for no gain. The settle-verify // chain in installZoomReassertOnWindowEvents re-applies only when the // window actually drifted from the persisted level. const current = window.webContents?.getZoomLevel?.() if (current != null && Math.abs(current - saved) < 1e-9) { return } applyZoomLevel(window.webContents, saved) applyTitleBarOverlay(window) return } // No JSON yet: paint the shipped default immediately so a fresh install // doesn't flash Chromium 100%, then try localStorage for pre-JSON installs // and overwrite if a legacy value is there. applyZoomLevel(window.webContents, DEFAULT_ZOOM_LEVEL) applyTitleBarOverlay(window) window.webContents .executeJavaScript( `(() => { try { return localStorage.getItem(${JSON.stringify(ZOOM_STORAGE_KEY)}) } catch { return null } })()` ) .then(stored => { if (!window || window.isDestroyed()) { return } const level = stored == null ? DEFAULT_ZOOM_LEVEL : Number(stored) const applied = applyZoomLevel(window.webContents, level) writeZoomState(applied) applyTitleBarOverlay(window) }) .catch(error => rememberLog(`[zoom] restore failed: ${error?.message || error}`)) } function installZoomShortcuts(window) { // Override Ctrl/Cmd + +/-/0 with half Chromium's default zoom step (ZOOM_STEP // is 0.1 vs Chromium's 0.2). The menu items handle this on macOS (where the // menu is always present), but on Linux/Windows the menu is null and // Chromium's default handler would use the full 0.2 step, so we intercept // here for consistency. Ctrl/Cmd+0 resets to DEFAULT_ZOOM_LEVEL, not Chromium 0. window.webContents.on('before-input-event', (event, input) => { const action = windowAcceleratorAction(input, IS_MAC) if (action === 'zoom-reset') { event.preventDefault() setAndPersistZoomLevel(window, DEFAULT_ZOOM_LEVEL) } else if (action === 'zoom-in') { // Zoom-in must accept the shift modifier: on US layouts Plus is // physically Shift+=, so Cmd+Plus arrives as Cmd+Shift+'+' (or '=' // depending on platform). The old blanket shift guard silently // dropped keyboard zoom-in on macOS (#43517). event.preventDefault() setAndPersistZoomLevel(window, window.webContents.getZoomLevel() + ZOOM_STEP) } else if (action === 'zoom-out') { event.preventDefault() setAndPersistZoomLevel(window, window.webContents.getZoomLevel() - ZOOM_STEP) } }) // Ctrl/Cmd + mouse wheel — the standard desktop/browser zoom gesture // (#40295). Chromium surfaces it as the main-process 'zoom-changed' event // (wheel events are DOM-side, so before-input-event never sees them). // Route through the same persist+notify funnel as the keyboard shortcuts // so wheel zoom survives restarts and the settings Scale control stays in // sync, and use the same half step for consistency. window.webContents.on('zoom-changed', (event, zoomDirection) => { event.preventDefault() const delta = zoomDirection === 'in' ? ZOOM_STEP : -ZOOM_STEP setAndPersistZoomLevel(window, window.webContents.getZoomLevel() + delta) }) } /** * The custom (renderer) context menu's main-process half. * * The app popups no native menus: the renderer owns the menu UI so labels * are translated with the rest of the app. Main keeps only what Chromium * reports here and the renderer cannot see: * - spell-check facts (misspelled word + suggestions) — forwarded so the * renderer appends them to its already-open menu, * - the gesture coordinates — kept for copyImageAt, which needs them. */ const lastContextMenuPoint = new Map() function installContextMenuBridge(window: BrowserWindow) { window.webContents.on('context-menu', (_event, params) => { lastContextMenuPoint.set(window.webContents.id, { x: params.x, y: params.y }) const suggestions = Array.isArray(params.dictionarySuggestions) ? params.dictionarySuggestions : [] if (params.isEditable && params.misspelledWord) { window.webContents.send('hermes:context-menu-spellcheck', { misspelledWord: params.misspelledWord, suggestions }) } }) } // Chromium-initiated downloads (renderer anchor/blob downloads, drag-outs) // land here. Without a handler the OS save dialog opens with the process cwd // as the default directory (win-unpacked in packaged installs) and whatever // extensionless name the anchor carried. Route every download to the user's // Downloads directory and guarantee a MIME-derived extension. function installDownloadHandling() { session.defaultSession.on('will-download', (_event, item) => { const suggested = item.getFilename() || 'download' const hasExtension = Boolean(path.extname(suggested)) const extension = hasExtension ? '' : extensionForMimeType(item.getMimeType()) const filename = `${suggested}${extension}` try { item.setSaveDialogOptions({ title: 'Save File', defaultPath: path.join(app.getPath('downloads'), filename), filters: extension || /^image\//i.test(item.getMimeType() || '') ? [ { name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'] }, { name: 'All Files', extensions: ['*'] } ] : undefined }) } catch { // No Downloads directory to offer — keep Chromium's default prompt. } }) } function installMediaPermissions() { // Async request handler: the prompt-style path (most platforms). // clipboard-sanitized-write is granted ONLY to the exact Skills Hub origins // (hub-iframe-policy.ts): the picker's Copy controls write to the clipboard, // and every other frame — artifact previews included — stays denied. session.defaultSession.setPermissionRequestHandler((webContents, permission, callback, details) => { if ((permission as string) === 'clipboard-sanitized-write') { callback(isHermesHubClipboardWrite(focusedFrameOrigin(webContents))) return } callback(isMediaCapturePermission(permission, details)) }) // Synchronous check handler: Chromium consults this for getUserMedia on // Windows in addition to (or instead of) the request handler. Without it, // the check defaults to false and capture is denied before the request // handler ever runs. The check handler carries no mediaTypes metadata, so // the shared predicate runs with `undefined` details and allows the capture // permissions — identical policy to the request handler below, just without // the metadata refinement (absent metadata is allowed there too). session.defaultSession.setPermissionCheckHandler((webContents, permission) => { if ((permission as string) === 'clipboard-sanitized-write') { return isHermesHubClipboardWrite(focusedFrameOrigin(webContents)) } return isMediaCapturePermission(permission, undefined) }) } // Origin of the frame a permission request came from. The request handler is // given the webContents of the TOP document (Chromium routes subframe // permission requests through it in Electron 40 without exposing the frame // directly), so when the top document is NOT on a hub origin we fall back to // the request's own `requestingUrl` — the URL the frame actually asked for — // whose origin is exact for both hub deployments and `null` for anything // sandboxed or opaque. function focusedFrameOrigin( webContents: { getURL?: () => string } | null | undefined, details?: { requestingUrl?: string } ): string | null { try { if (details?.requestingUrl) { return new URL(details.requestingUrl).origin } if (webContents?.getURL) { return new URL(webContents.getURL()).origin } } catch { // Unparseable URL — report no origin; callers deny. } return null } /** The picker embed URL the hub iframe starts on (both deployments). */ function isHermesHubPickerUrl(url: string): boolean { try { const parsed = new URL(url) const isHubOrigin = parsed.origin === HERMES_HUB_ORIGIN || parsed.origin === HERMES_HUB_FALLBACK_ORIGIN const isPickerPath = parsed.pathname === '/hermes-agent/docs/skills' || parsed.pathname === '/docs/skills' return isHubOrigin && isPickerPath } catch { return false } } /** Look up a subframe by its process/routing id; never throws. */ function findFrameByIdentifier( webContents: { frames?: readonly unknown[]; framesInSubtree?: readonly unknown[] } | null | undefined, frameProcessId: number, frameRoutingId: number ): { origin?: string; reload?: () => void } | null { const candidates = [...(webContents?.frames ?? []), ...(webContents?.framesInSubtree ?? [])] as Array<{ processId?: number routingId?: number frameProcessId?: number frameRoutingId?: number origin?: string reload?: () => void }> return ( candidates.find( f => (f.frameProcessId ?? f.processId) === frameProcessId && (f.frameRoutingId ?? f.routingId) === frameRoutingId ) ?? null ) } /** `frame.origin` as a safe string; destroyed frames report opaque/'null'. */ function safeFrameOrigin(frame: { origin?: string } | null | undefined): string | null { if (!frame?.origin || frame.origin === 'null') { return null } return frame.origin } // --------------------------------------------------------------------------- // OAuth remote-gateway auth. // // Hosted Hermes gateways gate the dashboard behind an OAuth provider (e.g. // Nous Research) instead of a static session token. The auth model is // fundamentally different from the token path: // // * REST is authed by HttpOnly session cookies (``hermes_session_at``), // established by a browser redirect round-trip (/login → IDP → // /auth/callback sets cookies). We cannot read the HttpOnly cookie value // in JS — instead we let an Electron BrowserWindow complete the round // trip into a PERSISTENT session partition, and thereafter route our REST // through Electron's ``net`` bound to that same partition so the cookie // jar attaches the cookie automatically. // * WebSocket upgrades require a single-use ``?ticket=`` minted at // ``POST /api/auth/ws-ticket`` (cookie-authed). The legacy ``?token=`` // path is unconditionally rejected by gated gateways. // * Nous Portal now issues a 24h ROTATING, reuse-detected refresh token // alongside the ~15-min access token (Portal NAS #293 / hermes #37247). // Both are set as HttpOnly cookies (``hermes_session_at`` ~15 min, // ``hermes_session_rt`` 24h). When the AT cookie lapses but the RT cookie // is still alive, the gateway middleware transparently rotates a fresh AT // on the next authenticated request — so connectivity must NOT be gated on // the AT cookie alone. We probe liveness by actually minting a ws-ticket // (which triggers that server-side refresh) and treat a real 401 as // "needs re-login"; the AT-or-RT cookie presence check is only a cheap // "is the user signed in at all?" gate / display signal. // --------------------------------------------------------------------------- const OAUTH_SESSION_PARTITION = LEGACY_OAUTH_PARTITION let oauthSession = null function getOauthSession() { if (oauthSession || !app.isReady()) { return oauthSession } oauthSession = session.fromPartition(OAUTH_SESSION_PARTITION) installRemoteHeaderRulesOnSession(oauthSession) return oauthSession } // Per-connection cookie jars (#92183). A NON-primary v2 registry remote with // cookie auth rides its own partition so two registered gateways can never // evict — or be handed — each other's session cookies (Chromium jars ignore // the port, so two dashboards on one VPN host used to collide in the shared // jar above). The primary / v1 remote / cloud / portal flows keep the legacy // shared partition; see oauth-partition.ts for the full rules. const oauthSessionsByPartition = new Map() function resolveOauthPartitionForUrl(url, { connectionId = '', pendingAuthMode = '', pendingKind = '' } = {}) { try { return resolveOauthPartition(url, { connectionId, pendingAuthMode, pendingKind, registry: readDesktopConnectionsRegistry(), v1RemoteUrl: readDesktopConnectionConfig()?.remote?.url }) } catch { // A broken registry read must never take cookie auth down with it. return OAUTH_SESSION_PARTITION } } function getOauthSessionForUrl(url, { connectionId = '', pendingAuthMode = '', pendingKind = '' } = {}) { const partition = resolveOauthPartitionForUrl(url, { connectionId, pendingAuthMode, pendingKind }) if (partition === OAUTH_SESSION_PARTITION) { return getOauthSession() } if (!app.isReady()) { return null } let sess = oauthSessionsByPartition.get(partition) if (!sess) { sess = session.fromPartition(partition) oauthSessionsByPartition.set(partition, sess) installRemoteHeaderRulesOnSession(sess) } return sess } // Cold-start cookie-jar warm-up. A `persist:` partition materialized via // session.fromPartition() loads its on-disk cookie store LAZILY: the very first // cookies.get() on a fresh cold start can resolve BEFORE the jar has finished // hydrating from disk and return an empty array — even though the user is // signed in. That false-negative used to make hasLiveOauthSession() report // "not signed in", which on the initial boot path (startHermes → the renderer's // single-shot boot() with no retry) surfaced as the "Hermes couldn't start" // OAuth overlay that vanishes the instant the user clicks Retry. // // We force the store to hydrate once, up front: flushStorageData() then a // throwaway cookies.get(). The promise is memoized so every caller awaits the // same single warm-up. Best-effort — any error resolves so we fall back to the // live read (which then does its own bounded re-check). // Memoized per PARTITION: per-connection jars (#92183) hydrate independently. const oauthCookieWarmups = new Map() function warmOauthCookieStore(url?) { const partition = resolveOauthPartitionForUrl(url) const pending = oauthCookieWarmups.get(partition) if (pending) { return pending } const warmup = (async () => { const sess = getOauthSessionForUrl(url) if (!sess) { // App not ready yet — don't memoize a no-op; let a later call retry. oauthCookieWarmups.delete(partition) return } try { // flushStorageData() forces Chromium to reconcile the in-memory cookie // monster with the on-disk SQLite store; the subsequent get() then reads // a populated jar rather than racing the lazy first-access load. sess.flushStorageData?.() await sess.cookies.get({}) } catch { // Best effort; the real read below re-checks with bounded retries. } })() oauthCookieWarmups.set(partition, warmup) return warmup } // Bare + prefixed variants of the session cookies live in // connection-config.ts (cookiesHaveSession / cookiesHaveLiveSession). See // that module for details. // #61457: snapshot a partition jar's session cookies for this gateway into // the in-memory mirror, keyed by the SAME partition the jar belongs to. // Best-effort: a failed read just means the next response's Set-Cookie // capture populates the mirror instead. async function captureRemoteSessionCookiesIntoMirror(sess, partition, baseUrl) { if (!sess || !partition) { return } try { remoteSessionCookies.recordFromJar(partition, baseUrl, await sess.cookies.get({ url: baseUrl })) } catch (error) { rememberLog(`Remote session cookie mirror capture failed: ${error?.message || error}`) } } async function hasOauthSessionCookie(baseUrl, { connectionId = '', pendingAuthMode = '', pendingKind = '' } = {}) { const sess = getOauthSessionForUrl(baseUrl, { connectionId, pendingAuthMode, pendingKind }) if (!sess) { return false } const parsed = new URL(baseUrl) try { // Query by URL so the cookie jar applies Domain/Path/Secure scoping for us. const cookies = await sess.cookies.get({ url: baseUrl }) return cookiesHaveSession(cookies) } catch { // Fall back to a host match if the URL query path errors. try { const cookies = await sess.cookies.get({ domain: parsed.hostname }) return cookiesHaveSession(cookies) } catch { return false } } } // Like hasOauthSessionCookie, but returns true when EITHER a live access-token // cookie OR a (longer-lived) refresh-token cookie is present. This is the right // "is the user signed in at all?" check: an expired AT with a live RT is still // a connectable session because the gateway rotates a fresh AT server-side on // the next authenticated request. Gating on the AT alone forces a needless full // re-login every ~15 min. Used for the Settings "connected" indicator and as a // cheap early-out before attempting a network round-trip in resolveRemoteBackend. async function hasLiveOauthSession(baseUrl) { const sess = getOauthSessionForUrl(baseUrl) if (!sess) { return false } const parsed = new URL(baseUrl) const readLive = async () => { try { const cookies = await sess.cookies.get({ url: baseUrl }) return cookiesHaveLiveSession(cookies) } catch { try { const cookies = await sess.cookies.get({ domain: parsed.hostname }) return cookiesHaveLiveSession(cookies) } catch { return false } } } // First read against the (possibly still-hydrating) jar. if (await readLive()) { return true } // Cold-start false-negative guard. A `persist:` partition's cookie store // loads lazily, so the FIRST read on a fresh boot can come back empty even // for a signed-in user — the exact race that produced the transient "Hermes // couldn't start / not signed in" overlay that Retry always cleared. Before // trusting a negative, force the store to hydrate and re-read a couple of // times with a short backoff. A genuinely signed-out user still resolves // false quickly (≤ ~180ms); a signed-in user racing the load now wins. await warmOauthCookieStore(baseUrl) for (const delayMs of [30, 60, 90]) { if (await readLive()) { return true } await new Promise(resolve => setTimeout(resolve, delayMs)) } return readLive() } async function clearOauthSession(baseUrl) { const sess = getOauthSessionForUrl(baseUrl) if (!sess) { return } try { const cookies = await sess.cookies.get(baseUrl ? { url: baseUrl } : {}) await Promise.all( cookies.map(c => { const scheme = c.secure ? 'https' : 'http' const cookieUrl = `${scheme}://${c.domain.replace(/^\./, '')}${c.path || '/'}` return sess.cookies.remove(cookieUrl, c.name).catch(() => undefined) }) ) } catch { // Best effort — a stale cookie self-expires anyway. } } // Open a gateway login window in the OAuth session partition, resolving once // the access-token cookie appears (login done) or rejecting if the user closes // the window first. The window navigates through the IDP and back to // /auth/callback, which sets the session cookies on the partition; we poll the // cookie jar rather than try to read the HttpOnly value. // // `silent` selects the URL the window loads, which decides interactive-vs-silent: // - silent=false (default): load ``/login`` — the public interstitial that // renders the "Log in with X" provider chooser. This is the interactive // remote-gateway login the settings UI drives. // - silent=true: load the PROTECTED root ``/`` instead. ``/login`` is a public // route, so loading it NEVER triggers the gate's auto-SSO and always shows // the chooser. Loading a protected page with no session cookie makes the // gate run ``_auto_sso_response``: single registered provider + a live // portal session in this partition → a silent 302 through // ``/auth/login`` → portal ``/oauth/authorize`` (auto-approves org members) // → ``/auth/callback``, which sets the gateway cookie with NO interactive // prompt. This is the per-agent cloud cascade (decisions.md Q5). function openOauthLoginWindow( baseUrl, { silent = false, background = false, connectionId = '', pendingAuthMode = '', pendingKind = '' } = {} ) { return new Promise((resolve, reject) => { // Background roster work may silently renew a Cloud session, but must // never turn an expired saved gateway into a visible login window. const hiddenRecovery = background || !canShowInteractiveOauthLogin() if (!app.isReady()) { reject(new Error('Desktop is not ready to start an OAuth login.')) return } const sess = getOauthSessionForUrl(baseUrl, { connectionId, pendingAuthMode, pendingKind }) if (!sess) { reject(new Error('OAuth session partition is unavailable.')) return } let settled = false let win = null let pollTimer = null let revealTimer = null let deadlineTimer = null const finish = err => { if (settled) { return } settled = true if (pollTimer) { clearInterval(pollTimer) } if (revealTimer) { clearTimeout(revealTimer) } if (deadlineTimer) { clearTimeout(deadlineTimer) } try { if (win && !win.isDestroyed()) { win.destroy() } } catch { // window already torn down } if (err) { reject(err) } else { // #61457: the jar just got the fresh session cookies — mirror them // into memory immediately, before the jar can drop them again. void captureRemoteSessionCookiesIntoMirror( sess, resolveOauthPartitionForUrl(baseUrl, { connectionId, pendingAuthMode, pendingKind }), baseUrl ) resolve({ baseUrl, ok: true }) } } const checkCookie = async () => { if (settled) { return } if (await hasOauthSessionCookie(baseUrl, { connectionId, pendingAuthMode, pendingKind })) { finish(null) } } try { win = new BrowserWindow({ width: 520, height: 720, title: silent ? 'Connecting to Hermes Cloud agent…' : 'Sign in to Hermes gateway', autoHideMenuBar: true, // Silent cascade: start HIDDEN. The auto-SSO 302 chain completes in // well under a second, so the window normally never needs to show. We // only reveal it as a fallback if the cascade DOESN'T complete quickly // (e.g. the portal session lapsed and the gate fell through to the // interactive chooser) — see the reveal timer below. show: !silent && !hiddenRecovery, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true, session: sess, webSecurity: true } }) } catch (error) { finish(error instanceof Error ? error : new Error(String(error))) return } // Re-check the cookie jar on every successful navigation (the callback // redirect is the moment cookies get set) plus a low-frequency poll as a // belt-and-braces fallback for IDPs that finish via in-page JS. win.webContents.on('did-navigate', () => void checkCookie()) win.webContents.on('did-redirect-navigation', () => void checkCookie()) win.webContents.on('did-frame-navigate', () => void checkCookie()) // Log-only lifecycle diagnostics: a crashed sign-in renderer is invisible // to the window's promise path (it never settles), so without this the // failure leaves no trace in desktop.log (#81290 follow-up). installWindowRendererLifecycle(win, { kind: 'oauth', callbacks: { log: rememberLog } }) pollTimer = setInterval(() => void checkCookie(), 750) // Silent-mode reveal fallback: if the cascade hasn't settled shortly, the // auto-SSO didn't go through silently (no portal session, multi-provider, // loop-guard tripped, etc.) and the window is now showing an interactive // page. Reveal it so the user can complete sign-in manually rather than // staring at nothing. Cleared on finish(). if (silent && win && !hiddenRecovery) { revealTimer = setTimeout(() => { try { if (!settled && win && !win.isDestroyed() && !win.isVisible()) { win.show() } } catch { // window torn down } }, 2500) } if (hiddenRecovery) { deadlineTimer = setTimeout(() => finish(new Error('Cloud session recovery requires sign-in.')), 12_000) } win.on('closed', () => { if (!settled) { finish(new Error('Login window closed before authentication completed.')) } }) // ``next`` is intentionally omitted: the gateway lands on ``/`` after // login, which is a valid authenticated page that sets the cookies. We // only care that the cookie jar is populated. // // silent=true loads the protected root so the gate auto-SSOs (no chooser); // silent=false loads the public ``/login`` chooser for interactive sign-in. const normalizedBase = normalizeRemoteBaseUrl(baseUrl) const loginUrl = silent ? `${normalizedBase}/` : `${normalizedBase}/login` const loginHeaders = headersForRemoteRequest(loginUrl) rememberLog( `OAuth login: attaching ${Object.keys(loginHeaders).length} extra gateway header(s) to ${new URL(normalizedBase).host}` ) win.loadURL(loginUrl, oauthLoginLoadUrlOptions(loginHeaders)).catch(error => { // Callback navigation can abort the original load after setting cookies. // Keep the bounded hidden recovery alive long enough to observe them. if (hiddenRecovery && isExpectedOauthNavigationAbort(error)) { void checkCookie() return } finish(error instanceof Error ? error : new Error(String(error))) }) }) } // JSON request routed through the OAuth session partition so the HttpOnly // session cookie is attached automatically by Electron's net stack. Used for // authed REST against a gated gateway, including minting WS tickets. // // #61457: the partition's Chromium jar is not a reliable cookie source — it can // drop the `hermes_session*` cookies (Windows %3A profile folders, lazy // hydration, flush races) and `useSessionCookies: true` then intermittently // omits the cookie → 401 `no_cookie` right after a successful sign-in. Two // mitigations, both keyed by the request's resolved OAuth partition + origin // (the same owner the jar itself is scoped to, so same-origin gateways on // separate jars stay separate here too): // 1. an explicit `Cookie` header built from the in-memory session-cookie // mirror (remote-session-cookies.ts) — an explicit header bypasses the // network stack's jar lookup entirely, and every `Set-Cookie` observed // here (and in the login window) feeds the mirror back; and // 2. one forced silent re-login + single retry when the gateway still // answers 401 — ONLY when shouldReplayAfterCookie401 holds: the 401 is // the auth gate's pre-handler refusal AND the operation is idempotent or // vouched replay-safe (`options.replayOn401`). Anything else keeps the // no-replay rule of requestWithOauthFallback. function fetchJsonViaOauthSession(url, options: any = {}) { const partition = resolveOauthPartitionForUrl(url) const attempt = (): Promise => 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 body = serializeJsonBody(options.body) const timeoutMs = resolveTimeoutMs(options.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS) const request = electronNet.request({ method: options.method || 'GET', url, session: sess, useSessionCookies: true, redirect: 'follow' } as any) setJsonRequestHeaders(request) const headerBag = { ...headersForRemoteRequest(url), ...(options.headers || {}) } // Explicit mirror cookies ride last so an existing caller-supplied // Cookie header still wins, and the mirror never clobbers intent. const mirroredCookies = remoteSessionCookies.cookieHeaderFor(partition, url) if (mirroredCookies && headerBag.Cookie === undefined && headerBag.cookie === undefined) { headerBag.Cookie = mirroredCookies } for (const [name, value] of Object.entries(headerBag)) { request.setHeader(name, String(value)) } let timedOut = false const timer = setTimeout(() => { timedOut = true try { request.abort() } catch { // already finished } reject(new Error(`Timed out connecting to Hermes backend after ${timeoutMs}ms`)) }, timeoutMs) request.on('response', (res: Electron.IncomingMessage): void => { wireOauthSessionResponse(res, { url, isTimedOut: (): boolean => timedOut, clearTimer: (): void => clearTimeout(timer), resolve, reject, onSetCookies: setCookie => remoteSessionCookies.record(partition, url, setCookie) }) }) request.on('error', error => { if (timedOut) { return } clearTimeout(timer) reject(error) }) if (body) { request.write(body) } request.end() }) return attempt().catch(async error => { return retryCookie401WithLogin(error, options, { clearCookies: () => remoteSessionCookies.clear(partition, url), login: async () => { try { await openOauthLoginWindow(new URL(url).origin, { silent: true }) } catch (reloginError) { rememberLog( `Remote session re-login after 401 failed for ${new URL(url).host}: ${reloginError?.message || reloginError}` ) throw reloginError } }, retry: attempt }) }) } // --------------------------------------------------------------------------- // RFC 8252 native-app tokens (system-browser + loopback + PKCE). // // Unlike the cookie flow, the native flow hands the desktop opaque bearer // tokens it holds itself: the access token authenticates REST via // ``Authorization: Bearer`` (which the gateway gate now accepts) and mints WS // tickets the same way, so NO browser session cookie or embedded webview is // involved. Tokens are persisted encrypted at rest via Electron ``safeStorage`` // (OS keychain) keyed by gateway base URL, and refreshed via // ``/auth/native/refresh`` before expiry. This is the desktop half of the // feature; the server half lives in hermes_cli/dashboard_auth/native_flow.py. // --------------------------------------------------------------------------- // In-memory cache of decrypted native tokens, keyed by normalized base URL. // Backed by the encrypted on-disk store so it survives restarts. const _nativeTokens = new Map() function _nativeTokenStorePath() { // Co-located with the connection config under userData; one JSON file mapping // baseUrl → { encoding, value } safeStorage payloads. return path.join(app.getPath('userData'), 'native-oauth-tokens.json') } // The electron-coupled half of the token store: safeStorage encryption plus the // userData file. native-token-store.ts owns the serialization/parse round trip // so it can be tested without an Electron runtime. function _nativeTokenStoreIo(): NativeTokenStoreIo { return { encrypt: encryptDesktopSecret, decrypt: decryptDesktopSecret, readStoreText: () => fs.readFileSync(_nativeTokenStorePath(), 'utf8'), writeStoreText: (text: string) => { fs.mkdirSync(path.dirname(_nativeTokenStorePath()), { recursive: true }) fs.writeFileSync(_nativeTokenStorePath(), text, { mode: 0o600 }) }, rememberLog } } function _persistNativeTokens(baseUrl: string, tokens: NativeTokenSet | null) { persistNativeTokenSet(baseUrl, tokens, _nativeTokenStoreIo()) } function _loadNativeTokens(baseUrl: string): NativeTokenSet | null { baseUrl = normalizeRemoteBaseUrl(baseUrl) const cached = _nativeTokens.get(baseUrl) if (cached) { return cached } const tokens = loadNativeTokenSet(baseUrl, _nativeTokenStoreIo()) if (tokens) { _nativeTokens.set(baseUrl, tokens) } return tokens } function _storeNativeTokens(baseUrl: string, tokens: NativeTokenSet) { _persistNativeTokens(baseUrl, tokens) _nativeTokens.set(baseUrl, tokens) } function _clearNativeTokens(baseUrl: string) { _nativeTokens.delete(baseUrl) _persistNativeTokens(baseUrl, null) } // True when we hold native bearer tokens for this gateway (the native-flow // analogue of hasLiveOauthSession's cookie check). function hasNativeSession(baseUrl: string): boolean { return _loadNativeTokens(baseUrl) !== null } // POST JSON WITHOUT the OAuth cookie partition — used for the native token + // refresh exchanges, which are cookieless by design. Thin wrapper over // fetchJson (no token) so it shares timeout/JSON handling. function postJsonNoAuth(url: string, body: unknown, opts: any = {}) { // resolveJsonBody passes the object through UNCHANGED — fetchJson owns // JSON.stringify. Pre-stringifying here double-encodes the body (a JSON // string inside a JSON string), which the gateway's Pydantic model rejects // with a 422 "Input should be a valid dictionary" (the native // /auth/native/token + /auth/native/refresh legs both go through here). return fetchJson(url, null, { method: 'POST', body: resolveJsonBody(body), ...opts }) } // All explicit mutations go through the coordinator; only its refresh/store // dependencies may call the raw persistence helpers above. It single-flights // the /auth/native/refresh rotation per host (concurrent callers share one // flight instead of racing rotations and losing the winner) and fences a // refresh that lands after a login/logout changed the identity underneath it // (22751c8fd9b9). A 401 on refresh means the RT is dead — tokens are dropped // so the UI prompts a fresh native login; a 503/transient keeps them. const nativeAccessTokenCoordinator: ReturnType = createNativeAccessTokenCoordinator({ clearTokens: _clearNativeTokens, isRefreshAuthRejection: (error: unknown): boolean => readStatusCode(error) === 401, loadTokens: _loadNativeTokens, normalizeBaseUrl: normalizeRemoteBaseUrl, refreshTokens: async (baseUrl: string, tokens: NativeTokenSet): Promise => parseTokenResponse( await postJsonNoAuth( nativeRefreshUrl(baseUrl), { refresh_token: tokens.refreshToken, provider: tokens.provider }, { timeoutMs: 10_000 } ) ), storeTokens: _storeNativeTokens, tokenNeedsRefresh }) // Return a valid native access token for baseUrl, refreshing via // /auth/native/refresh if the stored one is at/near expiry. Returns null when // there are no tokens or the refresh is terminally rejected (caller re-logins). const ensureNativeAccessToken: (baseUrl: string, options?: NativeAccessTokenOptions) => Promise = nativeAccessTokenCoordinator.ensure interface GatewayFileConnection extends RegistryBackendRequestScope { authMode?: 'oauth' | 'token' baseUrl: string token?: null | string } interface GatewayFileSavePayload { sessionId?: string connectionId?: unknown path?: unknown profile?: unknown suggestedName?: unknown } function gatewayFileRequestPath( connection: GatewayFileConnection, 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 = {}): Promise { const filePath = gatewayFilePath(payload.path) if (!filePath) { throw new Error('Missing gateway file path') } const { connection, connectionId, profile } = await resolveGatewayFileBackend(payload, { ensureLegacy: ensureBackend, ensureRegistry: ensureRegistryBackend }) const suggested = String(payload.suggestedName || '').trim() const fallbackName = path.basename(filePath) || suggested || 'download' const ctx: GatewayFileSaveContext = { suggested, fallbackName } const requestPaths = gatewayFileRequestPaths( filePath, requestPath => gatewayFileRequestPath(connection, connectionId, profile, requestPath), payload.sessionId ) const deps: GatewayFileSaveDeps = { showSaveDialog: (options: GatewaySaveDialogOptions): Promise => dialog.showSaveDialog(mainWindow, options) } return saveGatewayDownload(requestPaths, ctx, { ...deps, download: async (requestPath: string, context: GatewayFileSaveContext): Promise => { const url: string = `${connection.baseUrl}${requestPath}` if (connection.authMode === 'oauth') { return requestWithOauthFallback(connection.baseUrl, { ensureNativeAccessToken, requestWithBearer: (bearer: string): Promise => downloadViaTokenToFile(url, null, context, deps, { bearer }), requestWithCookie: (): Promise => downloadViaOauthSessionToFile(url, context, { ...deps, getSession: getOauthSessionForUrl, request: electronNet.request }) }) } return downloadViaTokenToFile(url, connection.token ?? null, context, deps) }, readDataUrl: (requestPath: string): Promise => readGatewayFileDataUrl(connection, requestPath) }) } async function readGatewayFileDataUrl(connection: GatewayFileConnection, requestPath: string): Promise { const json: unknown = await fetchJsonForBackend(connection, requestPath) const dataUrl = json && typeof json === 'object' && 'dataUrl' in json && typeof json.dataUrl === 'string' ? json.dataUrl : '' if (!dataUrl) { throw new Error('Gateway returned no file data') } return dataUrl } // Recover a Cloud cookie only after a confirmed cookie-auth ticket 401. // Each caller still mints its own single-use ticket after the shared recovery. const recoverCloudCookieSession = createCloudSessionRecovery({ hasNativeSession, onRecovered: baseUrl => rememberLog(`[cloud] saved gateway session recovered for ${hostLabelFromBaseUrl(baseUrl)}`), restoreCookieSession: async baseUrl => { // The saved portal identity is the authority for cookie agent sessions. // Roster polling must never reveal an interactive sign-in window. if (!(await hasLivePortalSession())) { return false } if (!(await hasPortalAccessToken()) && !(await renewPortalAccessSilently())) { return false } await openOauthLoginWindow(baseUrl, { silent: true, background: true }) return true } }) // Native bearer first (including one forced 401 rotation), OAuth cookie second. // Transient ticket POST failures keep their bounded retry before Cloud recovery. async function mintGatewayWsTicket(baseUrl: string, headers: Record = {}): Promise { return recoverCloudCookieSession(baseUrl, () => withTransientRetries( (): Promise => mintOauthGatewayWsTicket(baseUrl, { ensureNativeAccessToken, fetchJson, fetchJsonViaOauthSession }, headers), { isRetryable: (error: Error): boolean => !(error instanceof NativeAuthChangedError) && !isGatewayAuthRejection(error) } ) ) } // Build a fresh WS URL for the *current* connection. Critical for reconnects: // OAuth WS tickets are single-use with a ~30s TTL, so the ticket baked into // the cached connection's wsUrl is stale on the second connect. The renderer // calls this immediately before every gateway.connect() so each WS upgrade // carries a freshly-minted ticket. For local/token connections this just // reuses the static token (no minting needed). async function freshGatewayWsUrl(profile) { // Mint for the requested profile's backend, NOT always the primary. The // renderer re-mints right before every gateway.connect(); when swapping to a // pooled profile we must return THAT backend's ws URL, otherwise the connect // silently lands back on the primary (default) backend and writes sessions to // the wrong profile's DB. A null/empty profile resolves to the primary, so // legacy callers and single-profile users are unchanged. const connection = await ensureBackend(profile) if (connection.authMode === 'oauth') { const ticket = await mintGatewayWsTicket(connection.baseUrl, connection.headers) const wsUrl = buildGatewayWsUrlWithTicket(connection.baseUrl, ticket) rememberRemoteWsHeaders(wsUrl, connection.headers) return wsUrl } // Local/token: the cached wsUrl already carries the (long-lived) token. rememberRemoteWsHeaders(connection.wsUrl, connection.headers) return connection.wsUrl } // --- Hermes Cloud discovery + silent per-agent sign-in (cloud-auto-discovery // Phase 3) --------------------------------------------------------------- // // The "cloud" connection mode lets a user sign in to the Nous portal ONCE in // the OAuth session partition, then (a) discover their hosted agents and (b) // connect to any of them with no second interactive sign-in. Both ride the one // portal session cookie living in `persist:hermes-remote-oauth`: // - discovery → GET {portal}/api/agents over the partition-bound net; the // portal session cookie authenticates it (NAS Phase 2.5 accepts the cookie). // - cascade → opening an agent's own /login in the same partition hits the // portal's silent auto-approve (org member, existing session) and 302s back // with that agent's session cookie — no prompt. Each agent still completes // its own PKCE exchange; SSO removes the human click, not a security check. const { hasLivePortalSession, hasPortalAccessToken, renewPortalAccessSilently, openPortalLoginWindow } = createPortalSession({ isReady: () => app.isReady(), getOauthSession, resolvePortalBaseUrl, warmOauthCookieStore, createWindow: options => new BrowserWindow(options), rememberLog }) // Discover the hosted (Hermes Cloud) agents the signed-in user can see. Calls // the NAS trimmed-summary endpoint over the partition-bound net, so the portal // session cookie is attached automatically (no bearer needed — NAS accepts the // cookie). Returns { agents } on success, or { needsOrgSelection: true, orgs } // when the user belongs to multiple orgs and hasn't picked one yet (NAS 409 // org_selection_required). Pass `org` (a slug/id from a prior org list) to // scope discovery to that org. Throws a needsCloudLogin-tagged error when no // portal session is present. async function discoverCloudAgents(org?: string) { const portalBaseUrl = resolvePortalBaseUrl() if (!(await hasLivePortalSession())) { const err = new Error( 'You are not signed in to Hermes Cloud. Open Settings → Gateway, choose Hermes Cloud, and sign in.' ) as any err.needsCloudLogin = true throw err } // Access cookies expire before refresh credentials. Let the portal renew // whichever session this browser currently holds before discovery. if (!(await hasPortalAccessToken())) { await renewPortalAccessSilently() } let body const fetchAgents = () => discoverWithTeamFallback( selectedOrg => fetchJsonViaOauthSession( `${portalBaseUrl}/api/agents${selectedOrg ? `?org=${encodeURIComponent(selectedOrg)}` : ''}`, { method: 'GET', timeoutMs: 15_000 } ), org ) try { body = (await fetchAgents()) as any } catch (initialError) { let error = initialError as any // A 401 with renewal material still in the jar: attempt ONE bounded silent // renewal and retry, so a lapsed access token doesn't surface as a full // interactive re-login while a 30-day refresh session sits unused. Only a // rejected/failed renewal (or a second 401 on genuinely fresh access) // falls through to needsCloudLogin. if (error && error.statusCode === 401 && (await renewPortalAccessSilently({ force: true }))) { try { body = (await fetchAgents()) as any } catch (retryError) { error = retryError } } if (body === undefined) { // A 401 means the portal session lapsed (and silent renewal could not // recover it) — surface it as a re-login, not a generic failure. if (error && error.statusCode === 401) { const err = new Error( 'Your Hermes Cloud session has expired. Open Settings → Gateway and sign in again.' ) as any err.needsCloudLogin = true err.cause = error throw err } // A 409 means we're a multi-org user who hasn't picked an org. The body // carries the user's org list; surface it so the renderer shows a picker // and re-calls discovery with the chosen org. (fetchJsonViaOauthSession // throws on >=400 with err.statusCode + err.message "409: ".) if (error && error.statusCode === 409) { const orgs = parseOrgSelectionError(error) if (orgs) { return { needsOrgSelection: true, orgs } } } throw error } } return { agents: trimCloudAgents(body), org: trimCloudOrg(body?.org) } } // Project a NAS response org ({ id, slug, name, isPersonal }) to the trimmed // shape the renderer persists, or null when absent/malformed. function trimCloudOrg(org) { if (!org || typeof org !== 'object' || typeof org.id !== 'string') { return null } return { id: org.id, slug: typeof org.slug === 'string' ? org.slug : null, name: typeof org.name === 'string' ? org.name : org.id, isPersonal: Boolean(org.isPersonal), role: typeof org.role === 'string' ? org.role : 'MEMBER' } } // Extract the org list from a 409 org_selection_required error body. Parse // defensively and return null if it isn't the shape we expect (caller then // rethrows). function parseOrgSelectionError(error) { const parsed = readJsonErrorBody(error) if (parsed?.error !== 'org_selection_required' || !Array.isArray(parsed.orgs)) { return null } return parsed.orgs .filter(o => o && typeof o === 'object' && typeof o.id === 'string') .map(o => ({ id: o.id, slug: typeof o.slug === 'string' ? o.slug : null, name: typeof o.name === 'string' ? o.name : o.id, isPersonal: Boolean(o.isPersonal), role: typeof o.role === 'string' ? o.role : 'MEMBER' })) } // Project NAS's agent rows to the trimmed DTO the renderer consumes. function trimCloudAgents(body) { const agents = Array.isArray(body?.agents) ? body.agents : [] return agents .filter(a => a && typeof a === 'object' && typeof a.id === 'string') .map(a => ({ id: a.id, name: typeof a.name === 'string' ? a.name : a.id, status: typeof a.status === 'string' ? a.status : 'unknown', dashboardUrl: typeof a.dashboardUrl === 'string' ? a.dashboardUrl : null, dashboardGatewayState: typeof a.dashboardGatewayState === 'string' ? a.dashboardGatewayState : 'unknown' })) } // Silent per-agent sign-in: open the selected agent dashboard's /login in the // SAME OAuth partition. Because the user already holds a live portal session // there, the agent's /oauth/authorize auto-approves (org member) and 302s back, // setting that agent's gateway session cookie WITHOUT a second interactive // prompt. Reuses openOauthLoginWindow — the window self-closes the instant the // agent's session cookie lands (a silent flow finishes in well under a second; // if the portal session were absent it would fall through to an interactive // login, which the discovery gate already prevents). Returns once the agent's // gateway session cookie is present. async function cloudAgentSilentSignIn(dashboardUrl) { const baseUrl = normalizeRemoteBaseUrl(dashboardUrl) // Pre-req: a live portal session must exist, or this would surface an // interactive prompt rather than a silent cascade. Discovery already gates on // this, but a selection can arrive after the session lapsed. if (!(await hasLivePortalSession())) { const err = new Error('Your Hermes Cloud session has expired. Sign in to Hermes Cloud again.') as any err.needsCloudLogin = true throw err } // The cascade rides the portal's auto-approve, which needs the short-lived // access state just like discovery. If only renewal material survived the // restart, mint a fresh access token first so the hidden cascade window // auto-SSOs instead of stalling on an interactive chooser (#73495). if (!(await hasPortalAccessToken())) { await renewPortalAccessSilently() } await openOauthLoginWindow(baseUrl, { silent: true }) return { baseUrl, connected: await hasOauthSessionCookie(baseUrl) } } // --------------------------------------------------------------------------- // Opt-in keychain encryption (secret-storage-policy.ts owns the decision). // Default OFF: no safeStorage call is ever made, so a broken/locked macOS // login keychain can never throw its password dialog on launch. Settings → // Gateway exposes the toggle; flipping it re-encrypts (or decrypts) the // stored secrets in place. // --------------------------------------------------------------------------- const SECRET_STORAGE_POLICY_PATH = path.join(app.getPath('userData'), SECRET_STORAGE_POLICY_FILE) const _secretStoragePolicyIo = { readText: () => fs.readFileSync(SECRET_STORAGE_POLICY_PATH, 'utf8'), writeText: (text: string) => writeSecretFileAtomic(SECRET_STORAGE_POLICY_PATH, text, { encoding: 'utf8' }) } let _secretStoragePolicy: SecretStoragePolicy | null = null function secretStoragePolicy(): SecretStoragePolicy { if (!_secretStoragePolicy) { _secretStoragePolicy = readSecretStoragePolicy(_secretStoragePolicyIo) } return _secretStoragePolicy } function setSecretStoragePolicy(next: SecretStoragePolicy) { _secretStoragePolicy = { on: next.on === true, migrated: next.migrated === true } writeSecretStoragePolicy(_secretStoragePolicy, _secretStoragePolicyIo) } /** * Keychain availability as the renderer should see it. With encryption * opted out this must NOT probe safeStorage — isEncryptionAvailable() is * itself a keychain touch that raises the macOS dialog this feature exists * to avoid. We report `true` so no plain-text warning banners fire: storing * plaintext is the user's chosen (default) mode, not a degraded state. */ function probeSecureTokenStorage(): boolean { if (!secretStoragePolicy().on) { return true } try { return Boolean(safeStorage.isEncryptionAvailable()) } catch { return false } } /** * Rewrite every stored desktop secret (v1 connection.json token/headers + * per-profile overrides, v2 registry connections, native OAuth token store) * through `reencode`. Returns true when any store was rewritten. Shared by * the one-shot legacy migration and the Settings encryption toggle. */ function rewriteAllStoredSecrets(shouldRewrite: (secret: any) => boolean, reencode: (secret: any) => any): boolean { let touched = false const rewriteBlock = (block: any) => { if (!block || typeof block !== 'object') { return block } const next = { ...block, ...(block.token ? { token: reencode(block.token) } : {}) } if (block.headers && typeof block.headers === 'object') { next.headers = Object.fromEntries(Object.entries(block.headers).map(([k, v]) => [k, reencode(v)])) } return next } const blockNeedsRewrite = (o: any) => shouldRewrite(o?.token) || Object.values(o?.headers && typeof o.headers === 'object' ? o.headers : {}).some(shouldRewrite) // v1 connection.json. const config = readDesktopConnectionConfig() if (blockNeedsRewrite(config.remote) || Object.values(config.profiles || {}).some(blockNeedsRewrite)) { touched = true writeDesktopConnectionConfig({ ...config, remote: rewriteBlock(config.remote), profiles: Object.fromEntries(Object.entries(config.profiles || {}).map(([k, v]) => [k, rewriteBlock(v)])) }) } // v2 connections.json registry. const registry = readDesktopConnectionsRegistry() if (registry.connections?.some(blockNeedsRewrite)) { touched = true writeDesktopConnectionsRegistry({ ...registry, connections: registry.connections.map(rewriteBlock) }) } // Native OAuth token store: baseUrl → blob. const io = _nativeTokenStoreIo() try { const store = JSON.parse(io.readStoreText()) if (store && typeof store === 'object' && !Array.isArray(store)) { const entries = Object.entries(store) if (entries.some(([, v]) => shouldRewrite(v))) { touched = true io.writeStoreText(JSON.stringify(Object.fromEntries(entries.map(([k, v]) => [k, reencode(v)])))) } } } catch { // Missing/corrupt native token store: nothing to rewrite. } return touched } /** * One-shot legacy migration: builds before the opt-in policy wrote every * secret as a safeStorage blob. With encryption now defaulting OFF, decrypt * each stored blob once and rewrite it as plain so no future launch touches * the keychain. Marked `migrated` whether or not every blob decrypts — a * broken keychain costs at most ONE prompt (this pass), never one per * launch; blobs that would not decrypt are left in place and simply read as * absent from then on (classifyStoredSecret → 'drop'), so opting encryption * back ON later can still recover them on a healthy keychain. * * Runs before createWindow() so every later read sees the final encodings. */ function migrateLegacyEncryptedSecretsOnce() { const policy = secretStoragePolicy() if (policy.on || policy.migrated) { return } const needsMigration = (secret: any) => classifyStoredSecret(secret, policy) === 'migrate' const reencode = (secret: any) => { if (!needsMigration(secret)) { return secret } const plaintext = decryptDesktopSecret(secret) // Undecryptable now (locked/absent keychain): keep the blob for a // potential future opt-in, but post-migration reads treat it as unset. return plaintext ? { encoding: 'plain', value: plaintext } : secret } let touchedKeychain = false try { touchedKeychain = rewriteAllStoredSecrets(needsMigration, reencode) } catch (error) { const detail = error instanceof Error ? error.message : String(error) rememberLog(`[secret-storage] legacy migration pass failed: ${detail}`) } setSecretStoragePolicy({ on: false, migrated: true }) if (touchedKeychain) { rememberLog('[secret-storage] migrated legacy keychain-encrypted secrets to opt-out storage (one-shot pass)') } } /** * Settings → Gateway toggle: flip keychain-backed encryption and re-encode * every stored secret to match. Turning ON encrypts plain blobs through * strict safeStorage (throws loudly when the keychain is unusable — the * toggle stays off and the renderer shows the error). Turning OFF decrypts * back to plain; this is user-initiated, so a keychain prompt here is * expected and acceptable. */ function applySecretStorageEncryption(on: boolean) { const enable = on === true if (secretStoragePolicy().on === enable) { return { on: enable } } if (enable) { const needsEncrypt = (secret: any) => secret?.encoding === 'plain' && Boolean(secret.value) // Probe FIRST so an unusable keychain fails before any store is touched. if ( !(() => { try { return Boolean(safeStorage.isEncryptionAvailable()) } catch { return false } })() ) { throw new Error( 'OS keychain encryption is unavailable on this machine, so stored gateway secrets cannot be encrypted.' ) } setSecretStoragePolicy({ on: true, migrated: true }) try { rewriteAllStoredSecrets(needsEncrypt, secret => needsEncrypt(secret) ? encryptDesktopSecretStrict(String(secret.value), safeStorage) : secret ) } catch (error) { // Encryption failed midway: revert the policy so reads keep working // against whatever encodings are on disk (mixed stores read fine — // decryptDesktopSecret handles both encodings under either policy). setSecretStoragePolicy({ on: false, migrated: true }) throw error } return { on: true } } // Turning OFF: decrypt everything back to plain while the keychain is // still readable, then flip the policy. const needsDecrypt = (secret: any) => secret?.encoding === SAFE_STORAGE_ENCODING rewriteAllStoredSecrets(needsDecrypt, (secret: any) => { if (!needsDecrypt(secret)) { return secret } const plaintext = decryptDesktopSecret(secret) return plaintext ? { encoding: 'plain', value: plaintext } : secret }) setSecretStoragePolicy({ on: false, migrated: true }) return { on: false } } function encryptDesktopSecret(value, options = {}) { if (!secretStoragePolicy().on) { const raw = String(value || '') return raw ? { encoding: 'plain', value: raw } : null } return encryptDesktopSecretStrict(value, safeStorage, options) } function decryptDesktopSecret(secret) { if (!secret || typeof secret !== 'object') { return '' } const value = String(secret.value || '') if (!value) { return '' } if (secret.encoding === SAFE_STORAGE_ENCODING) { // Legacy blob under an opted-out policy: once the one-shot migration pass // has run, never touch safeStorage again — a dead keychain would otherwise // prompt on every read. Before that pass, decryption is allowed so the // migration itself (and this launch's reads) can recover the value. if (classifyStoredSecret(secret, secretStoragePolicy()) === 'drop') { return '' } try { return safeStorage.decryptString(Buffer.from(value, 'base64')) } catch { return '' } } // Any other encoding (a hand-edited config, or one written by a pre-release // build) is returned verbatim on purpose: this fallback is what lets such a // config connect at all. Not a plaintext-writing path — nothing in this file // persists a token this way. return value } function decryptRemoteHeaders(headers) { const normalized = normalizeRemoteHeaders(headers) const out = {} for (const [name, secret] of Object.entries(normalized)) { // Sanitize AFTER decryption as well as at ingest: a safeStorage envelope // stores ciphertext, so normalizeRemoteHeaders never sees its plaintext. // This is the single funnel every consumer of header values goes through // (login window extraHeaders, onBeforeSendHeaders, electronNet setHeader, // and both connection-test paths), so CR/LF can't reach a request here. const value = sanitizeRemoteHeaderValue(decryptDesktopSecret(secret)) if (value) { out[name] = value } } return out } /** * Turn an editor payload of remote gateway headers into stored secret * envelopes. The payload map is authoritative (a name missing from it is * cleared); per-name values are: * - non-empty string → new plaintext value, encrypted like a token * - null → keep the currently stored envelope for that name * (the editor shows a set-but-hidden secret) * - envelope object → stored verbatim (hand-edited import path) * Name filtering (forbidden/managed headers) happens in * normalizeRemoteHeaders at the registry/config layer. */ function encryptIncomingRemoteHeaders(raw, existing, options: { allowPlainText?: boolean } = {}) { const out = {} const stored = normalizeRemoteHeaders(existing) for (const [name, value] of Object.entries(raw || {})) { const key = String(name || '').trim() if (!key) { continue } if (typeof value === 'string') { const trimmed = value.trim() if (trimmed) { out[key] = encryptDesktopSecret(trimmed, { allowPlainText: options.allowPlainText === true }) } continue } if (value === null) { if (stored[key]) { out[key] = stored[key] } continue } if (value && typeof value === 'object') { out[key] = value } } return out } function rememberRemoteWsHeaders(wsUrl, headers = {}) { remoteWsHeaderStore.remember(wsUrl, headers) } // Decrypted header sources, memoized against the two config caches this // process already keys off mtime. onBeforeSendHeaders now runs on every OAuth // partition as well as defaultSession, so without this every subresource // request would decrypt EVERY registry connection's headers — and a // safeStorage-encoded value costs a keychain round-trip per read. // Both readers refresh their cache object whenever the file mtime moves, so // identity comparison on the cached objects is a correct staleness check. let remoteHeaderSourcesCache: any = null let remoteHeaderSourcesConfigKey: any = null let remoteHeaderSourcesRegistryKey: any = null function remoteHeaderSources() { const config = readDesktopConnectionConfig() const registry = readDesktopConnectionsRegistry() if ( remoteHeaderSourcesCache && remoteHeaderSourcesConfigKey === config && remoteHeaderSourcesRegistryKey === registry ) { return remoteHeaderSourcesCache } const sources = collectRemoteHeaderSources({ connections: (registry?.connections || []).map(entry => ({ kind: entry.kind, url: entry.url, headers: decryptRemoteHeaders(entry.headers) })), v1Remote: modeIsRemoteLike(config.mode) && config.remote?.url ? { url: config.remote.url, headers: decryptRemoteHeaders(config.remote.headers) } : null }) remoteHeaderSourcesCache = sources remoteHeaderSourcesConfigKey = config remoteHeaderSourcesRegistryKey = registry return sources } function headersForRemoteRequest(requestUrl) { return resolveRemoteRequestHeaders(requestUrl, { exactHeaders: remoteWsHeaderStore.headersFor(requestUrl), sources: remoteHeaderSources() }) } function installRemoteHeaderRulesOnSession(sess) { if (!sess || remoteHeaderSessions.has(sess)) { return } remoteHeaderSessions.add(sess) attachRemoteRequestHeaderListener(sess, headersForRemoteRequest) } function installRemoteHeaderRules() { installRemoteHeaderRulesOnSession(session.defaultSession) } // Validate + normalize the per-profile remote overrides map read from disk. // Drops malformed names/entries and keeps only the recognized fields so a // hand-edited or stale connection.json can't inject junk into resolution. function sanitizeConnectionProfiles(raw: Record) { if (!raw || typeof raw !== 'object') { return {} } const out = {} for (const [name, entry] of Object.entries(raw)) { if (!entry || typeof entry !== 'object') { continue } if (name !== 'default' && !PROFILE_NAME_RE.test(name)) { continue } if (entry.mode === 'ssh') { const ssh = normalizeSshConfig(entry) if (ssh) { if (entry.token && typeof entry.token === 'object') { ssh.token = entry.token } out[name] = ssh } continue } const cleaned: { mode: 'remote' | 'local' | 'cloud' url?: string authMode?: string token?: object headers?: object org?: string name?: string remoteProfile?: string savedSsh?: object } = { mode: modeIsRemoteLike(entry.mode) ? entry.mode : 'local' } if (cleaned.mode === 'local') { const savedSsh = normalizeSshConfig(entry.savedSsh) if (savedSsh) { cleaned.savedSsh = savedSsh } } const url = String(entry.url || '').trim() if (url) { cleaned.url = url } cleaned.authMode = normAuthMode(entry.authMode) if ((entry as any).token && typeof entry.token === 'object') { cleaned.token = entry.token } // A URL-remote/cloud per-profile override can map its Desktop routing label // onto the backend's profile namespace (same contract as SSH remoteProfile). const remoteProfileName = normalizeRemoteProfileName((entry as any).remoteProfile) if (remoteProfileName) { cleaned.remoteProfile = remoteProfileName.remoteProfile } const headers = normalizeRemoteHeaders((entry as any).headers) if (Object.keys(headers).length > 0) { cleaned.headers = headers } // Preserve the Hermes Cloud org tag on cloud-mode entries so Settings can // reopen into the same org for a per-profile cloud connection. if (cleaned.mode === 'cloud') { const cloudName = String(entry.name || '').trim() if (cloudName) { cleaned.name = cloudName } const org = String(entry.org || '').trim() if (org) { cleaned.org = org } } out[name] = cleaned } return out } function readDesktopConnectionConfig() { // Check if file changed on disk since last read (e.g. modified by another // process or an external tool). Our own writes update the cache inline // via writeDesktopConnectionConfig, but external changes would be missed. let mtime = null try { mtime = fs.statSync(DESKTOP_CONNECTION_CONFIG_PATH).mtimeMs } catch { mtime = null } if (connectionConfigCache && connectionConfigCacheMtime === mtime) { return connectionConfigCache } let config = { mode: 'local', remote: {}, profiles: {} } try { const raw = fs.readFileSync(DESKTOP_CONNECTION_CONFIG_PATH, 'utf8') // Tighten an install written before this file was owner-only. Every write // now goes out at 0600, but a file already on disk keeps its old 0644 bits // until something chmods it, and waiting for the user's next Settings save // would leave it group/other-readable indefinitely. Runs on a cache miss // only (once per launch, plus after an external edit); chmod moves ctime, // not mtime, so it cannot invalidate the cache it sits inside. // // Deliberately BEFORE JSON.parse, not after: a truncated or hand-mangled // connection.json still contains the token bytes, and parse throws into the // catch below, which swallows the error and falls back to local mode. With // the tighten after the parse, exactly the file that is both corrupt AND // world-readable would be the one file never tightened — and nothing would // ever retry it, because the fallback config is not written back. The chmod // needs only the path, so it has no reason to wait for valid JSON. tightenSecretFileMode(DESKTOP_CONNECTION_CONFIG_PATH) const parsed = JSON.parse(raw) // NOT done here: migrating a legacy non-safeStorage token payload to // ciphertext at rest. Deferred deliberately — it has to honor the opt-in // plaintext choice PR #62319 adds (re-encrypting it converts a portable // credential into a keychain-bound one and can lose the token), write // through sanitizeConnectionProfiles below rather than persisting raw // `parsed`, and tell the user to ROTATE, since every existing backup copy // still holds the old secret. Do not add it without those three. if (parsed && typeof parsed === 'object') { const remote = parsed.remote && typeof parsed.remote === 'object' ? parsed.remote : {} // authMode lives on the remote sub-object: 'oauth' (cookie + ws-ticket) // or 'token' (legacy static session token). Default to 'token' for // backward compatibility with configs written before OAuth support. remote.authMode = remote.authMode === 'oauth' ? 'oauth' : 'token' config = { mode: parsed.mode === 'ssh' ? 'ssh' : modeIsRemoteLike(parsed.mode) ? parsed.mode : 'local', remote, // Per-profile remote overrides: each profile may point at its own // backend (local spawn or its own remote URL). Preserved verbatim so // profileRemoteOverride() can resolve them; normalized lazily on save. profiles: sanitizeConnectionProfiles(parsed.profiles) } } } catch { // Missing or malformed connection settings should fall back to local. } connectionConfigCache = config connectionConfigCacheMtime = mtime return config } function writeDesktopConnectionConfig(config) { fs.mkdirSync(path.dirname(DESKTOP_CONNECTION_CONFIG_PATH), { recursive: true }) // Owner-only, not writeFileAtomic: this is the single choke point for every // connection.json write (the IPC save/apply handlers and // persistSshConnectionToken all land here), and the file carries the // safeStorage-encrypted gateway token plus its URL and SSH host/user/keyPath. // safeStorage keeps the token opaque; 0600 keeps the whole record — and the // fields that are NOT encrypted — off other local accounts, matching // native-oauth-tokens.json and desktop-installation.json. writeSecretFileAtomic(DESKTOP_CONNECTION_CONFIG_PATH, JSON.stringify(config, null, 2)) connectionConfigCache = config connectionConfigCacheMtime = fs.statSync(DESKTOP_CONNECTION_CONFIG_PATH).mtimeMs } // ── v2 connection registry (multi-source) ────────────────────────────────── /** * Read the v2 registry, importing from v1 connection.json exactly once (when * connections.json does not exist yet). Same mtime-cache + tighten-mode * discipline as readDesktopConnectionConfig; a corrupt registry degrades to * local-only via normalizeRegistry rather than throwing at boot. * * An EXISTING registry is additionally reconciled against v1 when the two have * drifted — see reconcileRegistryDrift. The one-shot migration cannot cover a * user who registered nothing and then pointed Settings -> Gateway at a remote, * and until that heals, every launch re-homes them onto a local backend. */ function readDesktopConnectionsRegistry() { let mtime = null try { mtime = fs.statSync(DESKTOP_CONNECTIONS_REGISTRY_PATH).mtimeMs } catch { mtime = null } if (connectionRegistryCache && connectionRegistryCacheMtime === mtime) { return connectionRegistryCache } let registry if (mtime === null) { // First run on this build: import the v1 single-connection config. The v1 // file is NOT modified or deleted — older builds keep reading it. The // migration is deterministic over the v1 input, so even if two processes // race the first run (updater relaunch, second window), both derive the // same registry and the later atomic write is a no-op content-wise. registry = migrateV1ToRegistry(readDesktopConnectionConfig()) try { writeDesktopConnectionsRegistry(registry) } catch { // Write failed (full disk, read-only userData). Keep the migrated // registry in memory so list/save keep working this session instead of // hard-failing every hermes:connections:* call. connectionRegistryCache = registry connectionRegistryCacheMtime = null } return connectionRegistryCache } try { // Same rationale as connection.json: tighten BEFORE parse so a corrupt // file that still holds token bytes gets its mode fixed anyway. tightenSecretFileMode(DESKTOP_CONNECTIONS_REGISTRY_PATH) registry = normalizeRegistry(JSON.parse(fs.readFileSync(DESKTOP_CONNECTIONS_REGISTRY_PATH, 'utf8'))) } catch { // Whole-file corruption (truncated write, mangled hand-edit). The // degraded local-only registry keeps boot working, but the file BYTES are // the user's connection data — preserve them in a sidecar BEFORE any // later write (drift reconcile, connection save) overwrites the file // (#94246: recovery must never be data loss). preserveCorruptRegistrySidecar() registry = normalizeRegistry(null) } if (registry?.quarantined?.length) { rememberLog( `[connections] ${registry.quarantined.length} malformed registry entr${registry.quarantined.length === 1 ? 'y was' : 'ies were'} quarantined (kept under "quarantined" in connections.json); healthy connections loaded normally.` ) } // Heal v1 -> v2 drift: the v1 global route names a remote this registry has // never heard of, so the live descriptor resolves to no connectionId and the // launch pick sends the window somewhere else. Persist so the repair is a // one-time event rather than a recomputation on every read; a failed write // still returns the healed registry for this session. const reconciled = reconcileRegistryDrift(registry, readDesktopConnectionConfig()) if (reconciled.changed) { registry = reconciled.registry try { writeDesktopConnectionsRegistry(registry) return connectionRegistryCache } catch { connectionRegistryCache = registry connectionRegistryCacheMtime = null return registry } } connectionRegistryCache = registry connectionRegistryCacheMtime = mtime return registry } // Copy an unparseable connections.json aside (once per corruption event) so a // later registry write can never destroy the only copy of the user's saved // connections (#94246). Best effort: failure to preserve must not block boot. function preserveCorruptRegistrySidecar() { try { const rawText = fs.readFileSync(DESKTOP_CONNECTIONS_REGISTRY_PATH, 'utf8') if (!rawText.trim()) { return } const sidecar = `${DESKTOP_CONNECTIONS_REGISTRY_PATH}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}` if (!fs.existsSync(sidecar)) { fs.writeFileSync(sidecar, rawText, { mode: 0o600 }) } rememberLog( `[connections] connections.json could not be parsed; preserved the original file at ${sidecar} and continuing with a local-only registry. No connection data was deleted.` ) } catch { // The read itself failed (missing file, permissions) — nothing to save. } } function writeDesktopConnectionsRegistry(registry) { fs.mkdirSync(path.dirname(DESKTOP_CONNECTIONS_REGISTRY_PATH), { recursive: true }) // Owner-only for the same reason as connection.json: entries carry // safeStorage-encrypted tokens plus URLs and SSH host/user/keyPath. writeSecretFileAtomic(DESKTOP_CONNECTIONS_REGISTRY_PATH, JSON.stringify(registry, null, 2)) connectionRegistryCache = registry connectionRegistryCacheMtime = fs.statSync(DESKTOP_CONNECTIONS_REGISTRY_PATH).mtimeMs } /** * Renderer-facing view of a registry entry: token bytes never cross the IPC * boundary — the renderer gets a preview + set flag, mirroring * sanitizeDesktopConnectionConfig. */ function sanitizeRegistryConnection(entry) { const { token, headers, ...rest } = entry const decrypted = decryptDesktopSecret(token) // Last-known stable backend identity (from roster enumeration / Test) so // Settings can hint "Same backend as