Skip to content

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

TypeScript

fix: route Desktop handoffs to exact REST environments

Josuée701b8d3eacb
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 3152d5e7d..a2c389cad 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/desktopEnvironmentHandoff.test.ts
@@ -73,6 +73,7 @@ function createHandler(
refreshRuntimeConfigState,
handleSelectRuntimeConfig: selectRuntimeConfig,
onSessionNeedsLoad: vi.fn(async () => undefined),
+ logoutForEnvironmentMismatch: vi.fn(async () => undefined),
setPendingDesktopEnvironmentSetup,
setStatus,
})
@@ -132,7 +133,10 @@ describe('Desktop environment handoff concurrency', () => {
refreshRuntimeConfigState
)
- const first = handler(targetEnvironment)
+ const first = handler({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
+ })
const second = handler(otherEnvironment)
finishRefreshes.forEach(finishRefresh => finishRefresh())
await Promise.all([first, second])
@@ -144,7 +148,7 @@ describe('Desktop environment handoff concurrency', () => {
})
})
-describe('Desktop environment origin matching', () => {
+describe('Desktop environment REST endpoint matching', () => {
it.each([
[
'a REST host suffix',
@@ -181,7 +185,7 @@ describe('Desktop environment origin matching', () => {
})
})
- it('selects the unique saved REST profile when the link omits RPC', async () => {
+ it('selects the exact saved REST profile when the link omits RPC', async () => {
const state = await runtimeConfigModule!.getDesktopRuntimeConfigState()
const savedTarget = state.options.find(
option =>
@@ -192,7 +196,10 @@ describe('Desktop environment origin matching', () => {
() => ({ booting: false, busy: false, authTransitioning: false, isAuthenticated: false })
)
- await handler({ ...targetEnvironment, rpcProxyBaseUrl: '' })
+ await handler({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
+ })
expect(selectRuntimeConfig).toHaveBeenCalledWith(savedTarget.id)
expect(setPendingDesktopEnvironmentSetup).toHaveBeenCalledWith(null)
@@ -212,7 +219,6 @@ describe('Desktop environment origin matching', () => {
await handler({
...targetEnvironment,
externalRestApiBaseUrl: 'https://api.example.test./api/v1',
- rpcProxyBaseUrl: '',
})
const finalState = await runtimeConfigModule!.getDesktopRuntimeConfigState()
@@ -246,27 +252,39 @@ describe('Desktop environment origin matching', () => {
)
})
- 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,
- }))
+ it.each(['one saved profile', 'multiple saved profiles'])(
+ 'offers to add an unmatched REST path with %s on the same origin',
+ async profileCount => {
+ if (profileCount === 'multiple saved profiles') {
+ 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: '' })
+ await handler({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/other`,
+ })
- expect(selectRuntimeConfig).not.toHaveBeenCalled()
- expect(setPendingDesktopEnvironmentSetup).toHaveBeenCalledWith(null)
- expect(setStatus).toHaveBeenCalledWith(
- expect.stringMatching(/multiple saved environments use this REST host/i),
- 'error'
- )
- })
+ expect(selectRuntimeConfig).not.toHaveBeenCalled()
+ expect(setPendingDesktopEnvironmentSetup).toHaveBeenCalledWith({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/other`,
+ rpcProxyBaseUrl: '',
+ })
+ expect(setStatus).not.toHaveBeenCalledWith(
+ expect.stringMatching(/multiple saved environments/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 7f41406fc..889e5df46 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
@@ -10,6 +10,7 @@ import { useAuthController } from '../useAuthController'
const mocks = vi.hoisted(() => ({
clearQueryCache: vi.fn(),
getRuntimeConfigState: vi.fn(),
+ logoutForEnvironmentMismatch: vi.fn(),
onDesktopEnvironmentSetup: vi.fn(),
onDesktopSetupToken: vi.fn(),
onExternalLogout: vi.fn(),
@@ -35,7 +36,10 @@ const otherEnvironment = {
rpcProxyBaseUrl: 'https://other-rpc.example.test',
}
-type DesktopEnvironmentSetupPayload = typeof targetEnvironment
+type DesktopEnvironmentSetupPayload = {
+ externalRestApiBaseUrl: string
+ appName?: string
+}
let desktopEnvironmentSetupListener:
| ((payload: DesktopEnvironmentSetupPayload) => void | Promise<void>)
@@ -51,6 +55,7 @@ function Probe() {
const auth = useAuthController({
setStatus: mocks.setStatus,
onSessionNeedsLoad: mocks.loadSession,
+ logoutForEnvironmentMismatch: mocks.logoutForEnvironmentMismatch,
})
setBootingForTest = auth.setBooting
setAuthenticatedForTest = auth.setIsAuthenticated
@@ -125,6 +130,9 @@ beforeEach(async () => {
return runtimeConfigModule!.getDesktopRuntimeConfigState()
})
mocks.loadSession.mockImplementation(async () => setBootingForTest?.(false))
+ mocks.logoutForEnvironmentMismatch.mockImplementation(async () => {
+ setAuthenticatedForTest?.(false)
+ })
mocks.onDesktopSetupToken.mockReturnValue(() => undefined)
mocks.onExternalLogout.mockReturnValue(() => undefined)
mocks.onDesktopEnvironmentSetup.mockImplementation(
@@ -157,13 +165,16 @@ afterEach(async () => {
})
describe('Desktop environment handoff', () => {
- it('switches to a saved environment matching both service origins', async () => {
+ it('switches to a saved environment matching its REST endpoint', async () => {
render(<Probe />)
await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
const targetOptionId = await savedTargetOptionId()
mocks.loadSession.mockClear()
- await dispatchDesktopEnvironmentLink()
+ await dispatchDesktopEnvironmentLink({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
+ })
expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(targetOptionId)
expect(mocks.clearQueryCache).toHaveBeenCalledOnce()
@@ -183,7 +194,10 @@ describe('Desktop environment handoff', () => {
render(<Probe />)
await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
- await dispatchDesktopEnvironmentLink()
+ await dispatchDesktopEnvironmentLink({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
+ })
expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()
expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
@@ -193,7 +207,7 @@ describe('Desktop environment handoff', () => {
)
})
- it('rejects a link that proposes a different RPC proxy for a saved REST environment', async () => {
+ it('selects a saved REST environment without trusting the linked RPC proxy', async () => {
await runtimeConfigModule!.saveDesktopRuntimeConfig({
...targetEnvironment,
externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
@@ -204,10 +218,11 @@ describe('Desktop environment handoff', () => {
await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
await dispatchDesktopEnvironmentLink({
...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
rpcProxyBaseUrl: 'https://rpc.attacker.test',
})
- expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()
+ expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(await savedTargetOptionId())
expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
expect(screen.getByTestId('pending-rpc')).toHaveTextContent('none')
expect(
@@ -216,10 +231,6 @@ describe('Desktop environment handoff', () => {
option.externalRestApiBaseUrl === `${targetEnvironment.externalRestApiBaseUrl}/api/v1`
)?.rpcProxyBaseUrl
).toBe(`${targetEnvironment.rpcProxyBaseUrl}/rpc`)
- expect(mocks.setStatus).toHaveBeenCalledWith(
- expect.stringMatching(/RPC proxy.*saved environment/i),
- 'error'
- )
})
it('selects a saved REST profile without saving or rediscovering its RPC when the link omits RPC', async () => {
@@ -264,7 +275,7 @@ describe('Desktop environment handoff', () => {
render(<Probe />)
await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
- await dispatchDesktopEnvironmentLink({ ...targetEnvironment, rpcProxyBaseUrl: '' })
+ await dispatchDesktopEnvironmentLink(targetEnvironment)
await act(async () => {
await confirmDesktopEnvironmentSetupForTest?.()
@@ -431,7 +442,7 @@ describe('Desktop environment handoff', () => {
expect(screen.getByTestId('pending-rpc')).toHaveTextContent('none')
})
- it('does not switch away from another saved environment while signed in', async () => {
+ it('logs out and selects the linked saved environment when REST endpoints differ', async () => {
const state = await runtimeConfigModule!.getDesktopRuntimeConfigState()
const otherOption = state.options.find(
option => option.externalRestApiBaseUrl === otherEnvironment.externalRestApiBaseUrl
@@ -445,14 +456,14 @@ describe('Desktop environment handoff', () => {
mocks.selectRuntimeConfig.mockClear()
mocks.setStatus.mockClear()
- await dispatchDesktopEnvironmentLink()
+ await dispatchDesktopEnvironmentLink({
+ ...targetEnvironment,
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v1`,
+ })
- expect(mocks.selectRuntimeConfig).not.toHaveBeenCalled()
+ expect(mocks.logoutForEnvironmentMismatch).toHaveBeenCalledOnce()
+ expect(mocks.selectRuntimeConfig).toHaveBeenCalledWith(await savedTargetOptionId())
expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
- expect(mocks.setStatus).toHaveBeenCalledWith(
- expect.stringMatching(/sign out.*before opening another/i),
- 'info'
- )
})
it('does not let a desktop link select the built-in Localhost environment', async () => {
@@ -493,4 +504,53 @@ describe('Desktop environment handoff', () => {
'error'
)
})
+
+ it('adds a REST API path when only another path on the same host is saved', async () => {
+ const linkedEnvironment = {
+ appName: 'API v2 tenant',
+ externalRestApiBaseUrl: `${targetEnvironment.externalRestApiBaseUrl}/api/v2`,
+ rpcProxyBaseUrl: '',
+ }
+ 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({
+ ...linkedEnvironment,
+ rpcProxyBaseUrl: 'https://rpc.example.test/api-v2',
+ }),
+ }
+ 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)
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent(
+ linkedEnvironment.externalRestApiBaseUrl
+ )
+
+ await act(async () => {
+ await confirmDesktopEnvironmentSetupForTest?.()
+ })
+
+ const finalState = await runtimeConfigModule!.getDesktopRuntimeConfigState()
+ const savedTarget = finalState.options.find(
+ option => option.externalRestApiBaseUrl === linkedEnvironment.externalRestApiBaseUrl
+ )
+ const originalTarget = finalState.options.find(
+ option =>
+ option.externalRestApiBaseUrl === `${targetEnvironment.externalRestApiBaseUrl}/api/v1`
+ )
+ expect(serviceInternals.authClient.getDesktopEnvironment).toHaveBeenCalledOnce()
+ expect(savedTarget?.rpcProxyBaseUrl).toBe('https://rpc.example.test/api-v2')
+ expect(originalTarget).toBeDefined()
+ expect(finalState.activeOptionId).toBe(savedTarget?.id)
+ expect(screen.getByTestId('setup-complete')).toHaveTextContent('yes')
+ expect(screen.getByTestId('pending-environment')).toHaveTextContent('none')
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts b/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts
index 00a08344c..b1e88cf12 100644
--- a/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts
+++ b/desktop-app/ui/src/hooks/domain/desktopEnvironmentHandoff.ts
@@ -1,6 +1,7 @@
import {
canonicalizeDesktopRestEndpoint,
desktopRestEndpointOrigin,
+ sameDesktopRestEndpoint,
} from '../../../../src/desktopEnvironmentUrl'
import type { DesktopRuntimeConfig, DesktopRuntimeConfigState } from '../../../../src/types'
import type { SetStatusFn } from './types'
@@ -16,7 +17,6 @@ type DesktopEnvironmentHandoffState = {
type DesktopEnvironmentSetupPayload = {
externalRestApiBaseUrl: string
- rpcProxyBaseUrl?: string
appName?: string
}
@@ -25,45 +25,18 @@ type DesktopEnvironmentSetupHandlerOptions = {
refreshRuntimeConfigState: () => Promise<DesktopRuntimeConfigState>
handleSelectRuntimeConfig: (optionId: string) => Promise<DesktopRuntimeConfigState | null>
onSessionNeedsLoad: (options?: { preserveNav?: boolean }) => Promise<void>
+ logoutForEnvironmentMismatch: () => Promise<void>
setPendingDesktopEnvironmentSetup: (config: DesktopRuntimeConfig | null) => void
setStatus: SetStatusFn
}
-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 (
- desktopRestEndpointOrigin(left.externalRestApiBaseUrl) ===
- desktopRestEndpointOrigin(right.externalRestApiBaseUrl) &&
- (left.rpcProxyBaseUrl?.trim() ? environmentOrigin(left.rpcProxyBaseUrl) : '') ===
- (right.rpcProxyBaseUrl?.trim() ? environmentOrigin(right.rpcProxyBaseUrl) : '')
- )
- } catch {
- return false
- }
-}
-
-function savedEnvironmentsForRestOrigin(
+function savedEnvironmentsForRestEndpoint(
options: DesktopRuntimeConfigState['options'],
- restOrigin: string
+ externalRestApiBaseUrl: string
) {
return options.filter(option => {
if (option.source === 'localhost' || option.id === LOCALHOST_OPTION_ID) return false
- try {
- return desktopRestEndpointOrigin(option.externalRestApiBaseUrl) === restOrigin
- } catch {
- return false
- }
+ return sameDesktopRestEndpoint(option.externalRestApiBaseUrl, externalRestApiBaseUrl)
})
}
@@ -71,7 +44,7 @@ function isLocalhostOption(option: DesktopRuntimeConfigState['options'][number])
return option.source === 'localhost' || option.id === LOCALHOST_OPTION_ID
}
-export function getDesktopEnvironmentRestOriginMatches(
+export function getDesktopEnvironmentRestMatches(
configState: DesktopRuntimeConfigState,
externalRestApiBaseUrl: string
) {
@@ -85,41 +58,10 @@ export function getDesktopEnvironmentRestOriginMatches(
return false
}
}),
- saved: savedEnvironmentsForRestOrigin(configState.options, restOrigin),
+ saved: savedEnvironmentsForRestEndpoint(configState.options, externalRestApiBaseUrl),
}
}
-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
}
@@ -129,6 +71,7 @@ export function createDesktopEnvironmentSetupHandler({
refreshRuntimeConfigState,
handleSelectRuntimeConfig,
onSessionNeedsLoad,
+ logoutForEnvironmentMismatch,
setPendingDesktopEnvironmentSetup,
setStatus,
}: DesktopEnvironmentSetupHandlerOptions) {
@@ -136,21 +79,19 @@ export function createDesktopEnvironmentSetupHandler({
const processLink = async ({
externalRestApiBaseUrl,
- rpcProxyBaseUrl,
appName,
}: DesktopEnvironmentSetupPayload) => {
const normalizedExternalRestApiBaseUrl = externalRestApiBaseUrl.trim()
if (!normalizedExternalRestApiBaseUrl) return
const linkedConfig: DesktopRuntimeConfig = {
externalRestApiBaseUrl: normalizedExternalRestApiBaseUrl,
- rpcProxyBaseUrl: rpcProxyBaseUrl?.trim() || '',
+ rpcProxyBaseUrl: '',
appName: appName?.trim() || 'Evenfire',
}
try {
linkedConfig.externalRestApiBaseUrl = canonicalizeDesktopRestEndpoint(
linkedConfig.externalRestApiBaseUrl
)
- if (linkedConfig.rpcProxyBaseUrl) environmentOrigin(linkedConfig.rpcProxyBaseUrl)
} catch (error) {
setStatus(
`Desktop setup link rejected: ${error instanceof Error ? error.message : String(error)}`,
@@ -175,11 +116,11 @@ export function createDesktopEnvironmentSetupHandler({
return
}
- const restOriginMatches = getDesktopEnvironmentRestOriginMatches(
+ let restMatches = getDesktopEnvironmentRestMatches(
configState,
linkedConfig.externalRestApiBaseUrl
)
- if (restOriginMatches.localhost) {
+ if (restMatches.localhost) {
setPendingDesktopEnvironmentSetup(null)
setStatus(
'Desktop setup link rejected: the Localhost environment cannot be opened from a link.',
@@ -188,28 +129,57 @@ export function createDesktopEnvironmentSetupHandler({
return
}
- const savedDecision = decideSavedEnvironment(restOriginMatches.saved, linkedConfig)
- const activeEnvironmentMatches = Boolean(
+ let authState = getAuthState()
+ const activeRestEndpointMatches = Boolean(
configState.configured &&
configState.currentConfig &&
- (sameDesktopEnvironment(configState.currentConfig, linkedConfig) ||
- (savedDecision.kind === 'select' && savedDecision.option.id === configState.activeOptionId))
+ sameDesktopRestEndpoint(
+ configState.currentConfig.externalRestApiBaseUrl,
+ linkedConfig.externalRestApiBaseUrl
+ )
)
- if (activeEnvironmentMatches) {
+ if (authState.isAuthenticated && !activeRestEndpointMatches) {
setPendingDesktopEnvironmentSetup(null)
- setStatus(`Opening ${linkedConfig.appName} in Evenfire Desktop.`, 'success')
- return
+ try {
+ await logoutForEnvironmentMismatch()
+ } catch (error) {
+ setStatus(
+ `Could not sign out before switching desktop environments: ${error instanceof Error ? error.message : String(error)}`,
+ 'error'
+ )
+ return
+ }
+ authState = getAuthState()
+ if (authState.isAuthenticated) return
+ try {
+ configState = await refreshRuntimeConfigState()
+ } catch {
+ setStatus('Could not verify the desktop environment. Try opening it again.', 'error')
+ return
+ }
+ restMatches = getDesktopEnvironmentRestMatches(
+ configState,
+ linkedConfig.externalRestApiBaseUrl
+ )
+ if (restMatches.localhost) {
+ setPendingDesktopEnvironmentSetup(null)
+ setStatus(
+ 'Desktop setup link rejected: the Localhost environment cannot be opened from a link.',
+ 'error'
+ )
+ return
+ }
}
- if (getAuthState().isAuthenticated) {
+ if (authState.isAuthenticated) {
setPendingDesktopEnvironmentSetup(null)
- setStatus('Sign out before opening another desktop environment.', 'info')
+ setStatus(`Opening ${linkedConfig.appName} in Evenfire Desktop.`, 'success')
return
}
- if (savedDecision.kind === 'select') {
+ if (restMatches.saved.length === 1) {
setPendingDesktopEnvironmentSetup(null)
- const selectedState = await handleSelectRuntimeConfig(savedDecision.option.id)
+ const selectedState = await handleSelectRuntimeConfig(restMatches.saved[0].id)
if (!selectedState) return
try {
await onSessionNeedsLoad({ preserveNav: true })
@@ -222,19 +192,16 @@ export function createDesktopEnvironmentSetupHandler({
return
}
- if (savedDecision.kind === 'reject') {
+ if (restMatches.saved.length > 1) {
setPendingDesktopEnvironmentSetup(null)
setStatus(
- 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.',
+ 'Desktop setup link rejected because multiple saved environments use this REST API.',
'error'
)
return
}
- // The RPC URL in an external link is untrusted. Desktop discovers it from
- // the selected REST endpoint after confirmation.
+ // The backend supplies the RPC endpoint after the user confirms this REST API.
setPendingDesktopEnvironmentSetup({ ...linkedConfig, rpcProxyBaseUrl: '' })
}
diff --git a/desktop-app/ui/src/hooks/domain/useAuthController.ts b/desktop-app/ui/src/hooks/domain/useAuthController.ts
index 57bf8cf02..34e36ccee 100644
--- a/desktop-app/ui/src/hooks/domain/useAuthController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAuthController.ts
@@ -12,13 +12,14 @@ import type {
import type { Tone } from '../../uiTypes'
import {
createDesktopEnvironmentSetupHandler,
- getDesktopEnvironmentRestOriginMatches,
+ getDesktopEnvironmentRestMatches,
} from './desktopEnvironmentHandoff'
import type { SetStatusFn } from './types'
interface UseAuthControllerParams {
setStatus: SetStatusFn
onSessionNeedsLoad: (options?: { preserveNav?: boolean }) => Promise<void>
+ logoutForEnvironmentMismatch: () => Promise<void>
}
function isInvitationExpiredError(error: unknown) {
@@ -41,7 +42,11 @@ function isUnauthorizedError(error: unknown) {
return /\b401\s+unauthorized\b/.test(message) || /:\s*401\s/.test(message)
}
-export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthControllerParams) {
+export function useAuthController({
+ setStatus,
+ onSessionNeedsLoad,
+ logoutForEnvironmentMismatch,
+}: UseAuthControllerParams) {
const [booting, setBootingState] = useState(true)
const bootingRef = useRef(true)
const setBooting = useCallback((next: boolean) => {
@@ -376,6 +381,7 @@ export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthCont
refreshRuntimeConfigState,
handleSelectRuntimeConfig,
onSessionNeedsLoad,
+ logoutForEnvironmentMismatch,
setPendingDesktopEnvironmentSetup,
setStatus,
})
@@ -383,6 +389,7 @@ export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthCont
}, [
getDesktopEnvironmentHandoffAuthState,
handleSelectRuntimeConfig,
+ logoutForEnvironmentMismatch,
onSessionNeedsLoad,
refreshRuntimeConfigState,
setStatus,
@@ -430,12 +437,12 @@ export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthCont
return
}
- const restOriginMatches = getDesktopEnvironmentRestOriginMatches(
+ const restMatches = getDesktopEnvironmentRestMatches(
currentConfigState,
nextConfig.externalRestApiBaseUrl
)
- if (restOriginMatches.localhost) {
+ if (restMatches.localhost) {
setPendingDesktopEnvironmentSetup(null)
setStatus(
'Desktop setup link rejected: the Localhost environment cannot be opened from a link.',
@@ -444,17 +451,17 @@ export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthCont
return
}
- if (restOriginMatches.saved.length > 0) {
- if (restOriginMatches.saved.length > 1) {
+ if (restMatches.saved.length > 0) {
+ if (restMatches.saved.length > 1) {
setPendingDesktopEnvironmentSetup(null)
setStatus(
- 'Desktop setup link rejected because multiple saved environments use this REST host.',
+ 'Desktop setup link rejected because multiple saved environments use this REST API.',
'error'
)
return
}
- const selectedState = await handleSelectRuntimeConfig(restOriginMatches.saved[0].id)
+ const selectedState = await handleSelectRuntimeConfig(restMatches.saved[0].id)
if (!selectedState) return
setPendingDesktopEnvironmentSetup(null)
try {
@@ -471,11 +478,11 @@ export function useAuthController({ setStatus, onSessionNeedsLoad }: UseAuthCont
const state = await handleSaveRuntimeConfig(nextConfig)
if (!state) return
const selectedOption = state.options.find(option => option.id === state.activeOptionId)
- const selectedRestOriginMatches = getDesktopEnvironmentRestOriginMatches(
+ const selectedRestMatches = getDesktopEnvironmentRestMatches(
state,
nextConfig.externalRestApiBaseUrl
).saved.some(option => option.id === state.activeOptionId)
- if (!selectedOption || !selectedRestOriginMatches || !selectedOption.rpcProxyBaseUrl.trim()) {
+ if (!selectedOption || !selectedRestMatches || !selectedOption.rpcProxyBaseUrl.trim()) {
setPendingDesktopEnvironmentSetup(null)
setStatus(
'Desktop environment setup could not verify the confirmed REST and RPC endpoints.',
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index 57b371f67..4fe54c645 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -182,11 +182,17 @@ export function useAppController() {
const onSessionNeedsLoad = useCallback(async (options?: { preserveNav?: boolean }) => {
return loadSessionRef.current(options)
}, [])
+ const logoutForEnvironmentMismatchRef = useRef<() => Promise<void>>(async () => undefined)
+ const logoutForEnvironmentMismatch = useCallback(
+ () => logoutForEnvironmentMismatchRef.current(),
+ []
+ )
// ─── Auth ───
const auth = useAuthController({
setStatus: fullSetStatus,
onSessionNeedsLoad,
+ logoutForEnvironmentMismatch,
})
// ─── First-run onboarding ───
@@ -940,6 +946,7 @@ export function useAppController() {
resetWorkflowsData,
teamsData.reset,
])
+ logoutForEnvironmentMismatchRef.current = handleLogout
// ─── Cross-domain: handleOpenAgentWorkspace ───
const openAgentWorkspace = useCallback(