From 539e0601d5f14b350a8ca20c408326058efa05b3 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Thu, 16 Jul 2026 19:24:10 -0700 Subject: [PATCH] fix(github): render GitHub Enterprise PR avatars via API avatar_url (#9107) Co-authored-by: Claude Opus 4.8 (1M context) Co-authored-by: davkim1030 --- src/main/github/client.ts | 35 +++-- src/main/github/work-item-details.test.ts | 112 ++++++++++++++ src/main/github/work-item-details.ts | 138 ++++++++++++++++-- .../src/components/GitHubItemDialog.tsx | 13 +- .../src/components/PullRequestPage.tsx | 23 +-- src/renderer/src/components/TaskPage.tsx | 18 +-- .../github/github-user-avatar.test.tsx | 107 ++++++++++++++ .../components/github/github-user-avatar.tsx | 104 +++++++++++++ .../repro-8784-ghe-avatar-fallback.test.ts | 55 +++++++ src/shared/types.ts | 5 + 10 files changed, 547 insertions(+), 63 deletions(-) create mode 100644 src/renderer/src/components/github/github-user-avatar.test.tsx create mode 100644 src/renderer/src/components/github/github-user-avatar.tsx create mode 100644 src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 54572bd40..ac8566983 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -485,16 +485,32 @@ function mapIssueWorkItem(item: Record): MainWorkItem { .filter(Boolean) : [], updatedAt: String(item.updated_at ?? item.updatedAt ?? ''), - author: - typeof item.user === 'object' && item.user !== null && 'login' in item.user - ? String((item.user as { login?: unknown }).login ?? '') - : typeof item.author === 'object' && item.author !== null && 'login' in item.author - ? String((item.author as { login?: unknown }).login ?? '') - : null, + ...authorFieldsFromUnknown(item), ...(item.assignees !== undefined ? { assignees: usersFromUnknown(item.assignees) } : {}) } } +/** + * Derive both the author login and its API avatar_url in one place so GHE + * avatars render (the login-only `github.com/{login}.png` URL 404s on GHE). + * + * REST exposes `user.avatar_url`; gh/GraphQL expose `author.avatarUrl`. `gh pr + * view` omits the avatar entirely, so authorAvatarUrl is left undefined and the + * UI falls back to the login URL then a placeholder. See #8784. + */ +function authorFieldsFromUnknown( + item: Record +): Pick { + const user = userFromUnknown(item.user ?? item.author) + if (!user) { + return { author: null } + } + return { + author: user.login, + ...(user.avatarUrl ? { authorAvatarUrl: user.avatarUrl } : {}) + } +} + function extractHeadOwnerLogin(item: Record): string | null { // gh CLI `pr list --json headRepositoryOwner` shape: { login } if (typeof item.headRepositoryOwner === 'object' && item.headRepositoryOwner !== null) { @@ -746,12 +762,7 @@ function mapPullRequestWorkItem( .filter(Boolean) : [], updatedAt: String(item.updated_at ?? item.updatedAt ?? ''), - author: - typeof item.user === 'object' && item.user !== null && 'login' in item.user - ? String((item.user as { login?: unknown }).login ?? '') - : typeof item.author === 'object' && item.author !== null && 'login' in item.author - ? String((item.author as { login?: unknown }).login ?? '') - : null, + ...authorFieldsFromUnknown(item), branchName: typeof item.head === 'object' && item.head !== null && 'ref' in item.head ? String((item.head as { ref?: unknown }).ref ?? '') diff --git a/src/main/github/work-item-details.test.ts b/src/main/github/work-item-details.test.ts index 6d3d14c99..4fd21131c 100644 --- a/src/main/github/work-item-details.test.ts +++ b/src/main/github/work-item-details.test.ts @@ -216,6 +216,56 @@ describe('getWorkItemDetails', () => { expect(details?.participants?.[0]?.login).toBe('issue-author') }) + it('enriches a non-participating assignee avatar from the GraphQL assignees connection', async () => { + // Why: a GHE assignee who never commented is absent from `participants`, so + // the enrichment must also draw avatars from the `assignees` connection or + // item.assignees keeps the blank avatar `gh` returns. + getWorkItemMock.mockResolvedValueOnce({ + id: 'issue:924', + type: 'issue', + number: 924, + title: 'Assignee avatar', + state: 'open', + url: 'https://github.com/acme/widgets/issues/924', + labels: [], + updatedAt: '2026-04-01T00:00:00Z', + author: 'issue-author', + assignees: [{ login: 'ghe-assignee', name: 'GHE Assignee', avatarUrl: '' }] + }) + getIssueOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + data: { + repository: { + issue: { + body: 'Issue body', + assignees: { + nodes: [ + { + login: 'ghe-assignee', + name: 'GHE Assignee', + avatarUrl: 'https://ghe.example.com/avatars/ghe-assignee' + } + ] + }, + participants: { nodes: [{ login: 'issue-author', avatarUrl: 'https://x/y' }] }, + comments: { nodes: [] } + } + } + } + }) + }) + .mockResolvedValueOnce({ stdout: '' }) + + const details = await getWorkItemDetails('/repo-root', 924, 'issue') + + expect(details?.item.assignees?.[0]).toMatchObject({ + login: 'ghe-assignee', + avatarUrl: 'https://ghe.example.com/avatars/ghe-assignee' + }) + }) + it('caps issue timeline pagination by supported activity items', async () => { getWorkItemMock.mockResolvedValueOnce({ id: 'issue:923', @@ -568,4 +618,66 @@ describe('getWorkItemDetails', () => { expect(details?.filesUnavailable).toBe(false) expect(details?.files).toEqual([]) }) + + // Why: `gh pr view` omits avatar_url, so the login-based github.com URL 404s on + // GHE. getWorkItemDetails must resolve author/reviewer/assignee avatars via the + // GraphQL user(login:) batch and stamp them onto the returned item. See #8784. + it('enriches PR author, reviewer, and assignee avatars from the GraphQL user lookup', async () => { + getWorkItemMock.mockResolvedValueOnce({ + id: 'pr:1102', + type: 'pr', + number: 1102, + title: 'Enterprise PR', + state: 'open', + url: 'https://ghe.example.com/acme/widgets/pull/1102', + labels: [], + updatedAt: '2026-07-11T00:00:00Z', + author: 'seah', + reviewRequests: [{ login: 'ludi', name: null, avatarUrl: '' }], + latestReviews: [{ login: 'inho', state: 'APPROVED', avatarUrl: '' }], + // A default `u/0` placeholder must be replaced by the resolved avatar. + assignees: [{ login: 'seah', name: 'Seah', avatarUrl: 'https://avatars.example.com/u/0?v=4' }] + }) + getOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) + getPRCommentsMock.mockResolvedValue([]) + getPRChecksMock.mockResolvedValue([]) + const avatars: Record = { + seah: 'https://avatars.example.com/u/1?v=4', + ludi: 'https://avatars.example.com/u/2?v=4', + inho: 'https://avatars.example.com/u/3?v=4' + } + ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { + const target = args.at(-1) + if (target === 'repos/acme/widgets/pulls/1102') { + return { + stdout: JSON.stringify({ body: 'PR body', head: { sha: 'h' }, base: { sha: 'b' } }) + } + } + if (target === 'repos/acme/widgets/pulls/1102/files?per_page=100') { + return { stdout: '[]' } + } + const query = args.find((arg) => arg.startsWith('query=')) ?? '' + if (query.includes('user(login:')) { + // Return the aliased users the batch asked for, keyed by their login. + const data: Record = {} + let index = 0 + for (const login of Object.keys(avatars)) { + if (query.includes(`user(login: "${login}")`)) { + data[`u${index}`] = { login, name: null, avatarUrl: avatars[login] } + index += 1 + } + } + return { stdout: JSON.stringify({ data }) } + } + return { stdout: JSON.stringify({ data: {} }) } + }) + + const details = await getWorkItemDetails('/repo-root', 1102, 'pr') + + expect(details?.item.authorAvatarUrl).toBe(avatars.seah) + expect(details?.item.reviewRequests?.[0]?.avatarUrl).toBe(avatars.ludi) + expect(details?.item.latestReviews?.[0]?.avatarUrl).toBe(avatars.inho) + // The default u/0 placeholder is overridden by the resolved avatar. + expect(details?.item.assignees?.[0]?.avatarUrl).toBe(avatars.seah) + }) }) diff --git a/src/main/github/work-item-details.ts b/src/main/github/work-item-details.ts index 9aa2de2b2..bd126641f 100644 --- a/src/main/github/work-item-details.ts +++ b/src/main/github/work-item-details.ts @@ -85,7 +85,7 @@ const ISSUE_DETAILS_QUERY = `query($owner: String!, $repo: String!, $number: Int repository(owner: $owner, name: $repo) { issue(number: $number) { body - assignees(first: 50) { nodes { login } } + assignees(first: 50) { nodes { login avatarUrl(size: 48) ... on User { name } } } participants(first: 100) { nodes { login avatarUrl(size: 48) ... on User { name } } } @@ -111,7 +111,7 @@ type GraphQLIssueDetailsResponse = { repository?: { issue?: { body?: string | null - assignees?: { nodes?: { login?: string }[] } + assignees?: { nodes?: { login?: string; avatarUrl?: string; name?: string | null }[] } participants?: { nodes?: GitHubAssignableUser[] } comments?: { nodes?: { @@ -323,6 +323,12 @@ async function getIssueTimelineItems( } } +/** + * Fetch an issue's body, comments, assignees, participants, and timeline in a + * single GraphQL round-trip. Returns null on any partial error so the caller + * falls back to the strict REST path. Assignee/participant avatars are resolved + * here so GitHub Enterprise users don't render blank. + */ async function getIssueDetailsViaGraphQL( repoPath: string, issueNumber: number, @@ -332,6 +338,10 @@ async function getIssueDetailsViaGraphQL( body: string comments: PRComment[] assignees: string[] + // Avatar-bearing assignees, kept separate from the `assignees` login list so + // callers that only need logins are unaffected; used to enrich assignee + // avatars that `gh` leaves blank (notably GitHub Enterprise users). + assigneeUsers: GitHubAssignableUser[] participants: GitHubAssignableUser[] timelineItems: GitHubIssueTimelineItem[] } | null> { @@ -386,9 +396,16 @@ async function getIssueDetailsViaGraphQL( url: c.url ?? '', isBot: c.author?.__typename === 'Bot' })) - const assignees = (issue.assignees?.nodes ?? []) - .map((a) => a.login) - .filter((login): login is string => Boolean(login)) + const assigneeUsers: GitHubAssignableUser[] = (issue.assignees?.nodes ?? []) + .filter((a): a is { login: string; avatarUrl?: string; name?: string | null } => + Boolean(a.login) + ) + .map((a) => ({ + login: a.login, + name: a.name ?? null, + avatarUrl: a.avatarUrl ?? '' + })) + const assignees = assigneeUsers.map((a) => a.login) const participants: GitHubAssignableUser[] = (issue.participants?.nodes ?? []) .filter((u) => Boolean(u.login)) .map((u) => ({ @@ -401,6 +418,7 @@ async function getIssueDetailsViaGraphQL( body: issue.body ?? '', comments, assignees, + assigneeUsers, participants, timelineItems } @@ -877,6 +895,11 @@ async function getGitHubUsersByLogin( return [] } if (rateLimitGuard('graphql').blocked) { + // Why: surface the skip. Callers degrade silently to login-based avatar URLs + // (blank on GHE), so without this log "why are avatars missing" is untraceable. + console.warn( + `getGitHubUsersByLogin skipped: GraphQL rate-limit budget exhausted (${uniqueLogins.length} logins unresolved)` + ) return [] } const fields = uniqueLogins @@ -921,19 +944,100 @@ async function getGitHubUsersByLogin( } } +/** + * Stamp GraphQL-resolved avatars onto a work item's author, reviewers, review + * requests, latest reviews, and assignees. + * + * The work item's users come from `gh pr view`, which omits avatar_url. On + * GitHub Enterprise the login-based `github.com/{login}.png` URL 404s, so those + * avatars render blank while comment avatars (fetched via GraphQL) work. + * `knownUsers` (participants + the mention-author batch, which already includes + * the item's reviewers/assignees) carries the resolved avatars, so we apply + * them without any extra round-trip. See #8784. + */ +function enrichItemDisplayAvatars( + item: Omit, + knownUsers: GitHubAssignableUser[] +): Omit { + const avatarByLogin = new Map() + for (const user of knownUsers) { + if (user.login && user.avatarUrl) { + avatarByLogin.set(user.login.toLowerCase(), user.avatarUrl) + } + } + if (avatarByLogin.size === 0) { + return item + } + // Why: prefer the GraphQL-resolved avatar over whatever `gh` returned. `gh pr + // view` often yields an empty avatar or the default `u/0` placeholder for + // enterprise users; the resolved avatar is the authoritative one for that + // login. Fall back to the original only when the lookup found nothing. + const avatarFor = (login: string): string | undefined => avatarByLogin.get(login.toLowerCase()) + const resolvedAvatar = (login: string, existing?: string | null): string | undefined => + avatarFor(login) || existing || undefined + // Callers coalesce a missing result to the field's "no avatar" sentinel ('' + // for GitHubAssignableUser, null for GitHubPRReviewSummary); GitHubUserAvatar + // treats both as falsy and falls back to the login URL then initials. + const authorAvatarUrl = (item.author ? avatarFor(item.author) : undefined) || item.authorAvatarUrl + return { + ...item, + ...(authorAvatarUrl ? { authorAvatarUrl } : {}), + ...(item.reviewRequests + ? { + reviewRequests: item.reviewRequests.map((user) => ({ + ...user, + avatarUrl: resolvedAvatar(user.login, user.avatarUrl) ?? '' + })) + } + : {}), + ...(item.latestReviews + ? { + latestReviews: item.latestReviews.map((review) => ({ + ...review, + avatarUrl: resolvedAvatar(review.login, review.avatarUrl) ?? null + })) + } + : {}), + ...(item.assignees + ? { + assignees: item.assignees.map((user) => ({ + ...user, + avatarUrl: resolvedAvatar(user.login, user.avatarUrl) ?? '' + })) + } + : {}) + } +} + async function getMentionParticipants( repoPath: string, - item: Pick, + item: Pick< + GitHubWorkItem, + 'author' | 'number' | 'type' | 'reviewRequests' | 'latestReviews' | 'assignees' + >, comments: PRComment[], participants: GitHubAssignableUser[], connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} ): Promise { - const visibleLogins = [item.author ?? '', ...comments.map((comment) => comment.author)] - // Why: one aliased GraphQL query returns login/name/avatarUrl for every - // mentioned author in a single round-trip. The previous REST fan-out - // (/users/) returned the same fields but cost one rate-limit point - // per user. + // Why: resolve mention authors AND the item's reviewers/assignees in ONE + // aliased GraphQL round-trip. Folding the display users in here means the + // caller can reuse this result to stamp avatars (see enrichItemDisplayAvatars) + // without a second, separately rate-limited lookup — which is what made GHE + // reviewer/assignee avatars resolve intermittently. See #8784. + // Why: order the always-visible display users (author, reviewers, assignees) + // before comment authors so the 40-login cap in getGitHubUsersByLogin never + // drops a reviewer/assignee avatar on a PR with many commenters. On a PR with + // 40+ distinct participants the trailing comment authors are dropped from this + // batch and lose only their @mention-suggestion avatar; rendered comment + // avatars are unaffected (they carry their own avatarUrl from the comment). + const visibleLogins = [ + item.author ?? '', + ...(item.reviewRequests ?? []).map((user) => user.login), + ...(item.latestReviews ?? []).map((review) => review.login), + ...(item.assignees ?? []).map((user) => user.login), + ...comments.map((comment) => comment.author) + ] const graphQlUsers = await getGitHubUsersByLogin( repoPath, visibleLogins, @@ -1007,7 +1111,13 @@ export async function getWorkItemDetails( ) if (collapsed) { return { - item, + // Include assigneeUsers: a non-participating assignee is absent from + // the participants connection, so without them item.assignees keeps a + // blank/placeholder avatar (common for GitHub Enterprise users). + item: enrichItemDisplayAvatars(item, [ + ...collapsed.participants, + ...collapsed.assigneeUsers + ]), body: collapsed.body, comments: collapsed.comments, assignees: collapsed.assignees, @@ -1030,7 +1140,7 @@ export async function getWorkItemDetails( localGitOptions ) return { - item, + item: enrichItemDisplayAvatars(item, mentionParticipants), body, comments, assignees, @@ -1064,7 +1174,7 @@ export async function getWorkItemDetails( ]) return { - item, + item: enrichItemDisplayAvatars(item, mentionParticipants), body, comments, headSha: shas?.headSha, diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index d076f0b32..6f6b7fb24 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -181,7 +181,7 @@ import { filterGitHubPRReviewerCandidates, getGitHubPRReviewerQueryState } from '@/components/github/github-pr-reviewer-candidate-filter' -import { githubAvatarUrl } from '@/components/github/github-issue-comment-helpers' +import { GitHubUserAvatar } from '@/components/github/github-user-avatar' import { presentGitHubPRMergeState } from '@/components/github-pr-merge-state' import { GITHUB_PR_MERGE_METHOD_LABELS, @@ -421,16 +421,7 @@ function ReviewerAvatar({ login: string avatarUrl: string }): React.JSX.Element { - return ( - - ) + return } function mergeReviewerSuggestions( diff --git a/src/renderer/src/components/PullRequestPage.tsx b/src/renderer/src/components/PullRequestPage.tsx index d807dacf8..b53ba3546 100644 --- a/src/renderer/src/components/PullRequestPage.tsx +++ b/src/renderer/src/components/PullRequestPage.tsx @@ -157,7 +157,7 @@ import { filterGitHubPRReviewerCandidates, getGitHubPRReviewerQueryState } from '@/components/github/github-pr-reviewer-candidate-filter' -import { githubAvatarUrl } from '@/components/github/github-issue-comment-helpers' +import { GitHubUserAvatar } from '@/components/github/github-user-avatar' import { filterGitHubMentionOptions } from '@/components/github/github-mention-option-filter' import { getCommentBodySubmitState, @@ -468,16 +468,7 @@ function ReviewerAvatar({ login: string avatarUrl: string }): React.JSX.Element { - return ( - - ) + return } function mergeReviewerSuggestions( @@ -7148,12 +7139,10 @@ export default function PullRequestPage({ {workItem.author ? ( - ) : null} diff --git a/src/renderer/src/components/TaskPage.tsx b/src/renderer/src/components/TaskPage.tsx index af47d2673..e43cc6a80 100644 --- a/src/renderer/src/components/TaskPage.tsx +++ b/src/renderer/src/components/TaskPage.tsx @@ -133,6 +133,7 @@ import { } from '../../../shared/linear-links' import PRFilterDropdowns, { type PRFilterChange } from '@/components/github/PRFilterDropdowns' import { GitHubMarkdownComposer } from '@/components/github/GitHubMarkdownComposer' +import { GitHubUserAvatar } from '@/components/github/github-user-avatar' import { buildGitHubRepoUrl, parseGitHubIssueOrPRLink } from '@/lib/github-links' import { findGithubWorkItemWorkspaceAttachment, @@ -1520,17 +1521,16 @@ function ReviewChipAvatar({ reviewer: GitHubPRPrimaryReviewer | null }): React.JSX.Element { if (reviewer?.login) { - // Why: `gh pr list --json reviewRequests` can return only logins; GitHub's - // public avatar endpoint keeps the list visual aligned with assignee cells. - const avatarUrl = reviewer.avatarUrl || `https://github.com/${reviewer.login}.png?size=40` + // Why: `gh pr list --json reviewRequests` can return only logins. Prefer the + // API avatar_url so GHE renders; GitHubUserAvatar falls back to the login URL + // and then an initials placeholder when no avatar loads. See #8784. return ( - ) } diff --git a/src/renderer/src/components/github/github-user-avatar.test.tsx b/src/renderer/src/components/github/github-user-avatar.test.tsx new file mode 100644 index 000000000..5eeed1564 --- /dev/null +++ b/src/renderer/src/components/github/github-user-avatar.test.tsx @@ -0,0 +1,107 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, describe, expect, it } from 'vitest' +import { GitHubUserAvatar, resolveGitHubUserAvatarSrc } from './github-user-avatar' + +function render(node: React.JSX.Element): { root: Root; container: HTMLDivElement } { + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + act(() => { + root.render(node) + }) + return { root, container } +} + +describe('GitHubUserAvatar', () => { + let root: Root | null = null + let container: HTMLDivElement | null = null + + afterEach(() => { + act(() => root?.unmount()) + container?.remove() + root = null + container = null + }) + + it('renders the API avatar_url when provided (works for github.com and GHE)', () => { + const url = 'https://avatars.example.com/u/42?u=hash&v=4' + ;({ root, container } = render()) + const img = container.querySelector('img') + expect(img?.getAttribute('src')).toBe(url) + }) + + it('falls back to the login URL when no avatar_url is available', () => { + ;({ root, container } = render()) + const img = container.querySelector('img') + expect(img?.getAttribute('src')).toBe('https://github.com/octocat.png?size=64') + }) + + it('degrades to an initials placeholder when the image fails to load (GHE 404)', () => { + ;({ root, container } = render( + + )) + const img = container.querySelector('img') + expect(img).not.toBeNull() + act(() => { + img?.dispatchEvent(new Event('error')) + }) + expect(container.querySelector('img')).toBeNull() + expect(container.textContent).toBe('AL') + }) + + it('skips leading non-BMP chars so initials never render a broken surrogate', () => { + ;({ root, container } = render()) + act(() => { + container?.querySelector('img')?.dispatchEvent(new Event('error')) + }) + // Emoji word is skipped entirely rather than split into a broken half. + expect(container.textContent).toBe('D') + }) + + it('derives initials from the login when no name is given', () => { + ;({ root, container } = render()) + act(() => { + container?.querySelector('img')?.dispatchEvent(new Event('error')) + }) + expect(container.textContent).toBe('OC') + }) + + it('retries when avatarUrl changes after an earlier src failed (late-arriving avatar)', () => { + // Why: PR detail enrichment supplies avatar_url after first paint. A row that + // 404s on the early login-based URL must recover once the real URL lands. + ;({ root, container } = render()) + // First src is the login fallback; simulate the GHE 404. + act(() => { + container?.querySelector('img')?.dispatchEvent(new Event('error')) + }) + expect(container.querySelector('img')).toBeNull() + // Enriched avatar_url arrives → component must render the new image, not the + // latched placeholder. + const url = 'https://avatars.example.com/u/7?v=4' + act(() => { + root?.render() + }) + expect(container.querySelector('img')?.getAttribute('src')).toBe(url) + }) + + it('shows initials immediately when login and avatarUrl are both empty', () => { + ;({ root, container } = render()) + expect(container.querySelector('img')).toBeNull() + expect(container.textContent).toBe('AD') + }) +}) + +describe('resolveGitHubUserAvatarSrc', () => { + it('prefers trimmed API avatar over login.png', () => { + expect(resolveGitHubUserAvatarSrc('u', ' https://avatars.example.com/u/1?v=4 ')).toBe( + 'https://avatars.example.com/u/1?v=4' + ) + }) + + it('skips empty login so no github.com/.png request is built', () => { + expect(resolveGitHubUserAvatarSrc('', null)).toBeNull() + }) +}) diff --git a/src/renderer/src/components/github/github-user-avatar.tsx b/src/renderer/src/components/github/github-user-avatar.tsx new file mode 100644 index 000000000..385c7feda --- /dev/null +++ b/src/renderer/src/components/github/github-user-avatar.tsx @@ -0,0 +1,104 @@ +import { useState } from 'react' +import { cn } from '@/lib/utils' +import { githubAvatarUrl } from '@/components/github/github-issue-comment-helpers' + +/** + * Build a 1-2 character initials placeholder from a display name or login, + * used when no avatar image is available or the image fails to load. + */ +function initialsFor(login: string, name?: string | null): string { + const source = (name?.trim() || login).trim() + if (!source) { + return '?' + } + // Iterate by code point (not UTF-16 unit) and keep only letters/digits, so a + // display name that leads with an emoji or other non-BMP char yields clean + // initials instead of a broken surrogate half. Words that are all symbols are + // skipped; an all-symbol name falls back to '?'. + const alnum = (word: string): string[] => [...word].filter((ch) => /[\p{L}\p{N}]/u.test(ch)) + const parts = source.split(/\s+/).filter(Boolean) + const letters = + parts.length >= 2 + ? parts + .map((word) => alnum(word)[0]) + .filter(Boolean) + .slice(0, 2) + .join('') + : alnum(source).slice(0, 2).join('') + return letters.toUpperCase() || '?' +} + +/** + * Prefer the API `avatar_url`, then the public login.png URL. Empty/whitespace + * API values and empty logins never produce a bogus request. See #8784. + */ +export function resolveGitHubUserAvatarSrc( + login: string, + avatarUrl?: string | null +): string | null { + const fromApi = avatarUrl?.trim() + if (fromApi) { + return fromApi + } + const trimmedLogin = login.trim() + if (!trimmedLogin) { + return null + } + return githubAvatarUrl(trimmedLogin) +} + +/** + * Avatar for a GitHub user that renders correctly on github.com and GitHub + * Enterprise. GHE logins don't exist on github.com, so the login-based + * `github.com/{login}.png` URL 404s. We prefer the API-provided `avatarUrl` + * and, when it (or the login fallback) fails to load, degrade to an initials + * placeholder instead of a broken image. See #8784. + */ +export function GitHubUserAvatar({ + login, + name, + avatarUrl, + title, + className +}: { + login: string + name?: string | null + avatarUrl?: string | null + title?: string + className?: string +}): React.JSX.Element { + // Why: track the specific src that failed rather than a boolean. Avatar data + // arrives after the first paint (PR detail enrichment), so a row that 404s on + // the early login-based URL must retry once the real avatar_url lands — a + // latched boolean would keep showing the placeholder forever. See #8784. + const [failedSrc, setFailedSrc] = useState(null) + const src = resolveGitHubUserAvatarSrc(login, avatarUrl) + if (src && failedSrc !== src) { + return ( + setFailedSrc(src)} + className={cn( + 'shrink-0 rounded-full border border-border/50 bg-muted object-cover', + className + )} + /> + ) + } + return ( + + {initialsFor(login, name)} + + ) +} diff --git a/src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts b/src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts new file mode 100644 index 000000000..7b8312709 --- /dev/null +++ b/src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts @@ -0,0 +1,55 @@ +/** + * Issue #8784 — GHE PR avatars must prefer API avatar_url over github.com/{login}.png. + * + * Regression guard (was a repro that documented the broken path). After the fix: + * - resolveGitHubUserAvatarSrc prefers API URLs + * - PullRequestPage author uses authorAvatarUrl via GitHubUserAvatar + * - TaskPage ReviewChipAvatar no longer hardcodes github.com login.png + * + * Re-run: + * pnpm exec vitest run --config config/vitest.config.ts \ + * src/renderer/src/components/github/repro-8784-ghe-avatar-fallback.test.ts + */ +import { describe, expect, it } from 'vitest' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { githubAvatarUrl } from './github-issue-comment-helpers' +import { resolveGitHubUserAvatarSrc } from './github-user-avatar' + +describe('issue #8784 GHE avatar fallback (regression)', () => { + it('prefers API avatar_url over login.png (GHE healthy path)', () => { + const api = 'https://ghe.example.com/avatars/u/42?v=4' + expect(resolveGitHubUserAvatarSrc('enterprise-only-user', api)).toBe(api) + }) + + it('trims whitespace-only avatarUrl and falls back to login.png for github.com', () => { + expect(resolveGitHubUserAvatarSrc('octocat', ' ')).toBe( + 'https://github.com/octocat.png?size=64' + ) + expect(resolveGitHubUserAvatarSrc('octocat', null)).toBe(githubAvatarUrl('octocat')) + }) + + it('returns null when neither avatarUrl nor login is usable (no bogus request)', () => { + expect(resolveGitHubUserAvatarSrc('', '')).toBeNull() + expect(resolveGitHubUserAvatarSrc(' ', null)).toBeNull() + }) + + it('login-only fallback still hardcodes public github.com png (github.com path)', () => { + // Why: github.com users without avatar_url still use this; GHE relies on + // enrichment + image onError → initials when this 404s. + expect(githubAvatarUrl('corp-user')).toBe('https://github.com/corp-user.png?size=64') + }) + + it('source routes PR author/reviewer avatars through GitHubUserAvatar + authorAvatarUrl', () => { + const prPage = readFileSync(join(__dirname, '../PullRequestPage.tsx'), 'utf8') + expect(prPage).toMatch(/GitHubUserAvatar/) + expect(prPage).toMatch(/authorAvatarUrl/) + // Why: author chip must not ignore API avatar_url and only pass login. + expect(prPage).not.toMatch(/githubAvatarUrl\(workItem\.author\)/) + + const taskPage = readFileSync(join(__dirname, '../TaskPage.tsx'), 'utf8') + expect(taskPage).toMatch(/GitHubUserAvatar/) + // Why: list chip must not hardcode github.com/{login}.png. + expect(taskPage).not.toMatch(/github\.com\/\$\{reviewer\.login\}\.png/) + }) +}) diff --git a/src/shared/types.ts b/src/shared/types.ts index ff46520c4..362974817 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1491,6 +1491,11 @@ export type GitHubWorkItem = { labels: string[] updatedAt: string author: string | null + // Why: GHE user logins don't exist on github.com, so the github.com/{login}.png + // fallback 404s. Carry the API-provided avatar_url so github.com + Enterprise + // both render; absent on the gh-pr-view path (gh omits avatar), then the UI + // falls back to the login URL and finally an initials placeholder. See #8784. + authorAvatarUrl?: string branchName?: string baseRefName?: string // Why: PR checks are keyed by head commit; carrying this lets task rows use