: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
feat(desktop): add profile picture to general settings (#91323)
Charles Vien749f920dc16c
diff --git a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.tsindex 652936afa9bb..19fa039644f2 100644--- a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts+++ b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.test.ts@@ -8,22 +8,31 @@ describe("useGravatarUrl", () => {expect(result.current).toBeUndefined();});- it("builds a SHA-256 Gravatar URL with the d=404 fallback", async () => {- const { result } = renderHook(() => useGravatarUrl("[email protected]"));- await waitFor(() =>- expect(result.current).toBe(+ it.each([+ {+ name: "builds a SHA-256 Gravatar URL with the d=404 fallback",+ email: "[email protected]",+ size: undefined,+ expected:"https://www.gravatar.com/avatar/b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514?s=96&d=404",- ),- );- });-- it("lowercases and trims the email before hashing", async () => {- const { result } = renderHook(() => useGravatarUrl(" [email protected] "));- await waitFor(() =>- expect(result.current).toBe(+ },+ {+ name: "lowercases and trims the email before hashing",+ email: " [email protected] ",+ size: undefined,+ expected:"https://www.gravatar.com/avatar/973dfe463ec85785f5f95af5ba3906eedb2d931c24e69824a89ea65dba4e813b?s=96&d=404",- ),- );+ },+ {+ name: "requests the size the caller asks for",+ email: "[email protected]",+ size: 160,+ expected:+ "https://www.gravatar.com/avatar/b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514?s=160&d=404",+ },+ ])("$name", async ({ email, size, expected }) => {+ const { result } = renderHook(() => useGravatarUrl(email, size));+ await waitFor(() => expect(result.current).toBe(expected));});it("clears the previous URL while a changed email is hashing", async () => {diff --git a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.tsindex c0bc24c33e5a..1474073ead32 100644--- a/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts+++ b/products/desktop/packages/ui/src/features/auth/useGravatarUrl.ts@@ -1,10 +1,15 @@import { useEffect, useState } from "react";+const DEFAULT_GRAVATAR_SIZE = 96;+// Gravatar accepts a SHA-256 hex hash of the lowercased, trimmed email, so we hash// with the built-in Web Crypto API rather than pulling in an md5 dependency. `d=404`// 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): Promise<string | undefined> {+async function gravatarUrlForEmail(+ email: string,+ size: number,+): Promise<string | undefined> {if (!globalThis.crypto?.subtle) return undefined;const normalized = email.trim().toLowerCase();const bytes = new TextEncoder().encode(normalized);@@ -12,10 +17,13 @@ async function gravatarUrlForEmail(email: string): Promise<string | undefined> {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`;+ return `https://www.gravatar.com/avatar/${hash}?s=${size}&d=404`;}-export function useGravatarUrl(email?: string | null): string | undefined {+export function useGravatarUrl(+ email?: string | null,+ size: number = DEFAULT_GRAVATAR_SIZE,+): string | undefined {const [url, setUrl] = useState<string | undefined>(undefined);useEffect(() => {@@ -27,7 +35,7 @@ export function useGravatarUrl(email?: string | null): string | undefined {// 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)+ gravatarUrlForEmail(email, size).then((next) => {if (!cancelled) setUrl(next);})@@ -37,7 +45,7 @@ export function useGravatarUrl(email?: string | null): string | undefined {return () => {cancelled = true;};- }, [email]);+ }, [email, size]);return url;}diff --git a/products/desktop/packages/ui/src/features/auth/useImageProbe.test.ts b/products/desktop/packages/ui/src/features/auth/useImageProbe.test.tsnew file mode 100644index 000000000000..17e7296a1370--- /dev/null+++ b/products/desktop/packages/ui/src/features/auth/useImageProbe.test.ts@@ -0,0 +1,66 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { type ImageProbe, useImageProbe } from "./useImageProbe";++class FakeImage {+ static instances: FakeImage[] = [];+ onload: (() => void) | null = null;+ onerror: (() => void) | null = null;+ src = "";++ constructor() {+ FakeImage.instances.push(this);+ }+}++const FIRST_URL = "https://example.com/avatar.png";+const RECHECK_URL = "https://example.com/avatar.png?_=2";++describe("useImageProbe", () => {+ beforeEach(() => {+ FakeImage.instances = [];+ vi.stubGlobal("Image", FakeImage);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it.each<{ name: string; settle: "onload" | "onerror"; expected: ImageProbe }>(+ [+ {+ name: "swaps to the new picture once the re-check loads",+ settle: "onload",+ expected: { result: "loaded", url: RECHECK_URL, loading: false },+ },+ {+ name: "drops the picture when the re-check fails",+ settle: "onerror",+ expected: { result: "failed", url: undefined, loading: false },+ },+ ],+ )(+ "keeps the last picture while re-checking, then $name",+ ({ settle, expected }) => {+ const { result, rerender } = renderHook(({ url }) => useImageProbe(url), {+ initialProps: { url: FIRST_URL },+ });+ act(() => FakeImage.instances[0].onload?.());+ expect(result.current).toEqual({+ result: "loaded",+ url: FIRST_URL,+ loading: false,+ });++ rerender({ url: RECHECK_URL });+ expect(result.current).toEqual({+ result: "loaded",+ url: FIRST_URL,+ loading: true,+ });++ act(() => FakeImage.instances[1][settle]?.());+ expect(result.current).toEqual(expected);+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/auth/useImageProbe.ts b/products/desktop/packages/ui/src/features/auth/useImageProbe.tsnew file mode 100644index 000000000000..6f6c317a3439--- /dev/null+++ b/products/desktop/packages/ui/src/features/auth/useImageProbe.ts@@ -0,0 +1,45 @@+import { useEffect, useState } from "react";++export type ImageProbeResult = "unknown" | "loaded" | "failed";++export interface ImageProbe {+ result: ImageProbeResult;+ url: string | undefined;+ loading: boolean;+}++const INITIAL_PROBE: ImageProbe = {+ result: "unknown",+ url: undefined,+ loading: false,+};++export function useImageProbe(url: string | undefined): ImageProbe {+ const [probe, setProbe] = useState<ImageProbe>(INITIAL_PROBE);++ useEffect(() => {+ if (!url) {+ setProbe(INITIAL_PROBE);+ return;+ }+ let cancelled = false;+ setProbe((previous) => ({ ...previous, loading: true }));+ const image = new Image();+ image.onload = () => {+ if (!cancelled) setProbe({ result: "loaded", url, loading: false });+ };+ image.onerror = () => {+ if (!cancelled) {+ setProbe({ result: "failed", url: undefined, loading: false });+ }+ };+ image.src = url;+ return () => {+ cancelled = true;+ image.onload = null;+ image.onerror = null;+ };+ }, [url]);++ return probe;+}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.tsxnew file mode 100644index 000000000000..46e24ddc204f--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.stories.tsx@@ -0,0 +1,59 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { AccountSettingsView } from "./AccountSettings";++const user = {+ uuid: "0192b3a4-5c6d-7e8f-9a0b-1c2d3e4f5a6b",+ email: "[email protected]",+ first_name: "Max",+ last_name: "Hedgehog",+};++const SAMPLE_PICTURE = `data:image/svg+xml;utf8,${encodeURIComponent(+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 144 144"><rect width="144" height="144" fill="#f54e00"/><circle cx="72" cy="56" r="28" fill="#fdfdfc"/><path d="M20 144c0-32 24-52 52-52s52 20 52 52z" fill="#fdfdfc"/></svg>',+)}`;++const meta: Meta<typeof AccountSettingsView> = {+ title: "Settings/AccountSettings",+ component: AccountSettingsView,+ args: {+ user,+ status: "found",+ checking: false,+ imageUrl: SAMPLE_PICTURE,+ accountUrl: "https://us.posthog.com/settings/user",+ onRefresh: () => {},+ onOpenGravatar: () => {},+ },+ decorators: [+ (Story) => (+ <div className="mx-auto my-8 max-w-[800px] px-6">+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof AccountSettingsView>;++export const WithGravatar: Story = {};++export const NoGravatar: Story = {+ args: { status: "missing", imageUrl: undefined },+};++export const Checking: Story = {+ args: { status: "unknown", checking: true, imageUrl: undefined },+};++export const Refreshing: Story = {+ args: { checking: true },+};++export const EmailOnly: Story = {+ args: {+ status: "missing",+ imageUrl: undefined,+ user: { uuid: user.uuid, email: "[email protected]" },+ },+};diff --git a/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.tsxnew file mode 100644index 000000000000..76098e924cf5--- /dev/null+++ b/products/desktop/packages/ui/src/features/settings/sections/AccountSettings.tsx@@ -0,0 +1,225 @@+import { ArrowSquareOut, ArrowsClockwise, Camera } from "@phosphor-icons/react";+import { avatarColor } from "@posthog/core/auth/avatarColor";+import { buildPostHogUrl } from "@posthog/core/settings/posthogUrl";+import { Avatar, AvatarFallback, Button, cn } from "@posthog/quill";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+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";+import { useGravatarUrl } from "@posthog/ui/features/auth/useGravatarUrl";+import {+ type ImageProbeResult,+ useImageProbe,+} from "@posthog/ui/features/auth/useImageProbe";+import { getUserInitials } from "@posthog/ui/features/auth/userInitials";+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";+import {+ SettingsCard,+ SettingsCardRow,+ SettingsSection,+} from "@posthog/ui/features/settings/components/SettingsCard";+import { Tooltip } from "@posthog/ui/primitives/Tooltip";+import { useCallback, useState } from "react";++const GRAVATAR_MANAGE_URL = "https://gravatar.com/profile/avatars";+const GRAVATAR_IMAGE_SIZE = 144;++export type ProfilePictureStatus = "unknown" | "found" | "missing";++interface ProfilePictureRowProps {+ user: AvatarPerson;+ imageUrl?: string;+ status: ProfilePictureStatus;+ checking: boolean;+ onRefresh: () => void;+ onOpenGravatar: () => void;+}++function profilePictureDescription(+ status: ProfilePictureStatus,+ email: string,+): string {+ switch (status) {+ case "unknown":+ return `Checking Gravatar for ${email}`;+ case "found":+ return `Comes from Gravatar, matched to ${email}. Change it there, then refresh to see it here.`;+ case "missing":+ return `No picture yet. Add one on Gravatar for ${email} and it shows here and anywhere teammates see you.`;+ }+}++function probeStatus(result: ImageProbeResult): ProfilePictureStatus {+ switch (result) {+ case "loaded":+ return "found";+ case "failed":+ return "missing";+ case "unknown":+ return "unknown";+ }+}++export function ProfilePictureRow({+ user,+ imageUrl,+ status,+ checking,+ onRefresh,+ onOpenGravatar,+}: ProfilePictureRowProps) {+ const name = userDisplayName(user);+ const color = avatarColor(user.uuid ?? user.email ?? name);+ const gravatarActionLabel =+ status === "found" ? "Change on Gravatar" : "Add on Gravatar";++ return (+ <div className="flex flex-wrap items-center gap-4 px-3.5 py-3">+ <button+ type="button"+ aria-label={`${gravatarActionLabel} (opens gravatar.com)`}+ data-attr="settings-profile-picture-avatar"+ onClick={onOpenGravatar}+ className="group relative shrink-0 cursor-pointer rounded-(--radius-3) border-0 bg-transparent p-0 focus-visible:outline-(--accent-8) focus-visible:outline-2 focus-visible:outline-offset-2"+ >+ <Avatar+ className={cn(+ "rounded-(--radius-3) font-medium text-xl [--avatar-size:4.5rem]",+ status === "missing" &&+ "outline-dashed outline-(--gray-8) outline-1 outline-offset-2",+ )}+ >+ <AvatarFallback+ style={{ backgroundColor: color.bg, color: color.text }}+ >+ {getUserInitials(user)}+ </AvatarFallback>+ {imageUrl ? (+ <img+ src={imageUrl}+ alt=""+ className="absolute inset-0 size-full object-cover"+ />+ ) : null}+ </Avatar>+ <span+ aria-hidden+ className="pointer-events-none absolute inset-0 flex items-center justify-center rounded-(--radius-3) bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100 motion-reduce:transition-none"+ >+ <Camera size={20} weight="fill" />+ </span>+ </button>++ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="font-medium text-[13px] text-foreground leading-snug">+ Profile picture+ </span>+ <span className="min-h-[2lh] text-[12px] text-muted-foreground leading-snug">+ {profilePictureDescription(status, user.email ?? "your email")}+ </span>+ </div>++ <div className="flex shrink-0 items-center gap-1.5">+ <Tooltip content="Check Gravatar again">+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ aria-label="Check Gravatar again"+ data-attr="settings-profile-picture-refresh"+ disabled={checking}+ onClick={onRefresh}+ >+ <ArrowsClockwise+ size={12}+ className={cn(checking && "motion-safe:animate-spin")}+ />+ </Button>+ </Tooltip>+ <Button+ type="button"+ variant="outline"+ size="sm"+ data-attr="settings-profile-picture-gravatar"+ onClick={onOpenGravatar}+ >+ {gravatarActionLabel}+ <ArrowSquareOut size={12} />+ </Button>+ </div>+ </div>+ );+}++interface AccountSettingsViewProps extends ProfilePictureRowProps {+ accountUrl: string | null;+}++export function AccountSettingsView({+ accountUrl,+ ...pictureProps+}: AccountSettingsViewProps) {+ return (+ <SettingsSection+ label="Account"+ description="Who you are signed in as and how you appear to teammates"+ >+ <SettingsCard>+ <ProfilePictureRow {...pictureProps} />+ <SettingsCardRow+ label="PostHog account"+ description="Account and billing details are managed on PostHog"+ >+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={!accountUrl}+ onClick={() => {+ if (accountUrl) window.open(accountUrl, "_blank");+ }}+ >+ Manage+ <ArrowSquareOut size={12} />+ </Button>+ </SettingsCardRow>+ </SettingsCard>+ </SettingsSection>+ );+}++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 probe = useImageProbe(candidateUrl);++ const handleRefresh = useCallback(() => {+ setRefreshedAt(Date.now());+ }, []);++ const handleOpenGravatar = useCallback(() => {+ window.open(GRAVATAR_MANAGE_URL, "_blank");+ }, []);++ if (!user) return null;++ return (+ <AccountSettingsView+ user={user}+ imageUrl={probe.url}+ status={probeStatus(probe.result)}+ checking={probe.loading || !candidateUrl}+ onRefresh={handleRefresh}+ onOpenGravatar={handleOpenGravatar}+ accountUrl={buildPostHogUrl("/settings/user", cloudRegion)}+ />+ );+}diff --git a/products/desktop/packages/ui/src/features/settings/sections/GeneralSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/GeneralSettings.tsxindex 6ee1ffc7d005..96f547e0b89a 100644--- a/products/desktop/packages/ui/src/features/settings/sections/GeneralSettings.tsx+++ b/products/desktop/packages/ui/src/features/settings/sections/GeneralSettings.tsx@@ -1,15 +1,12 @@-import { ArrowSquareOut } from "@phosphor-icons/react";-import { buildPostHogUrl } from "@posthog/core/settings/posthogUrl";import { useServiceOptional } from "@posthog/di/react";import { useHostTRPC } from "@posthog/host-router/react";-import { Button, Switch } from "@posthog/quill";+import { Switch } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared";import {EFFORT_LEVEL_DOCS_URLS,EFFORT_LEVEL_LABELS,EFFORT_LEVELS,} from "@posthog/shared/domain-types";-import { useAuthStateValue } from "@posthog/ui/features/auth/store";import {MISSION_CONTROL_CLIENT,type MissionControlClient,@@ -26,6 +23,7 @@ import {import { SettingsSegmented } from "@posthog/ui/features/settings/components/SettingsSegmented";import { SettingsSelect } from "@posthog/ui/features/settings/components/SettingsSelect";import { ThemePicker } from "@posthog/ui/features/settings/components/ThemePicker";+import { AccountSection } from "@posthog/ui/features/settings/sections/AccountSettings";import { UpdatesSection } from "@posthog/ui/features/settings/sections/UpdatesSettings";import {type AutoConvertLongText,@@ -59,10 +57,6 @@ const MESSAGING_MODE_OPTIONS = [export function GeneralSettings() {const hostTRPC = useHostTRPC();- const isAuthenticated = useAuthStateValue(- (state) => state.status === "authenticated",- );- const cloudRegion = useAuthStateValue((state) => state.cloudRegion);const theme = useThemeStore((state) => state.theme);const setTheme = useThemeStore((state) => state.setTheme);@@ -250,31 +244,9 @@ export function GeneralSettings() {[sendMessagesWith, setSendMessagesWith],);- const accountUrl = buildPostHogUrl("/settings/user", cloudRegion);-return (<div className="flex flex-col gap-7">- {isAuthenticated && (- <SettingsCard>- <SettingsCardRow- label="PostHog account"- description="Account and billing details are managed on PostHog"- >- <Button- type="button"- variant="outline"- size="sm"- disabled={!accountUrl}- onClick={() => {- if (accountUrl) window.open(accountUrl, "_blank");- }}- >- Manage- <ArrowSquareOut size={12} />- </Button>- </SettingsCardRow>- </SettingsCard>- )}+ <AccountSection /><SettingsSectionlabel="Appearance"diff --git a/products/desktop/packages/ui/src/features/settings/settingsSearch.ts b/products/desktop/packages/ui/src/features/settings/settingsSearch.tsindex 293e2d79d6b8..225b94ac1f4d 100644--- a/products/desktop/packages/ui/src/features/settings/settingsSearch.ts+++ b/products/desktop/packages/ui/src/features/settings/settingsSearch.ts@@ -18,6 +18,11 @@ export const SETTINGS_SEARCH_INDEX: SettingsSearchEntry[] = [label: "Theme",keywords: ["appearance", "light", "dark", "system"],},+ {+ category: "general",+ label: "Profile picture",+ keywords: ["gravatar", "avatar", "photo", "picture", "account"],+ },{category: "general",label: "PostHog account",