From 80978dcc637abc435e1bddded17ac3720e0db790 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 18 Aug 2026 09:50:50 +0200 Subject: [PATCH 1/2] fix(profile): keep extended profile fields across cache refreshes --- .../settings/account/AnimalCosmetics.tsx | 7 +- .../settings/account/Profile.test.tsx | 37 +++- src/app/features/settings/account/Profile.tsx | 18 +- src/app/hooks/useUserProfile.test.tsx | 155 ++++++++++++++++- src/app/hooks/useUserProfile.ts | 162 +++++++++++++----- 5 files changed, 325 insertions(+), 54 deletions(-) diff --git a/src/app/features/settings/account/AnimalCosmetics.tsx b/src/app/features/settings/account/AnimalCosmetics.tsx index 4d05db368..ad659da06 100644 --- a/src/app/features/settings/account/AnimalCosmetics.tsx +++ b/src/app/features/settings/account/AnimalCosmetics.tsx @@ -5,6 +5,7 @@ import type { UserProfile } from '$hooks/useUserProfile'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { profilesCacheAtom } from '$state/userRoomProfile'; +import { invalidateUserProfileCache } from '$hooks/useUserProfile'; import { Box, IconButton, Input, Text } from 'folds'; import { useSetAtom } from 'jotai'; import { useCallback, useEffect, useState, type ChangeEvent } from 'react'; @@ -88,11 +89,7 @@ export function AnimalCosmetics({ profile, userId }: Readonly { await mx.setExtendedProfileProperty?.(key, value); - setGlobalProfiles((prev) => { - const newCache = { ...prev }; - delete newCache[userId]; - return newCache; - }); + invalidateUserProfileCache(mx, userId, setGlobalProfiles); }, [mx, userId, setGlobalProfiles] ); diff --git a/src/app/features/settings/account/Profile.test.tsx b/src/app/features/settings/account/Profile.test.tsx index d00c55058..9ec8a3117 100644 --- a/src/app/features/settings/account/Profile.test.tsx +++ b/src/app/features/settings/account/Profile.test.tsx @@ -1,9 +1,18 @@ -import { render, within } from '@testing-library/react'; +import { act, render, within } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize'; import { SettingsLinkProvider } from '$features/settings/SettingsLinkContext'; +import { showToast } from '$state/toast'; import { Profile } from './Profile'; +vi.mock('$state/toast', () => ({ + showToast: vi.fn<(text: string) => void>(), +})); + +const timezoneEditorMock = vi.hoisted(() => ({ + props: undefined as { current?: string; onSave: (tz: string) => void } | undefined, +})); + const mockMatrixClient = { getUserId: () => '@alice:example.org', setAvatarUrl: vi.fn<() => Promise>(), @@ -72,7 +81,10 @@ vi.mock('jotai', async () => { }); vi.mock('./TimezoneEditor', () => ({ - TimezoneEditor: () =>
Timezone
, + TimezoneEditor: (props: { current?: string; onSave: (tz: string) => void }) => { + timezoneEditorMock.props = props; + return
Timezone
; + }, })); vi.mock('./PronounEditor', () => ({ @@ -119,4 +131,25 @@ describe('Profile', () => { within(customFieldTile as HTMLElement).queryByRole('button', { name: /copy settings link/i }) ).not.toBeInTheDocument(); }); + + it('surfaces a toast when saving the timezone fails', async () => { + mockMatrixClient.setExtendedProfileProperty.mockRejectedValue( + new Error('Server does not support extended profiles') + ); + + render( + + + + + + ); + + expect(timezoneEditorMock.props).toBeDefined(); + await act(async () => { + timezoneEditorMock.props?.onSave('Europe/Paris'); + }); + + expect(showToast).toHaveBeenCalledWith(expect.stringContaining('Failed to save profile field')); + }); }); diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index b90ff9569..306c234af 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -9,7 +9,7 @@ import { SettingMenuSelector } from '$components/setting-menu-selector'; import { SettingTile } from '$components/setting-tile'; import { useMatrixClient } from '$hooks/useMatrixClient'; import type { UserProfile, MSC4440Bio, ColorSet } from '$hooks/useUserProfile'; -import { useUserProfile } from '$hooks/useUserProfile'; +import { invalidateUserProfileCache, useUserProfile } from '$hooks/useUserProfile'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; import { UserAvatar } from '$components/user-avatar'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -38,6 +38,7 @@ import { NameColorEditor } from './NameColorEditor'; import { StatusEditor } from './StatusEditor'; import { AnimalCosmetics } from './AnimalCosmetics'; import * as prefix from '$unstable/prefixes'; +import { showToast } from '$state/toast'; import { confirm } from '$components/confirm/confirm'; import { AvatarUploadTile } from '$components/avatar-upload-tile/AvatarUploadTile'; import { accessibleColor } from '$plugins/color'; @@ -406,12 +407,15 @@ function ProfileExtended({ profile, userId }: Readonly) { const handleSaveField = useCallback( async (key: string, value: unknown) => { - await mx.setExtendedProfileProperty?.(key, value); - setGlobalProfiles((prev) => { - const newCache = { ...prev }; - delete newCache[userId]; - return newCache; - }); + try { + await mx.setExtendedProfileProperty?.(key, value); + } catch (error) { + showToast( + `Failed to save profile field: ${error instanceof Error ? error.message : String(error)}` + ); + return; + } + invalidateUserProfileCache(mx, userId, setGlobalProfiles); }, [mx, userId, setGlobalProfiles] ); diff --git a/src/app/hooks/useUserProfile.test.tsx b/src/app/hooks/useUserProfile.test.tsx index 914be09da..4ccdd6f9c 100644 --- a/src/app/hooks/useUserProfile.test.tsx +++ b/src/app/hooks/useUserProfile.test.tsx @@ -5,9 +5,11 @@ import { Provider as JotaiProvider, createStore } from 'jotai'; import { afterEach, describe, expect, it, vi } from 'vitest'; import type { MatrixClient } from '$types/matrix-sdk'; +import { profilesCacheAtom } from '$state/userRoomProfile'; +import { PROFILE_CACHE_FRESH_MS } from '$client/userProfileCache'; import { MatrixClientProvider } from './useMatrixClient'; import { IsInactivePanelProvider } from './useRoom'; -import { useUserProfile } from './useUserProfile'; +import { invalidateUserProfileCache, useUserProfile } from './useUserProfile'; vi.mock('$state/hooks/settings', () => ({ useSetting: (_atom: unknown, key: string) => { @@ -117,4 +119,155 @@ describe('useUserProfile', () => { expect(requested[4]).toBe(userIds[5]); }); + + it('keeps cached profile fields when a refetch response omits them', async () => { + vi.useFakeTimers(); + const mx = { + getProfileInfo: vi + .fn<() => Promise<{ displayname: string }>>() + .mockResolvedValue({ displayname: 'Alice' }), + getUser: vi.fn<() => void>(), + getUserId: vi.fn<() => string>().mockReturnValue('@me:example.org'), + } as unknown as MatrixClient; + + const store = createStore(); + store.set(profilesCacheAtom, { + '@alice:example.org': { + displayName: 'Alice', + timezone: 'Europe/Paris', + _fetched: true, + _fetchedAt: Date.now() - PROFILE_CACHE_FRESH_MS - 1000, + }, + }); + + const wrapper = ({ children }: { children: ReactNode }) => + createElement( + JotaiProvider, + { store }, + createElement( + MatrixClientProvider, + { value: mx }, + createElement(IsInactivePanelProvider, { value: false }, children) + ) + ); + + const { result } = renderHook(() => useUserProfile('@alice:example.org'), { wrapper }); + + await act(async () => { + await vi.advanceTimersByTimeAsync(150); + }); + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + + expect(mx.getProfileInfo).toHaveBeenCalledOnce(); + expect(result.current.timezone).toBe('Europe/Paris'); + }); + + it('updates cached timezone when a refetch response contains a new value', async () => { + vi.useFakeTimers(); + const mx = { + getProfileInfo: vi + .fn<() => Promise<{ displayname: string; 'm.tz': string }>>() + .mockResolvedValue({ displayname: 'Alice', 'm.tz': 'America/New_York' }), + getUser: vi.fn<() => void>(), + getUserId: vi.fn<() => string>().mockReturnValue('@me:example.org'), + } as unknown as MatrixClient; + + const store = createStore(); + store.set(profilesCacheAtom, { + '@alice:example.org': { + displayName: 'Alice', + timezone: 'Europe/Paris', + _fetched: true, + _fetchedAt: Date.now() - PROFILE_CACHE_FRESH_MS - 1000, + }, + }); + + const wrapper = ({ children }: { children: ReactNode }) => + createElement( + JotaiProvider, + { store }, + createElement( + MatrixClientProvider, + { value: mx }, + createElement(IsInactivePanelProvider, { value: false }, children) + ) + ); + + const { result } = renderHook(() => useUserProfile('@alice:example.org'), { wrapper }); + + await act(async () => { + await vi.advanceTimersByTimeAsync(150); + }); + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + + expect(result.current.timezone).toBe('America/New_York'); + }); + + it('discards an in-flight response captured before a profile write', async () => { + vi.useFakeTimers(); + + let resolveStale: ((info: { displayname: string; 'm.tz': string }) => void) | undefined; + const mx = { + getProfileInfo: vi + .fn<() => Promise<{ displayname: string; 'm.tz': string }>>() + .mockImplementationOnce( + () => + new Promise((resolve) => { + resolveStale = resolve; + }) + ) + .mockResolvedValue({ displayname: 'Alice', 'm.tz': 'America/New_York' }), + getUser: vi.fn<() => void>(), + getUserId: vi.fn<() => string>().mockReturnValue('@me:example.org'), + } as unknown as MatrixClient; + + const store = createStore(); + store.set(profilesCacheAtom, { + '@alice:example.org': { + displayName: 'Alice', + timezone: 'Europe/Paris', + _fetched: true, + _fetchedAt: Date.now() - PROFILE_CACHE_FRESH_MS - 1000, + }, + }); + + const wrapper = ({ children }: { children: ReactNode }) => + createElement( + JotaiProvider, + { store }, + createElement( + MatrixClientProvider, + { value: mx }, + createElement(IsInactivePanelProvider, { value: false }, children) + ) + ); + + const { result } = renderHook(() => useUserProfile('@alice:example.org'), { wrapper }); + + await act(async () => { + await vi.advanceTimersByTimeAsync(150); + }); + expect(mx.getProfileInfo).toHaveBeenCalledOnce(); + + await act(async () => { + invalidateUserProfileCache(mx, '@alice:example.org', (update) => + store.set(profilesCacheAtom, update) + ); + }); + + await act(async () => { + resolveStale?.({ displayname: 'Alice', 'm.tz': 'Europe/Paris' }); + await vi.advanceTimersByTimeAsync(0); + }); + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + + expect(mx.getProfileInfo).toHaveBeenCalledTimes(2); + expect(result.current.timezone).toBe('America/New_York'); + }); }); diff --git a/src/app/hooks/useUserProfile.ts b/src/app/hooks/useUserProfile.ts index 4a1005d3b..2b494f1fb 100644 --- a/src/app/hooks/useUserProfile.ts +++ b/src/app/hooks/useUserProfile.ts @@ -24,6 +24,16 @@ const PROFILE_REQUEST_DWELL_MS = 150; const inFlightProfiles = new WeakMap>>>(); const activeProfileRequests = new WeakMap(); const profileRequestQueues = new WeakMap void>>(); +const profileFetchGenerations = new WeakMap>(); + +const getFetchGeneration = (mx: MatrixClient, userId: string): number => + profileFetchGenerations.get(mx)?.get(userId) ?? 0; + +const bumpFetchGeneration = (mx: MatrixClient, userId: string): void => { + const generations = profileFetchGenerations.get(mx) ?? new Map(); + profileFetchGenerations.set(mx, generations); + generations.set(userId, (generations.get(userId) ?? 0) + 1); +}; export type ColorSet = { on_light?: string; @@ -118,48 +128,111 @@ const normalizeInfo = (info: Record): UserProfile => { } }); - return { + const normalized: UserProfile = { avatarUrl: info.avatar_url as string | undefined, displayName: info.displayname as string | undefined, - pronouns: info[prefix.MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME] as - | PronounSet[] - | undefined, - timezone: (info[prefix.MATRIX_UNSTABLE_PROFILE_TIMEZONE_PROPERTY_NAME] || - info[prefix.MATRIX_STABLE_PROFILE_TIMEZONE_PROPERTY_NAME]) as string | undefined, - bio: - msc4440Bio?.['m.text']?.[0]?.body || - (info[prefix.MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME] as string | undefined) || - (info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME] as string | undefined), - status: info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_STATUS_PROPERTY_NAME] as string | undefined, - bannerUrl: info[prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME] as string | undefined, - nameColor: info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME] as string | undefined, - nameColorDark: info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME] as - | string - | undefined, - nameColorLight: info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME] as - | string - | undefined, - nameColors: info[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined, - heroColorScheme: info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME] as - | Record - | undefined, - isCat: info[prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME] as - | boolean - | undefined, - hasCats: info[prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME] as - | boolean - | undefined, - isAnimal: info[prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_ANIMAL_PROPERTY_NAME] as string, - hasAnimal: info[ - prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_ANIMAL_PROPERTY_NAME - ] as string, - animalNeed: info[ - prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_ANIMAL_NEED_PROPERTY_NAME - ] as string, - extended, _fetched: true, _fetchedAt: Date.now(), }; + + if (prefix.MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME in info) { + normalized.pronouns = info[prefix.MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME] as + | PronounSet[] + | undefined; + } + if ( + prefix.MATRIX_UNSTABLE_PROFILE_TIMEZONE_PROPERTY_NAME in info || + prefix.MATRIX_STABLE_PROFILE_TIMEZONE_PROPERTY_NAME in info + ) { + normalized.timezone = (info[prefix.MATRIX_UNSTABLE_PROFILE_TIMEZONE_PROPERTY_NAME] || + info[prefix.MATRIX_STABLE_PROFILE_TIMEZONE_PROPERTY_NAME]) as string | undefined; + } + if ( + prefix.MATRIX_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME in info || + prefix.MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME in info || + prefix.MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME in info + ) { + normalized.bio = + msc4440Bio?.['m.text']?.[0]?.body || + (info[prefix.MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME] as string | undefined) || + (info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME] as string | undefined); + } + if (prefix.MATRIX_COMMET_UNSTABLE_PROFILE_STATUS_PROPERTY_NAME in info) { + normalized.status = info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_STATUS_PROPERTY_NAME] as + | string + | undefined; + } + if (prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME in info) { + normalized.bannerUrl = info[prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME] as + | string + | undefined; + } + if (prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME in info) { + normalized.nameColor = info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME] as + | string + | undefined; + } + if (prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME in info) { + normalized.nameColorDark = info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME] as + | string + | undefined; + } + if (prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME in info) { + normalized.nameColorLight = info[ + prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME + ] as string | undefined; + } + if (prefix.MATRIX_UNSTABLE_COLORS in info) { + normalized.nameColors = info[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined; + } + if (prefix.MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME in info) { + normalized.heroColorScheme = info[ + prefix.MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME + ] as Record | undefined; + } + if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME in info) { + normalized.isCat = info[prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME] as + | boolean + | undefined; + } + if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME in info) { + normalized.hasCats = info[ + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME + ] as boolean | undefined; + } + if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_ANIMAL_PROPERTY_NAME in info) { + normalized.isAnimal = info[ + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_ANIMAL_PROPERTY_NAME + ] as string; + } + if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_ANIMAL_PROPERTY_NAME in info) { + normalized.hasAnimal = info[ + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_ANIMAL_PROPERTY_NAME + ] as string; + } + if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_ANIMAL_NEED_PROPERTY_NAME in info) { + normalized.animalNeed = info[ + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_ANIMAL_NEED_PROPERTY_NAME + ] as string; + } + if (Object.keys(extended).length > 0) { + normalized.extended = extended; + } + + return normalized; +}; + +export const invalidateUserProfileCache = ( + mx: MatrixClient, + userId: string, + setProfiles: (update: (prev: Record) => Record) => void +): void => { + bumpFetchGeneration(mx, userId); + setProfiles((prev) => { + const existing = prev[userId]; + if (!existing) return prev; + return { ...prev, [userId]: { ...existing, _fetchedAt: 0 } }; + }); }; export const isValidHex = (c: unknown): string | undefined => { @@ -227,11 +300,12 @@ export const useUserProfile = ( useEffect(() => { if (!needsFetch) return undefined; - const timeoutId = window.setTimeout(() => { + const startFetch = () => { const clientInFlight = inFlightProfiles.get(mx) ?? new Map(); inFlightProfiles.set(mx, clientInFlight); if (clientInFlight.has(userId)) return; + const generation = getFetchGeneration(mx, userId); const fetchPromise = scheduleProfileRequest(mx, () => mx.getProfileInfo(userId)).finally( () => { clientInFlight.delete(userId); @@ -243,6 +317,10 @@ export const useUserProfile = ( // the initiating row: a completed request remains useful after a fast virtualized scroll. fetchPromise .then((info: Record) => { + if (getFetchGeneration(mx, userId) !== generation) { + startFetch(); + return; + } const normalized = normalizeInfo(info); setGlobalProfiles((prev) => { const { [userId]: previousProfile, ...otherProfiles } = prev; @@ -253,12 +331,18 @@ export const useUserProfile = ( }); }) .catch(() => { + if (getFetchGeneration(mx, userId) !== generation) { + startFetch(); + return; + } setGlobalProfiles((prev) => ({ ...prev, [userId]: { ...prev[userId], _fetched: true, _fetchedAt: Date.now() }, })); }); - }, PROFILE_REQUEST_DWELL_MS); + }; + + const timeoutId = window.setTimeout(startFetch, PROFILE_REQUEST_DWELL_MS); return () => window.clearTimeout(timeoutId); }, [userId, needsFetch, mx, setGlobalProfiles]); From 4a5505bbd9a8d35d8881903944e7488e1cfaea94 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 18 Aug 2026 10:01:41 +0200 Subject: [PATCH 2/2] fix(profile): surface banner and animal identity save failures --- .../settings/account/AnimalCosmetics.tsx | 10 ++++- src/app/features/settings/account/Profile.tsx | 42 ++++++++++++++----- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/src/app/features/settings/account/AnimalCosmetics.tsx b/src/app/features/settings/account/AnimalCosmetics.tsx index ad659da06..4a197cf2b 100644 --- a/src/app/features/settings/account/AnimalCosmetics.tsx +++ b/src/app/features/settings/account/AnimalCosmetics.tsx @@ -5,6 +5,7 @@ import type { UserProfile } from '$hooks/useUserProfile'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { profilesCacheAtom } from '$state/userRoomProfile'; +import { showToast } from '$state/toast'; import { invalidateUserProfileCache } from '$hooks/useUserProfile'; import { Box, IconButton, Input, Text } from 'folds'; import { useSetAtom } from 'jotai'; @@ -88,7 +89,14 @@ export function AnimalCosmetics({ profile, userId }: Readonly { - await mx.setExtendedProfileProperty?.(key, value); + try { + await mx.setExtendedProfileProperty?.(key, value); + } catch (error) { + showToast( + `Failed to save profile field: ${error instanceof Error ? error.message : String(error)}` + ); + return; + } invalidateUserProfileCache(mx, userId, setGlobalProfiles); }, [mx, userId, setGlobalProfiles] diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index 306c234af..07b679354 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -108,8 +108,9 @@ function ProfileAvatar({ profile, userId, propagateTo }: Readonly) ); } -function ProfileBanner({ profile }: Readonly>) { +function ProfileBanner({ profile, userId }: Readonly>) { const mx = useMatrixClient(); + const setGlobalProfiles = useSetAtom(profilesCacheAtom); const useAuthentication = useMediaAuthentication(); const [stagedUrl, setStagedUrl] = useState(); const [isRemoving, setIsRemoving] = useState(false); @@ -145,15 +146,27 @@ function ProfileBanner({ profile }: Readonly>) { }, []); const handleUploaded = useCallback( - (upload: UploadSuccess) => { + async (upload: UploadSuccess) => { const { mxc } = upload; if (imageFileURL) setStagedUrl(imageFileURL); - - mx.setExtendedProfileProperty?.(prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME, mxc); setImageFile(undefined); + + try { + await mx.setExtendedProfileProperty?.( + prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME, + mxc + ); + } catch (error) { + showToast( + `Failed to save profile field: ${error instanceof Error ? error.message : String(error)}` + ); + setStagedUrl(undefined); + return; + } + invalidateUserProfileCache(mx, userId, setGlobalProfiles); }, - [mx, imageFileURL] + [mx, userId, imageFileURL, setGlobalProfiles] ); const handleRemoveBanner = async () => { @@ -167,10 +180,19 @@ function ProfileBanner({ profile }: Readonly>) { setIsRemoving(true); setStagedUrl(undefined); setImageFile(undefined); - await mx.setExtendedProfileProperty?.( - prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME, - null - ); + try { + await mx.setExtendedProfileProperty?.( + prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME, + null + ); + } catch (error) { + showToast( + `Failed to save profile field: ${error instanceof Error ? error.message : String(error)}` + ); + setIsRemoving(false); + return; + } + invalidateUserProfileCache(mx, userId, setGlobalProfiles); } }; @@ -719,7 +741,7 @@ export function Profile() { direction="Column" gap="400" > - +