Skip to content

: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.

fix(desktop): serve avatars from the disk cache (#90680)

Charles Vien990c458264ad
diff --git a/products/desktop/packages/ui/src/features/auth/UserAvatar.tsx b/products/desktop/packages/ui/src/features/auth/UserAvatar.tsx
index 892fc175fdf8..de28ff2b49f8 100644
--- a/products/desktop/packages/ui/src/features/auth/UserAvatar.tsx
+++ b/products/desktop/packages/ui/src/features/auth/UserAvatar.tsx
@@ -1,9 +1,14 @@
import { avatarColor } from "@posthog/core/auth/avatarColor";
import type { UserLike } from "@posthog/core/auth/userInitials";
import { Avatar, AvatarFallback, AvatarImage } from "@posthog/quill";
+import {
+ rememberAvatarImageStatus,
+ rememberedAvatarImageStatus,
+} from "@posthog/ui/features/auth/avatarImageStatus";
import { useGravatarUrl } from "@posthog/ui/features/auth/useGravatarUrl";
import { getUserInitials } from "@posthog/ui/features/auth/userInitials";
import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+import { cachedImageUrl } from "@posthog/ui/shell/cachedImageUrl";
type AvatarSize = "lg" | "default" | "sm" | "xs";
@@ -20,6 +25,8 @@ interface UserAvatarProps {
title?: string;
}
+const KNOWN_IMAGE_FALLBACK_DELAY_MS = 300;
+
// A person's avatar: Gravatar (by email) when one exists, otherwise a colored
// initials bubble. The color is seeded off a stable identifier so each person keeps
// one hue everywhere. When the Gravatar image loads it covers the colored fallback.
@@ -30,15 +37,35 @@ export function UserAvatar({
title,
}: UserAvatarProps) {
const gravatarUrl = useGravatarUrl(user?.email);
+ const src = gravatarUrl ? cachedImageUrl(gravatarUrl) : undefined;
+ const knownStatus = rememberedAvatarImageStatus(src);
const seed = user?.uuid ?? user?.email ?? userDisplayName(user);
const color = avatarColor(seed);
return (
<Avatar size={size} className={className} title={title}>
- {gravatarUrl ? (
- <AvatarImage src={gravatarUrl} alt={userDisplayName(user)} />
+ {src && knownStatus !== "error" ? (
+ <AvatarImage
+ src={src}
+ alt={userDisplayName(user)}
+ onLoadingStatusChange={(status) => {
+ if (status === "loaded" || status === "error") {
+ rememberAvatarImageStatus(src, status);
+ }
+ }}
+ />
) : null}
- <AvatarFallback style={{ backgroundColor: color.bg, color: color.text }}>
+ {/* Base UI reads `delay` once, when the fallback mounts, and never arms the
+ hold again. A surface that keeps one avatar and swaps the person, such as
+ the handoff dialog, must remount the fallback to get the hold for the new
+ image. */}
+ <AvatarFallback
+ key={src}
+ delay={
+ knownStatus === "loaded" ? KNOWN_IMAGE_FALLBACK_DELAY_MS : undefined
+ }
+ style={{ backgroundColor: color.bg, color: color.text }}
+ >
{getUserInitials(user)}
</AvatarFallback>
</Avatar>
diff --git a/products/desktop/packages/ui/src/features/auth/avatarImageStatus.test.ts b/products/desktop/packages/ui/src/features/auth/avatarImageStatus.test.ts
new file mode 100644
index 000000000000..b5e27c845105
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/auth/avatarImageStatus.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ rememberAvatarImageStatus,
+ rememberedAvatarImageStatus,
+} from "./avatarImageStatus";
+
+const PAST_RETRY_WINDOW_MS = 61_000;
+
+describe("avatarImageStatus", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("forgets an error once the retry window has passed", () => {
+ rememberAvatarImageStatus("https://example.com/offline.png", "error");
+ expect(rememberedAvatarImageStatus("https://example.com/offline.png")).toBe(
+ "error",
+ );
+
+ vi.advanceTimersByTime(PAST_RETRY_WINDOW_MS);
+
+ expect(
+ rememberedAvatarImageStatus("https://example.com/offline.png"),
+ ).toBeUndefined();
+ });
+
+ it("keeps remembering a loaded image past the error retry window", () => {
+ rememberAvatarImageStatus("https://example.com/loaded.png", "loaded");
+
+ vi.advanceTimersByTime(PAST_RETRY_WINDOW_MS);
+
+ expect(rememberedAvatarImageStatus("https://example.com/loaded.png")).toBe(
+ "loaded",
+ );
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/auth/avatarImageStatus.ts b/products/desktop/packages/ui/src/features/auth/avatarImageStatus.ts
new file mode 100644
index 000000000000..0ae4475ead39
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/auth/avatarImageStatus.ts
@@ -0,0 +1,33 @@
+export type AvatarImageStatus = "loaded" | "error";
+
+// An error is only trusted for a short while. The disk cache answers with 404 both
+// when the address has no Gravatar and when it holds no copy and the fetch failed,
+// so an avatar that failed while the app was offline must get another try once the
+// network is back, instead of staying on initials until the app restarts.
+const ERROR_RETRY_AFTER_MS = 60_000;
+
+const statuses = new Map<
+ string,
+ { status: AvatarImageStatus; recordedAt: number }
+>();
+
+export function rememberAvatarImageStatus(
+ src: string,
+ status: AvatarImageStatus,
+): void {
+ statuses.set(src, { status, recordedAt: Date.now() });
+}
+
+export function rememberedAvatarImageStatus(
+ src: string | undefined,
+): AvatarImageStatus | undefined {
+ const remembered = src ? statuses.get(src) : undefined;
+ if (!remembered) return undefined;
+ if (
+ remembered.status === "error" &&
+ Date.now() - remembered.recordedAt >= ERROR_RETRY_AFTER_MS
+ ) {
+ return undefined;
+ }
+ return remembered.status;
+}
diff --git a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts
index 19fa039644f2..b525d2c18142 100644
--- a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts
+++ b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts
@@ -2,6 +2,17 @@ import { renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { useGravatarUrl } from "./useGravatarUrl";
+async function gravatarUrl(email: string): Promise<string> {
+ const digest = await crypto.subtle.digest(
+ "SHA-256",
+ new TextEncoder().encode(email),
+ );
+ const hash = Array.from(new Uint8Array(digest))
+ .map((b) => b.toString(16).padStart(2, "0"))
+ .join("");
+ return `https://www.gravatar.com/avatar/${hash}?s=96&d=404`;
+}
+
describe("useGravatarUrl", () => {
it("returns undefined when there is no email", () => {
const { result } = renderHook(() => useGravatarUrl(undefined));
@@ -35,25 +46,28 @@ describe("useGravatarUrl", () => {
await waitFor(() => expect(result.current).toBe(expected));
});
- it("clears the previous URL while a changed email is hashing", async () => {
+ it("resolves synchronously on a later mount of an email hashed before", async () => {
+ const expected = await gravatarUrl("[email protected]");
+ const first = renderHook(() => useGravatarUrl("[email protected]"));
+ await waitFor(() => expect(first.result.current).toBe(expected));
+ first.unmount();
+
+ const second = renderHook(() => useGravatarUrl("[email protected]"));
+ expect(second.result.current).toBe(expected);
+ });
+
+ it("never shows the previous person's URL while a changed email is hashing", async () => {
+ const firstUrl = await gravatarUrl("[email protected]");
+ const secondUrl = await gravatarUrl("[email protected]");
const { result, rerender } = renderHook(
({ email }) => useGravatarUrl(email),
- { initialProps: { email: "[email protected]" } },
- );
- await waitFor(() =>
- expect(result.current).toContain(
- "b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514",
- ),
+ { initialProps: { email: "[email protected]" } },
);
+ await waitFor(() => expect(result.current).toBe(firstUrl));
- rerender({ email: "[email protected]" });
- // The prior person's URL must not linger during the new hash.
- expect(result.current).toBeUndefined();
+ rerender({ email: "[email protected]" });
+ expect(result.current).not.toBe(firstUrl);
- await waitFor(() =>
- expect(result.current).toContain(
- "973dfe463ec85785f5f95af5ba3906eedb2d931c24e69824a89ea65dba4e813b",
- ),
- );
+ await waitFor(() => expect(result.current).toBe(secondUrl));
});
});
diff --git a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts
index 1474073ead32..7d436842c3c0 100644
--- a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts
+++ b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts
@@ -7,12 +7,11 @@ const DEFAULT_GRAVATAR_SIZE = 96;
// makes Gravatar return 404 (instead of a default silhouette) when the address has no
// avatar, so the <img> errors and the initials fallback stays visible.
async function gravatarUrlForEmail(
- email: string,
+ normalizedEmail: string,
size: number,
): Promise<string | undefined> {
if (!globalThis.crypto?.subtle) return undefined;
- const normalized = email.trim().toLowerCase();
- const bytes = new TextEncoder().encode(normalized);
+ const bytes = new TextEncoder().encode(normalizedEmail);
const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
const hash = Array.from(new Uint8Array(digest))
.map((b) => b.toString(16).padStart(2, "0"))
@@ -20,32 +19,43 @@ async function gravatarUrlForEmail(
return `https://www.gravatar.com/avatar/${hash}?s=${size}&d=404`;
}
+const gravatarUrls = new Map<string, string>();
+
+function cacheKey(normalizedEmail: string, size: number): string {
+ return `${normalizedEmail}:${size}`;
+}
+
+interface HashedGravatar {
+ key: string;
+ url: string | undefined;
+}
+
export function useGravatarUrl(
email?: string | null,
size: number = DEFAULT_GRAVATAR_SIZE,
): string | undefined {
- const [url, setUrl] = useState<string | undefined>(undefined);
+ const normalized = email?.trim().toLowerCase() || undefined;
+ const key = normalized ? cacheKey(normalized, size) : undefined;
+ const cached = key ? gravatarUrls.get(key) : undefined;
+ const [hashed, setHashed] = useState<HashedGravatar | null>(null);
useEffect(() => {
- if (!email) {
- setUrl(undefined);
- return;
- }
+ if (!normalized || cached) return;
+ const pendingKey = cacheKey(normalized, size);
let cancelled = false;
- // Clear any prior URL so a reused avatar whose email just changed shows
- // initials during the async hash rather than the previous person's photo.
- setUrl(undefined);
- gravatarUrlForEmail(email, size)
- .then((next) => {
- if (!cancelled) setUrl(next);
+ gravatarUrlForEmail(normalized, size)
+ .then((url) => {
+ if (url) gravatarUrls.set(pendingKey, url);
+ if (!cancelled) setHashed({ key: pendingKey, url });
})
.catch(() => {
- if (!cancelled) setUrl(undefined);
+ if (!cancelled) setHashed({ key: pendingKey, url: undefined });
});
return () => {
cancelled = true;
};
- }, [email, size]);
+ }, [normalized, size, cached]);
- return url;
+ if (cached) return cached;
+ return hashed && hashed.key === key ? hashed.url : undefined;
}
diff --git a/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.tsx b/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.tsx
index 981d3f1b003d..9fa993639ef9 100644
--- a/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.tsx
+++ b/products/desktop/packages/ui/src/features/code-review/components/PrCommentThread.tsx
@@ -18,6 +18,7 @@ import {
import { Button } from "@posthog/quill";
import type { PrReviewComment } from "@posthog/shared";
import { formatRelativeTimeShort } from "@posthog/shared";
+import { cachedImageUrl } from "@posthog/ui/shell/cachedImageUrl";
import { Avatar, Badge, Box, Flex, Text } from "@radix-ui/themes";
import {
type ReactNode,
@@ -224,7 +225,7 @@ function CommentBody({
<Avatar
size="1"
radius="full"
- src={comment.user.avatar_url}
+ src={cachedImageUrl(comment.user.avatar_url)}
fallback={comment.user.login[0]?.toUpperCase() ?? "?"}
className="shrink-0"
/>
diff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx
index 7b91fe46760e..96e022905cbb 100644
--- a/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx
+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx
@@ -14,7 +14,10 @@ vi.mock("@posthog/ui/features/auth/authClient", () => ({
vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({
useCurrentUser: () => ({ data: { uuid: "user-1" } }),
}));
-vi.mock("@posthog/di/container", () => ({ resolveService: () => ({}) }));
+vi.mock("@posthog/di/container", () => ({
+ resolveService: () => ({}),
+ resolveServiceOptional: () => null,
+}));
vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
useFeatureFlag: () => false,
}));
diff --git a/products/desktop/packages/ui/src/features/inbox/components/detail/ArtefactLogList.tsx b/products/desktop/packages/ui/src/features/inbox/components/detail/ArtefactLogList.tsx
index 31ecb1f82874..e369c8c33520 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/detail/ArtefactLogList.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/detail/ArtefactLogList.tsx
@@ -27,6 +27,7 @@ import { SignalReportPriorityBadge } from "@posthog/ui/features/inbox/components
import { CodeBlock } from "@posthog/ui/primitives/CodeBlock";
import { HighlightedCode } from "@posthog/ui/primitives/HighlightedCode";
import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";
+import { cachedImageUrl } from "@posthog/ui/shell/cachedImageUrl";
import { Badge, Box, Flex, Text } from "@radix-ui/themes";
import { useState } from "react";
@@ -201,7 +202,9 @@ function ReviewersBody({ reviewers }: { reviewers: SuggestedReviewer[] }) {
>
{reviewer.github_login ? (
<img
- src={`https://github.com/${reviewer.github_login}.png?size=28`}
+ src={cachedImageUrl(
+ `https://github.com/${reviewer.github_login}.png?size=28`,
+ )}
alt=""
className="github-avatar h-[18px] w-[18px] shrink-0 rounded-full"
onLoad={(e) => e.currentTarget.classList.add("loaded")}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/utils/SuggestedReviewerAvatar.tsx b/products/desktop/packages/ui/src/features/inbox/components/utils/SuggestedReviewerAvatar.tsx
index b98064ce5453..6afd17e5f078 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/utils/SuggestedReviewerAvatar.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/utils/SuggestedReviewerAvatar.tsx
@@ -1,4 +1,5 @@
import { cn } from "@posthog/quill";
+import { cachedImageUrl } from "@posthog/ui/shell/cachedImageUrl";
import posthogIcon from "../../assets/posthog-icon.svg";
const SIZE = {
@@ -50,7 +51,9 @@ export function SuggestedReviewerAvatar({
return (
<img
- src={`https://github.com/${githubLogin}.png?size=${config.pixels}`}
+ src={cachedImageUrl(
+ `https://github.com/${githubLogin}.png?size=${config.pixels}`,
+ )}
alt=""
className={cn(
"github-avatar shrink-0 rounded-full",
diff --git a/products/desktop/packages/ui/src/features/pr-review/PrCommentsSection.tsx b/products/desktop/packages/ui/src/features/pr-review/PrCommentsSection.tsx
index cf2d57436710..69b267e307b9 100644
--- a/products/desktop/packages/ui/src/features/pr-review/PrCommentsSection.tsx
+++ b/products/desktop/packages/ui/src/features/pr-review/PrCommentsSection.tsx
@@ -3,6 +3,7 @@ import { Spinner } from "@posthog/quill";
import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
import { NestedButton } from "@posthog/ui/primitives/NestedButton";
import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";
+import { cachedImageUrl } from "@posthog/ui/shell/cachedImageUrl";
import { useMemo, useState } from "react";
import { openExternalUrl } from "../../shell/openExternal";
import { PrSectionHeader } from "./PrSectionHeader";
@@ -139,7 +140,7 @@ function CommentRow({ item }: { item: CommentItem }) {
<div className="flex min-w-0 items-center gap-2 text-[11px] text-gray-11">
{item.avatarUrl && (
<img
- src={item.avatarUrl}
+ src={cachedImageUrl(item.avatarUrl)}
alt=""
className="h-4 w-4 shrink-0 rounded-full"
/>
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx b/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx
index 8aef01c50c36..58315ade44f8 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/CommentThreadCard.tsx
@@ -22,6 +22,7 @@ import type { CommentEntry } from "@posthog/ui/features/canvas/components/taskCo
import { githubCommentComponents } from "@posthog/ui/features/editor/components/githubCommentImages";
import { githubRehypePlugins } from "@posthog/ui/features/editor/components/githubMarkdownPlugins";
import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import { cachedImageUrl } from "@posthog/ui/shell/cachedImageUrl";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { type ReactNode, useState } from "react";
import { CommentComposer } from "./CommentComposer";
@@ -36,7 +37,7 @@ function CommentBody({ entry }: { entry: CommentEntry }) {
<UserAvatar user={entry.user} size="sm" />
) : (
<Avatar size="sm">
- <AvatarImage src={entry.avatarUrl} alt="" />
+ <AvatarImage src={cachedImageUrl(entry.avatarUrl)} alt="" />
<AvatarFallback>{entry.authorName.slice(0, 2)}</AvatarFallback>
</Avatar>
)}