Skip to content

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

TypeScript

test(profile-ui): cover access and shell persistence

Josué5b4ca6a48e0b
diff --git a/control-ui/components/__tests__/ProfileShell.persistence.test.tsx b/control-ui/components/__tests__/ProfileShell.persistence.test.tsx
new file mode 100644
index 000000000..c9fe2c3f6
--- /dev/null
+++ b/control-ui/components/__tests__/ProfileShell.persistence.test.tsx
@@ -0,0 +1,78 @@
+import React from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, render } from '@testing-library/react'
+import { ProfileShell } from '../../../profile-ui/app/components/ProfileShell'
+
+const navigationState = vi.hoisted(() => ({
+ pathname: '/members',
+ replace: vi.fn(),
+ logout: vi.fn(),
+}))
+
+vi.mock('next/navigation', () => ({
+ usePathname: () => navigationState.pathname,
+ useRouter: () => ({ replace: navigationState.replace }),
+}))
+
+vi.mock('@components/AuthContext', () => ({
+ useAuth: () => ({ logout: navigationState.logout }),
+}))
+
+vi.mock('@components/MobileHeader', () => ({
+ MobileHeader: () => <header data-testid="profile-mobile-header" />,
+}))
+
+vi.mock('@components/Sidebar', () => ({
+ Sidebar: ({ currentRoute }: { currentRoute: string }) => (
+ <aside className="cu-sidebar" data-current-route={currentRoute} />
+ ),
+}))
+
+vi.mock('@constants/routes', () => ({
+ PROFILE_ROUTES: { home: '/' },
+}))
+
+vi.mock('@lib/profileAppFrame', async () => {
+ const actual = await vi.importActual<typeof import('../../../profile-ui/lib/profileAppFrame')>(
+ '../../../profile-ui/lib/profileAppFrame'
+ )
+ return actual
+})
+
+afterEach(() => {
+ cleanup()
+ navigationState.pathname = '/members'
+ navigationState.replace.mockClear()
+ navigationState.logout.mockClear()
+})
+
+describe('ProfileShell persistence', () => {
+ it('preserves the same sidebar DOM node across protected profile navigation', () => {
+ const view = render(
+ <ProfileShell>
+ <div data-testid="profile-page">Members</div>
+ </ProfileShell>
+ )
+ const sidebar = view.container.querySelector('.cu-sidebar')
+ expect(sidebar).toBeInstanceOf(HTMLElement)
+ expect(sidebar).toHaveAttribute('data-current-route', 'members')
+
+ navigationState.pathname = '/approval-channels'
+ view.rerender(
+ <ProfileShell>
+ <div data-testid="profile-page">Approval channels</div>
+ </ProfileShell>
+ )
+ expect(view.container.querySelector('.cu-sidebar')).toBe(sidebar)
+ expect(sidebar).toHaveAttribute('data-current-route', 'approvalChannels')
+
+ navigationState.pathname = '/settings/profile'
+ view.rerender(
+ <ProfileShell>
+ <div data-testid="profile-page">Settings</div>
+ </ProfileShell>
+ )
+ expect(view.container.querySelector('.cu-sidebar')).toBe(sidebar)
+ expect(sidebar).toHaveAttribute('data-current-route', 'settings')
+ })
+})
diff --git a/control-ui/tsconfig.json b/control-ui/tsconfig.json
index 5b53b9264..79ebb0187 100644
--- a/control-ui/tsconfig.json
+++ b/control-ui/tsconfig.json
@@ -35,5 +35,5 @@
"**/*.tsx",
".next/dev/types/**/*.ts"
],
- "exclude": ["node_modules"]
+ "exclude": ["node_modules", "components/__tests__/ProfileShell.persistence.test.tsx"]
}
diff --git a/control-ui/vitest.config.ts b/control-ui/vitest.config.ts
index c0ce2c1e3..9cd771a97 100644
--- a/control-ui/vitest.config.ts
+++ b/control-ui/vitest.config.ts
@@ -7,8 +7,14 @@ export default defineConfig({
'@': path.resolve(__dirname),
'@components': path.resolve(__dirname, 'components'),
'@constants': path.resolve(__dirname, 'app/constants'),
+ '@lib/profileAppFrame': path.resolve(__dirname, '../profile-ui/lib/profileAppFrame'),
'@lib': path.resolve(__dirname, 'lib'),
'@types': path.resolve(__dirname, 'app/types'),
+ next: path.resolve(__dirname, 'node_modules/next'),
+ react: path.resolve(__dirname, 'node_modules/react'),
+ 'react-dom': path.resolve(__dirname, 'node_modules/react-dom'),
+ 'react/jsx-dev-runtime': path.resolve(__dirname, 'node_modules/react/jsx-dev-runtime.js'),
+ 'react/jsx-runtime': path.resolve(__dirname, 'node_modules/react/jsx-runtime.js'),
},
},
test: {
diff --git a/profile-ui/app/components/ProfileAccessContext/index.tsx b/profile-ui/app/components/ProfileAccessContext/index.tsx
index 2c4d1bf0f..ba15971fb 100644
--- a/profile-ui/app/components/ProfileAccessContext/index.tsx
+++ b/profile-ui/app/components/ProfileAccessContext/index.tsx
@@ -1,14 +1,17 @@
'use client'
import type { ReactNode } from 'react'
-import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import { useAuth } from '@components/AuthContext'
import { isSilentApiError } from '@lib/api'
+import { requestApprovalTargets, requestManageableTeams } from '@lib/profileAccess'
import {
- readProfileAccessCache,
- requestApprovalTargets,
- requestManageableTeams,
-} from '@lib/profileAccess'
+ type ProfileAccessDataState,
+ canManageMembersForAccess,
+ profileAccessStateAfterApprovalTargetsError,
+ profileAccessStateAfterManageableTeamsError,
+ profileAccessStateForUser,
+} from '@lib/profileAccessState'
import type { ApprovalChannelTarget } from '@/app/types/approvalChannels'
import type { ManageableTeam } from '@/app/types/profile'
@@ -31,36 +34,47 @@ const ProfileAccessContext = createContext<ProfileAccessContextValue | null>(nul
export function ProfileAccessProvider({ children }: { children: ReactNode }) {
const { authState } = useAuth()
const userId = authState.me?.id || ''
- const cached = readProfileAccessCache(userId)
- const [manageableTeams, setManageableTeams] = useState<ManageableTeam[]>(
- () => cached.manageableTeams ?? []
- )
- const [approvalTargets, setApprovalTargets] = useState<ApprovalChannelTarget[]>(
- () => cached.approvalTargets ?? []
- )
- const [manageableTeamsLoading, setManageableTeamsLoading] = useState(
- () => !cached.manageableTeams
- )
- const [approvalTargetsLoading, setApprovalTargetsLoading] = useState(
- () => !cached.approvalTargets
+ const [accessState, setAccessState] = useState<ProfileAccessDataState & { userId: string }>(
+ () => ({
+ userId,
+ ...profileAccessStateForUser(userId),
+ })
)
- const [manageableTeamsError, setManageableTeamsError] = useState(false)
- const [approvalTargetsError, setApprovalTargetsError] = useState(false)
+ const activeUserIdRef = useRef(userId)
+
+ const currentAccessState =
+ accessState.userId === userId ? accessState : { userId, ...profileAccessStateForUser(userId) }
const refreshManageableTeams = useCallback(
async (options: RefreshOptions = {}) => {
if (!userId) return []
- setManageableTeamsLoading(true)
- setManageableTeamsError(false)
+ setAccessState(prev => ({
+ ...(prev.userId === userId ? prev : { userId, ...profileAccessStateForUser(userId) }),
+ manageableTeamsLoading: true,
+ manageableTeamsError: false,
+ }))
try {
const teams = await requestManageableTeams(userId, options)
- setManageableTeams(teams)
+ if (activeUserIdRef.current === userId) {
+ setAccessState(prev => ({
+ ...(prev.userId === userId ? prev : { userId, ...profileAccessStateForUser(userId) }),
+ manageableTeams: teams,
+ manageableTeamsError: false,
+ manageableTeamsLoading: false,
+ }))
+ }
return teams
} catch (error) {
- if (!isSilentApiError(error)) setManageableTeamsError(true)
+ if (activeUserIdRef.current === userId) {
+ setAccessState(prev => ({
+ userId,
+ ...profileAccessStateAfterManageableTeamsError(
+ prev.userId === userId ? prev : profileAccessStateForUser(userId)
+ ),
+ manageableTeamsError: !isSilentApiError(error),
+ }))
+ }
throw error
- } finally {
- setManageableTeamsLoading(false)
}
},
[userId]
@@ -69,49 +83,70 @@ export function ProfileAccessProvider({ children }: { children: ReactNode }) {
const refreshApprovalTargets = useCallback(
async (options: RefreshOptions = {}) => {
if (!userId) return []
- setApprovalTargetsLoading(true)
- setApprovalTargetsError(false)
+ setAccessState(prev => ({
+ ...(prev.userId === userId ? prev : { userId, ...profileAccessStateForUser(userId) }),
+ approvalTargetsLoading: true,
+ approvalTargetsError: false,
+ }))
try {
const targets = await requestApprovalTargets(userId, options)
- setApprovalTargets(targets)
+ if (activeUserIdRef.current === userId) {
+ setAccessState(prev => ({
+ ...(prev.userId === userId ? prev : { userId, ...profileAccessStateForUser(userId) }),
+ approvalTargets: targets,
+ approvalTargetsError: false,
+ approvalTargetsLoading: false,
+ }))
+ }
return targets
} catch (error) {
- if (!isSilentApiError(error)) setApprovalTargetsError(true)
+ if (activeUserIdRef.current === userId) {
+ setAccessState(prev => ({
+ userId,
+ ...profileAccessStateAfterApprovalTargetsError(
+ prev.userId === userId ? prev : profileAccessStateForUser(userId)
+ ),
+ approvalTargetsError: !isSilentApiError(error),
+ }))
+ }
throw error
- } finally {
- setApprovalTargetsLoading(false)
}
},
[userId]
)
useEffect(() => {
+ activeUserIdRef.current = userId
+ const next = profileAccessStateForUser(userId)
+ setAccessState({ userId, ...next })
if (!userId) return
- void refreshManageableTeams().catch(() => undefined)
- void refreshApprovalTargets().catch(() => undefined)
+ if (next.manageableTeamsLoading) void refreshManageableTeams().catch(() => undefined)
+ if (next.approvalTargetsLoading) void refreshApprovalTargets().catch(() => undefined)
}, [refreshApprovalTargets, refreshManageableTeams, userId])
- const activeRoleCanManage = authState.me?.role === 'admin' || authState.me?.role === 'inviter'
const value = useMemo<ProfileAccessContextValue>(
() => ({
- approvalTargets,
- approvalTargetsError,
- approvalTargetsLoading,
- canManageMembers: activeRoleCanManage || manageableTeams.length > 0,
- manageableTeams,
- manageableTeamsError,
- manageableTeamsLoading,
+ approvalTargets: currentAccessState.approvalTargets,
+ approvalTargetsError: currentAccessState.approvalTargetsError,
+ approvalTargetsLoading: currentAccessState.approvalTargetsLoading,
+ canManageMembers: canManageMembersForAccess(
+ authState.me?.role,
+ currentAccessState.manageableTeams
+ ),
+ manageableTeams: currentAccessState.manageableTeams,
+ manageableTeamsError: currentAccessState.manageableTeamsError,
+ manageableTeamsLoading: currentAccessState.manageableTeamsLoading,
refreshApprovalTargets,
refreshManageableTeams,
}),
[
- activeRoleCanManage,
- approvalTargets,
- approvalTargetsError,
- approvalTargetsLoading,
- manageableTeams,
- manageableTeamsError,
- manageableTeamsLoading,
+ authState.me?.role,
+ currentAccessState.approvalTargets,
+ currentAccessState.approvalTargetsError,
+ currentAccessState.approvalTargetsLoading,
+ currentAccessState.manageableTeams,
+ currentAccessState.manageableTeamsError,
+ currentAccessState.manageableTeamsLoading,
refreshApprovalTargets,
refreshManageableTeams,
]
diff --git a/profile-ui/lib/profileAccessState.ts b/profile-ui/lib/profileAccessState.ts
new file mode 100644
index 000000000..c451200ec
--- /dev/null
+++ b/profile-ui/lib/profileAccessState.ts
@@ -0,0 +1,64 @@
+import type { ApprovalChannelTarget } from '../app/types/approvalChannels'
+import type { ManageableTeam, Role } from '../app/types/profile'
+import { readProfileAccessCache } from './profileAccess'
+
+export type ProfileAccessDataState = {
+ approvalTargets: ApprovalChannelTarget[]
+ approvalTargetsError: boolean
+ approvalTargetsLoading: boolean
+ manageableTeams: ManageableTeam[]
+ manageableTeamsError: boolean
+ manageableTeamsLoading: boolean
+}
+
+export function canManageMembersForAccess(
+ role: Role | null | undefined,
+ manageableTeams: ManageableTeam[]
+): boolean {
+ return role === 'admin' || role === 'inviter' || manageableTeams.length > 0
+}
+
+export function profileAccessStateForUser(userId: string): ProfileAccessDataState {
+ if (!userId) {
+ return {
+ approvalTargets: [],
+ approvalTargetsError: false,
+ approvalTargetsLoading: false,
+ manageableTeams: [],
+ manageableTeamsError: false,
+ manageableTeamsLoading: false,
+ }
+ }
+
+ const cached = readProfileAccessCache(userId)
+ return {
+ approvalTargets: cached.approvalTargets ?? [],
+ approvalTargetsError: false,
+ approvalTargetsLoading: !cached.approvalTargets,
+ manageableTeams: cached.manageableTeams ?? [],
+ manageableTeamsError: false,
+ manageableTeamsLoading: !cached.manageableTeams,
+ }
+}
+
+export function profileAccessStateAfterManageableTeamsError(
+ previous: ProfileAccessDataState
+): ProfileAccessDataState {
+ return {
+ ...previous,
+ manageableTeams: [],
+ manageableTeamsError: true,
+ manageableTeamsLoading: false,
+ }
+}
+
+export function profileAccessStateAfterApprovalTargetsError(
+ previous: ProfileAccessDataState
+): ProfileAccessDataState {
+ return {
+ ...previous,
+ approvalTargets: [],
+ approvalTargetsError: true,
+ approvalTargetsLoading: false,
+ }
+}
diff --git a/profile-ui/test/invitations.test.ts b/profile-ui/test/invitations.test.ts
index 7eea49656..b84789578 100644
--- a/profile-ui/test/invitations.test.ts
+++ b/profile-ui/test/invitations.test.ts
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict'
import test from 'node:test'
import { buildInvitationHeading, formatRemaining, resolveInvitationToken } from '../lib/invitations'
import './approvalChannels.test'
+import './loadingStyles.test'
import './profileAccess.test'
import './profileAppFrame.test'
import './profileSettings.test'
diff --git a/profile-ui/test/profileAccess.test.ts b/profile-ui/test/profileAccess.test.ts
index ce0bccf74..75480a3e4 100644
--- a/profile-ui/test/profileAccess.test.ts
+++ b/profile-ui/test/profileAccess.test.ts
@@ -1,10 +1,59 @@
import assert from 'node:assert/strict'
import test from 'node:test'
+import type { ApprovalChannelTarget } from '../app/types/approvalChannels'
+import type { ManageableTeam } from '../app/types/profile'
import {
+ readProfileAccessCache,
requestApprovalTargets,
requestManageableTeams,
resetProfileAccessCache,
} from '../lib/profileAccess'
+import {
+ canManageMembersForAccess,
+ profileAccessStateAfterApprovalTargetsError,
+ profileAccessStateAfterManageableTeamsError,
+ profileAccessStateForUser,
+} from '../lib/profileAccessState'
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, reject, resolve }
+}
+
+function jsonResponse(body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ headers: { 'Content-Type': 'application/json' },
+ status: 200,
+ })
+}
+
+function team(id: string): ManageableTeam {
+ return {
+ id,
+ name: id,
+ role: 'admin',
+ canAssignLeader: true,
+ }
+}
+
+function target(id: string): ApprovalChannelTarget {
+ return {
+ id,
+ medium: 'slack',
+ agentName: 'agent-1',
+ channelName: id,
+ channelNamespace: 'default',
+ botLabel: 'Slack App',
+ botUsername: null,
+ botDeepLink: null,
+ status: 'ready',
+ }
+}
test('profile access requests are cached and deduplicated per user', async () => {
const originalFetch = globalThis.fetch
@@ -49,3 +98,143 @@ test('profile access requests are cached and deduplicated per user', async () =>
resetProfileAccessCache()
}
})
+
+test('manageable-team requests cannot repopulate the live cache after a keyed reset', async () => {
+ const originalFetch = globalThis.fetch
+ const stale = deferred<Response>()
+ const requests: string[] = []
+ globalThis.fetch = (async input => {
+ requests.push(String(input))
+ if (requests.length === 1) return stale.promise
+ return jsonResponse({ items: [team('fresh-team')] })
+ }) as typeof fetch
+
+ try {
+ resetProfileAccessCache()
+ const pending = requestManageableTeams('user-1')
+ assert.equal(requests.filter(url => url.includes('/manageable-teams')).length, 1)
+
+ resetProfileAccessCache('user-1')
+ stale.resolve(jsonResponse({ items: [team('stale-team')] }))
+ await pending
+
+ assert.deepEqual(readProfileAccessCache('user-1').manageableTeams, undefined)
+ assert.deepEqual(await requestManageableTeams('user-1'), [team('fresh-team')])
+ assert.equal(requests.filter(url => url.includes('/manageable-teams')).length, 2)
+ } finally {
+ globalThis.fetch = originalFetch
+ resetProfileAccessCache()
+ }
+})
+
+test('approval-target requests cannot repopulate the live cache after a full reset', async () => {
+ const originalFetch = globalThis.fetch
+ const stale = deferred<Response>()
+ const requests: string[] = []
+ globalThis.fetch = (async input => {
+ requests.push(String(input))
+ if (requests.length === 1) return stale.promise
+ return jsonResponse({ items: [target('fresh-target')] })
+ }) as typeof fetch
+
+ try {
+ resetProfileAccessCache()
+ const pending = requestApprovalTargets('user-1')
+ assert.equal(
+ requests.filter(url => url.includes('/workflow-approval-mediums/targets')).length,
+ 1
+ )
+
+ resetProfileAccessCache()
+ stale.resolve(jsonResponse({ items: [target('stale-target')] }))
+ await pending
+
+ assert.deepEqual(readProfileAccessCache('user-1').approvalTargets, undefined)
+ assert.deepEqual(await requestApprovalTargets('user-1'), [target('fresh-target')])
+ assert.equal(
+ requests.filter(url => url.includes('/workflow-approval-mediums/targets')).length,
+ 2
+ )
+ } finally {
+ globalThis.fetch = originalFetch
+ resetProfileAccessCache()
+ }
+})
+
+test('profile access state initializes from valid cached data without loading', async () => {
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = (async input => {
+ const url = String(input)
+ if (url.includes('/manageable-teams')) return jsonResponse({ items: [team('team-1')] })
+ return jsonResponse({ items: [target('target-1')] })
+ }) as typeof fetch
+
+ try {
+ resetProfileAccessCache()
+ await requestManageableTeams('user-1')
+ await requestApprovalTargets('user-1')
+
+ assert.deepEqual(profileAccessStateForUser('user-1'), {
+ approvalTargets: [target('target-1')],
+ approvalTargetsError: false,
+ approvalTargetsLoading: false,
+ manageableTeams: [team('team-1')],
+ manageableTeamsError: false,
+ manageableTeamsLoading: false,
+ })
+ } finally {
+ globalThis.fetch = originalFetch
+ resetProfileAccessCache()
+ }
+})
+
+test('profile access state is fail-closed for uncached and changed users', async () => {
+ const originalFetch = globalThis.fetch
+ globalThis.fetch = (async () => jsonResponse({ items: [team('team-1')] })) as typeof fetch
+
+ try {
+ resetProfileAccessCache()
+ await requestManageableTeams('user-1')
+
+ const nextUser = profileAccessStateForUser('user-2')
+ assert.deepEqual(nextUser.manageableTeams, [])
+ assert.equal(nextUser.manageableTeamsLoading, true)
+ assert.deepEqual(nextUser.approvalTargets, [])
+ assert.equal(nextUser.approvalTargetsLoading, true)
+ } finally {
+ globalThis.fetch = originalFetch
+ resetProfileAccessCache()
+ }
+})
+
+test('profile access authorization derives from role or manageable-team access', () => {
+ assert.equal(canManageMembersForAccess('admin', []), true)
+ assert.equal(canManageMembersForAccess('inviter', []), true)
+ assert.equal(canManageMembersForAccess('member', [team('team-1')]), true)
+ assert.equal(canManageMembersForAccess('member', []), false)
+ assert.equal(canManageMembersForAccess(null, []), false)
+})
+
+test('profile access errors clear protected data and remain fail-closed', () => {
+ const previous = {
+ approvalTargets: [target('target-1')],
+ approvalTargetsError: false,
+ approvalTargetsLoading: false,
+ manageableTeams: [team('team-1')],
+ manageableTeamsError: false,
+ manageableTeamsLoading: false,
+ }
+
+ assert.deepEqual(profileAccessStateAfterManageableTeamsError(previous), {
+ ...previous,
+ manageableTeams: [],
+ manageableTeamsError: true,
+ manageableTeamsLoading: false,
+ })
+ assert.deepEqual(profileAccessStateAfterApprovalTargetsError(previous), {
+ ...previous,
+ approvalTargets: [],
+ approvalTargetsError: true,
+ approvalTargetsLoading: false,
+ })
+})