Skip to content

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

TypeScript

test(desktop): derive auth fixtures from AppService (R13-L11)

Josué4548b1d071c5
diff --git a/desktop-app/src/__tests__/appService.prewarm.test.ts b/desktop-app/src/__tests__/appService.prewarm.test.ts
index dac10c9a1..34c91ac01 100644
--- a/desktop-app/src/__tests__/appService.prewarm.test.ts
+++ b/desktop-app/src/__tests__/appService.prewarm.test.ts
@@ -9,6 +9,7 @@ import { ApiError } from '../httpClient.js'
vi.mock('../config.js', () => ({
getActiveEnvKey: () => 'test-env',
getActiveLegacyEnvKeys: () => [],
+ getDesktopRuntimeConfigState: () => ({ activeOptionId: 'test-profile' }),
config: {
rpcProxyBaseUrl: 'http://proxy',
externalRestApiBaseUrl: 'http://rest',
@@ -379,7 +380,13 @@ describe('AppService.prewarmHost — bounded wake re-emission', () => {
const svc = makeService()
const switchSessionToTeam = vi
.spyOn(
- svc as unknown as { switchSessionToTeam: () => Promise<string> },
+ svc as unknown as {
+ switchSessionToTeam: (
+ teamId: string,
+ token: string,
+ options?: { advanceSessionGeneration?: boolean }
+ ) => Promise<string>
+ },
'switchSessionToTeam'
)
.mockImplementation(async () => (svc as unknown as { sessionToken: string }).sessionToken)
@@ -402,7 +409,9 @@ describe('AppService.prewarmHost — bounded wake re-emission', () => {
return operation
})
await operationStarted
- expect(switchSessionToTeam).toHaveBeenCalledWith('team-2', expect.any(String))
+ expect(switchSessionToTeam).toHaveBeenCalledWith('team-2', expect.any(String), {
+ advanceSessionGeneration: false,
+ })
expect(
(
svc as unknown as { prewarmAttemptAtByHostRef: Map<string, number> }
@@ -414,7 +423,9 @@ describe('AppService.prewarmHost — bounded wake re-emission', () => {
finishOperation()
await hop
- expect(switchSessionToTeam).toHaveBeenCalledWith('team-1', expect.any(String))
+ expect(switchSessionToTeam).toHaveBeenCalledWith('team-1', expect.any(String), {
+ advanceSessionGeneration: false,
+ })
await expect(svc.prewarmHost('chatllm')).resolves.toEqual({
requested: false,
skipped: 'cooldown',
diff --git a/desktop-app/src/__tests__/appService.teamTransitionOwnership.test.ts b/desktop-app/src/__tests__/appService.teamTransitionOwnership.test.ts
index 4e8db900c..80701fff9 100644
--- a/desktop-app/src/__tests__/appService.teamTransitionOwnership.test.ts
+++ b/desktop-app/src/__tests__/appService.teamTransitionOwnership.test.ts
@@ -334,17 +334,16 @@ describe('AppService deliberate team transition ownership', () => {
it('keeps REST discovery for the same profile when logout advances session generation', async () => {
const { service, runtimeConfig, restA } = await createNativeCommitTestHarness()
- await runtimeConfig.saveDesktopRuntimeConfig({
- externalRestApiBaseUrl: restA,
- rpcProxyBaseUrl: '',
- appName: 'Environment A',
- })
const discovery = deferred<{
externalRestApiBaseUrl: string
rpcProxyBaseUrl: string
appName: string
}>()
const discoveryStarted = deferred<void>()
+ const getDesktopEnvironment = vi.fn(() => {
+ discoveryStarted.resolve()
+ return discovery.promise
+ })
const app = service as unknown as {
sessionToken: string | null
me: { id: string; email: string; name: string; picture: null; teamId: string; role: string }
@@ -353,23 +352,29 @@ describe('AppService deliberate team transition ownership', () => {
suspendDesktopGfsUploadsForAuthBoundary: () => Promise<void>
getDependenciesHealth(): Promise<unknown>
}
- app.sessionToken = 'session-a'
- app.me = {
- id: 'user-a',
- email: '[email protected]',
- name: 'User A',
- picture: null,
- teamId: 'team-a',
- role: 'member',
- }
app.authClient = {
- getDesktopEnvironment: vi.fn(() => {
- discoveryStarted.resolve()
- return discovery.promise
+ googleLogin: vi.fn().mockResolvedValue({
+ token: 'session-a',
+ me: {
+ id: 'user-a',
+ email: '[email protected]',
+ name: 'User A',
+ picture: null,
+ teamId: 'team-a',
+ teamName: 'Team A',
+ role: 'member',
+ },
}),
+ getDesktopEnvironment,
health: vi.fn().mockResolvedValue({ status: 'ok' }),
}
app.rpcClient = { health: vi.fn().mockResolvedValue({ status: 'ok' }) }
+ await service.googleLogin('synthetic-google-token')
+ await runtimeConfig.saveDesktopRuntimeConfig({
+ externalRestApiBaseUrl: restA,
+ rpcProxyBaseUrl: '',
+ appName: 'Environment A',
+ })
app.suspendDesktopGfsUploadsForAuthBoundary = vi.fn().mockResolvedValue(undefined)
const healthRequest = app.getDependenciesHealth()
@@ -406,16 +411,21 @@ describe('AppService deliberate team transition ownership', () => {
runWithTeamContext<T>(teamId: string, operation: (token: string) => Promise<T>): Promise<T>
suspendDesktopGfsUploadsForAuthBoundary: () => Promise<void>
}
- app.sessionToken = 'session-a'
- app.me = {
- id: 'user-a',
- email: '[email protected]',
- name: 'User A',
- picture: null,
- teamId: 'team-a',
- teamName: 'Team A',
- role: 'member',
+ app.authClient = {
+ googleLogin: vi.fn().mockResolvedValue({
+ token: 'session-a',
+ me: {
+ id: 'user-a',
+ email: '[email protected]',
+ name: 'User A',
+ picture: null,
+ teamId: 'team-a',
+ teamName: 'Team A',
+ role: 'member',
+ },
+ }),
}
+ await service.googleLogin('synthetic-google-token')
app.suspendDesktopGfsUploadsForAuthBoundary = vi.fn().mockResolvedValue(undefined)
const operation = app.runWithTeamContext('team-a', async () => {
requestStarted.resolve()
@@ -458,22 +468,25 @@ describe('AppService deliberate team transition ownership', () => {
runWithTeamContext<T>(teamId: string, operation: (token: string) => Promise<T>): Promise<T>
suspendDesktopGfsUploadsForAuthBoundary: () => Promise<void>
}
- app.sessionToken = 'session-a'
- app.me = {
- id: 'user-a',
- email: '[email protected]',
- name: 'User A',
- picture: null,
- teamId: null,
- teamName: null,
- role: 'member',
- }
app.authClient = {
+ googleLogin: vi.fn().mockResolvedValue({
+ token: 'session-a',
+ me: {
+ id: 'user-a',
+ email: '[email protected]',
+ name: 'User A',
+ picture: null,
+ teamId: null,
+ teamName: null,
+ role: 'member',
+ },
+ }),
getMe: vi.fn(() => {
discoveryStarted.resolve()
return meResponse.promise
}),
}
+ await service.googleLogin('synthetic-google-token')
app.suspendDesktopGfsUploadsForAuthBoundary = vi.fn(async () => logoutStarted.resolve())
const operation = vi.fn(async () => 'team result')
const contextRequest = app.runWithTeamContext('team-a', operation)
diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.desktopEnvironmentHandoff.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.desktopEnvironmentHandoff.test.tsx
index d180eb752..97a973abb 100644
--- a/desktop-app/ui/src/hooks/__tests__/useAppController.desktopEnvironmentHandoff.test.tsx
+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.desktopEnvironmentHandoff.test.tsx
@@ -1,8 +1,12 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, waitFor } from '@testing-library/react'
-import type { DesktopRuntimeConfigState } from '../../../../src/types'
import {
+ cleanupNativeCommitTestHarness,
+ createNativeCommitTestHarness,
+} from '../../../../testSupport/appService.nativeCommitTestHarness'
+import {
+ type AppControllerDesktopEnvironmentHandoffProducer,
installAppControllerClerum,
renderAppController,
} from '../domain/__tests__/__fixtures__/appControllerHarness'
@@ -10,57 +14,43 @@ import { uninstallMockClerum } from '../domain/__tests__/__fixtures__/mockClerum
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
-function runtimeConfigState(): DesktopRuntimeConfigState {
- const current = {
- appName: 'Current environment',
- externalRestApiBaseUrl: 'https://current-api.example.test/api/v1',
- rpcProxyBaseUrl: 'https://current-rpc.example.test',
- }
- const target = {
- appName: 'Target environment',
- externalRestApiBaseUrl: 'https://target-api.example.test/api/v1',
- rpcProxyBaseUrl: 'https://target-rpc.example.test',
- }
- return {
- configured: true,
- isLocalhost: false,
- selectorVisible: true,
- activeOptionId: 'current-profile',
- currentConfig: current,
- envKey: 'current-environment',
- storagePath: '/harness/runtime-configs',
- options: [
- {
- id: 'current-profile',
- label: 'Current environment',
- source: 'file',
- configPath: '/harness/current.json',
- ...current,
- },
- {
- id: 'target-profile',
- label: 'Target environment',
- source: 'file',
- configPath: '/harness/target.json',
- ...target,
- },
- ],
- }
-}
-
describe('useAppController desktop environment handoff', () => {
let unmount: (() => void) | null = null
- afterEach(() => {
+ afterEach(async () => {
unmount?.()
unmount = null
vi.restoreAllMocks()
uninstallMockClerum()
+ await cleanupNativeCommitTestHarness()
})
async function openSwitchConfirmation() {
+ const native = await createNativeCommitTestHarness()
+ const producer = native.service as unknown as AppControllerDesktopEnvironmentHandoffProducer & {
+ authClient: unknown
+ googleLogin: (token: string) => Promise<unknown>
+ suspendDesktopGfsUploadsForAuthBoundary: () => Promise<void>
+ }
+ producer.authClient = {
+ googleLogin: vi.fn().mockResolvedValue({
+ token: 'session-a',
+ me: {
+ id: 'user-1',
+ email: '[email protected]',
+ name: 'Test User',
+ picture: null,
+ teamId: 'team-a',
+ teamName: 'Team A',
+ role: 'member',
+ },
+ }),
+ }
+ producer.suspendDesktopGfsUploadsForAuthBoundary = vi.fn(async () => {})
+ await producer.googleLogin('synthetic-google-token')
+
const { handle } = installAppControllerClerum({
- runtimeConfigState: runtimeConfigState(),
+ desktopEnvironmentHandoffProducer: producer,
})
const app = renderAppController()
unmount = app.unmount
@@ -71,17 +61,17 @@ describe('useAppController desktop environment handoff', () => {
let handoff!: Promise<void>
await act(async () => {
handoff = handle.emitDesktopEnvironmentSetup({
- appName: 'Target environment',
- externalRestApiBaseUrl: 'https://target-api.example.test/api/v1',
+ appName: 'Environment B',
+ externalRestApiBaseUrl: native.restB,
})
})
await waitFor(() =>
expect(app.result.current.pendingDesktopEnvironmentSwitchConfirmation).toMatchObject({
- targetEnvironmentName: 'Target environment',
- targetExternalRestApiBaseUrl: 'https://target-api.example.test/api/v1',
+ targetEnvironmentName: 'Environment B',
+ targetExternalRestApiBaseUrl: native.restB,
})
)
- return { app, handle, handoff }
+ return { app, handle, handoff, targetOptionId: native.optionB.id }
}
it('keeps the signed-in session and skips selection when the user cancels', async () => {
@@ -100,31 +90,39 @@ describe('useAppController desktop environment handoff', () => {
})
it('signs out before selecting the saved environment with the logout generation', async () => {
- const { app, handle, handoff } = await openSwitchConfirmation()
+ const { app, handle, handoff, targetOptionId } = await openSwitchConfirmation()
await act(async () => app.result.current.handleConfirmDesktopEnvironmentSwitchConfirmation())
await act(async () => handoff)
expect(handle.logout).toHaveBeenCalledOnce()
- expect(handle.selectRuntimeConfigForHandoff).toHaveBeenCalledWith('target-profile', 1)
+ const logoutResult = await handle.logout.mock.results[0]?.value
+ expect(handle.selectRuntimeConfigForHandoff).toHaveBeenCalledWith(
+ targetOptionId,
+ logoutResult.sessionGeneration
+ )
expect(handle.logout.mock.invocationCallOrder[0]!).toBeLessThan(
handle.selectRuntimeConfigForHandoff.mock.invocationCallOrder[0]!
)
expect(app.result.current.isAuthenticated).toBe(false)
- expect(app.result.current.runtimeConfigState?.activeOptionId).toBe('target-profile')
+ expect(app.result.current.runtimeConfigState?.activeOptionId).toBe(targetOptionId)
})
it('keeps the committed logout when renderer session reload fails', async () => {
- const { app, handle, handoff } = await openSwitchConfirmation()
+ const { app, handle, handoff, targetOptionId } = await openSwitchConfirmation()
handle.setSessionStateError(new Error('session read unavailable'))
await act(async () => app.result.current.handleConfirmDesktopEnvironmentSwitchConfirmation())
await act(async () => handoff)
expect(handle.logout).toHaveBeenCalledOnce()
- expect(handle.selectRuntimeConfigForHandoff).toHaveBeenCalledWith('target-profile', 1)
+ const logoutResult = await handle.logout.mock.results[0]?.value
+ expect(handle.selectRuntimeConfigForHandoff).toHaveBeenCalledWith(
+ targetOptionId,
+ logoutResult.sessionGeneration
+ )
expect(app.result.current.isAuthenticated).toBe(false)
- expect(app.result.current.runtimeConfigState?.activeOptionId).toBe('target-profile')
+ expect(app.result.current.runtimeConfigState?.activeOptionId).toBe(targetOptionId)
expect(app.result.current.statusText).toContain(
'Could not load the selected desktop environment'
)
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
index 10d84e6fc..8d1a793a4 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
@@ -3,8 +3,12 @@ import { vi } from 'vitest'
import { AgentTaskTrackerProvider } from '@contexts/AgentTaskTrackerContext'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { renderHook } from '@testing-library/react'
-import type { DesktopRuntimeConfigState } from '../../../../../../src/types'
+import type {
+ DesktopRuntimeConfigHandoffSelection,
+ DesktopRuntimeConfigState,
+} from '../../../../../../src/types'
import { useAppController } from '../../../useAppController'
+import { wrapLikeElectronIpc } from './ipcErrors'
import { type MockClerum, installMockClerum } from './mockClerum'
/**
@@ -115,8 +119,23 @@ export interface AppControllerClerumOptions {
me?: Partial<typeof HARNESS_ME>
/** Runtime profiles exposed to the desktop-environment handoff flow. */
runtimeConfigState?: DesktopRuntimeConfigState
+ /** Real main-process producer for auth and runtime-config IPC contract tests. */
+ desktopEnvironmentHandoffProducer?: {
+ getSessionState: () => Promise<{ authenticated: boolean; me: unknown | null }>
+ getSessionGeneration: () => number
+ getRuntimeConfigState: () => DesktopRuntimeConfigState
+ selectRuntimeConfigForHandoff: (
+ optionId: string,
+ expectedGeneration: number
+ ) => Promise<DesktopRuntimeConfigHandoffSelection>
+ logout: () => Promise<number>
+ }
}
+export type AppControllerDesktopEnvironmentHandoffProducer = NonNullable<
+ AppControllerClerumOptions['desktopEnvironmentHandoffProducer']
+>
+
export interface AppControllerClerumHandle {
getDependenciesHealth: Fn
getSessionState: Fn
@@ -176,6 +195,7 @@ export function extendMockClerumForAppController(
options: [],
}
let sessionMe = { ...HARNESS_ME, ...options.me }
+ const handoffProducer = options.desktopEnvironmentHandoffProducer
const teamDirectoryPayload = options.teamDirectory ?? {
items: [],
currentTeamId: HARNESS_ME.teamId,
@@ -192,6 +212,7 @@ export function extendMockClerumForAppController(
})
const getSessionState = vi.fn(async () => {
if (sessionStateError) throw sessionStateError
+ if (handoffProducer) return handoffProducer.getSessionState()
return createSessionState(authenticated, sessionMe)
})
const passwordLogin = vi.fn(async () => {
@@ -199,11 +220,30 @@ export function extendMockClerumForAppController(
authenticated = true
return createSessionState(true, sessionMe)
})
- const getSessionGeneration = vi.fn(async () => sessionGeneration)
- const getRuntimeConfigState = vi.fn(async () => runtimeConfigState)
+ const getSessionGeneration = vi.fn(async () =>
+ handoffProducer ? handoffProducer.getSessionGeneration() : sessionGeneration
+ )
+ const getRuntimeConfigState = vi.fn(async () =>
+ handoffProducer ? handoffProducer.getRuntimeConfigState() : runtimeConfigState
+ )
const selectRuntimeConfigForHandoff = vi.fn(
async (optionId: string, expectedGeneration: number) => {
- if (expectedGeneration !== sessionGeneration) throw new Error('stale_session_generation')
+ if (handoffProducer) {
+ try {
+ return await handoffProducer.selectRuntimeConfigForHandoff(optionId, expectedGeneration)
+ } catch (error) {
+ throw wrapLikeElectronIpc(
+ 'auth:selectRuntimeConfigForHandoff',
+ error instanceof Error ? error : new Error(String(error))
+ )
+ }
+ }
+ if (expectedGeneration !== sessionGeneration) {
+ throw wrapLikeElectronIpc(
+ 'auth:selectRuntimeConfigForHandoff',
+ new Error('stale_session_generation')
+ )
+ }
const selected = runtimeConfigState.options.find(option => option.id === optionId)
if (!selected) throw new Error('runtime configuration not found')
runtimeConfigState = {
@@ -221,6 +261,18 @@ export function extendMockClerumForAppController(
}
)
const logout = vi.fn(async () => {
+ if (handoffProducer) {
+ try {
+ const generation = await handoffProducer.logout()
+ authenticated = false
+ return { ok: true as const, sessionGeneration: generation }
+ } catch (error) {
+ throw wrapLikeElectronIpc(
+ 'auth:logout',
+ error instanceof Error ? error : new Error(String(error))
+ )
+ }
+ }
authenticated = false
sessionGeneration += 1
return { ok: true as const, sessionGeneration }
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 655509873..f6efb8648 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
@@ -698,8 +698,9 @@ describe('Desktop environment handoff', () => {
await waitFor(() => expect(screen.getByTestId('configuration-loaded')).toHaveTextContent('yes'))
mocks.loadSession.mockClear()
mocks.selectRuntimeConfigForHandoff.mockRejectedValueOnce(
- new Error(
- "Error invoking remote method 'auth:selectRuntimeConfigForHandoff': Error: stale_session_generation"
+ wrapLikeElectronIpc(
+ 'auth:selectRuntimeConfigForHandoff',
+ new Error('stale_session_generation')
)
)