fix(desktop): allow restoring default primary profile
This commit is contained in:
parent
c896c09c42
commit
52291d8cee
|
|
@ -0,0 +1,91 @@
|
|||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
applyDesktopPrimaryProfile,
|
||||
readDesktopPrimaryProfile,
|
||||
writeDesktopPrimaryProfile
|
||||
} from './desktop-primary-profile'
|
||||
|
||||
describe('Desktop primary profile persistence', () => {
|
||||
let configPath: string
|
||||
let temporaryDirectory: string
|
||||
|
||||
beforeEach(() => {
|
||||
temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-primary-profile-'))
|
||||
configPath = path.join(temporaryDirectory, 'active-profile.json')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(temporaryDirectory, { force: true, recursive: true })
|
||||
})
|
||||
|
||||
it('persists named to default before tearing down and reloading the primary backend', async () => {
|
||||
writeDesktopPrimaryProfile(configPath, 'dev')
|
||||
const events: string[] = []
|
||||
|
||||
await expect(
|
||||
applyDesktopPrimaryProfile(configPath, 'default', {
|
||||
teardownPrimary: async () => {
|
||||
events.push(`teardown:${readDesktopPrimaryProfile(configPath)}`)
|
||||
},
|
||||
reload: () => events.push('reload')
|
||||
})
|
||||
).resolves.toBe('default')
|
||||
|
||||
expect(fs.readFileSync(configPath, 'utf8')).toBe(JSON.stringify({ profile: 'default' }, null, 2))
|
||||
expect(events).toEqual(['teardown:default', 'reload'])
|
||||
})
|
||||
|
||||
it('persists default to a named primary profile and runs the same lifecycle', async () => {
|
||||
writeDesktopPrimaryProfile(configPath, 'default')
|
||||
const teardownPrimary = vi.fn(async () => undefined)
|
||||
const reload = vi.fn()
|
||||
|
||||
await expect(applyDesktopPrimaryProfile(configPath, 'dev', { reload, teardownPrimary })).resolves.toBe('dev')
|
||||
|
||||
expect(readDesktopPrimaryProfile(configPath)).toBe('dev')
|
||||
expect(teardownPrimary).toHaveBeenCalledOnce()
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('retries the re-home when a prior teardown failed after persistence', async () => {
|
||||
writeDesktopPrimaryProfile(configPath, 'dev')
|
||||
|
||||
const teardownPrimary = vi
|
||||
.fn<() => Promise<void>>()
|
||||
.mockRejectedValueOnce(new Error('backend did not stop'))
|
||||
.mockResolvedValueOnce(undefined)
|
||||
|
||||
const reload = vi.fn()
|
||||
|
||||
await expect(applyDesktopPrimaryProfile(configPath, 'default', { reload, teardownPrimary })).rejects.toThrow(
|
||||
'backend did not stop'
|
||||
)
|
||||
expect(readDesktopPrimaryProfile(configPath)).toBe('default')
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
|
||||
await expect(applyDesktopPrimaryProfile(configPath, 'default', { reload, teardownPrimary })).resolves.toBe(
|
||||
'default'
|
||||
)
|
||||
expect(teardownPrimary).toHaveBeenCalledTimes(2)
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('rejects an invalid profile without changing persisted state or lifecycle', async () => {
|
||||
writeDesktopPrimaryProfile(configPath, 'dev')
|
||||
const teardownPrimary = vi.fn(async () => undefined)
|
||||
const reload = vi.fn()
|
||||
|
||||
await expect(applyDesktopPrimaryProfile(configPath, 'Not Valid!', { reload, teardownPrimary })).rejects.toThrow(
|
||||
'Invalid profile name'
|
||||
)
|
||||
|
||||
expect(readDesktopPrimaryProfile(configPath)).toBe('dev')
|
||||
expect(teardownPrimary).not.toHaveBeenCalled()
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
// Mirrors hermes_cli.profiles._PROFILE_ID_RE so the Desktop never persists a
|
||||
// value the profile resolver would reject during the next backend launch.
|
||||
export const DESKTOP_PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/
|
||||
|
||||
function normalizeDesktopPrimaryProfile(name: unknown): string | null {
|
||||
const value = typeof name === 'string' ? name.trim() : ''
|
||||
|
||||
if (value && value !== 'default' && !DESKTOP_PROFILE_NAME_RE.test(value)) {
|
||||
throw new Error(`Invalid profile name: ${value}`)
|
||||
}
|
||||
|
||||
return value || null
|
||||
}
|
||||
|
||||
// Returns the persisted Desktop primary profile. Explicit "default" pins the
|
||||
// root HERMES_HOME; null preserves the legacy launch without a --profile flag.
|
||||
export function readDesktopPrimaryProfile(configPath: string): string | null {
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(configPath, 'utf8'))
|
||||
const name = parsed && typeof parsed.profile === 'string' ? parsed.profile.trim() : ''
|
||||
|
||||
if (name && (name === 'default' || DESKTOP_PROFILE_NAME_RE.test(name))) {
|
||||
return name
|
||||
}
|
||||
} catch {
|
||||
// Missing or malformed means there is no persisted preference.
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function writeDesktopPrimaryProfile(configPath: string, name: unknown): string | null {
|
||||
const value = normalizeDesktopPrimaryProfile(name)
|
||||
const temporaryPath = `${configPath}.tmp`
|
||||
|
||||
fs.mkdirSync(path.dirname(configPath), { recursive: true })
|
||||
fs.writeFileSync(temporaryPath, JSON.stringify({ profile: value }, null, 2))
|
||||
fs.renameSync(temporaryPath, configPath)
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
interface DesktopPrimaryProfileLifecycle {
|
||||
reload: () => void
|
||||
teardownPrimary: () => Promise<void>
|
||||
}
|
||||
|
||||
// Persist first, then re-home the primary backend and reload its renderer. Do
|
||||
// not infer the running backend from the file: a prior teardown may have failed
|
||||
// after persistence, and a retry still needs to complete the re-home.
|
||||
export async function applyDesktopPrimaryProfile(
|
||||
configPath: string,
|
||||
name: unknown,
|
||||
lifecycle: DesktopPrimaryProfileLifecycle
|
||||
): Promise<string | null> {
|
||||
const next = normalizeDesktopPrimaryProfile(name)
|
||||
|
||||
writeDesktopPrimaryProfile(configPath, next)
|
||||
await lifecycle.teardownPrimary()
|
||||
lifecycle.reload()
|
||||
|
||||
return next
|
||||
}
|
||||
|
|
@ -84,6 +84,12 @@ import {
|
|||
import { describeCrashReason, installCrashForensics } from './crash-forensics'
|
||||
import { adoptServedDashboardToken } from './dashboard-token'
|
||||
import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'
|
||||
import {
|
||||
applyDesktopPrimaryProfile,
|
||||
DESKTOP_PROFILE_NAME_RE,
|
||||
readDesktopPrimaryProfile,
|
||||
writeDesktopPrimaryProfile
|
||||
} from './desktop-primary-profile'
|
||||
import {
|
||||
buildPosixCleanupScript,
|
||||
buildWindowsCleanupScript,
|
||||
|
|
@ -651,7 +657,7 @@ const DESKTOP_WINDOW_STATE_PATH = path.join(app.getPath('userData'), 'window-sta
|
|||
const DESKTOP_PROFILE_CONFIG_PATH = path.join(app.getPath('userData'), 'active-profile.json')
|
||||
// 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 = /^[a-z0-9][a-z0-9_-]{0,63}$/
|
||||
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().
|
||||
|
|
@ -6893,32 +6899,11 @@ function writeDesktopConnectionConfig(config) {
|
|||
// a valid stored value (pins the root HERMES_HOME explicitly); null means "no
|
||||
// preference" and preserves the legacy launch (no --profile flag).
|
||||
function readActiveDesktopProfile() {
|
||||
try {
|
||||
const raw = fs.readFileSync(DESKTOP_PROFILE_CONFIG_PATH, 'utf8')
|
||||
const parsed = JSON.parse(raw)
|
||||
const name = parsed && typeof parsed.profile === 'string' ? parsed.profile.trim() : ''
|
||||
|
||||
if (name && (name === 'default' || PROFILE_NAME_RE.test(name))) {
|
||||
return name
|
||||
}
|
||||
} catch {
|
||||
// Missing or malformed → no preference.
|
||||
}
|
||||
|
||||
return null
|
||||
return readDesktopPrimaryProfile(DESKTOP_PROFILE_CONFIG_PATH)
|
||||
}
|
||||
|
||||
function writeActiveDesktopProfile(name) {
|
||||
const value = typeof name === 'string' ? name.trim() : ''
|
||||
|
||||
if (value && value !== 'default' && !PROFILE_NAME_RE.test(value)) {
|
||||
throw new Error(`Invalid profile name: ${value}`)
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(DESKTOP_PROFILE_CONFIG_PATH), { recursive: true })
|
||||
writeFileAtomic(DESKTOP_PROFILE_CONFIG_PATH, JSON.stringify({ profile: value || null }, null, 2))
|
||||
|
||||
return value || null
|
||||
return writeDesktopPrimaryProfile(DESKTOP_PROFILE_CONFIG_PATH, name)
|
||||
}
|
||||
|
||||
// Sanitize a connection config into the renderer-facing shape. With no
|
||||
|
|
@ -10553,13 +10538,13 @@ ipcMain.handle('hermes:connection-config:apply', async (_event, payload) => {
|
|||
|
||||
ipcMain.handle('hermes:profile:get', async () => ({ profile: readActiveDesktopProfile() }))
|
||||
ipcMain.handle('hermes:profile:set', async (_event, name) => {
|
||||
const next = writeActiveDesktopProfile(name)
|
||||
|
||||
// Switching profiles is a backend re-home: relaunch the dashboard under the
|
||||
// new HERMES_HOME. Pool backends keep their own homes, so only the primary
|
||||
// is torn down.
|
||||
await teardownPrimaryBackendAndWait()
|
||||
mainWindow?.reload()
|
||||
const next = await applyDesktopPrimaryProfile(DESKTOP_PROFILE_CONFIG_PATH, name, {
|
||||
// Switching profiles is a backend re-home: relaunch the dashboard under
|
||||
// the new HERMES_HOME. Pool backends keep their own homes, so only the
|
||||
// primary is torn down.
|
||||
teardownPrimary: teardownPrimaryBackendAndWait,
|
||||
reload: () => mainWindow?.reload()
|
||||
})
|
||||
|
||||
return { profile: next }
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import type * as Nanostores from 'nanostores'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { deleteProfile } from '@/hermes'
|
||||
import { refreshProfiles, selectProfile, setActiveProfile } from '@/store/profile'
|
||||
import { refreshPrimaryProfile, refreshProfiles, selectProfile, setActiveProfile, switchProfile } from '@/store/profile'
|
||||
import type { ProfileInfo } from '@/types/hermes'
|
||||
|
||||
import { ProfilesView } from './index'
|
||||
|
|
@ -39,28 +39,46 @@ vi.mock('@/store/notifications', () => ({
|
|||
notifyError: vi.fn()
|
||||
}))
|
||||
|
||||
const { $activeGatewayProfile: activeGateway, $profileColors } = vi.hoisted(() => {
|
||||
const {
|
||||
$activeGatewayProfile: activeGateway,
|
||||
$activeProfile: activePrimary,
|
||||
$primaryDesktopProfileState: primaryDesktopState,
|
||||
$profileColors
|
||||
} = vi.hoisted(() => {
|
||||
const { atom } = require('nanostores') as typeof Nanostores
|
||||
|
||||
return {
|
||||
$activeGatewayProfile: atom<string>('default'),
|
||||
$activeProfile: atom<string>('default'),
|
||||
$primaryDesktopProfileState: atom({ current: 'default', persisted: 'default' as null | string | undefined }),
|
||||
$profileColors: atom<Record<string, string>>({})
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/store/profile', () => ({
|
||||
$activeGatewayProfile: activeGateway,
|
||||
$activeProfile: activePrimary,
|
||||
$primaryDesktopProfileState: primaryDesktopState,
|
||||
$profileColors,
|
||||
normalizeProfileKey: (name: null | string | undefined) => (name ?? '').trim() || 'default',
|
||||
refreshPrimaryProfile: vi.fn(async () => undefined),
|
||||
refreshProfiles: vi.fn(async () => [] as ProfileInfo[]),
|
||||
selectProfile: vi.fn(),
|
||||
setActiveProfile: vi.fn()
|
||||
setActiveProfile: vi.fn(),
|
||||
switchProfile: vi.fn()
|
||||
}))
|
||||
|
||||
// The one non-default profile these tests act on. Its name doubles as the row's
|
||||
// accessible name, so the delete helper queries by it rather than a literal.
|
||||
const NAMED_PROFILE = 'work'
|
||||
|
||||
beforeEach(() => {
|
||||
activePrimary.set('default')
|
||||
primaryDesktopState.set({ current: 'default', persisted: 'default' })
|
||||
vi.mocked(refreshPrimaryProfile).mockReset()
|
||||
vi.mocked(refreshPrimaryProfile).mockResolvedValue(primaryDesktopState.get())
|
||||
})
|
||||
|
||||
function makeProfile(name: string, isDefault = false): ProfileInfo {
|
||||
return {
|
||||
has_env: false,
|
||||
|
|
@ -152,4 +170,49 @@ describe('ProfilesView', () => {
|
|||
expect(selectProfile).not.toHaveBeenCalled()
|
||||
expect(setActiveProfile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('offers an explicit action that switches the primary Desktop profile back to default', async () => {
|
||||
vi.mocked(refreshProfiles).mockResolvedValue([makeProfile('default', true), makeProfile(NAMED_PROFILE)])
|
||||
vi.mocked(refreshPrimaryProfile).mockImplementationOnce(async () => {
|
||||
activePrimary.set(NAMED_PROFILE)
|
||||
const state = { current: NAMED_PROFILE, persisted: NAMED_PROFILE }
|
||||
primaryDesktopState.set(state)
|
||||
|
||||
return state
|
||||
})
|
||||
|
||||
await renderProfilesView()
|
||||
expect(refreshPrimaryProfile).toHaveBeenCalledOnce()
|
||||
realClick(await findRowMenu('default'))
|
||||
fireEvent.click(await screen.findByRole('menuitem', { name: 'Make primary Desktop profile' }))
|
||||
|
||||
await waitFor(() => expect(switchProfile).toHaveBeenCalledWith('default'))
|
||||
})
|
||||
|
||||
it('supports making a named profile primary', async () => {
|
||||
vi.mocked(switchProfile).mockClear()
|
||||
vi.mocked(refreshProfiles).mockResolvedValue([makeProfile('default', true), makeProfile(NAMED_PROFILE)])
|
||||
activePrimary.set('default')
|
||||
|
||||
await renderProfilesView()
|
||||
realClick(await findRowMenu(NAMED_PROFILE))
|
||||
fireEvent.click(await screen.findByRole('menuitem', { name: 'Make primary Desktop profile' }))
|
||||
|
||||
await waitFor(() => expect(switchProfile).toHaveBeenCalledWith(NAMED_PROFILE))
|
||||
})
|
||||
|
||||
it('marks the current primary Desktop profile and disables its restart action', async () => {
|
||||
vi.mocked(switchProfile).mockClear()
|
||||
vi.mocked(refreshProfiles).mockResolvedValue([makeProfile('default', true), makeProfile(NAMED_PROFILE)])
|
||||
activePrimary.set('default')
|
||||
|
||||
await renderProfilesView()
|
||||
expect(await screen.findByText('Primary for Desktop')).toBeTruthy()
|
||||
realClick(await findRowMenu('default'))
|
||||
const action = await screen.findByRole('menuitem', { name: 'Make primary Desktop profile' })
|
||||
|
||||
expect(action.getAttribute('data-disabled')).not.toBeNull()
|
||||
fireEvent.click(action)
|
||||
expect(switchProfile).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,7 +13,14 @@ import { AlertTriangle, Save } from '@/lib/icons'
|
|||
import { resolveProfileColor } from '@/lib/profile-color'
|
||||
import { normalize } from '@/lib/text'
|
||||
import { notify, notifyError } from '@/store/notifications'
|
||||
import { $profileColors, refreshProfiles } from '@/store/profile'
|
||||
import {
|
||||
$primaryDesktopProfileState,
|
||||
$profileColors,
|
||||
normalizeProfileKey,
|
||||
refreshPrimaryProfile,
|
||||
refreshProfiles,
|
||||
switchProfile
|
||||
} from '@/store/profile'
|
||||
|
||||
import { useRefreshHotkey } from '../hooks/use-refresh-hotkey'
|
||||
import {
|
||||
|
|
@ -48,10 +55,11 @@ export function ProfilesView({ onClose }: ProfilesViewProps) {
|
|||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [pendingRename, setPendingRename] = useState<null | ProfileInfo>(null)
|
||||
const [pendingDelete, setPendingDelete] = useState<null | ProfileInfo>(null)
|
||||
const primaryProfileState = useStore($primaryDesktopProfileState)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const list = await refreshProfiles()
|
||||
const [list] = await Promise.all([refreshProfiles(), refreshPrimaryProfile()])
|
||||
setProfiles(list)
|
||||
setSelectedName(current => {
|
||||
if (current && list.some(p => p.name === current)) {
|
||||
|
|
@ -102,6 +110,17 @@ export function ProfilesView({ onClose }: ProfilesViewProps) {
|
|||
[refresh]
|
||||
)
|
||||
|
||||
const makePrimary = useCallback(
|
||||
async (profile: ProfileInfo) => {
|
||||
try {
|
||||
await switchProfile(profile.name)
|
||||
} catch (err) {
|
||||
notifyError(err, p.failedSetPrimaryDesktop)
|
||||
}
|
||||
},
|
||||
[p]
|
||||
)
|
||||
|
||||
return (
|
||||
<Panel closeLabel={p.close} onClose={onClose}>
|
||||
{!profiles ? (
|
||||
|
|
@ -131,19 +150,27 @@ export function ProfilesView({ onClose }: ProfilesViewProps) {
|
|||
<ProfileRow
|
||||
active={selected?.name === profile.name}
|
||||
key={profile.name}
|
||||
menuItems={
|
||||
profile.is_default
|
||||
? []
|
||||
: [
|
||||
menuItems={[
|
||||
{
|
||||
disabled:
|
||||
primaryProfileState.current === normalizeProfileKey(profile.name) &&
|
||||
primaryProfileState.persisted === normalizeProfileKey(profile.name),
|
||||
icon: 'server-process',
|
||||
label: p.makePrimaryDesktop,
|
||||
onSelect: () => void makePrimary(profile)
|
||||
},
|
||||
...(!profile.is_default
|
||||
? [
|
||||
{ icon: 'edit', label: p.renameMenu, onSelect: () => setPendingRename(profile) },
|
||||
{
|
||||
icon: 'trash',
|
||||
label: t.common.delete,
|
||||
onSelect: () => setPendingDelete(profile),
|
||||
tone: 'danger'
|
||||
tone: 'danger' as const
|
||||
}
|
||||
]
|
||||
}
|
||||
: [])
|
||||
]}
|
||||
onSelect={() => setSelectedName(profile.name)}
|
||||
profile={profile}
|
||||
/>
|
||||
|
|
@ -152,7 +179,11 @@ export function ProfilesView({ onClose }: ProfilesViewProps) {
|
|||
</PanelList>
|
||||
|
||||
{selected ? (
|
||||
<ProfileDetail key={selected.name} profile={selected} />
|
||||
<ProfileDetail
|
||||
isPrimary={primaryProfileState.current === normalizeProfileKey(selected.name)}
|
||||
key={selected.name}
|
||||
profile={selected}
|
||||
/>
|
||||
) : (
|
||||
<PanelEmpty description={p.selectPrompt} icon="account" />
|
||||
)}
|
||||
|
|
@ -220,7 +251,7 @@ function ProfileRow({
|
|||
)
|
||||
}
|
||||
|
||||
function ProfileDetail({ profile }: { profile: ProfileInfo }) {
|
||||
function ProfileDetail({ isPrimary, profile }: { isPrimary: boolean; profile: ProfileInfo }) {
|
||||
const { t } = useI18n()
|
||||
const p = t.profiles
|
||||
|
||||
|
|
@ -231,6 +262,7 @@ function ProfileDetail({ profile }: { profile: ProfileInfo }) {
|
|||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h3 className="text-[0.95rem] font-semibold tracking-tight text-foreground">{profile.name}</h3>
|
||||
{profile.is_default && <PanelPill tone="good">{p.defaultBadge}</PanelPill>}
|
||||
{isPrimary && <PanelPill tone="muted">{p.primaryDesktopBadge}</PanelPill>}
|
||||
{profile.has_env && <PanelPill tone="muted">.env</PanelPill>}
|
||||
</div>
|
||||
<p
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ describe('Hermes REST helpers', () => {
|
|||
api = vi.fn().mockResolvedValue(emptySessionsResponse)
|
||||
Object.defineProperty(window, 'hermesDesktop', {
|
||||
configurable: true,
|
||||
value: { api }
|
||||
value: { api, profile: { get: vi.fn(async () => ({ profile: 'default' })) } }
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -1317,6 +1317,8 @@ export const ar = defineLocale({
|
|||
skills: count => `${count} مهارة`,
|
||||
env: 'البيئة',
|
||||
defaultBadge: 'افتراضي',
|
||||
primaryDesktopBadge: 'ملف سطح المكتب الأساسي',
|
||||
makePrimaryDesktop: 'تعيين كملف سطح المكتب الأساسي',
|
||||
rename: 'إعادة تسمية',
|
||||
copySetup: 'نسخ الإعداد',
|
||||
copying: 'جار النسخ...',
|
||||
|
|
@ -1365,6 +1367,7 @@ export const ar = defineLocale({
|
|||
failedCopy: 'فشل النسخ',
|
||||
failedLoadSoul: 'فشل تحميل التعليمات',
|
||||
failedSaveSoul: 'فشل حفظ التعليمات',
|
||||
failedSetPrimaryDesktop: 'فشل تغيير ملف سطح المكتب الأساسي',
|
||||
failedCreate: 'فشل الإنشاء',
|
||||
failedRename: 'فشل إعادة التسمية'
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1609,6 +1609,8 @@ export const en: Translations = {
|
|||
skills: count => `${count} ${count === 1 ? 'skill' : 'skills'}`,
|
||||
env: 'env',
|
||||
defaultBadge: 'Default',
|
||||
primaryDesktopBadge: 'Primary for Desktop',
|
||||
makePrimaryDesktop: 'Make primary Desktop profile',
|
||||
rename: 'Rename',
|
||||
renameMenu: 'Rename…',
|
||||
editSoul: 'Edit SOUL.md…',
|
||||
|
|
@ -1658,6 +1660,7 @@ export const en: Translations = {
|
|||
failedCopy: 'Failed to copy setup command',
|
||||
failedLoadSoul: 'Failed to load SOUL.md',
|
||||
failedSaveSoul: 'Failed to save SOUL.md',
|
||||
failedSetPrimaryDesktop: 'Failed to change the primary Desktop profile',
|
||||
failedCreate: 'Failed to create profile',
|
||||
failedRename: 'Failed to rename profile'
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1431,6 +1431,8 @@ export const ja = defineLocale({
|
|||
skills: count => `${count} スキル`,
|
||||
env: 'env',
|
||||
defaultBadge: 'デフォルト',
|
||||
primaryDesktopBadge: 'デスクトップのプライマリ',
|
||||
makePrimaryDesktop: 'デスクトップのプライマリプロファイルに設定',
|
||||
rename: '名前を変更',
|
||||
renameMenu: '名前を変更…',
|
||||
editSoul: 'SOUL.md を編集…',
|
||||
|
|
@ -1481,6 +1483,7 @@ export const ja = defineLocale({
|
|||
failedCopy: 'セットアップコマンドのコピーに失敗しました',
|
||||
failedLoadSoul: 'SOUL.md の読み込みに失敗しました',
|
||||
failedSaveSoul: 'SOUL.md の保存に失敗しました',
|
||||
failedSetPrimaryDesktop: 'デスクトップのプライマリプロファイルを変更できませんでした',
|
||||
failedCreate: 'プロファイルの作成に失敗しました',
|
||||
failedRename: 'プロファイルの名前変更に失敗しました'
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1346,6 +1346,8 @@ export interface Translations {
|
|||
skills: (count: number) => string
|
||||
env: string
|
||||
defaultBadge: string
|
||||
primaryDesktopBadge: string
|
||||
makePrimaryDesktop: string
|
||||
rename: string
|
||||
renameMenu: string
|
||||
editSoul: string
|
||||
|
|
@ -1395,6 +1397,7 @@ export interface Translations {
|
|||
failedCopy: string
|
||||
failedLoadSoul: string
|
||||
failedSaveSoul: string
|
||||
failedSetPrimaryDesktop: string
|
||||
failedCreate: string
|
||||
failedRename: string
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1379,6 +1379,8 @@ export const zhHant = defineLocale({
|
|||
skills: count => `${count} 個技能`,
|
||||
env: 'env',
|
||||
defaultBadge: '預設',
|
||||
primaryDesktopBadge: '桌面主要設定檔',
|
||||
makePrimaryDesktop: '設為桌面主要設定檔',
|
||||
rename: '重新命名',
|
||||
renameMenu: '重新命名…',
|
||||
editSoul: '編輯 SOUL.md…',
|
||||
|
|
@ -1428,6 +1430,7 @@ export const zhHant = defineLocale({
|
|||
failedCopy: '複製安裝指令失敗',
|
||||
failedLoadSoul: '載入 SOUL.md 失敗',
|
||||
failedSaveSoul: '儲存 SOUL.md 失敗',
|
||||
failedSetPrimaryDesktop: '變更桌面主要設定檔失敗',
|
||||
failedCreate: '建立設定檔失敗',
|
||||
failedRename: '重新命名設定檔失敗'
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1801,6 +1801,8 @@ export const zh: Translations = {
|
|||
skills: count => `${count} 个技能`,
|
||||
env: 'env',
|
||||
defaultBadge: '默认',
|
||||
primaryDesktopBadge: '桌面主配置档案',
|
||||
makePrimaryDesktop: '设为桌面主配置档案',
|
||||
rename: '重命名',
|
||||
renameMenu: '重命名…',
|
||||
editSoul: '编辑 SOUL.md…',
|
||||
|
|
@ -1850,6 +1852,7 @@ export const zh: Translations = {
|
|||
failedCopy: '复制安装命令失败',
|
||||
failedLoadSoul: '加载 SOUL.md 失败',
|
||||
failedSaveSoul: '保存 SOUL.md 失败',
|
||||
failedSetPrimaryDesktop: '更改桌面主配置档案失败',
|
||||
failedCreate: '创建配置档案失败',
|
||||
failedRename: '重命名配置档案失败'
|
||||
},
|
||||
|
|
|
|||
|
|
@ -14,13 +14,24 @@ const resetStarmapGraph = vi.fn()
|
|||
vi.mock('@/store/gateway', () => ({ $gateway, ensureGatewayForProfile, openGatewayForProfile }))
|
||||
vi.mock('@/hermes', () => ({
|
||||
getProfiles: vi.fn(async () => ({ profiles: [] })),
|
||||
setApiRequestProfile: vi.fn()
|
||||
setApiRequestProfile: vi.fn(),
|
||||
STARTUP_REQUEST_TIMEOUT_MS: 10_000
|
||||
}))
|
||||
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
|
||||
vi.mock('@/store/starmap', () => ({ resetStarmapGraph }))
|
||||
|
||||
const { $activeGatewayProfile, $profiles, ensureGatewayProfile, prewarmProfileBackend, refreshProfiles } =
|
||||
await import('./profile')
|
||||
const {
|
||||
$activeGatewayProfile,
|
||||
$activeProfile,
|
||||
$primaryDesktopProfileState,
|
||||
$profiles,
|
||||
ensureGatewayProfile,
|
||||
prewarmProfileBackend,
|
||||
refreshPrimaryProfile,
|
||||
refreshProfiles,
|
||||
selectProfile,
|
||||
switchProfile
|
||||
} = await import('./profile')
|
||||
|
||||
const { $connection } = await import('./session')
|
||||
const { invalidateProfileScopedQueries } = await import('@/lib/query-client')
|
||||
|
|
@ -43,16 +54,33 @@ const localConn = (over: Partial<HermesConnection> = {}): HermesConnection =>
|
|||
({ baseUrl: '', mode: 'local', profile: 'default', ...over }) as HermesConnection
|
||||
|
||||
const getConnection = vi.fn<(profile?: string | null) => Promise<HermesConnection>>()
|
||||
const getPrimaryProfile = vi.fn<() => Promise<{ profile: string | null }>>()
|
||||
const setPrimaryProfile = vi.fn<(profile: string) => Promise<{ profile: string | null }>>()
|
||||
const desktopApi = vi.fn<(request: { path: string; timeoutMs?: number }) => Promise<unknown>>()
|
||||
|
||||
beforeEach(() => {
|
||||
getConnection.mockReset()
|
||||
getPrimaryProfile.mockReset()
|
||||
getPrimaryProfile.mockResolvedValue({ profile: 'default' })
|
||||
setPrimaryProfile.mockReset()
|
||||
setPrimaryProfile.mockResolvedValue({ profile: 'default' })
|
||||
desktopApi.mockReset()
|
||||
desktopApi.mockResolvedValue({ active: 'default', current: 'default' })
|
||||
ensureGatewayForProfile.mockClear()
|
||||
openGatewayForProfile.mockClear()
|
||||
$gateway.set({ id: 'live-socket' })
|
||||
$activeProfile.set('default')
|
||||
$primaryDesktopProfileState.set({ current: 'default', persisted: 'default' })
|
||||
$activeGatewayProfile.set('default')
|
||||
$connection.set(localConn())
|
||||
$profiles.set([])
|
||||
vi.stubGlobal('window', { hermesDesktop: { getConnection } })
|
||||
vi.stubGlobal('window', {
|
||||
hermesDesktop: {
|
||||
api: desktopApi,
|
||||
getConnection,
|
||||
profile: { get: getPrimaryProfile, set: setPrimaryProfile }
|
||||
}
|
||||
})
|
||||
vi.mocked(invalidateProfileScopedQueries).mockClear()
|
||||
resetStarmapGraph.mockClear()
|
||||
})
|
||||
|
|
@ -172,3 +200,91 @@ describe('refreshProfiles shared rail list (#49289)', () => {
|
|||
expect($profiles.get().map(profile => profile.name)).toEqual(['default', 'test1'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('primary Desktop profile refresh', () => {
|
||||
it('reads the actual primary backend independently from workspace routing', async () => {
|
||||
$activeGatewayProfile.set('workspace')
|
||||
desktopApi.mockResolvedValueOnce({ active: 'dev', current: 'dev' })
|
||||
|
||||
await refreshPrimaryProfile()
|
||||
|
||||
expect(desktopApi).toHaveBeenCalledWith(expect.objectContaining({ path: '/api/profiles/active' }))
|
||||
expect(desktopApi.mock.calls[0]?.[0]).not.toHaveProperty('profile')
|
||||
expect($activeProfile.get()).toBe('dev')
|
||||
expect($primaryDesktopProfileState.get()).toEqual({ current: 'dev', persisted: 'default' })
|
||||
expect(getPrimaryProfile).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('falls back to the persisted primary while the backend is unavailable', async () => {
|
||||
desktopApi.mockRejectedValueOnce(new Error('backend starting'))
|
||||
getPrimaryProfile.mockResolvedValueOnce({ profile: 'dev' })
|
||||
|
||||
await refreshPrimaryProfile()
|
||||
|
||||
expect($activeProfile.get()).toBe('dev')
|
||||
expect($primaryDesktopProfileState.get()).toEqual({ current: null, persisted: 'dev' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('persisted Desktop primary profile switching (#85991)', () => {
|
||||
it('persists named to default through the Desktop profile IPC', async () => {
|
||||
$activeProfile.set('dev')
|
||||
$primaryDesktopProfileState.set({ current: 'dev', persisted: 'dev' })
|
||||
getPrimaryProfile.mockResolvedValueOnce({ profile: 'dev' })
|
||||
|
||||
await switchProfile('default')
|
||||
|
||||
expect(setPrimaryProfile).toHaveBeenCalledWith('default')
|
||||
})
|
||||
|
||||
it('persists default to a named primary profile through the same IPC', async () => {
|
||||
await switchProfile('dev')
|
||||
|
||||
expect(setPrimaryProfile).toHaveBeenCalledWith('dev')
|
||||
})
|
||||
|
||||
it('does not invoke the IPC for the already-primary profile', async () => {
|
||||
$activeProfile.set('dev')
|
||||
$primaryDesktopProfileState.set({ current: 'dev', persisted: 'dev' })
|
||||
getPrimaryProfile.mockResolvedValueOnce({ profile: 'dev' })
|
||||
|
||||
await switchProfile('dev')
|
||||
|
||||
expect(setPrimaryProfile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps a failed re-home retryable when persistence already succeeded', async () => {
|
||||
setPrimaryProfile.mockImplementationOnce(async profile => {
|
||||
getPrimaryProfile.mockResolvedValue({ profile })
|
||||
throw new Error('backend did not stop')
|
||||
})
|
||||
|
||||
await expect(switchProfile('dev')).rejects.toThrow('backend did not stop')
|
||||
expect($activeProfile.get()).toBe('default')
|
||||
expect($primaryDesktopProfileState.get()).toEqual({ current: 'default', persisted: 'dev' })
|
||||
|
||||
setPrimaryProfile.mockResolvedValueOnce({ profile: 'dev' })
|
||||
await switchProfile('dev')
|
||||
expect(setPrimaryProfile).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('keeps a persisted target retryable when the running primary is unconfirmed', async () => {
|
||||
$primaryDesktopProfileState.set({ current: null, persisted: 'default' })
|
||||
getPrimaryProfile.mockResolvedValueOnce({ profile: 'default' })
|
||||
|
||||
await switchProfile('default')
|
||||
|
||||
expect(setPrimaryProfile).toHaveBeenCalledWith('default')
|
||||
})
|
||||
|
||||
it('keeps an actual workspace switch independent from persisted primary state', async () => {
|
||||
$activeProfile.set('dev')
|
||||
$activeGatewayProfile.set('dev')
|
||||
getConnection.mockResolvedValue(localConn())
|
||||
|
||||
selectProfile('default')
|
||||
|
||||
await vi.waitFor(() => expect(ensureGatewayForProfile).toHaveBeenCalledWith('default'))
|
||||
expect(setPrimaryProfile).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -25,12 +25,25 @@ export function normalizeProfileKey(name: string | null | undefined): string {
|
|||
return value || 'default'
|
||||
}
|
||||
|
||||
// The profile the running local backend is actually scoped to (mirrors
|
||||
// /api/profiles/active `current`). "default" is the root ~/.hermes. This is the
|
||||
// display source of truth for the statusbar pill; the desktop's *stored*
|
||||
// preference (which may be unset) lives in the Electron main process.
|
||||
// Last known profile for the primary local backend. "default" is the root
|
||||
// ~/.hermes. During startup this may temporarily fall back to the persisted
|
||||
// preference; $primaryDesktopProfileState keeps that distinct from a confirmed
|
||||
// running backend for controls that can restart the Desktop.
|
||||
export const $activeProfile = atom<string>('default')
|
||||
|
||||
export interface PrimaryDesktopProfileState {
|
||||
current: string | null
|
||||
persisted: string | null | undefined
|
||||
}
|
||||
|
||||
// `current` is non-null only after /api/profiles/active confirms the running
|
||||
// primary. `persisted` is undefined only when Electron's profile.get failed;
|
||||
// null is its meaningful "no --profile preference" value.
|
||||
export const $primaryDesktopProfileState = atom<PrimaryDesktopProfileState>({
|
||||
current: null,
|
||||
persisted: undefined
|
||||
})
|
||||
|
||||
// Cached profile list for the picker. Refreshed lazily; the dropdown also
|
||||
// re-fetches on open so a profile created elsewhere shows up.
|
||||
export const $profiles = atom<ProfileInfo[]>([])
|
||||
|
|
@ -107,19 +120,44 @@ interface ActiveProfileResponse {
|
|||
current: string
|
||||
}
|
||||
|
||||
// Pull the primary backend's actual profile. If it is not ready yet, fall back
|
||||
// to Electron's persisted preference so primary-profile controls never mistake
|
||||
// their initial "default" atom value for confirmed state.
|
||||
export async function refreshPrimaryProfile(): Promise<PrimaryDesktopProfileState> {
|
||||
const [currentResult, persistedResult] = await Promise.allSettled([
|
||||
window.hermesDesktop.api<ActiveProfileResponse>({
|
||||
path: '/api/profiles/active',
|
||||
timeoutMs: STARTUP_REQUEST_TIMEOUT_MS
|
||||
}),
|
||||
window.hermesDesktop.profile.get()
|
||||
])
|
||||
|
||||
const current = currentResult.status === 'fulfilled' ? normalizeProfileKey(currentResult.value.current) : null
|
||||
|
||||
const persisted =
|
||||
persistedResult.status === 'fulfilled'
|
||||
? persistedResult.value.profile
|
||||
? normalizeProfileKey(persistedResult.value.profile)
|
||||
: null
|
||||
: undefined
|
||||
|
||||
const state = { current, persisted }
|
||||
|
||||
$primaryDesktopProfileState.set(state)
|
||||
|
||||
if (current) {
|
||||
setActiveProfile(current)
|
||||
} else if (persisted) {
|
||||
setActiveProfile(persisted)
|
||||
}
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
// Pull the running backend's current profile + the available profile list.
|
||||
// Best-effort: failures (backend not up yet) leave the prior values intact.
|
||||
export async function refreshActiveProfile(): Promise<void> {
|
||||
try {
|
||||
const res = await window.hermesDesktop.api<ActiveProfileResponse>({
|
||||
path: '/api/profiles/active',
|
||||
timeoutMs: STARTUP_REQUEST_TIMEOUT_MS
|
||||
})
|
||||
|
||||
setActiveProfile(res.current || 'default')
|
||||
} catch {
|
||||
// Backend may not be ready; keep the last known value.
|
||||
}
|
||||
await refreshPrimaryProfile()
|
||||
|
||||
try {
|
||||
await refreshProfiles()
|
||||
|
|
@ -133,12 +171,55 @@ export async function refreshActiveProfile(): Promise<void> {
|
|||
// (the renderer is torn down). We optimistically reflect the selection first so
|
||||
// the pill updates instantly if the reload is delayed.
|
||||
export async function switchProfile(name: string): Promise<void> {
|
||||
if (!name || name === $activeProfile.get()) {
|
||||
if (!name) {
|
||||
return
|
||||
}
|
||||
|
||||
setActiveProfile(name)
|
||||
await window.hermesDesktop.profile.set(name)
|
||||
const target = normalizeProfileKey(name)
|
||||
const previousState = $primaryDesktopProfileState.get()
|
||||
let persisted: string | null | undefined
|
||||
|
||||
try {
|
||||
const preference = await window.hermesDesktop.profile.get()
|
||||
persisted = preference.profile ? normalizeProfileKey(preference.profile) : null
|
||||
} catch {
|
||||
persisted = undefined
|
||||
}
|
||||
|
||||
if (previousState.current === target && persisted === target) {
|
||||
return
|
||||
}
|
||||
|
||||
const previous = $activeProfile.get()
|
||||
const switchingState = { current: null, persisted: target }
|
||||
|
||||
setActiveProfile(target)
|
||||
$primaryDesktopProfileState.set(switchingState)
|
||||
|
||||
try {
|
||||
await window.hermesDesktop.profile.set(target)
|
||||
} catch (error) {
|
||||
if (normalizeProfileKey($activeProfile.get()) === target) {
|
||||
setActiveProfile(previous)
|
||||
}
|
||||
|
||||
if ($primaryDesktopProfileState.get() === switchingState) {
|
||||
let failedPersisted: string | null | undefined
|
||||
|
||||
try {
|
||||
const preference = await window.hermesDesktop.profile.get()
|
||||
failedPersisted = preference.profile ? normalizeProfileKey(preference.profile) : null
|
||||
} catch {
|
||||
failedPersisted = undefined
|
||||
}
|
||||
|
||||
if ($primaryDesktopProfileState.get() === switchingState) {
|
||||
$primaryDesktopProfileState.set({ current: previousState.current, persisted: failedPersisted })
|
||||
}
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// ── Swap-minimal gateway routing ──────────────────────────────────────────
|
||||
|
|
|
|||
Loading…
Reference in New Issue