:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): retain refreshed gravatars and hide avatar fallback (#103853)
Dylan Martin0e8c2dc8b07f
diff --git a/products/desktop/docs/TESTING.md b/products/desktop/docs/TESTING.mdindex 20ef06761b59..0279d5f8c262 100644--- a/products/desktop/docs/TESTING.md+++ b/products/desktop/docs/TESTING.md@@ -57,6 +57,13 @@ Run the focus and submission checks with:pnpm --filter @posthog/ui test src/features/sessions/components/CommentComposer.integration.test.tsx```+## Profile pictures++In Settings > Account, check a Gravatar with a transparent background. The picture must not show initials behind it.+Refresh the picture, close Settings, then open Settings again. The refreshed picture must remain visible without another refresh.+Other avatars for the same email must use the refreshed URL, including avatars at different sizes. Refresh state lasts until the app reloads.+The `Settings/AccountSettings` stories cover transparent pictures, missing pictures, and loading states.+## File Location- Unit tests colocate with source as `.test.ts` or `.test.tsx`.diff --git a/products/desktop/packages/core/src/auth/gravatarRefresh.ts b/products/desktop/packages/core/src/auth/gravatarRefresh.tsnew file mode 100644index 000000000000..1d26a883c59f--- /dev/null+++ b/products/desktop/packages/core/src/auth/gravatarRefresh.ts@@ -0,0 +1,13 @@+export function getGravatarRefresh(+ email: string,+ refreshedAtByEmail: Record<string, number>,+ now: number,+): { email: string; refreshedAt: number } | undefined {+ const normalized = email.trim().toLowerCase();+ if (!normalized) return undefined;++ return {+ email: normalized,+ refreshedAt: Math.max(now, (refreshedAtByEmail[normalized] ?? 0) + 1),+ };+}diff --git a/products/desktop/packages/ui/src/features/auth/gravatarRefreshStore.ts b/products/desktop/packages/ui/src/features/auth/gravatarRefreshStore.tsnew file mode 100644index 000000000000..09ddfe38bea0--- /dev/null+++ b/products/desktop/packages/ui/src/features/auth/gravatarRefreshStore.ts@@ -0,0 +1,18 @@+import { create } from "zustand";++interface GravatarRefreshStore {+ refreshedAtByEmail: Record<string, number>;+ setRefreshedAt: (email: string, refreshedAt: number) => void;+}++export const useGravatarRefreshStore = create<GravatarRefreshStore>((set) => ({+ refreshedAtByEmail: {},+ setRefreshedAt: (email, refreshedAt) => {+ set((state) => ({+ refreshedAtByEmail: {+ ...state.refreshedAtByEmail,+ [email]: refreshedAt,+ },+ }));+ },+}));diff --git a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.tsindex b525d2c18142..3634634b9371 100644--- a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts+++ b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts@@ -1,7 +1,16 @@-import { renderHook, waitFor } from "@testing-library/react";-import { describe, expect, it } from "vitest";+import { getGravatarRefresh } from "@posthog/core/auth/gravatarRefresh";+import { act, renderHook, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import { useGravatarRefreshStore } from "./gravatarRefreshStore";import { useGravatarUrl } from "./useGravatarUrl";+function refreshGravatar(email: string, now: number): void {+ const { refreshedAtByEmail, setRefreshedAt } =+ useGravatarRefreshStore.getState();+ const refresh = getGravatarRefresh(email, refreshedAtByEmail, now);+ if (refresh) setRefreshedAt(refresh.email, refresh.refreshedAt);+}+async function gravatarUrl(email: string): Promise<string> {const digest = await crypto.subtle.digest("SHA-256",@@ -14,6 +23,60 @@ async function gravatarUrl(email: string): Promise<string> {}describe("useGravatarUrl", () => {+ afterEach(() => {+ act(() => useGravatarRefreshStore.setState({ refreshedAtByEmail: {} }));+ });++ it("keeps refreshed URLs after remount and updates all sizes for that email", async () => {+ const email = "[email protected]";+ const expected = await gravatarUrl(email);+ const profile = renderHook(() => useGravatarUrl(email, 144));+ const avatar = renderHook(() => useGravatarUrl(email));+ const other = renderHook(() => useGravatarUrl("[email protected]"));+ await waitFor(() => expect(profile.result.current).toBeDefined());+ await waitFor(() => expect(avatar.result.current).toBe(expected));+ await waitFor(() => expect(other.result.current).toBeDefined());+ const otherUrl = other.result.current;++ act(() => refreshGravatar(" [email protected] ", 1000));+ const refreshedAt =+ useGravatarRefreshStore.getState().refreshedAtByEmail[email];+ expect(avatar.result.current).toBe(`${expected}&_=${refreshedAt}`);+ expect(profile.result.current).toBe(+ `${expected.replace("s=96", "s=144")}&_=${refreshedAt}`,+ );+ expect(other.result.current).toBe(otherUrl);+ const refreshedUrl = profile.result.current;+ profile.unmount();++ const reopened = renderHook(() => useGravatarUrl(email, 144));+ expect(reopened.result.current).toBe(refreshedUrl);++ act(() => refreshGravatar(email, 1000));+ expect(reopened.result.current).toBe(+ `${expected.replace("s=96", "s=144")}&_=1001`,+ );+ });++ it.each(["", " "])("ignores an empty email (%j)", (email) => {+ expect(getGravatarRefresh(email, {}, 1000)).toBeUndefined();+ });++ it.each([+ { now: 999, expected: 1001 },+ { now: 1000, expected: 1001 },+ { now: 1002, expected: 1002 },+ ])("advances the refresh timestamp at $now", ({ now, expected }) => {+ const timestamps = { "[email protected]": 1000 };+ expect(+ getGravatarRefresh(" [email protected] ", timestamps, now),+ ).toEqual({+ email: "[email protected]",+ refreshedAt: expected,+ });+ expect(timestamps).toEqual({ "[email protected]": 1000 });+ });+it("returns undefined when there is no email", () => {const { result } = renderHook(() => useGravatarUrl(undefined));expect(result.current).toBeUndefined();diff --git a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.tsindex 7d436842c3c0..6a5fc0545bc2 100644--- a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts+++ b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts@@ -1,3 +1,4 @@+import { useGravatarRefreshStore } from "@posthog/ui/features/auth/gravatarRefreshStore";import { useEffect, useState } from "react";const DEFAULT_GRAVATAR_SIZE = 96;@@ -35,6 +36,9 @@ export function useGravatarUrl(size: number = DEFAULT_GRAVATAR_SIZE,): string | undefined {const normalized = email?.trim().toLowerCase() || undefined;+ const refreshedAt = useGravatarRefreshStore((state) =>+ normalized ? state.refreshedAtByEmail[normalized] : undefined,+ );const key = normalized ? cacheKey(normalized, size) : undefined;const cached = key ? gravatarUrls.get(key) : undefined;const [hashed, setHashed] = useState<HashedGravatar | null>(null);@@ -56,6 +60,6 @@ export function useGravatarUrl(};}, [normalized, size, cached]);- if (cached) return cached;- return hashed && hashed.key === key ? hashed.url : undefined;+ const url = cached ?? (hashed && hashed.key === key ? hashed.url : undefined);+ return url && refreshedAt ? `${url}&_=${refreshedAt}` : url;}diff --git a/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.stories.tsx b/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.stories.tsxindex 46e24ddc204f..8dc2e4113120 100644--- a/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.stories.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.stories.tsx@@ -38,6 +38,14 @@ type Story = StoryObj<typeof AccountSettingsView>;export const WithGravatar: Story = {};+export const TransparentGravatar: Story = {+ args: {+ imageUrl: `data:image/svg+xml;utf8,${encodeURIComponent(+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 144 144"><circle cx="72" cy="56" r="28" fill="#fdfdfc"/><path d="M20 144c0-32 24-52 52-52s52 20 52 52z" fill="#fdfdfc"/></svg>',+ )}`,+ },+};+export const NoGravatar: Story = {args: { status: "missing", imageUrl: undefined },};diff --git a/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.tsxindex 618cec7ff24a..3be65f560827 100644--- a/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.tsx@@ -1,8 +1,10 @@import { ArrowSquareOut, ArrowsClockwise, Camera } from "@phosphor-icons/react";import { avatarColor } from "@posthog/core/auth/avatarColor";+import { getGravatarRefresh } from "@posthog/core/auth/gravatarRefresh";import { buildPostHogUrl } from "@posthog/core/settings/posthogUrl";import { Avatar, AvatarFallback, Button, cn } from "@posthog/quill";import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useGravatarRefreshStore } from "@posthog/ui/features/auth/gravatarRefreshStore";import { useAuthStateValue } from "@posthog/ui/features/auth/store";import type { AvatarPerson } from "@posthog/ui/features/auth/UserAvatar";import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";@@ -20,7 +22,7 @@ import {} from "@posthog/ui/features/settings/components/SettingsCard";import { Spin } from "@posthog/ui/primitives/Spinner";import { Tooltip } from "@posthog/ui/primitives/Tooltip";-import { useCallback, useState } from "react";+import { useCallback } from "react";const GRAVATAR_MANAGE_URL = "https://gravatar.com/profile/avatars";const GRAVATAR_IMAGE_SIZE = 144;@@ -90,18 +92,19 @@ function ProfilePictureRow({"outline-dashed outline-(--gray-8) outline-1 outline-offset-2",)}>- <AvatarFallback- style={{ backgroundColor: color.bg, color: color.text }}- >- {getUserInitials(user)}- </AvatarFallback>{imageUrl ? (<imgsrc={imageUrl}alt=""className="absolute inset-0 size-full object-cover"/>- ) : null}+ ) : (+ <AvatarFallback+ style={{ backgroundColor: color.bg, color: color.text }}+ >+ {getUserInitials(user)}+ </AvatarFallback>+ )}</Avatar><spanaria-hidden@@ -192,18 +195,20 @@ export function AccountSection() {const client = useOptionalAuthenticatedClient();const { data: user } = useCurrentUser({ client });const cloudRegion = useAuthStateValue((state) => state.cloudRegion);- const gravatarUrl = useGravatarUrl(user?.email, GRAVATAR_IMAGE_SIZE);- const [refreshedAt, setRefreshedAt] = useState<number | null>(null);-- const candidateUrl =- gravatarUrl && refreshedAt- ? `${gravatarUrl}&_=${refreshedAt}`- : gravatarUrl;+ const candidateUrl = useGravatarUrl(user?.email, GRAVATAR_IMAGE_SIZE);const probe = useImageProbe(candidateUrl);const handleRefresh = useCallback(() => {- setRefreshedAt(Date.now());- }, []);+ if (!user?.email) return;+ const { refreshedAtByEmail, setRefreshedAt } =+ useGravatarRefreshStore.getState();+ const refresh = getGravatarRefresh(+ user.email,+ refreshedAtByEmail,+ Date.now(),+ );+ if (refresh) setRefreshedAt(refresh.email, refresh.refreshedAt);+ }, [user?.email]);const handleOpenGravatar = useCallback(() => {window.open(GRAVATAR_MANAGE_URL, "_blank");