Skip to content

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

TypeScript

fix(desktop): select saved profiles for R4-H1

Josuéd16e8658a34e
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 850b24632..e2da7f6e8 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -97,6 +97,15 @@ const HOST_WAKE_SCOPE: RpcScope = 'host:wake:write'
const PROFILE_UI_BASE_URL_ORIGIN_ERROR =
'PROFILE_UI_BASE_URL must be an origin URL with a root pathname and no search parameters'
+function requireHttpOrigin(rawValue: string): string {
+ const value = rawValue.trim()
+ const url = new URL(value)
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
+ throw new Error('Desktop environment URLs must use http(s) without credentials')
+ }
+ return url.origin
+}
+
function normalizeExplicitProfileUiBaseUrl(rawValue: string): string | null {
const value = rawValue.trim()
if (!value) return null
@@ -1943,9 +1952,19 @@ export class AppService {
hydrateDesktopRuntimeConfig()
if (!isDesktopRuntimeConfigured()) return
if (config.rpcProxyBaseUrl?.trim()) return
+ const externalRestApiBaseUrl = config.externalRestApiBaseUrl
+ const externalRestApiOrigin = requireHttpOrigin(externalRestApiBaseUrl)
const discovered = await this.authClient.getDesktopEnvironment()
+ if (
+ discovered.externalRestApiBaseUrl?.trim() &&
+ requireHttpOrigin(discovered.externalRestApiBaseUrl) !== externalRestApiOrigin
+ ) {
+ throw new Error('Desktop environment discovery returned a different REST host')
+ }
await saveDesktopRuntimeConfig({
- externalRestApiBaseUrl: discovered.externalRestApiBaseUrl || config.externalRestApiBaseUrl,
+ // Discovery is scoped to the configured REST endpoint; it may provide
+ // RPC details but must never switch or overwrite another REST profile.
+ externalRestApiBaseUrl,
rpcProxyBaseUrl: discovered.rpcProxyBaseUrl,
appName: discovered.appName || config.appName,
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts
index e216f5253..1205f6b31 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts
@@ -167,7 +167,6 @@ describe('Desktop environment origin matching', () => {
externalRestApiBaseUrl: 'http://api.example.test',
},
],
- ['a missing RPC endpoint', { ...targetEnvironment, rpcProxyBaseUrl: '' }],
])('does not switch to a saved environment with %s', async (_case, linkedEnvironment) => {
const { handler, selectRuntimeConfig, setPendingDesktopEnvironmentSetup } = createHandler(
() => ({ booting: false, busy: false, authTransitioning: false, isAuthenticated: false })
@@ -181,4 +180,45 @@ describe('Desktop environment origin matching', () => {
rpcProxyBaseUrl: '',
})
})
+
+ it('selects the unique saved REST profile when the link omits RPC', async () => {
+ const state = await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ const savedTarget = state.options.find(
+ option =>
+ option.externalRestApiBaseUrl === `${targetEnvironment.externalRestApiBaseUrl}/api/v1`
+ )
+ if (!savedTarget) throw new Error('The config producer did not return the saved REST profile')
+ const { handler, selectRuntimeConfig, setPendingDesktopEnvironmentSetup } = createHandler(
+ () => ({ booting: false, busy: false, authTransitioning: false, isAuthenticated: false })
+ )
+
+ await handler({ ...targetEnvironment, rpcProxyBaseUrl: '' })
+
+ expect(selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id)
+ expect(setPendingDesktopEnvironmentSetup).toHaveBeenCalledWith(null)
+ })
+
+ it('rejects an omitted RPC when multiple saved profiles share the REST origin', async () => {
+ await runtimeConfigModule!.saveDesktopRuntimeConfig({
+ appName: 'Second API profile',
+ externalRestApiBaseUrl: targetEnvironment.externalRestApiBaseUrl,
+ rpcProxyBaseUrl: 'https://second-rpc.example.test',
+ })
+ const { handler, selectRuntimeConfig, setPendingDesktopEnvironmentSetup, setStatus } =
+ createHandler(() => ({
+ booting: false,
+ busy: false,
+ authTransitioning: false,
+ isAuthenticated: false,
+ }))
+
+ await handler({ ...targetEnvironment, rpcProxyBaseUrl: '' })
+
+ expect(selectRuntimeConfig).not.toHaveBeenCalled()
+ expect(setPendingDesktopEnvironmentSetup).toHaveBeenCalledWith(null)
+ expect(setStatus).toHaveBeenCalledWith(
+ expect.stringMatching(/multiple saved environments use this REST host/i),
+ 'error'
+ )
+ })
})
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
index f7057249a..7f41406fc 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useAuthController.desktopEnvironment.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAuthController.desktopEnvironment.test.tsx
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
onDesktopEnvironmentSetup: vi.fn(),
onDesktopSetupToken: vi.fn(),
onExternalLogout: vi.fn(),
+ saveRuntimeConfig: vi.fn(),
selectRuntimeConfig: vi.fn(),
setStatus: vi.fn(),
loadSession: vi.fn(),
@@ -39,6 +40,7 @@ type DesktopEnvironmentSetupPayload = typeof targetEnvironment
let desktopEnvironmentSetupListener:
| ((payload: DesktopEnvironmentSetupPayload) => void | Promise<void>)
| null = null
+let confirmDesktopEnvironmentSetupForTest: (() => Promise<void>) | null = null
let setBootingForTest: ((value: boolean) => void) | null = null
let setAuthenticatedForTest: ((value: boolean) => void) | null = null
let runtimeConfigModule: typeof import('../../../../../src/config') | null = null
@@ -52,6 +54,7 @@ function Probe() {
})
setBootingForTest = auth.setBooting
setAuthenticatedForTest = auth.setIsAuthenticated
+ confirmDesktopEnvironmentSetupForTest = auth.handleConfirmDesktopEnvironmentSetup
return (
<>
@@ -62,6 +65,7 @@ function Probe() {
<div data-testid="pending-rpc">
{auth.pendingDesktopEnvironmentSetup?.rpcProxyBaseUrl || 'none'}
</div>
+ <div data-testid="setup-complete">{auth.desktopEnvironmentSetupComplete ? 'yes' : 'no'}</div>
</>
)
}
@@ -89,6 +93,7 @@ async function savedTargetOptionId(): Promise<string> {
beforeEach(async () => {
vi.clearAllMocks()
desktopEnvironmentSetupListener = null
+ confirmDesktopEnvironmentSetupForTest = null
setBootingForTest = null
setAuthenticatedForTest = null
runtimeConfigModule = null
@@ -133,6 +138,7 @@ beforeEach(async () => {
auth: {
...window.clerum?.auth,
getRuntimeConfigState: mocks.getRuntimeConfigState,
+ saveRuntimeConfig: mocks.saveRuntimeConfig,
selectRuntimeConfig: mocks.selectRuntimeConfig,
onDesktopEnvironmentSetup: mocks.onDesktopEnvironmentSetup,
onDesktopSetupToken: mocks.onDesktopSetupToken,
@@ -216,6 +222,198 @@ describe('Desktop environment handoff', () => {
)
})
+ it('selects a saved REST profile without saving or rediscovering its RPC when the link omits RPC', async () => {
+ await runtimeConfigModule!.saveDesktopRuntimeConfig(targetEnvironment)
+ const state = await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ const pathBasedTarget = state.options.find(
+ option =>
+ option.externalRestApiBaseUrl === `${targetEnvironment.externalRestApiBaseUrl}/api/v1`
+ )
+ if (!pathBasedTarget)
+ throw new Error('The config producer did not return the path-based target')
+ await runtimeConfigModule!.deleteDesktopRuntimeConfigOption(pathBasedTarget.id)
+
+ const savedTarget = (await runtimeConfigModule!.getDesktopRuntimeConfigState()).options.find(
+ option =>
+ option.externalRestApiBaseUrl === targetEnvironment.externalRestApiBaseUrl &&
+ option.rpcProxyBaseUrl === targetEnvironment.rpcProxyBaseUrl
+ )
+ if (!savedTarget) throw new Error('The config producer did not return the saved REST profile')
+ const other = (await runtimeConfigModule!.getDesktopRuntimeConfigState()).options.find(
+ option => option.id !== savedTarget.id && option.id !== '__localhost__'
+ )
+ if (!other) throw new Error('The config producer did not return the other saved profile')
+ await runtimeConfigModule!.selectDesktopRuntimeConfigOption(other.id)
+
+ const { AppService } = await import('../../../../../src/appService')
+ const service = new AppService()
+ const serviceInternals = service as unknown as {
+ authClient: { getDesktopEnvironment: ReturnType<typeof vi.fn> }
+ applyRuntimeEnvironmentChange: (operation: () => Promise<void>) => Promise<void>
+ saveRuntimeConfig: typeof service.saveRuntimeConfig
+ }
+ serviceInternals.authClient = {
+ getDesktopEnvironment: vi.fn().mockResolvedValue({
+ externalRestApiBaseUrl: targetEnvironment.externalRestApiBaseUrl,
+ rpcProxyBaseUrl: 'https://rpc.untrusted-discovery.test',
+ appName: 'Discovered tenant',
+ }),
+ }
+ serviceInternals.applyRuntimeEnvironmentChange = operation => operation()
+ mocks.saveRuntimeConfig.mockImplementation(serviceInternals.saveRuntimeConfig.bind(service))
+
+ render(<Probe />)
+ await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
+ await dispatchDesktopEnvironmentLink({ ...targetEnvironment, rpcProxyBaseUrl: '' })
+
+ await act(async () => {
+ await confirmDesktopEnvironmentSetupForTest?.()
+ })
+
+ const finalState = await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ expect(finalState.options.find(option => option.id === savedTarget.id)).toMatchObject({
+ externalRestApiBaseUrl: targetEnvironment.externalRestApiBaseUrl,
+ rpcProxyBaseUrl: targetEnvironment.rpcProxyBaseUrl,
+ appName: targetEnvironment.appName,
+ })
+ expect(serviceInternals.authClient.getDesktopEnvironment).not.toHaveBeenCalled()
+ expect(mocks.saveRuntimeConfig).not.toHaveBeenCalled()
+ expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id)
+ expect(finalState.activeOptionId).toBe(savedTarget.id)
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
+ })
+
+ it('rechecks saved REST profiles when setup is confirmed', async () => {
+ const linkedEnvironment = {
+ appName: 'New tenant',
+ externalRestApiBaseUrl: 'https://new-api.example.test',
+ rpcProxyBaseUrl: '',
+ }
+ render(<Probe />)
+ await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
+ await dispatchDesktopEnvironmentLink(linkedEnvironment)
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent(
+ linkedEnvironment.externalRestApiBaseUrl
+ )
+
+ await runtimeConfigModule!.saveDesktopRuntimeConfig({
+ ...linkedEnvironment,
+ rpcProxyBaseUrl: 'https://rpc.new-api.example.test',
+ })
+ const savedOption = (await runtimeConfigModule!.getDesktopRuntimeConfigState()).options.find(
+ option => option.externalRestApiBaseUrl === linkedEnvironment.externalRestApiBaseUrl
+ )
+ if (!savedOption) throw new Error('The config producer did not return the newly saved profile')
+
+ await act(async () => {
+ await confirmDesktopEnvironmentSetupForTest?.()
+ })
+
+ expect(mocks.saveRuntimeConfig).not.toHaveBeenCalled()
+ expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(savedOption.id)
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
+ expect((await runtimeConfigModule!.getDesktopRuntimeConfigState()).activeOptionId).toBe(
+ savedOption.id
+ )
+ })
+
+ it('does not let runtime discovery overwrite another saved REST profile', async () => {
+ const setupEnvironment = {
+ appName: 'Setup tenant',
+ externalRestApiBaseUrl: 'https://setup-api.example.test',
+ rpcProxyBaseUrl: '',
+ }
+ await runtimeConfigModule!.saveDesktopRuntimeConfig(setupEnvironment)
+ const setupOption = (await runtimeConfigModule!.getDesktopRuntimeConfigState()).options.find(
+ option => option.externalRestApiBaseUrl === setupEnvironment.externalRestApiBaseUrl
+ )
+ const discoveryTarget = (
+ await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ ).options.find(
+ option => option.externalRestApiBaseUrl === otherEnvironment.externalRestApiBaseUrl
+ )
+ if (!setupOption || !discoveryTarget) {
+ throw new Error('The config producer did not return the test profiles')
+ }
+ await runtimeConfigModule!.selectDesktopRuntimeConfigOption(setupOption.id)
+
+ const { AppService } = await import('../../../../../src/appService')
+ const service = new AppService()
+ const serviceInternals = service as unknown as {
+ authClient: { getDesktopEnvironment: ReturnType<typeof vi.fn> }
+ applyRuntimeEnvironmentChange: (operation: () => Promise<void>) => Promise<void>
+ saveRuntimeConfig: typeof service.saveRuntimeConfig
+ }
+ serviceInternals.authClient = {
+ getDesktopEnvironment: vi.fn().mockResolvedValue({
+ externalRestApiBaseUrl: otherEnvironment.externalRestApiBaseUrl,
+ rpcProxyBaseUrl: 'https://rpc.overwrite.test',
+ appName: 'Overwritten tenant',
+ }),
+ }
+ serviceInternals.applyRuntimeEnvironmentChange = operation => operation()
+
+ await service.saveRuntimeConfig(setupEnvironment)
+
+ const finalState = await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ expect(serviceInternals.authClient.getDesktopEnvironment).toHaveBeenCalledOnce()
+ expect(finalState.activeOptionId).toBe(setupOption.id)
+ expect(finalState.options.find(option => option.id === discoveryTarget.id)).toMatchObject({
+ externalRestApiBaseUrl: otherEnvironment.externalRestApiBaseUrl,
+ rpcProxyBaseUrl: otherEnvironment.rpcProxyBaseUrl,
+ appName: otherEnvironment.appName,
+ })
+ })
+
+ it('does not report setup complete when discovery returns another REST origin', async () => {
+ const linkedEnvironment = {
+ appName: 'New tenant',
+ externalRestApiBaseUrl: 'https://new-api.example.test',
+ rpcProxyBaseUrl: 'https://rpc.untrusted.test',
+ }
+ const { AppService } = await import('../../../../../src/appService')
+ const service = new AppService()
+ const serviceInternals = service as unknown as {
+ authClient: { getDesktopEnvironment: ReturnType<typeof vi.fn> }
+ applyRuntimeEnvironmentChange: (operation: () => Promise<void>) => Promise<void>
+ saveRuntimeConfig: typeof service.saveRuntimeConfig
+ }
+ serviceInternals.authClient = {
+ getDesktopEnvironment: vi.fn().mockResolvedValue({
+ externalRestApiBaseUrl: otherEnvironment.externalRestApiBaseUrl,
+ rpcProxyBaseUrl: 'https://rpc.overwrite.test',
+ appName: 'Other tenant',
+ }),
+ }
+ serviceInternals.applyRuntimeEnvironmentChange = operation => operation()
+ mocks.saveRuntimeConfig.mockImplementation(serviceInternals.saveRuntimeConfig.bind(service))
+
+ render(<Probe />)
+ await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
+ await dispatchDesktopEnvironmentLink(linkedEnvironment)
+ await act(async () => {
+ await confirmDesktopEnvironmentSetupForTest?.()
+ })
+
+ const finalState = await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ const savedTarget = finalState.options.find(
+ option => option.externalRestApiBaseUrl === linkedEnvironment.externalRestApiBaseUrl
+ )
+ const existingOther = finalState.options.find(
+ option => option.externalRestApiBaseUrl === otherEnvironment.externalRestApiBaseUrl
+ )
+ expect(serviceInternals.authClient.getDesktopEnvironment).toHaveBeenCalledOnce()
+ expect(finalState.activeOptionId).toBe(savedTarget?.id)
+ expect(savedTarget?.rpcProxyBaseUrl).toBe('')
+ expect(existingOther).toMatchObject(otherEnvironment)
+ expect(screen.getByTestId('setup-complete')).toHaveTextContent('no')
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
+ expect(mocks.setStatus).toHaveBeenLastCalledWith(
+ 'Desktop environment setup could not verify the confirmed REST and RPC endpoints.',
+ 'error'
+ )
+ })
+
it('does not retain an RPC proxy supplied by a new environment link', async () => {
const linkedEnvironment = {
appName: 'New tenant',
diff --git a/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts b/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts
index 3c930f897..59c711391 100644
--- a/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts
+++ b/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts
@@ -49,6 +49,73 @@ function sameDesktopEnvironment(
}
}
+function savedEnvironmentsForRestOrigin(
+ options: DesktopRuntimeConfigState['options'],
+ restOrigin: string
+) {
+ return options.filter(option => {
+ if (option.source === 'localhost' || option.id === LOCALHOST_OPTION_ID) return false
+ try {
+ return environmentOrigin(option.externalRestApiBaseUrl) === restOrigin
+ } catch {
+ return false
+ }
+ })
+}
+
+function isLocalhostOption(option: DesktopRuntimeConfigState['options'][number]): boolean {
+ return option.source === 'localhost' || option.id === LOCALHOST_OPTION_ID
+}
+
+export function getDesktopEnvironmentRestOriginMatches(
+ configState: DesktopRuntimeConfigState,
+ externalRestApiBaseUrl: string
+) {
+ const restOrigin = environmentOrigin(externalRestApiBaseUrl)
+ return {
+ localhost: configState.options.find(option => {
+ if (!isLocalhostOption(option)) return false
+ try {
+ return environmentOrigin(option.externalRestApiBaseUrl) === restOrigin
+ } catch {
+ return false
+ }
+ }),
+ saved: savedEnvironmentsForRestOrigin(configState.options, restOrigin),
+ }
+}
+
+type SavedEnvironmentDecision =
+ | { kind: 'select'; option: DesktopRuntimeConfigState['options'][number] }
+ | { kind: 'setup' }
+ | { kind: 'reject'; reason: 'ambiguous' | 'rpc-conflict' }
+
+function decideSavedEnvironment(
+ sameRestOrigin: DesktopRuntimeConfigState['options'],
+ linkedConfig: DesktopRuntimeConfig
+): SavedEnvironmentDecision {
+ const linkedRpcOrigin = linkedConfig.rpcProxyBaseUrl?.trim()
+ ? environmentOrigin(linkedConfig.rpcProxyBaseUrl)
+ : ''
+
+ if (!linkedRpcOrigin) {
+ if (sameRestOrigin.length > 1) return { kind: 'reject', reason: 'ambiguous' }
+ if (sameRestOrigin.length === 1) return { kind: 'select', option: sameRestOrigin[0] }
+ return { kind: 'setup' }
+ }
+
+ const exactMatch = sameRestOrigin.find(option => {
+ try {
+ return environmentOrigin(option.rpcProxyBaseUrl) === linkedRpcOrigin
+ } catch {
+ return false
+ }
+ })
+ if (exactMatch) return { kind: 'select', option: exactMatch }
+ if (sameRestOrigin.length) return { kind: 'reject', reason: 'rpc-conflict' }
+ return { kind: 'setup' }
+}
+
function isAuthenticationOperationInProgress(state: DesktopEnvironmentHandoffState): boolean {
return state.booting || state.busy || state.authTransitioning
}
@@ -102,8 +169,11 @@ export function createDesktopEnvironmentSetupHandler({
return
}
- const localhostOption = configState.options.find(option => option.id === LOCALHOST_OPTION_ID)
- if (localhostOption && sameDesktopEnvironment(localhostOption, linkedConfig)) {
+ const restOriginMatches = getDesktopEnvironmentRestOriginMatches(
+ configState,
+ linkedConfig.externalRestApiBaseUrl
+ )
+ if (restOriginMatches.localhost) {
setPendingDesktopEnvironmentSetup(null)
setStatus(
'Desktop setup link rejected: the Localhost environment cannot be opened from a link.',
@@ -112,10 +182,12 @@ export function createDesktopEnvironmentSetupHandler({
return
}
+ const savedDecision = decideSavedEnvironment(restOriginMatches.saved, linkedConfig)
const activeEnvironmentMatches = Boolean(
configState.configured &&
configState.currentConfig &&
- sameDesktopEnvironment(configState.currentConfig, linkedConfig)
+ (sameDesktopEnvironment(configState.currentConfig, linkedConfig) ||
+ (savedDecision.kind === 'select' && savedDecision.option.id === configState.activeOptionId))
)
if (activeEnvironmentMatches) {
setPendingDesktopEnvironmentSetup(null)
@@ -129,12 +201,9 @@ export function createDesktopEnvironmentSetupHandler({
return
}
- const savedEnvironment = configState.options.find(option =>
- sameDesktopEnvironment(option, linkedConfig)
- )
- if (savedEnvironment) {
+ if (savedDecision.kind === 'select') {
setPendingDesktopEnvironmentSetup(null)
- const selectedState = await handleSelectRuntimeConfig(savedEnvironment.id)
+ const selectedState = await handleSelectRuntimeConfig(savedDecision.option.id)
if (!selectedState) return
try {
await onSessionNeedsLoad({ preserveNav: true })
@@ -147,26 +216,12 @@ export function createDesktopEnvironmentSetupHandler({
return
}
- const linkedRestOrigin = environmentOrigin(linkedConfig.externalRestApiBaseUrl)
- const linkedRpcOrigin = linkedConfig.rpcProxyBaseUrl
- ? environmentOrigin(linkedConfig.rpcProxyBaseUrl)
- : ''
- const conflictingSavedEnvironment = configState.options.find(option => {
- if (!option.rpcProxyBaseUrl.trim()) return false
- try {
- return (
- environmentOrigin(option.externalRestApiBaseUrl) === linkedRestOrigin &&
- Boolean(linkedRpcOrigin) &&
- environmentOrigin(option.rpcProxyBaseUrl) !== linkedRpcOrigin
- )
- } catch {
- return false
- }
- })
- if (conflictingSavedEnvironment) {
+ if (savedDecision.kind === 'reject') {
setPendingDesktopEnvironmentSetup(null)
setStatus(
- 'Desktop setup link rejected because its RPC proxy does not match the saved environment.',
+ savedDecision.reason === 'ambiguous'
+ ? 'Desktop setup link rejected because multiple saved environments use this REST host.'
+ : 'Desktop setup link rejected because its RPC proxy does not match the saved environment.',
'error'
)
return
diff --git a/desktop-app/ui/src/hooks/domain/useAuthController.ts b/desktop-app/ui/src/hooks/domain/useAuthController.ts
index 5b650fb3c..57bf8cf02 100644
--- a/desktop-app/ui/src/hooks/domain/useAuthController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAuthController.ts
@@ -10,7 +10,10 @@ import type {
SessionMe,
} from '../../../../src/types'
import type { Tone } from '../../uiTypes'
-import { createDesktopEnvironmentSetupHandler } from './desktopEnvironmentHandoff'
+import {
+ createDesktopEnvironmentSetupHandler,
+ getDesktopEnvironmentRestOriginMatches,
+} from './desktopEnvironmentHandoff'
import type { SetStatusFn } from './types'
interface UseAuthControllerParams {
@@ -419,8 +422,67 @@ export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthCont
if (!nextConfig) return
setAuthTransitioning(true)
try {
+ let currentConfigState: DesktopRuntimeConfigState
+ try {
+ currentConfigState = await refreshRuntimeConfigState()
+ } catch {
+ setStatus('Could not verify the desktop environment. Try opening it again.', 'error')
+ return
+ }
+
+ const restOriginMatches = getDesktopEnvironmentRestOriginMatches(
+ currentConfigState,
+ nextConfig.externalRestApiBaseUrl
+ )
+
+ if (restOriginMatches.localhost) {
+ setPendingDesktopEnvironmentSetup(null)
+ setStatus(
+ 'Desktop setup link rejected: the Localhost environment cannot be opened from a link.',
+ 'error'
+ )
+ return
+ }
+
+ if (restOriginMatches.saved.length > 0) {
+ if (restOriginMatches.saved.length > 1) {
+ setPendingDesktopEnvironmentSetup(null)
+ setStatus(
+ 'Desktop setup link rejected because multiple saved environments use this REST host.',
+ 'error'
+ )
+ return
+ }
+
+ const selectedState = await handleSelectRuntimeConfig(restOriginMatches.saved[0].id)
+ if (!selectedState) return
+ setPendingDesktopEnvironmentSetup(null)
+ try {
+ await onSessionNeedsLoad({ preserveNav: true })
+ } catch (error) {
+ setStatus(
+ `Could not load the selected desktop environment: ${error instanceof Error ? error.message : String(error)}`,
+ 'error'
+ )
+ }
+ return
+ }
+
const state = await handleSaveRuntimeConfig(nextConfig)
if (!state) return
+ const selectedOption = state.options.find(option => option.id === state.activeOptionId)
+ const selectedRestOriginMatches = getDesktopEnvironmentRestOriginMatches(
+ state,
+ nextConfig.externalRestApiBaseUrl
+ ).saved.some(option => option.id === state.activeOptionId)
+ if (!selectedOption || !selectedRestOriginMatches || !selectedOption.rpcProxyBaseUrl.trim()) {
+ setPendingDesktopEnvironmentSetup(null)
+ setStatus(
+ 'Desktop environment setup could not verify the confirmed REST and RPC endpoints.',
+ 'error'
+ )
+ return
+ }
setPendingDesktopEnvironmentSetup(null)
setDesktopEnvironmentSetupComplete(true)
setStatus('Desktop environment saved.', 'success')