Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop): open matching environment from Profile Portal

Josuéabf6adcf4794
diff --git a/desktop-app/src/__tests__/evenfireDeepLinkRouter.test.ts b/desktop-app/src/__tests__/evenfireDeepLinkRouter.test.ts
index 8412aef0a..0eb7b8013 100644
--- a/desktop-app/src/__tests__/evenfireDeepLinkRouter.test.ts
+++ b/desktop-app/src/__tests__/evenfireDeepLinkRouter.test.ts
@@ -88,7 +88,7 @@ describe('evenfire deep-link router', () => {
)
harness.router.handle(
- 'evenfire://desktop-environment?externalRestApiBaseUrl=https%3A%2F%2Fapi.example.test&tenantName=Acme'
+ 'evenfire://desktop-environment?externalRestApiBaseUrl=https%3A%2F%2Fapi.example.test&rpcProxyBaseUrl=https%3A%2F%2Frpc.example.test&tenantName=Acme'
)
harness.router.handle(
'evenfire://desktop-setup?email=user%40example.test&authorizationToken=token-1'
@@ -99,7 +99,11 @@ describe('evenfire deep-link router', () => {
expect(harness.sent).toEqual([
{
channel: 'auth:desktopEnvironmentSetup',
- payload: { appName: 'Acme', externalRestApiBaseUrl: 'https://api.example.test' },
+ payload: {
+ appName: 'Acme',
+ externalRestApiBaseUrl: 'https://api.example.test',
+ rpcProxyBaseUrl: 'https://rpc.example.test',
+ },
window: 'initial',
},
{
@@ -141,7 +145,11 @@ describe('evenfire deep-link router', () => {
},
{
channel: 'auth:desktopEnvironmentSetup',
- payload: { appName: 'Env', externalRestApiBaseUrl: 'https://api.example.test' },
+ payload: {
+ appName: 'Env',
+ externalRestApiBaseUrl: 'https://api.example.test',
+ rpcProxyBaseUrl: '',
+ },
window: 'initial',
},
])
@@ -172,7 +180,11 @@ describe('evenfire deep-link router', () => {
},
{
channel: 'auth:desktopEnvironmentSetup',
- payload: { appName: 'Second', externalRestApiBaseUrl: 'https://api.example.test' },
+ payload: {
+ appName: 'Second',
+ externalRestApiBaseUrl: 'https://api.example.test',
+ rpcProxyBaseUrl: '',
+ },
window: 'recreated',
},
{
diff --git a/desktop-app/src/config.ts b/desktop-app/src/config.ts
index cac98035d..d747c42a3 100644
--- a/desktop-app/src/config.ts
+++ b/desktop-app/src/config.ts
@@ -876,6 +876,7 @@ export function getDesktopRuntimeConfigState(): DesktopRuntimeConfigState {
isLocalhost,
selectorVisible,
activeOptionId,
+ currentConfig: current,
envKey: resolveEnvKey(current.externalRestApiBaseUrl, current.rpcProxyBaseUrl),
storagePath: explicitRuntimeConfigPath() || runtimeConfigDirectoryPath(),
options,
diff --git a/desktop-app/src/evenfireDeepLinkRouter.ts b/desktop-app/src/evenfireDeepLinkRouter.ts
index 6ee444227..bc435371f 100644
--- a/desktop-app/src/evenfireDeepLinkRouter.ts
+++ b/desktop-app/src/evenfireDeepLinkRouter.ts
@@ -50,6 +50,7 @@ export function createEvenfireDeepLinkRouter<TWindow extends RendererTarget>(
const sendDesktopEnvironmentSetup = (parsed: URL, rawUrl: string): void => {
const externalRestApiBaseUrl = parsed.searchParams.get('externalRestApiBaseUrl') || ''
+ const rpcProxyBaseUrl = parsed.searchParams.get('rpcProxyBaseUrl') || ''
const appName =
parsed.searchParams.get('tenantName') || parsed.searchParams.get('appName') || ''
if (!externalRestApiBaseUrl) return
@@ -59,6 +60,7 @@ export function createEvenfireDeepLinkRouter<TWindow extends RendererTarget>(
options.focusMainWindow()
window.webContents.send('auth:desktopEnvironmentSetup', {
externalRestApiBaseUrl,
+ rpcProxyBaseUrl,
appName,
})
return
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index d9ce05167..6353ea26d 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -105,11 +105,19 @@ const clerum = Object.freeze({
return () => ipcRenderer.off('auth:desktopSetupToken', listener)
},
onDesktopEnvironmentSetup: (
- callback: (payload: { externalRestApiBaseUrl: string; appName?: string }) => void
+ callback: (payload: {
+ externalRestApiBaseUrl: string
+ rpcProxyBaseUrl: string
+ appName?: string
+ }) => void
) => {
const listener = (
_event: Electron.IpcRendererEvent,
- payload: { externalRestApiBaseUrl: string; appName?: string }
+ payload: {
+ externalRestApiBaseUrl: string
+ rpcProxyBaseUrl: string
+ appName?: string
+ }
) => callback(payload)
ipcRenderer.on('auth:desktopEnvironmentSetup', listener)
return () => ipcRenderer.off('auth:desktopEnvironmentSetup', listener)
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 23e5ecaff..b58881663 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -96,7 +96,11 @@ declare global {
callback: (payload: { email: string; authorizationToken: string }) => void
) => () => void
onDesktopEnvironmentSetup: (
- callback: (payload: { externalRestApiBaseUrl: string; appName?: string }) => void
+ callback: (payload: {
+ externalRestApiBaseUrl: string
+ rpcProxyBaseUrl: string
+ appName?: string
+ }) => void
) => () => void
getDesktopReleaseStatus: () => Promise<DesktopReleaseStatus>
getDesktopAppInfo: () => Promise<DesktopAppInfo>
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 04679d747..7b0afd92d 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -661,6 +661,7 @@ export type DesktopRuntimeConfigState = {
isLocalhost: boolean
selectorVisible: boolean
activeOptionId: string | null
+ currentConfig?: DesktopRuntimeConfig
/**
* Stable, filesystem-safe namespacing key for the ACTIVE environment (spec
* §5.1). Derived from `new URL(externalRestApiBaseUrl).origin`; every local
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 61b024077..32551f31b 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -2430,14 +2430,19 @@ export function App() {
body={
<>
<p>
- Profile UI is asking this desktop app to use{' '}
+ This environment is not saved in Evenfire Desktop yet. Add{' '}
<strong>{vm.pendingDesktopEnvironmentSetup.appName || 'Evenfire'}</strong>.
</p>
- <p>Only continue if you trust this External REST API host:</p>
+ <p>Only continue if you trust these service URLs:</p>
<p className="auth-environment-confirm-url">
{vm.pendingDesktopEnvironmentSetup.externalRestApiBaseUrl}
</p>
{pendingEnvironmentHost ? <p className="muted">Host: {pendingEnvironmentHost}</p> : null}
+ {vm.pendingDesktopEnvironmentSetup.rpcProxyBaseUrl ? (
+ <p className="auth-environment-confirm-url">
+ RPC proxy: {vm.pendingDesktopEnvironmentSetup.rpcProxyBaseUrl}
+ </p>
+ ) : null}
</>
}
cancelLabel="Cancel"
diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
index 64dda1896..aaea34599 100644
--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
@@ -1,7 +1,8 @@
// @vitest-environment jsdom
-import { useEffect, useReducer } from 'react'
+import { type ReactNode, useEffect, useReducer } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render, waitFor } from '@testing-library/react'
+import { renderToStaticMarkup } from 'react-dom/server'
import { DESKTOP_ROUTES, SIDEBAR_COLLAPSED_KEY } from '@constants/navigation'
import { useAppController } from '@hooks/useAppController'
import {
@@ -46,6 +47,7 @@ const confirmDialogHarness = vi.hoisted(() => ({
mountedCount: 0,
props: null as null | {
title: string
+ body?: ReactNode
onCancel: () => void
onConfirm: () => void
},
@@ -142,7 +144,12 @@ vi.mock('@components/CommandPalette', () => ({
vi.mock('@components/BootSplash', () => ({ BootSplash: () => null }))
vi.mock('@components/Common', () => ({ Button: () => null, ToastStack: () => null }))
vi.mock('@components/ConfirmDialog', () => ({
- ConfirmDialog: (props: { title: string; onCancel: () => void; onConfirm: () => void }) => {
+ ConfirmDialog: (props: {
+ title: string
+ body?: ReactNode
+ onCancel: () => void
+ onConfirm: () => void
+ }) => {
confirmDialogHarness.rendered(props)
confirmDialogHarness.props = props
useEffect(() => {
@@ -372,6 +379,24 @@ describe('App deep-link orchestration', () => {
// the persistence tests override the resolved value per case.
const getSandboxUiLocation = vi.fn().mockResolvedValue(null)
+ it('prompts to add an environment when a Profile Portal handoff has no saved match', () => {
+ currentController = makeController({
+ initialExperienceLoading: false,
+ pendingDesktopEnvironmentSetup: {
+ appName: 'Example tenant',
+ externalRestApiBaseUrl: 'https://api.example.test',
+ rpcProxyBaseUrl: 'https://rpc.example.test',
+ },
+ } as Partial<AppController>)
+
+ render(<App />)
+
+ expect(confirmDialogHarness.props?.title).toBe('Add desktop environment?')
+ const dialogBody = renderToStaticMarkup(<>{confirmDialogHarness.props?.body}</>)
+ expect(dialogBody).toContain('This environment is not saved in Evenfire Desktop yet.')
+ expect(dialogBody).toContain('https://rpc.example.test')
+ })
+
beforeEach(() => {
vi.clearAllMocks()
confirmDialogHarness.props = null
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAuthController.desktopEnvironment.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAuthController.desktopEnvironment.test.tsx
new file mode 100644
index 000000000..e35ee231b
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAuthController.desktopEnvironment.test.tsx
@@ -0,0 +1,219 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import '@testing-library/jest-dom/vitest'
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
+import fsp from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { useAuthController } from '../useAuthController'
+
+const mocks = vi.hoisted(() => ({
+ clearQueryCache: vi.fn(),
+ getRuntimeConfigState: vi.fn(),
+ onDesktopEnvironmentSetup: vi.fn(),
+ onDesktopSetupToken: vi.fn(),
+ onExternalLogout: vi.fn(),
+ selectRuntimeConfig: vi.fn(),
+ setStatus: vi.fn(),
+ loadSession: vi.fn(),
+}))
+
+vi.mock('@lib/queryClient', () => ({
+ desktopQueryClient: { clear: mocks.clearQueryCache },
+}))
+
+const targetEnvironment = {
+ appName: 'Example tenant',
+ externalRestApiBaseUrl: 'https://api.example.test',
+ rpcProxyBaseUrl: 'https://rpc.example.test',
+}
+
+const otherEnvironment = {
+ appName: 'Other tenant',
+ externalRestApiBaseUrl: 'https://other-api.example.test',
+ rpcProxyBaseUrl: 'https://other-rpc.example.test',
+}
+
+type DesktopEnvironmentSetupPayload = typeof targetEnvironment
+
+let desktopEnvironmentSetupListener:
+ | ((payload: DesktopEnvironmentSetupPayload) => void | Promise<void>)
+ | null = null
+let runtimeConfigModule: typeof import('../../../../../src/config') | null = null
+let runtimeConfigDirectory = ''
+const originalOnboardingPreview = process.env.EVENFIRE_ONBOARDING_PREVIEW
+
+function Probe() {
+ const auth = useAuthController({
+ setStatus: mocks.setStatus,
+ onSessionNeedsLoad: mocks.loadSession,
+ })
+
+ return (
+ <>
+ <div data-testid="configuration-loaded">{auth.runtimeConfigState ? 'yes' : 'no'}</div>
+ <div data-testid="pending-environment">
+ {auth.pendingDesktopEnvironmentSetup?.externalRestApiBaseUrl || 'none'}
+ </div>
+ <div data-testid="pending-rpc">
+ {auth.pendingDesktopEnvironmentSetup?.rpcProxyBaseUrl || 'none'}
+ </div>
+ </>
+ )
+}
+
+async function dispatchDesktopEnvironmentLink() {
+ if (!desktopEnvironmentSetupListener) {
+ throw new Error('Desktop environment listener was not registered')
+ }
+ await act(async () => {
+ await desktopEnvironmentSetupListener?.(targetEnvironment)
+ })
+}
+
+async function savedTargetOptionId(): Promise<string> {
+ const state = await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ const option = state.options.find(
+ candidate =>
+ candidate.externalRestApiBaseUrl === `${targetEnvironment.externalRestApiBaseUrl}/api/v1` &&
+ candidate.rpcProxyBaseUrl === `${targetEnvironment.rpcProxyBaseUrl}/rpc`
+ )
+ if (!option) throw new Error('The runtime config producer did not return the saved target')
+ return option.id
+}
+
+beforeEach(async () => {
+ vi.clearAllMocks()
+ desktopEnvironmentSetupListener = null
+ runtimeConfigModule = null
+ delete process.env.EVENFIRE_ONBOARDING_PREVIEW
+ runtimeConfigDirectory = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-desktop-env-test-'))
+ vi.doUnmock('electron')
+ vi.resetModules()
+ vi.doMock('electron', () => ({
+ app: {
+ getPath: vi.fn(() => runtimeConfigDirectory),
+ isPackaged: true,
+ isReady: vi.fn(() => true),
+ setName: vi.fn(),
+ },
+ }))
+ runtimeConfigModule = await import('../../../../../src/config')
+ await runtimeConfigModule.saveDesktopRuntimeConfig({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
+ rpcProxyBaseUrl: `${targetEnvironment.rpcProxyBaseUrl}/rpc`,
+ })
+ await runtimeConfigModule.saveDesktopRuntimeConfig(otherEnvironment)
+
+ mocks.getRuntimeConfigState.mockImplementation(async () =>
+ runtimeConfigModule!.getDesktopRuntimeConfigState()
+ )
+ mocks.selectRuntimeConfig.mockImplementation(async (optionId: string) => {
+ await runtimeConfigModule!.selectDesktopRuntimeConfigOption(optionId)
+ return runtimeConfigModule!.getDesktopRuntimeConfigState()
+ })
+ mocks.loadSession.mockResolvedValue(undefined)
+ mocks.onDesktopSetupToken.mockReturnValue(() => undefined)
+ mocks.onExternalLogout.mockReturnValue(() => undefined)
+ mocks.onDesktopEnvironmentSetup.mockImplementation(
+ (listener: (payload: DesktopEnvironmentSetupPayload) => void | Promise<void>) => {
+ desktopEnvironmentSetupListener = listener
+ return () => undefined
+ }
+ )
+ window.clerum = {
+ ...window.clerum,
+ auth: {
+ ...window.clerum?.auth,
+ getRuntimeConfigState: mocks.getRuntimeConfigState,
+ selectRuntimeConfig: mocks.selectRuntimeConfig,
+ onDesktopEnvironmentSetup: mocks.onDesktopEnvironmentSetup,
+ onDesktopSetupToken: mocks.onDesktopSetupToken,
+ onExternalLogout: mocks.onExternalLogout,
+ },
+ }
+})
+
+afterEach(async () => {
+ cleanup()
+ vi.doUnmock('electron')
+ vi.resetModules()
+ await fsp.rm(runtimeConfigDirectory, { recursive: true, force: true })
+ if (originalOnboardingPreview === undefined) delete process.env.EVENFIRE_ONBOARDING_PREVIEW
+ else process.env.EVENFIRE_ONBOARDING_PREVIEW = originalOnboardingPreview
+})
+
+describe('Desktop environment handoff', () => {
+ it('switches to a saved environment matching both service origins', async () => {
+ render(<Probe />)
+ await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
+ const targetOptionId = await savedTargetOptionId()
+ mocks.loadSession.mockClear()
+
+ await dispatchDesktopEnvironmentLink()
+
+ expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(targetOptionId)
+ expect(mocks.clearQueryCache).toHaveBeenCalledOnce()
+ expect(mocks.loadSession).toHaveBeenCalledWith({ preserveNav: true })
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
+ expect(mocks.setStatus).toHaveBeenCalledWith(
+ expect.stringContaining('Environment selected: Example tenant'),
+ 'success',
+ undefined,
+ { global: false, toast: true }
+ )
+ })
+
+ it('opens the active matching environment without prompting for setup', async () => {
+ const targetOptionId = await savedTargetOptionId()
+ await runtimeConfigModule!.selectDesktopRuntimeConfigOption(targetOptionId)
+
+ render(<Probe />)
+ await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
+ await dispatchDesktopEnvironmentLink()
+
+ expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
+ expect(mocks.setStatus).toHaveBeenCalledWith(
+ 'Opening Example tenant in Evenfire Desktop.',
+ 'success'
+ )
+ })
+
+ it('prompts to add the environment when its RPC proxy origin is not saved', async () => {
+ await runtimeConfigModule!.saveDesktopRuntimeConfig({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
+ rpcProxyBaseUrl: otherEnvironment.rpcProxyBaseUrl,
+ })
+
+ render(<Probe />)
+ await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
+ await dispatchDesktopEnvironmentLink()
+
+ expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent(
+ targetEnvironment.externalRestApiBaseUrl
+ )
+ expect(screen.getByTestId('pending-rpc')).toHaveTextContent(targetEnvironment.rpcProxyBaseUrl)
+ })
+
+ it('does not offer setup when the saved environment list cannot be verified', async () => {
+ mocks.getRuntimeConfigState.mockImplementationOnce(async () =>
+ runtimeConfigModule!.getDesktopRuntimeConfigState()
+ )
+ mocks.getRuntimeConfigState.mockRejectedValueOnce(new Error('IPC unavailable'))
+
+ render(<Probe />)
+ await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
+ await dispatchDesktopEnvironmentLink()
+
+ expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
+ expect(mocks.setStatus).toHaveBeenCalledWith(
+ 'Could not verify the desktop environment. Try opening it again.',
+ 'error'
+ )
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/useAuthController.ts b/desktop-app/ui/src/hooks/domain/useAuthController.ts
index d3cfcdf0e..864f5690a 100644
--- a/desktop-app/ui/src/hooks/domain/useAuthController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAuthController.ts
@@ -37,6 +37,30 @@ function isUnauthorizedError(error: unknown) {
return /\b401\s+unauthorized\b/.test(message) || /:\s*401\s/.test(message)
}
+function environmentOrigin(value: string): string {
+ const url = new URL(value.trim())
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ throw new Error('Only http(s) desktop environment URLs are supported')
+ }
+ return url.origin
+}
+
+function sameDesktopEnvironment(
+ left: Pick<DesktopRuntimeConfig, 'externalRestApiBaseUrl' | 'rpcProxyBaseUrl'>,
+ right: Pick<DesktopRuntimeConfig, 'externalRestApiBaseUrl' | 'rpcProxyBaseUrl'>
+): boolean {
+ try {
+ return (
+ environmentOrigin(left.externalRestApiBaseUrl) ===
+ environmentOrigin(right.externalRestApiBaseUrl) &&
+ (left.rpcProxyBaseUrl?.trim() ? environmentOrigin(left.rpcProxyBaseUrl) : '') ===
+ (right.rpcProxyBaseUrl?.trim() ? environmentOrigin(right.rpcProxyBaseUrl) : '')
+ )
+ } catch {
+ return false
+ }
+}
+
export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthControllerParams) {
const [booting, setBooting] = useState(true)
const [busy, setBusy] = useState(false)
@@ -134,30 +158,6 @@ export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthCont
})
}, [completeDesktopSetupWith, setStatus])
- useEffect(() => {
- return window.clerum.auth.onDesktopEnvironmentSetup(({ externalRestApiBaseUrl, appName }) => {
- const normalizedExternalRestApiBaseUrl = externalRestApiBaseUrl.trim()
- if (!normalizedExternalRestApiBaseUrl) return
- try {
- const url = new URL(normalizedExternalRestApiBaseUrl)
- if (url.protocol !== 'http:' && url.protocol !== 'https:') {
- throw new Error('Only http(s) desktop environment URLs are supported')
- }
- } catch (error) {
- setStatus(
- `Desktop setup link rejected: ${error instanceof Error ? error.message : String(error)}`,
- 'error'
- )
- return
- }
- setPendingDesktopEnvironmentSetup({
- externalRestApiBaseUrl: normalizedExternalRestApiBaseUrl,
- rpcProxyBaseUrl: '',
- appName: appName?.trim() || 'Evenfire',
- })
- })
- }, [setStatus])
-
useEffect(() => {
return window.clerum.auth.onExternalLogout(() => {
setIsAuthenticated(false)
@@ -325,38 +325,102 @@ export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthCont
}
}
- const handleSelectRuntimeConfig = async (
- optionId: string
- ): Promise<DesktopRuntimeConfigState | null> => {
- try {
- setBusy(true)
- setBackendSwitchHint(null)
- const state = await window.clerum.auth.selectRuntimeConfig(optionId)
- // Switching environment (pre-login) must not carry another env's cached
- // queries forward (spec §5.2 P1). The env is bound to login (D4: no switch
- // without logout), so a full clear is sufficient — no per-env query keys.
- desktopQueryClient.clear()
- setRuntimeConfigState(state)
- setDesktopSetupAuthorizationToken('')
- setDesktopSetupStarted(false)
- const selected = state.options.find(option => option.id === state.activeOptionId)
- setStatus(
- selected ? `Environment selected: ${selected.label}.` : 'Environment selected.',
- 'success',
- undefined,
- { global: false, toast: true }
- )
- return state
- } catch (error) {
- setStatus(
- `Failed to switch environment: ${error instanceof Error ? error.message : String(error)}`,
- 'error'
- )
- return null
- } finally {
- setBusy(false)
- }
- }
+ const handleSelectRuntimeConfig = useCallback(
+ async (optionId: string): Promise<DesktopRuntimeConfigState | null> => {
+ try {
+ setBusy(true)
+ setBackendSwitchHint(null)
+ const state = await window.clerum.auth.selectRuntimeConfig(optionId)
+ // Switching environment (pre-login) must not carry another env's cached
+ // queries forward (spec §5.2 P1). The env is bound to login (D4: no switch
+ // without logout), so a full clear is sufficient — no per-env query keys.
+ desktopQueryClient.clear()
+ setRuntimeConfigState(state)
+ setDesktopSetupAuthorizationToken('')
+ setDesktopSetupStarted(false)
+ const selected = state.options.find(option => option.id === state.activeOptionId)
+ setStatus(
+ selected ? `Environment selected: ${selected.label}.` : 'Environment selected.',
+ 'success',
+ undefined,
+ { global: false, toast: true }
+ )
+ return state
+ } catch (error) {
+ setStatus(
+ `Failed to switch environment: ${error instanceof Error ? error.message : String(error)}`,
+ 'error'
+ )
+ return null
+ } finally {
+ setBusy(false)
+ }
+ },
+ [setStatus]
+ )
+
+ useEffect(() => {
+ return window.clerum.auth.onDesktopEnvironmentSetup(
+ async ({ externalRestApiBaseUrl, rpcProxyBaseUrl, appName }) => {
+ const normalizedExternalRestApiBaseUrl = externalRestApiBaseUrl.trim()
+ if (!normalizedExternalRestApiBaseUrl) return
+ const targetConfig: DesktopRuntimeConfig = {
+ externalRestApiBaseUrl: normalizedExternalRestApiBaseUrl,
+ rpcProxyBaseUrl: rpcProxyBaseUrl?.trim() || '',
+ appName: appName?.trim() || 'Evenfire',
+ }
+ try {
+ environmentOrigin(targetConfig.externalRestApiBaseUrl)
+ if (targetConfig.rpcProxyBaseUrl) environmentOrigin(targetConfig.rpcProxyBaseUrl)
+ } catch (error) {
+ setStatus(
+ `Desktop setup link rejected: ${error instanceof Error ? error.message : String(error)}`,
+ 'error'
+ )
+ return
+ }
+
+ let configState: DesktopRuntimeConfigState
+ try {
+ configState = await refreshRuntimeConfigState()
+ } catch {
+ setStatus('Could not verify the desktop environment. Try opening it again.', 'error')
+ return
+ }
+
+ const activeEnvironmentMatches = Boolean(
+ configState.configured &&
+ configState.currentConfig &&
+ sameDesktopEnvironment(configState.currentConfig, targetConfig)
+ )
+ if (activeEnvironmentMatches) {
+ setPendingDesktopEnvironmentSetup(null)
+ setStatus(`Opening ${targetConfig.appName} in Evenfire Desktop.`, 'success')
+ return
+ }
+
+ const savedEnvironment = configState.options.find(option =>
+ sameDesktopEnvironment(option, targetConfig)
+ )
+ if (savedEnvironment) {
+ setPendingDesktopEnvironmentSetup(null)
+ const selectedState = await handleSelectRuntimeConfig(savedEnvironment.id)
+ if (!selectedState) return
+ try {
+ await onSessionNeedsLoad({ preserveNav: true })
+ } catch (error) {
+ setStatus(
+ `Could not load the selected desktop environment: ${error instanceof Error ? error.message : String(error)}`,
+ 'error'
+ )
+ }
+ return
+ }
+
+ setPendingDesktopEnvironmentSetup(targetConfig)
+ }
+ )
+ }, [handleSelectRuntimeConfig, onSessionNeedsLoad, refreshRuntimeConfigState, setStatus])
const handleClearRuntimeConfigSelection = async (): Promise<DesktopRuntimeConfigState | null> => {
try {
diff --git a/profile-ui/app/components/__tests__/ProfilePortalHome.test.tsx b/profile-ui/app/components/__tests__/ProfilePortalHome.test.tsx
index 6c2938480..7ece535aa 100644
--- a/profile-ui/app/components/__tests__/ProfilePortalHome.test.tsx
+++ b/profile-ui/app/components/__tests__/ProfilePortalHome.test.tsx
@@ -50,7 +50,7 @@ beforeEach(() => {
afterEach(cleanup)
-describe('Profile Portal home desktop setup link', () => {
+describe('Profile Portal home desktop app link', () => {
it('keeps the welcome, portal prompt, and account summary in three cards', () => {
api.getDesktopEnvironment.mockReturnValue(new Promise(() => {}))
@@ -66,7 +66,7 @@ describe('Profile Portal home desktop setup link', () => {
render(<Page />)
expect(screen.getByRole('status')).toHaveTextContent('Checking desktop app setup…')
- expect(screen.queryByRole('link', { name: 'Set up Desktop App' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: 'Open Desktop App' })).not.toBeInTheDocument()
})
it('explains unavailable setup and links to Settings when discovery fails', async () => {
@@ -81,7 +81,7 @@ describe('Profile Portal home desktop setup link', () => {
'href',
'/settings/profile'
)
- expect(screen.queryByRole('link', { name: 'Set up Desktop App' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: 'Open Desktop App' })).not.toBeInTheDocument()
})
it('explains unavailable setup when discovery has no External REST API URL', async () => {
@@ -99,25 +99,25 @@ describe('Profile Portal home desktop setup link', () => {
'href',
'/settings/profile'
)
- expect(screen.queryByRole('link', { name: 'Set up Desktop App' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: 'Open Desktop App' })).not.toBeInTheDocument()
})
- it('labels the environment setup handoff accurately', async () => {
+ it('labels the environment handoff as opening the desktop app instead', async () => {
const environment = desktopEnvironment
render(<Page />)
- const setupLink = await screen.findByRole('link', { name: 'Set up Desktop App' })
- const setupCopy = setupLink.closest('p')
- const href = new URL(setupLink.getAttribute('href') ?? '')
+ const openLink = await screen.findByRole('link', { name: 'Open Desktop App' })
+ const handoffCopy = openLink.closest('p')
+ const href = new URL(openLink.getAttribute('href') ?? '')
- expect(setupCopy).toHaveTextContent('Prefer the desktop app?')
- expect(setupCopy).not.toHaveTextContent('instead')
+ expect(handoffCopy).toHaveTextContent('Open Desktop App instead.')
expect(href.searchParams.get('externalRestApiBaseUrl')).toBe(environment.externalRestApiBaseUrl)
expect(href.searchParams.get('tenantName')).toBe(environment.appName)
+ expect(href.searchParams.get('rpcProxyBaseUrl')).toBe(environment.rpcProxyBaseUrl)
})
- it('builds the setup link from the production discovery response', () => {
+ it('builds the desktop app link from the production discovery response', () => {
const environment = desktopEnvironment
const href = buildDesktopEnvironmentLink(environment)
@@ -129,5 +129,6 @@ describe('Profile Portal home desktop setup link', () => {
environment.externalRestApiBaseUrl
)
expect(parsedLink.searchParams.get('tenantName')).toBe(environment.appName)
+ expect(parsedLink.searchParams.get('rpcProxyBaseUrl')).toBe(environment.rpcProxyBaseUrl)
})
})
diff --git a/profile-ui/app/page.tsx b/profile-ui/app/page.tsx
index dc0d14b7b..f4525dda8 100644
--- a/profile-ui/app/page.tsx
+++ b/profile-ui/app/page.tsx
@@ -59,10 +59,10 @@ function HomeContent() {
</p>
) : (
<p className="body-copy">
- Prefer the desktop app?{' '}
<a className="cu-home-desktop-link" href={desktopAppLink.href}>
- Set up Desktop App <IconExternalLink />
- </a>
+ Open Desktop App <IconExternalLink />
+ </a>{' '}
+ instead.
</p>
)}
</div>
diff --git a/profile-ui/lib/desktopAppLinks.ts b/profile-ui/lib/desktopAppLinks.ts
index 1247d8a06..9b87ff5cf 100644
--- a/profile-ui/lib/desktopAppLinks.ts
+++ b/profile-ui/lib/desktopAppLinks.ts
@@ -15,6 +15,9 @@ export function buildDesktopEnvironmentLink(
externalRestApiBaseUrl: environment.externalRestApiBaseUrl,
tenantName: environment.appName || 'Evenfire',
})
+ if (environment.rpcProxyBaseUrl) {
+ params.set('rpcProxyBaseUrl', environment.rpcProxyBaseUrl)
+ }
return `evenfire://desktop-environment?${params.toString()}`
}
diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.json
index 0f3823274..4442b8aad 100644
--- a/profile-ui/package-lock.json
+++ b/profile-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.157",
+ "version": "0.1.158",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-profile-ui",
- "version": "0.1.157",
+ "version": "0.1.158",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/profile-ui/package.json b/profile-ui/package.json
index 9718c3e8e..9fb684613 100644
--- a/profile-ui/package.json
+++ b/profile-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-profile-ui",
- "version": "0.1.157",
+ "version": "0.1.158",
"private": true,
"scripts": {
"dev": "next dev",