Skip to content

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

TypeScript

fix: preserve desktop localhost auth session

Josué7ab03086837d
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 034cb1673..bf7593734 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.319",
+ "version": "0.1.320",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.319",
+ "version": "0.1.320",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index d044facc6..424fb5ca2 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.319",
+ "version": "0.1.320",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/__tests__/appService.bootstrap.test.ts b/desktop-app/src/__tests__/appService.bootstrap.test.ts
index 779e8850d..3a888c8fe 100644
--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts
+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts
@@ -183,6 +183,135 @@ describe('AppService invitation configuration lookup', () => {
expect(service.authClient.passwordLogin).toHaveBeenCalledWith('[email protected]', 'password123')
})
+ it('keeps a saved token when startup session restore has a transient failure', async () => {
+ const configPath = path.join(
+ os.tmpdir(),
+ `clerum-desktop-restore-local-${Date.now()}-${Math.random().toString(16).slice(2)}.json`
+ )
+ await fs.writeFile(
+ configPath,
+ JSON.stringify({
+ externalRestApiBaseUrl: 'http://127.0.0.1:8091',
+ rpcProxyBaseUrl: 'http://127.0.0.1:8094',
+ appName: 'Localhost',
+ })
+ )
+ process.env.CLERUM_DESKTOP_CONFIG_PATH = configPath
+ process.env.EXTERNAL_REST_API_BASE_URL = 'http://127.0.0.1:8091'
+ process.env.RPC_PROXY_BASE_URL = 'http://127.0.0.1:8094'
+ delete process.env.PROFILE_UI_BASE_URL
+ vi.resetModules()
+
+ const [{ AppService }, { resolveEnvKey }] = await Promise.all([
+ import('../appService.js'),
+ import('../config.js'),
+ ])
+ const { bindChatStoreForUser } = await import('../chatStoreBinding.js')
+
+ const me = {
+ id: 'user-1',
+ email: '[email protected]',
+ name: null,
+ picture: null,
+ teamId: 'team-1',
+ teamName: 'Marketing',
+ role: 'member',
+ }
+ const getSessionToken = vi.fn().mockResolvedValue('stored-token')
+ const clearSessionToken = vi.fn().mockResolvedValue(undefined)
+ const service = new AppService() as unknown as {
+ authClient: { getMe: ReturnType<typeof vi.fn> }
+ tokenStore: {
+ getSessionToken: ReturnType<typeof vi.fn>
+ clearSessionToken: ReturnType<typeof vi.fn>
+ }
+ rpcTokenManager: { clear: ReturnType<typeof vi.fn> }
+ initialize: () => Promise<unknown>
+ getSessionState: () => Promise<unknown>
+ }
+
+ service.authClient = {
+ getMe: vi.fn().mockRejectedValueOnce(new Error('fetch failed')).mockResolvedValueOnce(me),
+ } as never
+ service.tokenStore = {
+ getSessionToken,
+ clearSessionToken,
+ } as never
+ service.rpcTokenManager = {
+ clear: vi.fn(),
+ } as never
+
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ try {
+ await expect(service.initialize()).resolves.toEqual({ authenticated: false, me: null })
+
+ expect(clearSessionToken).not.toHaveBeenCalled()
+
+ await expect(service.getSessionState()).resolves.toMatchObject({
+ authenticated: true,
+ me: { email: '[email protected]' },
+ })
+ expect(getSessionToken).toHaveBeenCalledTimes(2)
+ expect(bindChatStoreForUser).toHaveBeenCalledWith(
+ 'user-1',
+ resolveEnvKey('http://127.0.0.1:8091')
+ )
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ it('clears a saved token when startup session restore is rejected by the API', async () => {
+ const configPath = path.join(
+ os.tmpdir(),
+ `clerum-desktop-restore-api-${Date.now()}-${Math.random().toString(16).slice(2)}.json`
+ )
+ await fs.writeFile(
+ configPath,
+ JSON.stringify({
+ externalRestApiBaseUrl: 'https://api.example.com',
+ rpcProxyBaseUrl: 'https://rpc.example.com',
+ appName: 'Example',
+ })
+ )
+ process.env.CLERUM_DESKTOP_CONFIG_PATH = configPath
+ process.env.EXTERNAL_REST_API_BASE_URL = 'https://api.example.com'
+ process.env.RPC_PROXY_BASE_URL = 'https://rpc.example.com'
+ delete process.env.PROFILE_UI_BASE_URL
+ vi.resetModules()
+
+ const [{ AppService }, { resolveEnvKey }, { ApiError }] = await Promise.all([
+ import('../appService.js'),
+ import('../config.js'),
+ import('../httpClient.js'),
+ ])
+ const clearSessionToken = vi.fn().mockResolvedValue(undefined)
+ const service = new AppService() as unknown as {
+ authClient: { getMe: ReturnType<typeof vi.fn> }
+ tokenStore: {
+ getSessionToken: ReturnType<typeof vi.fn>
+ clearSessionToken: ReturnType<typeof vi.fn>
+ }
+ rpcTokenManager: { clear: ReturnType<typeof vi.fn> }
+ initialize: () => Promise<unknown>
+ }
+
+ service.authClient = {
+ getMe: vi.fn().mockRejectedValue(new ApiError('401 Unauthorized', 401, '')),
+ } as never
+ service.tokenStore = {
+ getSessionToken: vi.fn().mockResolvedValue('stored-token'),
+ clearSessionToken,
+ } as never
+ service.rpcTokenManager = {
+ clear: vi.fn(),
+ } as never
+
+ await expect(service.initialize()).resolves.toEqual({ authenticated: false, me: null })
+
+ expect(clearSessionToken).toHaveBeenCalledWith(resolveEnvKey('https://api.example.com'))
+ })
+
it('persists a manually saved runtime environment', async () => {
const configPath = path.join(
os.tmpdir(),
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index c17e4a0cb..e232ed13d 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -328,6 +328,10 @@ export class AppService {
)
}
+ private static isRejectedStoredSessionError(error: unknown): boolean {
+ return error instanceof ApiError && (error.status === 401 || error.status === 403)
+ }
+
/**
* Maps rpc-proxy's structured host-availability 503s ({code:'host_waking'}
* from the wake-and-hold subsystem, {code:'host_draining'} from the mcp-host
@@ -511,15 +515,31 @@ export class AppService {
)
}
- async initialize(): Promise<SessionState> {
+ private clearAuthenticatedSessionState(): void {
+ this.stopAllStreams()
+ this.sessionToken = null
+ this.me = null
+ this.accessCatalog = null
+ this.teamDirectoryCache = null
+ this.workflowApprovalTeamById.clear()
+ this.workflowTeamByKey.clear()
+ this.rpcTokenManager.clear()
+ unbindChatStore()
+ }
+
+ private async restoreSavedSession(options: { runLaunchMaintenance?: boolean } = {}) {
hydrateDesktopRuntimeConfig()
- this.sessionToken = await this.tokenStore.getSessionToken(getActiveEnvKey())
- if (!this.sessionToken) {
+ const envKey = getActiveEnvKey()
+ const token = await this.tokenStore.getSessionToken(envKey)
+ if (!token) {
+ this.clearAuthenticatedSessionState()
return { authenticated: false, me: null }
}
+
+ this.sessionToken = token
try {
- this.me = await this.authClient.getMe(this.sessionToken)
- await bindChatStoreForUser(this.me.id, getActiveEnvKey())
+ this.me = await this.authClient.getMe(token)
+ await bindChatStoreForUser(this.me.id, envKey)
this.accessCatalog = null
this.teamDirectoryCache = null
this.workflowApprovalTeamById.clear()
@@ -527,14 +547,25 @@ export class AppService {
// Launch-time sandbox-ui partition GC. Fire-and-forget: a failure
// here must not block the user from logging in. Any network or fs
// error is logged inside the module.
- void this.runSandboxUiPartitionGcSafely()
+ if (options.runLaunchMaintenance) {
+ void this.runSandboxUiPartitionGcSafely()
+ }
return { authenticated: true, me: this.me }
- } catch {
- await this.logout()
+ } catch (error) {
+ this.clearAuthenticatedSessionState()
+ if (AppService.isRejectedStoredSessionError(error)) {
+ await this.tokenStore.clearSessionToken(envKey)
+ } else {
+ console.warn('[AppService] Saved session restore failed; keeping token for retry:', error)
+ }
return { authenticated: false, me: null }
}
}
+ async initialize(): Promise<SessionState> {
+ return this.restoreSavedSession({ runLaunchMaintenance: true })
+ }
+
private async runSandboxUiPartitionGcSafely(): Promise<void> {
try {
const { app } = await import('electron')
@@ -810,16 +841,8 @@ export class AppService {
}
async logout(): Promise<void> {
- this.stopAllStreams()
- this.sessionToken = null
- this.me = null
- this.accessCatalog = null
- this.teamDirectoryCache = null
- this.workflowApprovalTeamById.clear()
- this.workflowTeamByKey.clear()
- this.rpcTokenManager.clear()
+ this.clearAuthenticatedSessionState()
await this.tokenStore.clearSessionToken(getActiveEnvKey())
- unbindChatStore()
}
/** Resolve a gfs:// URI to its current resource via the API (no local mirror). */
@@ -923,7 +946,7 @@ export class AppService {
}
async getSessionState(): Promise<SessionState> {
- if (!this.sessionToken || !this.me) return { authenticated: false, me: null }
+ if (!this.sessionToken || !this.me) return this.restoreSavedSession()
return { authenticated: true, me: this.me }
}
diff --git a/desktop-app/ui/src/pages/AuthPage/index.tsx b/desktop-app/ui/src/pages/AuthPage/index.tsx
index 4810036c6..bff4bbcd7 100644
--- a/desktop-app/ui/src/pages/AuthPage/index.tsx
+++ b/desktop-app/ui/src/pages/AuthPage/index.tsx
@@ -3,10 +3,7 @@ import { useEffect, useRef, useState } from 'react'
import { useAuthContext } from '@contexts/AuthContext'
import { Button, Field, IconButton, MenuItem, TextInput } from '@components/Common'
import { ConfirmDialog } from '@components/ConfirmDialog'
-import {
- LOCALHOST_RUNTIME_CONFIG_OPTION_ID,
- createLocalhostRuntimeConfigOption,
-} from '@constants/runtimeConfig'
+import { createLocalhostRuntimeConfigOption } from '@constants/runtimeConfig'
import { formatDesktopAppVersionTooltip, useDesktopAppInfo } from '@hooks/useDesktopAppInfo'
import type { DesktopRuntimeConfigOption } from '../../../../src/types'
@@ -31,14 +28,10 @@ export function AuthPage() {
handleSaveRuntimeConfig,
handleDeleteRuntimeConfig,
handleSelectRuntimeConfig,
- handleClearRuntimeConfigSelection,
} = useAuthContext()
const runtimeConfigOptions = runtimeConfigState?.options || []
const activeRuntimeConfigId = runtimeConfigState?.activeOptionId ?? null
- const selectedRuntimeConfig = runtimeConfigOptions.find(
- option => option.id === activeRuntimeConfigId
- )
const hasPasswordLoginCredentials = Boolean(email.trim()) && Boolean(password)
const [runtimeSetupVisible, setRuntimeSetupVisible] = useState(false)
const hasRuntimeSetupValues =
@@ -101,12 +94,7 @@ export function AuthPage() {
const handleRuntimeOptionSelect = (optionId: string) => {
setRuntimeMenuOpen(false)
- if (
- optionId === activeRuntimeConfigId &&
- (selectedRuntimeConfig?.source === 'localhost' ||
- optionId === LOCALHOST_RUNTIME_CONFIG_OPTION_ID)
- ) {
- handleClearRuntimeConfigSelection()
+ if (optionId === activeRuntimeConfigId) {
return
}
handleSelectRuntimeConfig(optionId)
diff --git a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
index 643781d9f..d7ce82b0d 100644
--- a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
@@ -157,4 +157,40 @@ describe('AuthPage', () => {
expect(handleSelectRuntimeConfig).toHaveBeenCalledWith(LOCALHOST_RUNTIME_CONFIG_OPTION_ID)
})
+
+ it('does not clear the selected localhost environment when clicked again', async () => {
+ const user = userEvent.setup()
+ const handleSelectRuntimeConfig = vi.fn()
+ const handleClearRuntimeConfigSelection = vi.fn()
+
+ renderAuthPage({
+ runtimeConfigState: {
+ configured: true,
+ isLocalhost: true,
+ selectorVisible: true,
+ activeOptionId: LOCALHOST_RUNTIME_CONFIG_OPTION_ID,
+ envKey: 'http_127_0_0_1_8091-eaf18b680d58',
+ storagePath: '/tmp/evenfire-runtime-config',
+ options: [
+ {
+ id: LOCALHOST_RUNTIME_CONFIG_OPTION_ID,
+ label: 'Localhost',
+ source: 'localhost',
+ configPath: null,
+ externalRestApiBaseUrl: 'http://127.0.0.1:8091',
+ rpcProxyBaseUrl: 'http://127.0.0.1:8094',
+ appName: 'Localhost',
+ },
+ ],
+ },
+ handleSelectRuntimeConfig,
+ handleClearRuntimeConfigSelection,
+ })
+
+ await user.click(screen.getByLabelText('Open environment selector'))
+ await user.click(screen.getByRole('button', { name: 'Localhost' }))
+
+ expect(handleSelectRuntimeConfig).not.toHaveBeenCalled()
+ expect(handleClearRuntimeConfigSelection).not.toHaveBeenCalled()
+ })
})