Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
refactor(profile-ui): model reset recovery phases (R13-9)
Josuécd127e5173fb
diff --git a/profile-ui/app/components/__tests__/InvitationClient.identityFence.test.tsx b/profile-ui/app/components/__tests__/InvitationClient.identityFence.test.tsxindex b6d52e414..6ec9b7552 100644--- a/profile-ui/app/components/__tests__/InvitationClient.identityFence.test.tsx+++ b/profile-ui/app/components/__tests__/InvitationClient.identityFence.test.tsx@@ -17,11 +17,15 @@ vi.mock('@components/AuthContext', () => ({useAuth: () => ({ checkAuth: mocks.checkAuth }),}))-vi.mock('@lib/api', () => ({- acceptInvitation: vi.fn(),- getEvenfireDownloadUrl: () => 'https://downloads.example.invalid/evenfire',- setupInvitationPasswordWithToken: mocks.setupInvitationPasswordWithToken,-}))+vi.mock('@lib/api', async () => {+ const actual = await vi.importActual<typeof import('@lib/api')>('@lib/api')+ return {+ ...actual,+ acceptInvitation: vi.fn(),+ getEvenfireDownloadUrl: () => 'https://downloads.example.invalid/evenfire',+ setupInvitationPasswordWithToken: mocks.setupInvitationPasswordWithToken,+ }+})const invitation: InvitationPreview = {id: 'r6-identity-reset',diff --git a/profile-ui/app/components/__tests__/InvitationClient.recoveryContract.test.tsx b/profile-ui/app/components/__tests__/InvitationClient.recoveryContract.test.tsxindex 596ae553c..d324ecde8 100644--- a/profile-ui/app/components/__tests__/InvitationClient.recoveryContract.test.tsx+++ b/profile-ui/app/components/__tests__/InvitationClient.recoveryContract.test.tsx@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { PROFILE_ROUTES } from '@constants/routes'+import { ProfileApiError } from '@lib/api'import type { InvitationPreview } from '@/app/types/api'import { InvitationClient } from '../../invitations/[token]/InvitationClient'@@ -19,11 +20,15 @@ vi.mock('@components/AuthContext', () => ({useAuth: () => ({ checkAuth: mocks.checkAuth }),}))-vi.mock('@lib/api', () => ({- acceptInvitation: mocks.acceptInvitation,- getEvenfireDownloadUrl: () => 'https://downloads.example.invalid/evenfire',- setupInvitationPasswordWithToken: mocks.setupInvitationPasswordWithToken,-}))+vi.mock('@lib/api', async () => {+ const actual = await vi.importActual<typeof import('@lib/api')>('@lib/api')+ return {+ ...actual,+ acceptInvitation: mocks.acceptInvitation,+ getEvenfireDownloadUrl: () => 'https://downloads.example.invalid/evenfire',+ setupInvitationPasswordWithToken: mocks.setupInvitationPasswordWithToken,+ }+})const passwordReset: InvitationPreview = {id: 'r6-reset-1',@@ -76,7 +81,10 @@ describe('R6 recovery outcome and identity fences', () => {it.each([['transport TypeError', new TypeError('socket closed after dispatch')],['response SyntaxError', new SyntaxError('upstream response was not JSON')],- ['unknown post-dispatch outcome', new Error('503 unavailable - recovery_outcome_unknown')],+ [+ 'unknown post-dispatch outcome',+ new ProfileApiError(503, 'recovery_outcome_unknown', 'temporary service message'),+ ],])('does not replay a reset after %s', async (_label, error) => {mocks.setupInvitationPasswordWithToken.mockRejectedValueOnce(error)renderReset()@@ -96,8 +104,11 @@ describe('R6 recovery outcome and identity fences', () => {})it.each([- ['rate limit', new Error('429 Too Many Requests - rate_limited')],- ['definite authority rejection', new Error('503 Service Unavailable - authority_unavailable')],+ ['rate limit', new ProfileApiError(429, 'rate_limited', 'upstream wording changed')],+ [+ 'definite authority rejection',+ new ProfileApiError(503, 'authority_unavailable', 'temporary authority message'),+ ],])('keeps a definite %s retryable rather than ambiguous', async (_label, error) => {mocks.setupInvitationPasswordWithToken.mockRejectedValueOnce(error).mockResolvedValueOnce({...passwordReset,diff --git a/profile-ui/app/components/__tests__/InvitationClient.reset.test.tsx b/profile-ui/app/components/__tests__/InvitationClient.reset.test.tsxindex d7cfad18e..af7320b4f 100644--- a/profile-ui/app/components/__tests__/InvitationClient.reset.test.tsx+++ b/profile-ui/app/components/__tests__/InvitationClient.reset.test.tsx@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { PROFILE_ROUTES } from '@constants/routes'+import { ProfileApiError } from '@lib/api'import type { InvitationPreview } from '@/app/types/api'import { InvitationClient } from '../../invitations/[token]/InvitationClient'@@ -19,11 +20,15 @@ vi.mock('@components/AuthContext', () => ({useAuth: () => ({ checkAuth: mocks.checkAuth }),}))-vi.mock('@lib/api', () => ({- acceptInvitation: mocks.acceptInvitation,- getEvenfireDownloadUrl: () => 'https://downloads.example.invalid/evenfire',- setupInvitationPasswordWithToken: mocks.setupInvitationPasswordWithToken,-}))+vi.mock('@lib/api', async () => {+ const actual = await vi.importActual<typeof import('@lib/api')>('@lib/api')+ return {+ ...actual,+ acceptInvitation: mocks.acceptInvitation,+ getEvenfireDownloadUrl: () => 'https://downloads.example.invalid/evenfire',+ setupInvitationPasswordWithToken: mocks.setupInvitationPasswordWithToken,+ }+})const passwordReset: InvitationPreview = {id: 'reset-1',@@ -180,7 +185,7 @@ describe('InvitationClient verified password recovery', () => {it('shows a retryable message when bounded recovery admission is busy', async () => {mocks.setupInvitationPasswordWithToken.mockRejectedValue(- new Error('429 Too Many Requests - rate_limited')+ new ProfileApiError(429, 'rate_limited', '429 Too Many Requests - upstream wording changed'))render(<InvitationClient@@ -204,7 +209,9 @@ describe('InvitationClient verified password recovery', () => {})it('shows a recovery-link error instead of blaming the new password', async () => {- mocks.setupInvitationPasswordWithToken.mockRejectedValue(new Error('invalid_invitation'))+ mocks.setupInvitationPasswordWithToken.mockRejectedValue(+ new ProfileApiError(400, 'invalid_invitation', '400 Bad Request - recovery link rejected')+ )render(<InvitationClientinvitationToken="invalid-reset-proof"@@ -223,7 +230,11 @@ describe('InvitationClient verified password recovery', () => {it('does not resubmit a reset proof after an ambiguous recovery outcome', async () => {mocks.setupInvitationPasswordWithToken.mockRejectedValue(- new Error('503 Service Unavailable - recovery_outcome_unknown')+ new ProfileApiError(+ 503,+ 'recovery_outcome_unknown',+ '503 Service Unavailable - mutation result unavailable'+ ))render(<InvitationClientdiff --git a/profile-ui/app/invitations/[token]/InvitationClient.tsx b/profile-ui/app/invitations/[token]/InvitationClient.tsxindex 7d13ba849..3c27a2936 100644--- a/profile-ui/app/invitations/[token]/InvitationClient.tsx+++ b/profile-ui/app/invitations/[token]/InvitationClient.tsx@@ -16,6 +16,7 @@ import { FormField } from '@components/FormField'import { TextInput } from '@components/TextInput'import { PROFILE_ROUTES } from '@constants/routes'import {+ ProfileApiError,acceptInvitation,getEvenfireDownloadUrl,setupInvitationPasswordWithToken,@@ -29,6 +30,15 @@ import { formatTeamRole } from '@lib/teamRoles'import type { InvitationPreview } from '@/app/types/api'import type { InvitationClientProps } from './types'+type RecoveryPhase =+ | { state: 'editing' }+ | { state: 'submitting' }+ | { state: 'checking_session' }+ | { state: 'committed' }+ | { state: 'session_unverified' }+ | { state: 'outcome_unknown' }+ | { state: 'authenticated' }+function statusForInvitation(invitation: InvitationPreview): string {if (invitation.purpose === 'password_reset') {return invitation.status === 'accepted'@@ -72,16 +82,12 @@ function statusForInvitation(invitation: InvitationPreview): string {function isAmbiguousRecoveryOutcome(value: unknown): boolean {if (!(value instanceof Error)) return true- const message = value.message.replace(/^\d{3}\s+[A-Za-z ]+\s+-\s+/, '')- if (message === 'recovery_outcome_unknown') return trueif (value instanceof TypeError || value.name === 'SyntaxError') return true- const status = value.message.match(/^\s*(\d{3})\b/)- return Boolean(- status &&- Number(status[1]) >= 500 &&- !message.includes('authority_unavailable') &&- !message.includes('rate_limited')- )+ if (!(value instanceof ProfileApiError)) return false+ if (value.code === 'recovery_outcome_unknown') return true+ if (value.code === 'authority_unavailable' || value.code === 'rate_limited') return false+ if (value.status === 429) return false+ return value.status >= 500}export function InvitationClient({@@ -100,9 +106,7 @@ export function InvitationClient({const [password, setPassword] = useState('')const [confirmPassword, setConfirmPassword] = useState('')const [submitting, setSubmitting] = useState<'accept' | 'password' | null>(null)- const [recoveryCommitted, setRecoveryCommitted] = useState(false)- const [recoveryOutcomeUnknown, setRecoveryOutcomeUnknown] = useState(false)- const [sessionCheckInFlight, setSessionCheckInFlight] = useState(false)+ const [recoveryPhase, setRecoveryPhase] = useState<RecoveryPhase>({ state: 'editing' })const actionInFlightRef = useRef(false)useEffect(() => {@@ -117,8 +121,7 @@ export function InvitationClient({}, [initialInvitation, initialError])useEffect(() => {- setRecoveryCommitted(false)- setRecoveryOutcomeUnknown(false)+ setRecoveryPhase({ state: 'editing' })}, [invitationToken])const invitationExpired = useMemo(() => {@@ -153,9 +156,43 @@ export function InvitationClient({email: invitation?.email.trim().toLowerCase(),})const busy = submitting !== null+ const recoveryNeedsSessionCheck =+ isPasswordReset &&+ ['committed', 'checking_session', 'session_unverified', 'authenticated'].includes(+ recoveryPhase.state+ )+ const recoveryOutcomeUnknown = isPasswordReset && recoveryPhase.state === 'outcome_unknown'- function friendlyInvitationError(value: unknown): string {+ function friendlyInvitationError(value: unknown, isRecovery = false): string {if (!(value instanceof Error)) return 'Failed to update invitation.'+ if (isRecovery) {+ if (!(value instanceof ProfileApiError)) {+ return 'We could not update your password. Please try again.'+ }+ if (value.code === 'invalid_password') return 'Password must be between 8 and 256 characters.'+ if (value.code === 'invalid_invitation') return 'This recovery link is invalid or expired.'+ if (value.code === 'invitation_not_accepted')+ return 'Accept the invitation before setting a password.'+ if (value.code === 'invitation_not_pending' || value.code === 'invitation_not_ready')+ return 'This invitation has already been used.'+ if (value.code === 'expired' || value.status === 410) return 'This invitation has expired.'+ if (value.code === 'forbidden' || value.status === 403)+ return 'Invitation email does not match.'+ if (value.code === 'not_found' || value.status === 404) return 'Invitation not found.'+ if (value.code === 'rate_limited' || value.status === 429) {+ return 'Account recovery is temporarily busy. Please wait a moment and try again.'+ }+ if (value.code === 'authority_unavailable') {+ return 'Account recovery is temporarily unavailable. Please try again shortly.'+ }+ if (value.code === 'recovery_outcome_unknown') {+ return 'We could not confirm whether your password change completed. Try signing in with the new password. If that does not work, request a new reset link.'+ }+ if (value.status === 400 || value.status === 401) {+ return 'This recovery link is invalid or expired.'+ }+ return 'We could not update your password. Please try again.'+ }const message = value.message.replace(/^\d{3}\s+[A-Za-z ]+\s+-\s+/, '')if (message === 'invalid_password') return 'Password must be between 8 and 256 characters.'if (message === 'invalid_invitation') return 'This recovery link is invalid or expired.'@@ -222,34 +259,44 @@ export function InvitationClient({}async function verifyRecoveredSession(expectedUserId: string) {- setSessionCheckInFlight(true)+ setRecoveryPhase({ state: 'checking_session' })setError('')try {const result = await checkAuth()if (result.status === 'authenticated') {if (result.me.id === expectedUserId) {+ setRecoveryPhase({ state: 'authenticated' })router.replace(PROFILE_ROUTES.home)return}+ setRecoveryPhase({ state: 'session_unverified' })setError('Your password was updated, but the signed-in account does not match this recovery link.')return}+ setRecoveryPhase({ state: 'session_unverified' })setError('Your password was updated, but we could not verify your account session. Try again.')} catch {+ setRecoveryPhase({ state: 'session_unverified' })setError('Your password was updated, but we could not verify your account session. Try again.')- } finally {- setSessionCheckInFlight(false)}}async function retryRecoveredSession() {- if (!recoveryCommitted || !invitation?.userId || sessionCheckInFlight || busy) return+ if (+ (recoveryPhase.state !== 'committed' &&+ recoveryPhase.state !== 'session_unverified' &&+ recoveryPhase.state !== 'authenticated') ||+ !invitation?.userId ||+ busy+ ) {+ return+ }await verifyRecoveredSession(invitation.userId)}@@ -258,7 +305,7 @@ export function InvitationClient({!invitation ||busy ||actionInFlightRef.current ||- (isPasswordReset && (recoveryCommitted || recoveryOutcomeUnknown))+ (isPasswordReset && recoveryPhase.state !== 'editing')) {return}@@ -273,6 +320,7 @@ export function InvitationClient({}actionInFlightRef.current = truesetSubmitting('password')+ if (isPasswordReset) setRecoveryPhase({ state: 'submitting' })try {const response = await setupInvitationPasswordWithToken(invitationToken,@@ -281,11 +329,12 @@ export function InvitationClient({password)if (isPasswordReset) {- setRecoveryCommitted(true)+ setRecoveryPhase({ state: 'committed' })setStatus('Your password has been updated.')setPassword('')setConfirmPassword('')if (!invitation.userId || response.userId !== invitation.userId) {+ setRecoveryPhase({ state: 'session_unverified' })setError('Your password was updated, but the signed-in account does not match this recovery link.')@@ -302,14 +351,15 @@ export function InvitationClient({})} catch (nextError) {if (isPasswordReset && isAmbiguousRecoveryOutcome(nextError)) {- setRecoveryOutcomeUnknown(true)+ setRecoveryPhase({ state: 'outcome_unknown' })setPassword('')setConfirmPassword('')setError('We could not confirm whether your password change completed. Try signing in with the new password. If that does not work, request a new reset link.')} else {- setError(friendlyInvitationError(nextError))+ if (isPasswordReset) setRecoveryPhase({ state: 'editing' })+ setError(friendlyInvitationError(nextError, isPasswordReset))}} finally {actionInFlightRef.current = false@@ -395,14 +445,16 @@ export function InvitationClient({</div>) : null}- {!invitation ? null : isPasswordReset && recoveryCommitted ? (+ {!invitation ? null : recoveryNeedsSessionCheck ? (<div className="stack"><Buttontype="button"- disabled={busy || sessionCheckInFlight || !invitation.userId}+ disabled={busy || recoveryPhase.state === 'checking_session' || !invitation.userId}onClick={() => void retryRecoveredSession()}>- {sessionCheckInFlight ? 'Checking account session...' : 'Retry account session check'}+ {recoveryPhase.state === 'checking_session'+ ? 'Checking account session...'+ : 'Retry account session check'}</Button><a className="cu-btn" href={profileLoginHref}>Sign in insteaddiff --git a/profile-ui/lib/api.ts b/profile-ui/lib/api.tsindex e47e60fe7..f26fcec43 100644--- a/profile-ui/lib/api.ts+++ b/profile-ui/lib/api.ts@@ -44,6 +44,17 @@ export class AuthExpiredError extends Error {}}+export class ProfileApiError extends Error {+ constructor(+ readonly status: number,+ readonly code: string | null,+ message: string+ ) {+ super(message)+ this.name = 'ProfileApiError'+ }+}+export function setGlobalAuthErrorHandler(handler: () => void): void {globalHandleAuthError = handler}@@ -126,9 +137,16 @@ export async function apiSend(const text = await res.text()if (res.status === 401) handleUnauthorized()let detail: string+ let code: string | null = nulltry {- const parsed = JSON.parse(text) as { error?: unknown; message?: unknown }- detail = String(parsed.message || parsed.error || text)+ const parsed = JSON.parse(text) as unknown+ if (parsed && typeof parsed === 'object') {+ const body = parsed as { error?: unknown; message?: unknown }+ code = typeof body.error === 'string' ? body.error : null+ detail = String(body.message || body.error || text)+ } else {+ detail = text+ }} catch {detail = text}@@ -146,7 +164,7 @@ export async function apiSend('Invitations are unavailable — member registration is misconfigured. Check the server logs for details.')}- throw new Error(`${res.status} ${res.statusText} - ${detail}`)+ throw new ProfileApiError(res.status, code, `${res.status} ${res.statusText} - ${detail}`)}if (res.status === 204) {return nulldiff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.jsonindex aa37c6a22..e4413f4f9 100644--- a/profile-ui/package-lock.json+++ b/profile-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-profile-ui",- "version": "0.1.176",+ "version": "0.1.177","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-profile-ui",- "version": "0.1.176",+ "version": "0.1.177","dependencies": {"@clerum/desktop-app-links": "file:../packages/desktop-app-links","@clerum/frontend-components": "file:../packages/frontend-components",diff --git a/profile-ui/package.json b/profile-ui/package.jsonindex a9b6aa8ac..84ab0fd0a 100644--- a/profile-ui/package.json+++ b/profile-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-profile-ui",- "version": "0.1.176",+ "version": "0.1.177","private": true,"scripts": {"dev": "next dev",