Skip to content

The agent that grows with you

fix(desktop): re-home backend after profile rename

wangdong69abe41f3673
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index be6cb891e92..792dc9f2a74 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -265,6 +265,7 @@ import {
} from './remote-liveness'
import { missingRendererAssets } from './renderer-bundle'
import { attachRendererConsoleCapture, formatRendererBoundaryReport } from './renderer-log'
+import { prepareProfileRenameLifecycle, profileRenameFromRequest } from './profile-rename-routing'
import {
buildSessionWindowUrl,
chatWindowWebPreferences,
@@ -10107,6 +10108,24 @@ async function prepareProfileDeleteRequest(request) {
return decision.profile
}
+async function prepareProfileRenameRequest(request) {
+ return prepareProfileRenameLifecycle(request, {
+ isValidProfileName: profile => PROFILE_NAME_RE.test(profile),
+ primaryProfileKey,
+ reloadPrimaryWindow: () => {
+ mainWindow?.reload()
+ },
+ restartPrimaryBackend: async () => {
+ await startHermes()
+ },
+ teardownPoolBackendAndWait,
+ teardownPrimaryBackendAndWait,
+ writeActiveDesktopProfile: profile => {
+ writeActiveDesktopProfile(profile)
+ }
+ })
+}
+
async function startHermes() {
// Only the single-instance lock holder may reap/spawn/claim the desktop
// backend. A lock-losing instance must stay inert even if some path reaches
@@ -13224,6 +13243,7 @@ async function handleHermesApiRequest(request) {
return rerouted
}
+ const profileRename = await prepareProfileRenameRequest(request)
const tornDownProfile = await prepareProfileDeleteRequest(request)
const profile = request?.profile
@@ -13235,67 +13255,97 @@ async function handleHermesApiRequest(request) {
// Safe local-profile REST calls also stay on the primary dashboard and carry
// ?profile=. Endpoints that cannot honor that scope retain their pooled
// backend so a destructive call can never fall through to the primary home.
+ //
+ // A profile rename tears down the old-name backend the same way; for a
+ // primary rename the lifecycle has already made `default` the temporary
+ // primary until the PATCH settles, so the request routes there.
const apiRoute = resolveProfileApiRequest(profile, request.path, profileRouteOptions(profile, request))
- const routeProfile = resolveRouteProfile(tornDownProfile, apiRoute.backendProfile)
-
- const connection = await ensureBackend(routeProfile)
- const timeoutMs = resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
+ const routeProfile = profileRename
+ ? profileRename.routeProfile
+ : resolveRouteProfile(tornDownProfile, apiRoute.backendProfile)
- const url = `${connection.baseUrl}${apiRoute.requestPath}`
+ let response
- // 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') {
- return fetchJson(url, null, {
+ try {
+ const connection = await ensureBackend(routeProfile)
+ 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,
- timeoutMs,
- bearer: restAuth.token
+ 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.
+ if (profileRename) {
+ try {
+ await profileRename.rollback()
+ } catch (rollbackError) {
+ rememberLog(`Failed to restore primary profile after rename error: ${String(rollbackError)}`)
+ }
+ }
- return fetchJsonViaOauthSession(url, {
- method: request?.method,
- body: request?.body,
- timeoutMs
- })
+ throw error
}
- return fetchJson(url, connection.token, {
- method: request?.method,
- body: request?.body,
- upload: request?.upload,
- timeoutMs
- })
+ await profileRename?.complete()
+
+ return response
}
ipcMain.handle('hermes:api', async (_event, request) => {
+ // Hold the deletion gate for BOTH profile deletes and renames: a concurrent
+ // renderer reconnect entering ensureBackend() mid-mutation would otherwise
+ // respawn the old-name backend and recreate its HERMES_HOME (#45474).
const deletingProfile = profileNameFromDeleteRequest(request)
+ const mutatingProfile = deletingProfile || profileRenameFromRequest(request)?.oldName || null
- if (!deletingProfile) {
+ if (!mutatingProfile) {
return handleHermesApiRequest(request)
}
- const releaseProfileDeletion = profileDeletionGate.acquire(deletingProfile)
+ const releaseProfileDeletion = profileDeletionGate.acquire(mutatingProfile)
return handleHermesApiRequest(request).finally(releaseProfileDeletion)
})
diff --git a/apps/desktop/electron/profile-delete-routing.ts b/apps/desktop/electron/profile-delete-routing.ts
index 55e79cb12e4..3338fe2420c 100644
--- a/apps/desktop/electron/profile-delete-routing.ts
+++ b/apps/desktop/electron/profile-delete-routing.ts
@@ -9,17 +9,9 @@
//
// These helpers are pure so they can be unit-tested without Electron.
-/**
- * Parse a `hermes:api` request into the profile name a DELETE targets, or
- * null when the request is not a profile-delete at all (wrong method, wrong
- * path, empty/invalid name).
- */
-export function profileNameFromDeleteRequest(request) {
- if (!request || String(request.method || 'GET').toUpperCase() !== 'DELETE') {
- return null
- }
-
- const match = String(request.path || '').match(/^\/api\/profiles\/([^/?#]+)(?:[?#].*)?$/)
+/** Parse a profile name from an `/api/profiles/<name>` request path. */
+export function profileNameFromPath(path: unknown): string | null {
+ const match = String(path || '').match(/^\/api\/profiles\/([^/?#]+)(?:[?#].*)?$/)
if (!match) {
return null
@@ -46,6 +38,15 @@ export function profileNameFromDeleteRequest(request) {
return name.toLowerCase()
}
+/** Parse a `hermes:api` request into the profile name a DELETE targets. */
+export function profileNameFromDeleteRequest(request) {
+ if (!request || String(request.method || 'GET').toUpperCase() !== 'DELETE') {
+ return null
+ }
+
+ return profileNameFromPath(request.path)
+}
+
export type ProfileDeleteAction = 'noop' | 'teardown-primary' | 'teardown-pool'
export interface ProfileDeleteDecision {
diff --git a/apps/desktop/electron/profile-rename-routing.test.ts b/apps/desktop/electron/profile-rename-routing.test.ts
new file mode 100644
index 00000000000..5804ed285a4
--- /dev/null
+++ b/apps/desktop/electron/profile-rename-routing.test.ts
@@ -0,0 +1,132 @@
+import assert from 'node:assert/strict'
+
+import { test } from 'vitest'
+
+import {
+ prepareProfileRenameLifecycle,
+ profileRenameFromRequest,
+ type ProfileRenameLifecycleDeps
+} from './profile-rename-routing'
+
+const renameRequest = {
+ body: { new_name: 'renamed-profile' },
+ method: 'PATCH',
+ path: '/api/profiles/primary-profile'
+}
+
+function lifecycleDeps(events: string[]): ProfileRenameLifecycleDeps {
+ return {
+ isValidProfileName: profile => /^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile),
+ primaryProfileKey: () => 'primary-profile',
+ reloadPrimaryWindow: () => events.push('reload-primary-window'),
+ restartPrimaryBackend: async () => {
+ events.push('restart-primary-backend')
+ },
+ teardownPoolBackendAndWait: async profile => {
+ events.push(`teardown-pool:${profile}`)
+ },
+ teardownPrimaryBackendAndWait: async () => {
+ events.push('teardown-primary')
+ },
+ writeActiveDesktopProfile: profile => {
+ events.push(`write-active:${profile}`)
+ }
+ }
+}
+
+test('profileRenameFromRequest parses string and object JSON bodies', () => {
+ assert.deepEqual(profileRenameFromRequest(renameRequest), {
+ newName: 'renamed-profile',
+ oldName: 'primary-profile'
+ })
+ assert.deepEqual(profileRenameFromRequest({ ...renameRequest, body: JSON.stringify({ new_name: 'String-Body' }) }), {
+ newName: 'string-body',
+ oldName: 'primary-profile'
+ })
+})
+
+test('profileRenameFromRequest rejects malformed and reserved rename requests', () => {
+ assert.equal(profileRenameFromRequest({ ...renameRequest, method: 'DELETE' }), null)
+ assert.equal(profileRenameFromRequest({ ...renameRequest, body: '{' }), null)
+ assert.equal(profileRenameFromRequest({ ...renameRequest, body: { new_name: 'default' } }), null)
+ assert.equal(profileRenameFromRequest({ ...renameRequest, path: '/api/profiles/default' }), null)
+})
+
+test('prepareProfileRenameLifecycle tears down a pooled backend and routes through the primary', async () => {
+ const events: string[] = []
+
+ const lifecycle = await prepareProfileRenameLifecycle(
+ { ...renameRequest, path: '/api/profiles/worker-profile' },
+ lifecycleDeps(events)
+ )
+
+ assert.equal(lifecycle?.kind, 'pool')
+ assert.equal(lifecycle?.routeProfile, null)
+ assert.deepEqual(events, ['teardown-pool:worker-profile'])
+
+ await lifecycle?.complete()
+ await lifecycle?.rollback()
+ assert.deepEqual(events, ['teardown-pool:worker-profile'])
+})
+
+test('prepareProfileRenameLifecycle re-homes a renamed primary after success', async () => {
+ const events: string[] = []
+ const lifecycle = await prepareProfileRenameLifecycle(renameRequest, lifecycleDeps(events))
+
+ assert.equal(lifecycle?.kind, 'primary')
+ assert.equal(lifecycle?.routeProfile, null)
+ assert.deepEqual(events, ['write-active:default', 'teardown-primary'])
+
+ await lifecycle?.complete()
+ assert.deepEqual(events, [
+ 'write-active:default',
+ 'teardown-primary',
+ 'write-active:renamed-profile',
+ 'teardown-primary',
+ 'reload-primary-window'
+ ])
+})
+
+test('prepareProfileRenameLifecycle restores the original primary after failure', async () => {
+ const events: string[] = []
+ const lifecycle = await prepareProfileRenameLifecycle(renameRequest, lifecycleDeps(events))
+
+ await lifecycle?.rollback()
+ assert.deepEqual(events, [
+ 'write-active:default',
+ 'teardown-primary',
+ 'write-active:primary-profile',
+ 'teardown-primary',
+ 'restart-primary-backend'
+ ])
+})
+
+test('prepareProfileRenameLifecycle restores the original primary when initial teardown fails', async () => {
+ const events: string[] = []
+ const deps = lifecycleDeps(events)
+
+ deps.teardownPrimaryBackendAndWait = async () => {
+ events.push('teardown-primary')
+ throw new Error('teardown failed')
+ }
+
+ await assert.rejects(prepareProfileRenameLifecycle(renameRequest, deps), /teardown failed/)
+ assert.deepEqual(events, [
+ 'write-active:default',
+ 'teardown-primary',
+ 'write-active:primary-profile',
+ 'restart-primary-backend'
+ ])
+})
+
+test('prepareProfileRenameLifecycle ignores invalid profile names without side effects', async () => {
+ const events: string[] = []
+
+ const lifecycle = await prepareProfileRenameLifecycle(
+ { ...renameRequest, body: { new_name: 'Not Valid!' } },
+ lifecycleDeps(events)
+ )
+
+ assert.equal(lifecycle, null)
+ assert.deepEqual(events, [])
+})
diff --git a/apps/desktop/electron/profile-rename-routing.ts b/apps/desktop/electron/profile-rename-routing.ts
new file mode 100644
index 00000000000..f136881fbc5
--- /dev/null
+++ b/apps/desktop/electron/profile-rename-routing.ts
@@ -0,0 +1,138 @@
+import { profileNameFromPath } from './profile-delete-routing'
+
+export interface ProfileRenameRequest {
+ body?: unknown
+ method?: unknown
+ path?: unknown
+}
+
+export interface ProfileRename {
+ newName: string
+ oldName: string
+}
+
+export interface ProfileRenameLifecycleDeps {
+ isValidProfileName: (profile: string) => boolean
+ primaryProfileKey: () => string
+ reloadPrimaryWindow: () => void
+ restartPrimaryBackend: () => Promise<void>
+ teardownPoolBackendAndWait: (profile: string) => Promise<void>
+ teardownPrimaryBackendAndWait: () => Promise<void>
+ writeActiveDesktopProfile: (profile: string) => void
+}
+
+export interface ProfileRenameLifecycle {
+ complete: () => Promise<void>
+ kind: 'pool' | 'primary'
+ rename: ProfileRename
+ rollback: () => Promise<void>
+ routeProfile: null
+}
+
+function parseJsonBody(body: unknown): Record<string, unknown> {
+ if (body == null || body === '') {
+ return {}
+ }
+
+ if (typeof body === 'object' && !Array.isArray(body)) {
+ return body as Record<string, unknown>
+ }
+
+ try {
+ const parsed = JSON.parse(String(body))
+
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
+ } catch {
+ return {}
+ }
+}
+
+export function profileRenameFromRequest(request: ProfileRenameRequest | null | undefined): ProfileRename | null {
+ if (!request || String(request.method || 'GET').toUpperCase() !== 'PATCH') {
+ return null
+ }
+
+ const oldName = profileNameFromPath(request.path)
+
+ if (!oldName || oldName === 'default') {
+ return null
+ }
+
+ const body = parseJsonBody(request.body)
+
+ const newName = String(body.new_name || '')
+ .trim()
+ .toLowerCase()
+
+ if (!newName || newName === 'default') {
+ return null
+ }
+
+ return { newName, oldName }
+}
+
+export async function prepareProfileRenameLifecycle(
+ request: ProfileRenameRequest | null | undefined,
+ deps: ProfileRenameLifecycleDeps
+): Promise<ProfileRenameLifecycle | null> {
+ const rename = profileRenameFromRequest(request)
+
+ if (!rename || !deps.isValidProfileName(rename.oldName) || !deps.isValidProfileName(rename.newName)) {
+ return null
+ }
+
+ if (rename.oldName !== deps.primaryProfileKey()) {
+ await deps.teardownPoolBackendAndWait(rename.oldName)
+
+ return {
+ complete: async () => {},
+ kind: 'pool',
+ rename,
+ rollback: async () => {},
+ routeProfile: null
+ }
+ }
+
+ // Make `default` the temporary primary before stopping the old backend.
+ // Concurrent primary requests then share the temporary connection instead
+ // of respawning the old profile and recreating its directory mid-rename.
+ deps.writeActiveDesktopProfile('default')
+
+ try {
+ await deps.teardownPrimaryBackendAndWait()
+ } catch (error) {
+ deps.writeActiveDesktopProfile(rename.oldName)
+
+ try {
+ await deps.restartPrimaryBackend()
+ } catch {
+ // Preserve the teardown error that prevented the rename from starting.
+ }
+
+ throw error
+ }
+
+ return {
+ complete: async () => {
+ deps.writeActiveDesktopProfile(rename.newName)
+
+ try {
+ await deps.teardownPrimaryBackendAndWait()
+ } finally {
+ deps.reloadPrimaryWindow()
+ }
+ },
+ kind: 'primary',
+ rename,
+ rollback: async () => {
+ deps.writeActiveDesktopProfile(rename.oldName)
+
+ try {
+ await deps.teardownPrimaryBackendAndWait()
+ } finally {
+ await deps.restartPrimaryBackend()
+ }
+ },
+ routeProfile: null
+ }
+}