Skip to content

The agent that grows with you

fix: restore upstream behavior lost in PM conflict resolutions

ethernetabe76b5176b9
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 0b792364202..543bebbc94a 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -130,6 +130,7 @@ import {
cookiesHaveSession,
gatewayWsUrlIpcResult,
hostLabelFromBaseUrl,
+ isGatewayAuthRejection,
localProfileEntry,
modeIsRemoteLike,
normalizeRemoteBaseUrl,
@@ -326,15 +327,12 @@ import { registerMcpOauthCallbackIpc } from './mcp-oauth-callback-ipc'
import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'
import { fetchLocalMedia } from './media-range'
import { createMinimizeToTray } from './minimize-to-tray'
-import { createNativeAccessTokenCoordinator, NativeAuthChangedError } from './native-access-token'
-import type { GatedDownloadAuth } from './native-auth-decisions'
import {
- oauthSessionIsLive,
- resolveGatedDownloadAuth,
- resolveJsonBody,
- resolveOauthRestAuth,
- resolveReadinessProbeAuth
-} from './native-auth-decisions'
+ createNativeAccessTokenCoordinator,
+ type NativeAccessTokenOptions,
+ NativeAuthChangedError
+} from './native-access-token'
+import { oauthSessionIsLive, resolveJsonBody, resolveReadinessProbeAuth } from './native-auth-decisions'
import {
nativeRefreshUrl,
type NativeTokenSet,
@@ -347,6 +345,7 @@ import { loadNativeTokenSet, type NativeTokenStoreIo, persistNativeTokenSet } fr
import { registerNativeNotifications } from './notification-ipc'
import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'
import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'
+import { mintGatewayWsTicket as mintOauthGatewayWsTicket, requestWithOauthFallback } from './oauth-rest-request'
import { wireOauthSessionResponse } from './oauth-session-response'
import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'
import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'
@@ -1393,8 +1392,7 @@ protocol.registerSchemesAsPrivileged([
function registerMediaProtocol(): void {
const handler: ReturnType<typeof createMediaProtocolHandler> = createMediaProtocolHandler({
- ensureRemoteBearer: (baseUrl: string): Promise<string | null> =>
- ensureNativeAccessToken(baseUrl).catch((): null => null),
+ ensureRemoteBearer: (baseUrl: string): Promise<string | null> => ensureNativeAccessToken(baseUrl),
// Electron's file:// loader ignores Range, which prevents video seeking.
fetchLocal: fetchLocalMedia,
fetchRemote: (url, headers, method) =>
@@ -1654,7 +1652,9 @@ function setPoolLimits(raw) {
poolLimits = clampPoolLimits(raw)
persistPoolLimits(poolLimits)
localBackendSpawnCoordinator.setLimit(poolLimits.maxBackends)
- evictLruPoolBackends(poolMaxBackends())
+ void evictLruPoolBackends(poolMaxBackends()).catch((error: Error): void =>
+ rememberLog(`Pool LRU eviction failed: ${String(error)}`)
+ )
startPoolIdleReaper()
return { ...poolLimits }
@@ -5969,25 +5969,22 @@ async function gatewayAuthProviders(baseUrl, headers = {}) {
// 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) {
- const nativeAt = authMode === 'oauth' ? await ensureNativeAccessToken(baseUrl).catch(() => null) : null
- const probeAuth = resolveReadinessProbeAuth(authMode, nativeAt, token)
-
- if (probeAuth.kind === 'bearer') {
+ 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, options: any = {}) => fetchJson(url, null, { ...options, bearer: probeAuth.token }),
+ probeHealth: (url: string, options: any = {}) =>
+ requestWithOauthFallback(baseUrl, {
+ ensureNativeAccessToken,
+ requestWithBearer: (bearer: string) => fetchJson(url, null, { ...options, bearer }),
+ requestWithCookie: () => fetchJsonViaOauthSession(url, options)
+ }),
probeIsCredentialed: true
}
}
- if (probeAuth.kind === 'cookie') {
- return {
- probeHealth: (url, options: any = {}) => fetchJsonViaOauthSession(url, options),
- probeIsCredentialed: true
- }
- }
+ const probeAuth = resolveReadinessProbeAuth(authMode, null, token)
if (probeAuth.kind === 'token' && probeAuth.token) {
return {
@@ -6634,6 +6631,21 @@ function installPreviewShortcut(window) {
// 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
@@ -7426,6 +7438,7 @@ function _persistNativeTokens(baseUrl: string, tokens: NativeTokenSet | null) {
}
function _loadNativeTokens(baseUrl: string): NativeTokenSet | null {
+ baseUrl = normalizeRemoteBaseUrl(baseUrl)
const cached = _nativeTokens.get(baseUrl)
if (cached) {
@@ -7442,8 +7455,8 @@ function _loadNativeTokens(baseUrl: string): NativeTokenSet | null {
}
function _storeNativeTokens(baseUrl: string, tokens: NativeTokenSet) {
- _nativeTokens.set(baseUrl, tokens)
_persistNativeTokens(baseUrl, tokens)
+ _nativeTokens.set(baseUrl, tokens)
}
function _clearNativeTokens(baseUrl: string) {
@@ -7497,7 +7510,8 @@ const nativeAccessTokenCoordinator: ReturnType<typeof createNativeAccessTokenCoo
// 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) => Promise<string | null> = nativeAccessTokenCoordinator.ensure
+const ensureNativeAccessToken: (baseUrl: string, options?: NativeAccessTokenOptions) => Promise<string | null> =
+ nativeAccessTokenCoordinator.ensure
interface GatewayFileConnection extends RegistryBackendRequestScope {
authMode?: 'oauth' | 'token'
@@ -7513,13 +7527,6 @@ interface GatewayFileSavePayload {
suggestedName?: unknown
}
-async function gatedFileAuth(connection: GatewayFileConnection): Promise<GatedDownloadAuth> {
- const nativeAt =
- connection.authMode === 'oauth' ? await ensureNativeAccessToken(connection.baseUrl).catch(() => null) : null
-
- return resolveGatedDownloadAuth(connection.authMode, nativeAt, connection.token)
-}
-
function gatewayFileRequestPath(
connection: GatewayFileConnection,
connectionId: null | string,
@@ -7562,40 +7569,29 @@ async function saveGatewayFile(payload: GatewayFileSavePayload = {}): Promise<Ga
...deps,
download: async (requestPath: string, context: GatewayFileSaveContext): Promise<GatewayFileSaveResult> => {
const url: string = `${connection.baseUrl}${requestPath}`
- const auth: GatedDownloadAuth = await gatedFileAuth(connection)
- if (auth.kind === 'cookie') {
- return downloadViaOauthSessionToFile<Session>(url, context, {
- ...deps,
- getSession: getOauthSessionForUrl,
- request: electronNet.request
+ if (connection.authMode === 'oauth') {
+ return requestWithOauthFallback(connection.baseUrl, {
+ ensureNativeAccessToken,
+ requestWithBearer: (bearer: string): Promise<GatewayFileSaveResult> =>
+ downloadViaTokenToFile(url, null, context, deps, { bearer }),
+ requestWithCookie: (): Promise<GatewayFileSaveResult> =>
+ downloadViaOauthSessionToFile<Session>(url, context, {
+ ...deps,
+ getSession: getOauthSessionForUrl,
+ request: electronNet.request
+ })
})
}
- return downloadViaTokenToFile(
- url,
- auth.token,
- context,
- deps,
- auth.kind === 'bearer' ? { bearer: auth.token } : {}
- )
+ return downloadViaTokenToFile(url, connection.token ?? null, context, deps)
},
readDataUrl: (requestPath: string): Promise<string> => readGatewayFileDataUrl(connection, requestPath)
})
}
async function readGatewayFileDataUrl(connection: GatewayFileConnection, requestPath: string): Promise<string> {
- const url = `${connection.baseUrl}${requestPath}`
- const auth = await gatedFileAuth(connection)
- let json: unknown
-
- if (auth.kind === 'bearer') {
- json = await fetchJson(url, null, { bearer: auth.token })
- } else if (auth.kind === 'cookie') {
- json = await fetchJsonViaOauthSession(url)
- } else {
- json = await fetchJson(url, auth.token)
- }
+ const json: unknown = await fetchJsonForBackend(connection, requestPath)
const dataUrl =
json && typeof json === 'object' && 'dataUrl' in json && typeof json.dataUrl === 'string' ? json.dataUrl : ''
@@ -7607,50 +7603,21 @@ async function readGatewayFileDataUrl(connection: GatewayFileConnection, request
return dataUrl
}
-// Mint a single-use WS ticket for a gated gateway. Returns the ticket string.
-// Prefers a native bearer token (cookieless RFC 8252 flow) when present,
-// falling back to the OAuth cookie partition otherwise.
-// Throws (with statusCode 401) if the session cookie is missing/expired —
-// callers treat that as "needs re-login".
+// Mint a single-use WS ticket for a gated gateway. Native bearer first (one
+// forced rotation on a confirmed 401, #95701), OAuth cookie partition second.
// Transient transport blips (brief host unreachable, 5xx, timeouts) are retried
// a few times before failing — those 1-3s flaps were promoting into the
-// full-screen "couldn't start" lockout on reconnect.
-async function mintGatewayWsTicket(baseUrl, headers = {}) {
- return withTransientRetries(async () => {
- // Native flow: mint the ticket with the bearer token, no cookie involved.
- const nativeAt = await ensureNativeAccessToken(baseUrl).catch(() => null)
-
- if (nativeAt) {
- const body = (await fetchJson(`${baseUrl}/api/auth/ws-ticket`, null, {
- method: 'POST',
- timeoutMs: 8_000,
- bearer: nativeAt,
- headers
- })) as any
-
- const ticket = body?.ticket
-
- if (!ticket || typeof ticket !== 'string') {
- throw new Error('Gateway did not return a WS ticket.')
- }
-
- return ticket
- }
-
- const body = (await fetchJsonViaOauthSession(`${baseUrl}/api/auth/ws-ticket`, {
- method: 'POST',
- timeoutMs: 8_000,
- headers
- })) as any
-
- const ticket = body?.ticket
-
- if (!ticket || typeof ticket !== 'string') {
- throw new Error('Gateway did not return a WS ticket.')
+// full-screen "couldn't start" lockout on reconnect. Ticket POSTs are
+// replay-safe; arbitrary REST mutations never use this retry loop.
+async function mintGatewayWsTicket(baseUrl: string, headers: Record<string, string> = {}): Promise<string> {
+ return withTransientRetries(
+ (): Promise<string> =>
+ mintOauthGatewayWsTicket(baseUrl, { ensureNativeAccessToken, fetchJson, fetchJsonViaOauthSession }, headers),
+ {
+ isRetryable: (error: Error): boolean =>
+ !(error instanceof NativeAuthChangedError) && !isGatewayAuthRejection(error)
}
-
- return ticket
- })
+ )
}
// Build a fresh WS URL for the *current* connection. Critical for reconnects:
@@ -10076,22 +10043,8 @@ async function fetchJsonForProfile(profile, path) {
// Issue an arbitrary method against a profile's resolved backend, parsed JSON.
async function requestJsonForProfile(profile: string, path: string, method: string, body?: string) {
const conn = await ensureBackend(profile)
- const url = `${conn.baseUrl}${path}`
- const opts = { method, body, timeoutMs: DEFAULT_FETCH_TIMEOUT_MS }
-
- if (conn.authMode === 'oauth') {
- // Native RFC 8252 flow: authenticate with the bearer token (cookieless)
- // when we hold one for this gateway; otherwise use the cookie partition.
- const nativeAt = await ensureNativeAccessToken(conn.baseUrl).catch(() => null)
-
- if (nativeAt) {
- return fetchJson(url, null, { ...opts, bearer: nativeAt, headers: conn.headers })
- }
-
- return fetchJsonViaOauthSession(url, { ...opts, headers: conn.headers })
- }
- return fetchJson(url, conn.token, { ...opts, headers: conn.headers })
+ return fetchJsonForBackend(conn, path, { method, body, timeoutMs: DEFAULT_FETCH_TIMEOUT_MS })
}
async function probeRemoteAuthMode(rawUrl) {
@@ -10316,25 +10269,9 @@ async function testDesktopConnectionConfig(input: any = {}) {
}
async function fetchConnectionStatus(baseUrl, authMode, token, headers = {}) {
- const url = `${baseUrl}/api/status`
-
- if (authMode === 'oauth') {
- // Native PKCE bearer first, OAuth session cookies second — the same two
- // credentials real traffic uses, in the same order. A refresh failure is
- // NOT a silent downgrade to an anonymous probe: the cookie path is still
- // an authenticated request, and if neither credential works the probe
- // fails, which is the correct answer for a gateway we cannot reach with
- // the credentials we hold.
- const nativeAt = await ensureNativeAccessToken(baseUrl).catch(() => null)
-
- if (nativeAt) {
- return fetchJson(url, null, { timeoutMs: 8_000, bearer: nativeAt, headers })
- }
-
- return fetchJsonViaOauthSession(url, { timeoutMs: 8_000, headers })
- }
-
- return fetchJson(url, token, { timeoutMs: 8_000, headers })
+ // Native PKCE bearer first, OAuth session cookies second — the same two
+ // credentials real traffic uses, in the same order (fetchJsonForBackend).
+ return fetchJsonForBackend({ baseUrl, authMode, token, headers }, '/api/status', { timeoutMs: 8_000 })
}
function resetBootProgressForReconnect() {
@@ -10529,7 +10466,15 @@ async function ensureBackend(
}
assertNotPassiveSpawn(passive, key)
- evictLruPoolBackends(poolMaxBackends() - 1)
+ // The hard slot is released only after the evicted child exits. Wait for
+ // that teardown before entering the spawn queue; otherwise a successful LRU
+ // choice still leaves this wake racing the old child for the slot. A
+ // concurrent dial may have installed this key meanwhile — reuse it.
+ await evictLruPoolBackends(poolMaxBackends() - 1)
+
+ if (backendPool.get(key)) {
+ return ensureBackend(profile, opts)
+ }
const entry = {
process: null,
@@ -10717,7 +10662,13 @@ async function ensureRegistryBackend(
}
assertNotPassiveSpawn(passive, localRoute.poolKey)
- evictLruPoolBackends(poolMaxBackends() - 1)
+ await evictLruPoolBackends(poolMaxBackends() - 1)
+
+ // The registry may have changed while we waited for an eviction. Never
+ // start a child from a removed or edited connection's old descriptor.
+ if (readDesktopConnectionsRegistry() !== registry || backendPool.get(localRoute.poolKey)) {
+ return ensureRegistryBackend(connectionId, profile, managedUpdateCorrelation, opts)
+ }
const localEntry = {
process: null,
@@ -10791,7 +10742,11 @@ async function ensureRegistryBackend(
}
assertNotPassiveSpawn(passive, key)
- evictLruPoolBackends(poolMaxBackends() - 1)
+ await evictLruPoolBackends(poolMaxBackends() - 1)
+
+ if (readDesktopConnectionsRegistry() !== registry || backendPool.get(key)) {
+ return ensureRegistryBackend(connectionId, profile, managedUpdateCorrelation, opts)
+ }
const entry = {
process: null,
@@ -11532,12 +11487,29 @@ function teardownFailedLocalBackend(poolKey: string, entry: any): Promise<void>
// `opts.forceLocal` skips remote resolution entirely (the registry 'local'
// entry means THIS machine regardless of the v1 routing table); `opts.poolKey`
// is the backendPool key when it differs from the profile name (composite
-// registry scopes) so the exit/error cleanup evicts the right entry.
-async function spawnPoolBackend(
+// registry scopes) so the exit/error cleanup evicts the right entry. Tracked by
+// the local lifecycle so quit waits for (and fences) a start still in flight.
+interface PoolBackendStartOptions {
+ forceLocal?: boolean
+ poolKey?: string
+ unscopableRequest?: boolean
+}
+
+type PoolBackendConnection = Awaited<ReturnType<typeof backendConnectionState.getPromise>>
+
+function spawnPoolBackend(
profile: string,
entry: any,
- opts: { forceLocal?: boolean; poolKey?: string; unscopableRequest?: boolean } = {}
-): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {
+ opts: PoolBackendStartOptions = {}
+): Promise<PoolBackendConnection> {
+ return localBackendLifecycle.start((): Promise<PoolBackendConnection> => runPoolBackendStart(profile, entry, opts))
+}
+
+async function runPoolBackendStart(
+ profile: string,
+ entry: any,
+ opts: PoolBackendStartOptions = {}
+): Promise<PoolBackendConnection> {
const poolKey = opts.poolKey || profile
await reapOrphanedBackendsOnce()
@@ -13545,11 +13517,16 @@ function rehomePetOverlay() {
// app's composer (slash commands, attachments, queue, voice) instead of a
// lookalike that drifts. Entering HUD mode hides the main window; leaving
// restores it.
-let hudWindow = null
-
-// Whether the main window was visible when HUD mode was entered, so exiting
-// puts the desktop back as it was rather than raising a window the user had
-// already minimized.
+let hudWindow: BrowserWindow | null = null
+// A closing HUD is no longer the active one, but its shortcut still belongs
+// to HUD until Electron actually destroys that window.
+const hudWindows = new WeakSet<BrowserWindow>()
+
+// Whether closing the HUD should bring the main window back. Armed whenever a
+// live main window exists at HUD-open time, visible or not: the HUD hides the
+// app window itself, so a main window minimized or behind another app when
+// the HUD opened still needs a surface back — arming only on `isVisible()`
+// left the user with NO Hermes window after the second toggle (#88513).
let hudRestoreMainWindow = false
// The session the HUD is currently on, reported by its renderer whenever the
@@ -13911,6 +13888,7 @@ function spawnHudWindow(sessionId, profile) {
// app) is the entire feature, so it gets the same stream-aware unthrottling
// every chat window does.
streamThrottle.register(win)
+ hudWindows.add(win)
wireCommonWindowHandlers(win, zoomWiringForWindowKind('chat'))
// Remember where the user parks and sizes it (debounced — these fire many
@@ -14037,7 +14015,7 @@ function openHudWindow(sessionId, profile) {
return hudWindow
}
- hudRestoreMainWindow = Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible())
+ hudRestoreMainWindow = Boolean(mainWindow && !mainWindow.isDestroyed())
hudSessionId = sessionId || null
hudProfile = profileKey
hudWindow = spawnHudWindow(sessionId, profileKey)
@@ -15758,23 +15736,17 @@ async function fetchJsonForBackend(
throw new Error('File uploads are not supported against OAuth-gated remote backends yet.')
}
- const nativeAt = await ensureNativeAccessToken(descriptor.baseUrl).catch(() => null)
-
- if (nativeAt) {
- return fetchJson(url, null, {
- method: opts.method,
- body: opts.body,
- timeoutMs: opts.timeoutMs,
- bearer: nativeAt,
- headers: descriptor.headers
- })
- }
-
- return fetchJsonViaOauthSession(url, {
+ const options = {
method: opts.method,
body: opts.body,
timeoutMs: opts.timeoutMs,
headers: descriptor.headers
+ }
+
+ return requestWithOauthFallback(descriptor.baseUrl, {
+ ensureNativeAccessToken,
+ requestWithBearer: (bearer: string) => fetchJson(url, null, { ...options, bearer }),
+ requestWithCookie: () => fetchJsonViaOauthSession(url, options)
})
}
@@ -15818,6 +15790,12 @@ ipcMain.handle('hermes:connection-config:oauth-login', async (_event, rawUrl) =>
const strategy = resolveLoginStrategy(statusBody, { providers })
+ // A newer login/logout can finish during the status/provider probes. Do not
+ // open a browser or login window for an attempt that no longer owns auth.
+ if (!authIsCurrent()) {
+ throw new NativeAuthChangedError()
+ }
+
if (strategy === 'native') {
try {
const tokens = await runNativeLogin(baseUrl, {
@@ -16481,51 +16459,12 @@ async function handleHermesApiRequest(request) {
})
const timeoutMs = resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
- const url = `${connection.baseUrl}${apiRoute.requestPath}`
-
- // OAuth gateways authenticate REST via EITHER a native bearer token
- // (cookieless RFC 8252 flow) OR the HttpOnly session cookie held in the OAuth
- // partition. Prefer the native bearer when present (mirroring
- // mintGatewayWsTicket): the native flow never sets a cookie, so routing an
- // oauth-mode REST call through the cookie-only path returns 401 no_cookie even
- // though a valid bearer is held. Cookie mode rides Electron's net stack bound
- // to the OAuth partition so the cookie attaches automatically. Token/local
- // modes keep using the static session-token header.
- if (connection.authMode === 'oauth') {
- // The OAuth path rides electron.net with JSON headers; multipart isn't
- // wired there. Fail loudly rather than corrupting the upload.
- if (request?.upload) {
- throw new Error('File uploads are not supported against OAuth-gated remote backends yet.')
- }
-
- // Native bearer first (cookieless). ensureNativeAccessToken transparently
- // refreshes a near-expiry AT via /auth/native/refresh; a null return means
- // no native session (resolveOauthRestAuth then selects the cookie path).
- const nativeAt = await ensureNativeAccessToken(connection.baseUrl).catch(() => null)
- const restAuth = resolveOauthRestAuth(nativeAt)
-
- if (restAuth.kind === 'bearer') {
- response = await fetchJson(url, null, {
- method: request?.method,
- body: request?.body,
- timeoutMs,
- bearer: restAuth.token
- })
- } else {
- response = await fetchJsonViaOauthSession(url, {
- method: request?.method,
- body: request?.body,
- timeoutMs
- })
- }
- } else {
- response = await fetchJson(url, connection.token, {
- method: request?.method,
- body: request?.body,
- upload: request?.upload,
- timeoutMs
- })
- }
+ response = await fetchJsonForBackend(connection, apiRoute.requestPath, {
+ method: request?.method,
+ body: request?.body,
+ upload: request?.upload,
+ timeoutMs
+ })
} catch (error) {
// A failed rename PATCH must not strand the app on the temporary primary:
// restore the original active profile and restart its backend.
diff --git a/apps/desktop/electron/updater/checkout-handoff.test.ts b/apps/desktop/electron/updater/checkout-handoff.test.ts
index ab51a8ba895..8e68f16303d 100644
--- a/apps/desktop/electron/updater/checkout-handoff.test.ts
+++ b/apps/desktop/electron/updater/checkout-handoff.test.ts
@@ -63,9 +63,11 @@ it.each([true, false])(
async (remote: boolean): Promise<void> => {
const { root, deps } = handoffFixture(remote)
const spawned: string[][] = []
+ const spawnOptions: Parameters<typeof updaterProcess.spawnUpdaterProcess>[2][] = []
vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation(
- (_command: string, args: string[]): updaterProcess.UpdaterChild => {
+ (_command: string, args: string[], options: Parameters<typeof updaterProcess.spawnUpdaterProcess>[2]): updaterProcess.UpdaterChild => {
spawned.push(args)
+ spawnOptions.push(options)
return { unref: (): void => {} }
}
@@ -75,6 +77,9 @@ it.each([true, false])(
expect(await createCheckoutStrategy(deps).apply()).toMatchObject({ ok: true, handedOff: true })
expect(spawned).toHaveLength(1)
const args: string[] = spawned[0]!
+ // The Windows cmd wrapper must inherit its hidden console; the POSIX
+ // script needs to outlive Electron as a detached child (#116161).
+ expect(spawnOptions[0]?.detached).toBe(!IS_WINDOWS)
expect(args).toContain(IS_WINDOWS ? '-Branch' : '--branch')
if (remote) {
diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.ts
index 3e553c16bfa..9d31141770e 100644
--- a/apps/desktop/electron/updater/checkout.ts
+++ b/apps/desktop/electron/updater/checkout.ts
@@ -240,9 +240,10 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
// A bare detached+hidden powershell spawn silently dies before -File
// processing (console-subsystem init failure — see
- // wrapHandoffForDetachedConsole). Route through `cmd start` so the
- // script gets its own minimized console and survives our exit. The
- // wrapper cmd.exe exits immediately, so child.pid is NOT the script's
+ // wrapHandoffForDetachedConsole). Spawn the cmd wrapper non-detached
+ // so windowsHide gives it a hidden console that `start /b` shares with
+ // PowerShell; the script still outlives us. The wrapper cmd.exe exits
+ // immediately, so child.pid is NOT the script's
// pid — the script claims the update marker itself with its own $PID
// as its first action, and a relaunched Desktop parks on that.
const wrappedArgs: string[] = [
@@ -269,7 +270,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
...sourceUpdateEnvironment(updateRoot, deps.hermesHome),
HERMES_UPDATE_STARTED_AT: String(updateStartedAt)
},
- detached: true,
+ detached: wrapped.detached,
stdio: 'ignore'
})
diff --git a/apps/desktop/src/components/remote-setup/use-remote-oauth.ts b/apps/desktop/src/components/remote-setup/use-remote-oauth.ts
index 96164281934..0c924b79cc0 100644
--- a/apps/desktop/src/components/remote-setup/use-remote-oauth.ts
+++ b/apps/desktop/src/components/remote-setup/use-remote-oauth.ts
@@ -104,6 +104,10 @@ export function useRemoteOAuth(options: RemoteOAuthOptions): RemoteOAuth {
}
const signOut = async (): Promise<void> => {
+ if (!url) {
+ return
+ }
+
const target: number = targetSeq.current
const seq: number = ++loginSeq.current
const current = (): boolean => target === targetSeq.current && seq === loginSeq.current
diff --git a/hermes_cli/plugin_catalog.py b/hermes_cli/plugin_catalog.py
index a8ca29ba3a0..05bc1664cce 100644
--- a/hermes_cli/plugin_catalog.py
+++ b/hermes_cli/plugin_catalog.py
@@ -33,6 +33,8 @@ CATALOG_TIERS = ("official", "community")
CATALOG_CATEGORIES = ("desktop", "memory", "platform", "web", "tools", "voice", "automation", "models", "general")
LIVE_CATALOG_URL = "https://hermes-agent.nousresearch.com/docs/api/plugin-catalog.json"
LIVE_CATALOG_TTL_SECONDS = 6 * 60 * 60
+# Offline pins expire, but cached removals remain a permanent kill list.
+LIVE_CATALOG_MAX_STALE_SECONDS = 24 * 60 * 60
LIVE_CATALOG_FAILURE_TTL_SECONDS = 60.0
_REQUEST_TIMEOUT = 5.0
_MAX_LIVE_BYTES = 2 * 1024 * 1024
@@ -314,9 +316,17 @@ _live_fetch_failed_until = 0.0
def _stale_live_cache(cache: Path) -> Optional[Dict[str, Any]]:
- """A previously fetched copy still beats the in-tree one when the network is down."""
+ """A previously fetched copy still beats the in-tree one when the network is down — for
+ :data:`LIVE_CATALOG_MAX_STALE_SECONDS`. Past that its pins may trail the checkout's own catalog
+ (a 90-day-old cache outranked a freshly updated in-tree pin), so the entries are dropped and the
+ caller falls back to in-tree; the removals are kept."""
try:
- return json.loads(cache.read_text(encoding="utf-8-sig")) if cache.is_file() else None
+ if not cache.is_file():
+ return None
+ data = json.loads(cache.read_text(encoding="utf-8-sig"))
+ if time.time() - cache.stat().st_mtime > LIVE_CATALOG_MAX_STALE_SECONDS:
+ data = {**data, "entries": []}
+ return data
except Exception:
return None
diff --git a/tests/hermes_cli/test_plugin_catalog.py b/tests/hermes_cli/test_plugin_catalog.py
index 5d4b29a1959..de8edcbe623 100644
--- a/tests/hermes_cli/test_plugin_catalog.py
+++ b/tests/hermes_cli/test_plugin_catalog.py
@@ -96,7 +96,7 @@ def test_find_removed_matches_name_or_normalized_repo(tmp_path):
@pytest.mark.parametrize("stale", [False, True])
def test_live_catalog_falls_back_to_in_tree_and_unions_removals(tmp_path, monkeypatch, stale):
- """Network failure → in-tree entries; a cached live doc contributes entries AND removals."""
+ """Offline live pins expire, but a cached removal keeps blocking installs."""
import httpx
requests = []
@@ -123,8 +123,11 @@ def test_live_catalog_falls_back_to_in_tree_and_unions_removals(tmp_path, monkey
# trigger a real retry once that window has passed.
monkeypatch.setattr(pc, "_live_fetch_failed_until", 0.0)
entries = pc.load_catalog_live()
- assert [e.name for e in entries] == ["live-only"]
- assert entries[0].description == "café"
+ if stale:
+ assert [e.name for e in entries] == [e.name for e in pc.load_catalog()]
+ else:
+ assert [e.name for e in entries] == ["live-only"]
+ assert entries[0].description == "café"
assert bool(requests) is stale
assert pc.find_removed("pulled-live").reason == "cve"
cache.write_text("{", encoding="utf-8-sig")
diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py
index a0be0ec341a..12e2e8985fc 100644
--- a/tools/code_execution_tool.py
+++ b/tools/code_execution_tool.py
@@ -926,3 +926,30 @@ registry.register(
handler=_execute_code_handler, check_fn=check_sandbox_requirements, emoji="🐍",
max_result_size_chars=100_000,
)
+
+
+# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
+# Names external plugins imported from this module before the Sep 2026 decomposition.
+# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
+# The whole block is removed by reverting the commit that added it.
+import platform # noqa: F401,E402
+import socket # noqa: F401,E402
+import sys # noqa: F401,E402
+
+DEFAULT_KERNEL_MODE = "session"
+
+KERNEL_MODES = ("per-call", "session") # legacy compat constant
+
+
+_PLUGIN_COMPAT_LAZY = {
+ 'thread_scoped_silence': ('agent.thread_scoped_output', 'thread_scoped_silence'),
+}
+
+
+def __getattr__(name): # PEP 562 — lazy so no import cycles
+ target = _PLUGIN_COMPAT_LAZY.get(name)
+ if target is None:
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+ import importlib
+ return getattr(importlib.import_module(target[0]), target[1])
+# ---- END PLUGIN-COMPAT ----