From 4b9b84110383edced63866d7f55afe67c37a21fc Mon Sep 17 00:00:00 2001 From: Wooseong Kim Date: Wed, 7 Oct 2026 11:51:34 +0900 Subject: [PATCH 1/8] fix(github-project): render linked PR and sub-issue progress values --- .../github/project-view-field-values.test.ts | 88 +++++++++++++++++++ .../project-view-field-normalization.ts | 26 ++++++ .../project-view-item-normalization.ts | 13 +++ .../project-view/project-view-item-page.ts | 11 ++- .../project-view-query-fragments.ts | 35 +++++++- .../github-project/ProjectCell.test.tsx | 77 ++++++++++++++++ .../components/github-project/ProjectCell.tsx | 27 ++++++ src/shared/github/project-types.ts | 9 ++ 8 files changed, 280 insertions(+), 6 deletions(-) create mode 100644 src/main/github/project-view-field-values.test.ts create mode 100644 src/renderer/src/components/github-project/ProjectCell.test.tsx diff --git a/src/main/github/project-view-field-values.test.ts b/src/main/github/project-view-field-values.test.ts new file mode 100644 index 000000000000..35521cb8d437 --- /dev/null +++ b/src/main/github/project-view-field-values.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest' +import { normalizeFieldValue } from './project-view/project-view-field-normalization' +import { normalizeItem } from './project-view/project-view-item-normalization' +import { + fieldValuesSelection, + itemContentSelection, + supportsProjectExtendedFields +} from './project-view/project-view-query-fragments' + +describe('normalizeFieldValue linked PR values', () => { + it('normalizes linked pull requests with a visible overflow count', () => { + const value = normalizeFieldValue({ + __typename: 'ProjectV2ItemFieldPullRequestValue', + field: { id: 'field-pr', name: 'Linked pull requests', dataType: 'LINKED_PULL_REQUESTS' }, + pullRequests: { + totalCount: 12, + pageInfo: { hasNextPage: true }, + nodes: [{ number: 12, title: 'Fix', url: 'https://github.com/o/r/pull/12' }, null] + } + }) + expect(value).toEqual({ + kind: 'pull-requests', + fieldId: 'field-pr', + pullRequests: [{ number: 12, title: 'Fix', url: 'https://github.com/o/r/pull/12' }], + truncated: true, + totalCount: 12 + }) + }) + + it('keeps the server count when all linked pull requests fit the page', () => { + const value = normalizeFieldValue({ + __typename: 'ProjectV2ItemFieldPullRequestValue', + field: { id: 'field-pr', name: 'Linked pull requests', dataType: 'LINKED_PULL_REQUESTS' }, + pullRequests: { + totalCount: 1, + pageInfo: { hasNextPage: false }, + nodes: [{ number: 7, title: 'Only', url: 'https://github.com/o/r/pull/7' }] + } + }) + expect(value).toMatchObject({ truncated: false, totalCount: 1 }) + }) + + it('drops a typename that is not in GitHub’s field-value union', () => { + expect( + normalizeFieldValue({ + __typename: 'ProjectV2ItemFieldProgressValue', + field: { id: 'field-sub', name: 'Sub-issues progress', dataType: 'SUB_ISSUES_PROGRESS' } + }) + ).toBeNull() + }) +}) + +describe('sub-issues progress in project item content', () => { + it('normalizes Issue.subIssuesSummary for the renderer', () => { + const result = normalizeItem( + { + id: 'item-1', + type: 'ISSUE', + content: { + __typename: 'Issue', + id: 'issue-1', + number: 42, + title: 'Parent issue', + subIssuesSummary: { completed: 1, total: 2, percentCompleted: 50 } + } + }, + 0 + ) + expect(result).toMatchObject({ + ok: true, + row: { content: { subIssuesProgress: { completed: 1, total: 2, percentCompleted: 50 } } } + }) + }) +}) + +describe('project extended GraphQL selections', () => { + it('requests linked PR values and issue summaries only on supported hosts', () => { + expect(fieldValuesSelection(true)).toContain('... on ProjectV2ItemFieldPullRequestValue') + expect(fieldValuesSelection(false)).not.toContain('ProjectV2ItemFieldPullRequestValue') + expect(itemContentSelection(true, true)).toContain( + 'subIssuesSummary { completed total percentCompleted }' + ) + expect(itemContentSelection(true, false)).not.toContain('subIssuesSummary') + expect(supportsProjectExtendedFields(undefined)).toBe(true) + expect(supportsProjectExtendedFields('github.com')).toBe(true) + expect(supportsProjectExtendedFields('github.example.com')).toBe(false) + }) +}) diff --git a/src/main/github/project-view/project-view-field-normalization.ts b/src/main/github/project-view/project-view-field-normalization.ts index 7b783ac35051..a1f767d38abe 100644 --- a/src/main/github/project-view/project-view-field-normalization.ts +++ b/src/main/github/project-view/project-view-field-normalization.ts @@ -112,6 +112,11 @@ export type RawFieldValue = { date?: string labels?: { nodes?: RawLabel[] } users?: { nodes?: RawUser[] } + pullRequests?: { + totalCount?: number + pageInfo?: { hasNextPage?: boolean } + nodes?: ({ number?: number; title?: string; url?: string } | null)[] + } } export function normalizeFieldValue( @@ -172,6 +177,27 @@ export function normalizeFieldValue( .filter((u): u is GitHubProjectUser => u !== null) return { kind: 'users', fieldId, users } } + case 'ProjectV2ItemFieldPullRequestValue': { + const pullRequests = (raw.pullRequests?.nodes ?? []) + .map((node) => { + if (!node || typeof node.number !== 'number') { + return null + } + return { + number: node.number, + title: typeof node.title === 'string' ? node.title : '', + url: typeof node.url === 'string' ? node.url : '' + } + }) + .filter((pr): pr is { number: number; title: string; url: string } => pr !== null) + const totalCount = + typeof raw.pullRequests?.totalCount === 'number' + ? raw.pullRequests.totalCount + : pullRequests.length + const truncated = + raw.pullRequests?.pageInfo?.hasNextPage === true || totalCount > pullRequests.length + return { kind: 'pull-requests', fieldId, pullRequests, truncated, totalCount } + } case undefined: default: // Ignore future field types rather than treating compatible schema additions as drift. diff --git a/src/main/github/project-view/project-view-item-normalization.ts b/src/main/github/project-view/project-view-item-normalization.ts index 3bcfda9d6bac..6b668cfdb5c5 100644 --- a/src/main/github/project-view/project-view-item-normalization.ts +++ b/src/main/github/project-view/project-view-item-normalization.ts @@ -30,6 +30,7 @@ type RawContent = { assignees?: { nodes?: RawUser[] } labels?: { nodes?: RawLabel[] } parent?: { number?: number; title?: string; url?: string } | null + subIssuesSummary?: { completed?: number; total?: number; percentCompleted?: number } issueType?: { id?: string name?: string @@ -100,6 +101,17 @@ export function normalizeItem(raw: RawItem, position: number): NormalizedItemOut typeof content.parent.url === 'string' ? { number: content.parent.number, title: content.parent.title, url: content.parent.url } : null + const subIssuesSummary = content?.subIssuesSummary + const subIssuesProgress = + typeof subIssuesSummary?.completed === 'number' && + typeof subIssuesSummary.total === 'number' && + typeof subIssuesSummary.percentCompleted === 'number' + ? { + completed: subIssuesSummary.completed, + total: subIssuesSummary.total, + percentCompleted: subIssuesSummary.percentCompleted + } + : null const issueType = content?.issueType && typeof content.issueType.id === 'string' && @@ -143,6 +155,7 @@ export function normalizeItem(raw: RawItem, position: number): NormalizedItemOut assignees, labels, parentIssue, + subIssuesProgress, issueType }, fieldValuesByFieldId, diff --git a/src/main/github/project-view/project-view-item-page.ts b/src/main/github/project-view/project-view-item-page.ts index 5d59427d6274..b42b82e94bf2 100644 --- a/src/main/github/project-view/project-view-item-page.ts +++ b/src/main/github/project-view/project-view-item-page.ts @@ -20,8 +20,9 @@ import { ownerQueryRoot } from './project-view-config' import type { RawItem } from './project-view-item-normalization' import { FIELD_CONFIG_FRAGMENT, - FIELD_VALUES_SELECTION, - itemContentSelection + fieldValuesSelection, + itemContentSelection, + supportsProjectExtendedFields } from './project-view-query-fragments' export type RawItemsPage = { @@ -67,8 +68,10 @@ export async function fetchItemsPageWithRaw(args: { id type updatedAt - content { ${itemContentSelection(args.includeParent)} } - ${FIELD_VALUES_SELECTION} + content { + ${itemContentSelection(args.includeParent, supportsProjectExtendedFields(args.host))} + } + ${fieldValuesSelection(supportsProjectExtendedFields(args.host))} } } } diff --git a/src/main/github/project-view/project-view-query-fragments.ts b/src/main/github/project-view/project-view-query-fragments.ts index dc339442c51b..8b9258490614 100644 --- a/src/main/github/project-view/project-view-query-fragments.ts +++ b/src/main/github/project-view/project-view-query-fragments.ts @@ -22,8 +22,23 @@ fragment FieldConfig on ProjectV2FieldConfiguration { } ` -export function itemContentSelection(includeParent: boolean): string { +export function supportsProjectExtendedFields(host?: string): boolean { + const hostname = host + ?.toLowerCase() + .replace(/^https?:\/\//, '') + .replace(/\/$/, '') + // Why: older GitHub Enterprise schemas may not expose these GitHub.com fields. + return !hostname || hostname === 'github.com' +} + +export function itemContentSelection( + includeParent: boolean, + includeSubIssuesSummary: boolean +): string { const parentFrag = includeParent ? 'parent { number title url }' : '' + const subIssuesSummaryFrag = includeSubIssuesSummary + ? 'subIssuesSummary { completed total percentCompleted }' + : '' return ` __typename ... on Issue { @@ -38,6 +53,7 @@ export function itemContentSelection(includeParent: boolean): string { labels(first:10) { nodes { name color } } issueType { id name color description } ${parentFrag} + ${subIssuesSummaryFrag} } ... on PullRequest { id @@ -54,7 +70,20 @@ export function itemContentSelection(includeParent: boolean): string { ` } -export const FIELD_VALUES_SELECTION = ` +export function fieldValuesSelection(includeLinkedPullRequests: boolean): string { + const linkedPullRequestsFrag = includeLinkedPullRequests + ? ` + ... on ProjectV2ItemFieldPullRequestValue { + field { ...FieldConfig } + pullRequests(first:10) { + totalCount + pageInfo { hasNextPage } + nodes { number title url } + } + } + ` + : '' + return ` fieldValues(first:${FIELD_VALUES_PAGE_SIZE}) { pageInfo { hasNextPage } nodes { @@ -66,6 +95,8 @@ export const FIELD_VALUES_SELECTION = ` ... on ProjectV2ItemFieldDateValue { field { ...FieldConfig } date } ... on ProjectV2ItemFieldLabelValue { field { ...FieldConfig } labels(first:10) { nodes { name color } } } ... on ProjectV2ItemFieldUserValue { field { ...FieldConfig } users(first:5) { nodes { login name avatarUrl } } } + ${linkedPullRequestsFrag} } } ` +} diff --git a/src/renderer/src/components/github-project/ProjectCell.test.tsx b/src/renderer/src/components/github-project/ProjectCell.test.tsx new file mode 100644 index 000000000000..69185dc2201d --- /dev/null +++ b/src/renderer/src/components/github-project/ProjectCell.test.tsx @@ -0,0 +1,77 @@ +// @vitest-environment happy-dom + +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it } from 'vitest' +import type { + GitHubProjectField, + GitHubProjectFieldValue, + GitHubProjectRow +} from '../../../../shared/github/project-types' +import ProjectCell from './ProjectCell' + +function row( + fieldValue?: GitHubProjectFieldValue, + subIssuesProgress?: GitHubProjectRow['content']['subIssuesProgress'] +): GitHubProjectRow { + return { + id: 'item-1', + itemType: 'ISSUE', + content: { + number: 42, + title: 'Parent issue', + body: null, + url: 'https://github.com/o/r/issues/42', + state: 'OPEN', + stateReason: null, + isDraft: null, + repository: 'o/r', + assignees: [], + labels: [], + parentIssue: null, + issueType: null, + subIssuesProgress + }, + fieldValuesByFieldId: fieldValue ? { [fieldValue.fieldId]: fieldValue } : {}, + updatedAt: '2026-10-07T00:00:00Z', + position: 0 + } +} + +function field(dataType: 'LINKED_PULL_REQUESTS' | 'SUB_ISSUES_PROGRESS'): GitHubProjectField { + return { kind: 'field', id: 'field-1', name: dataType, dataType } +} + +afterEach(cleanup) + +describe('ProjectCell extended values', () => { + it('shows linked PRs and how many were omitted from the first page', () => { + const value: GitHubProjectFieldValue = { + kind: 'pull-requests', + fieldId: 'field-1', + pullRequests: [{ number: 12, title: 'Fix', url: 'https://github.com/o/r/pull/12' }], + truncated: true, + totalCount: 3 + } + render( + + ) + expect(screen.getByText('#12 +2').textContent).toBe('#12 +2') + }) + + it('shows the Issue sub-issues summary in its project column', () => { + render( + + ) + expect(screen.getByText('1/2 (50%)').textContent).toBe('1/2 (50%)') + }) +}) diff --git a/src/renderer/src/components/github-project/ProjectCell.tsx b/src/renderer/src/components/github-project/ProjectCell.tsx index 6e2459a2a3ff..aa028122d26e 100644 --- a/src/renderer/src/components/github-project/ProjectCell.tsx +++ b/src/renderer/src/components/github-project/ProjectCell.tsx @@ -93,6 +93,33 @@ export default function ProjectCell({ ) } + if (field.dataType === 'LINKED_PULL_REQUESTS') { + if (value?.kind !== 'pull-requests') { + return + } + const labels = value.pullRequests.map((pr) => `#${pr.number}`) + const overflow = + value.truncated || value.totalCount > value.pullRequests.length + ? ` +${Math.max(value.totalCount - value.pullRequests.length, 1)}` + : '' + return ( + + {labels.join(', ')} + {overflow} + + ) + } + if (field.dataType === 'SUB_ISSUES_PROGRESS') { + const progress = row.content.subIssuesProgress + if (!progress || progress.total === 0) { + return + } + return ( + + {progress.completed}/{progress.total} ({progress.percentCompleted}%) + + ) + } if (field.kind === 'single-select') { return ( Date: Mon, 26 Oct 2026 18:05:34 -0700 Subject: [PATCH 2/8] fix(github-project): probe schema support for project column values --- .../github/project-view-field-values.test.ts | 68 ----- .../project-error-classification.ts | 20 +- .../project-view-field-normalization.ts | 5 +- .../project-view/project-view-item-page.ts | 7 +- .../github/project-view/project-view-items.ts | 2 +- .../project-view-query-fragments.ts | 18 +- .../github-project/ProjectCell.test.tsx | 251 ++++++++++++++---- .../components/github-project/ProjectCell.tsx | 4 +- .../github-project/group-sort.test.ts | 26 ++ src/shared/github/project-group-sort.ts | 6 +- src/shared/github/project-types.ts | 1 - 11 files changed, 243 insertions(+), 165 deletions(-) diff --git a/src/main/github/project-view-field-values.test.ts b/src/main/github/project-view-field-values.test.ts index 35521cb8d437..6d2f23f6530c 100644 --- a/src/main/github/project-view-field-values.test.ts +++ b/src/main/github/project-view-field-values.test.ts @@ -1,12 +1,5 @@ import { describe, expect, it } from 'vitest' import { normalizeFieldValue } from './project-view/project-view-field-normalization' -import { normalizeItem } from './project-view/project-view-item-normalization' -import { - fieldValuesSelection, - itemContentSelection, - supportsProjectExtendedFields -} from './project-view/project-view-query-fragments' - describe('normalizeFieldValue linked PR values', () => { it('normalizes linked pull requests with a visible overflow count', () => { const value = normalizeFieldValue({ @@ -14,7 +7,6 @@ describe('normalizeFieldValue linked PR values', () => { field: { id: 'field-pr', name: 'Linked pull requests', dataType: 'LINKED_PULL_REQUESTS' }, pullRequests: { totalCount: 12, - pageInfo: { hasNextPage: true }, nodes: [{ number: 12, title: 'Fix', url: 'https://github.com/o/r/pull/12' }, null] } }) @@ -22,67 +14,7 @@ describe('normalizeFieldValue linked PR values', () => { kind: 'pull-requests', fieldId: 'field-pr', pullRequests: [{ number: 12, title: 'Fix', url: 'https://github.com/o/r/pull/12' }], - truncated: true, totalCount: 12 }) }) - - it('keeps the server count when all linked pull requests fit the page', () => { - const value = normalizeFieldValue({ - __typename: 'ProjectV2ItemFieldPullRequestValue', - field: { id: 'field-pr', name: 'Linked pull requests', dataType: 'LINKED_PULL_REQUESTS' }, - pullRequests: { - totalCount: 1, - pageInfo: { hasNextPage: false }, - nodes: [{ number: 7, title: 'Only', url: 'https://github.com/o/r/pull/7' }] - } - }) - expect(value).toMatchObject({ truncated: false, totalCount: 1 }) - }) - - it('drops a typename that is not in GitHub’s field-value union', () => { - expect( - normalizeFieldValue({ - __typename: 'ProjectV2ItemFieldProgressValue', - field: { id: 'field-sub', name: 'Sub-issues progress', dataType: 'SUB_ISSUES_PROGRESS' } - }) - ).toBeNull() - }) -}) - -describe('sub-issues progress in project item content', () => { - it('normalizes Issue.subIssuesSummary for the renderer', () => { - const result = normalizeItem( - { - id: 'item-1', - type: 'ISSUE', - content: { - __typename: 'Issue', - id: 'issue-1', - number: 42, - title: 'Parent issue', - subIssuesSummary: { completed: 1, total: 2, percentCompleted: 50 } - } - }, - 0 - ) - expect(result).toMatchObject({ - ok: true, - row: { content: { subIssuesProgress: { completed: 1, total: 2, percentCompleted: 50 } } } - }) - }) -}) - -describe('project extended GraphQL selections', () => { - it('requests linked PR values and issue summaries only on supported hosts', () => { - expect(fieldValuesSelection(true)).toContain('... on ProjectV2ItemFieldPullRequestValue') - expect(fieldValuesSelection(false)).not.toContain('ProjectV2ItemFieldPullRequestValue') - expect(itemContentSelection(true, true)).toContain( - 'subIssuesSummary { completed total percentCompleted }' - ) - expect(itemContentSelection(true, false)).not.toContain('subIssuesSummary') - expect(supportsProjectExtendedFields(undefined)).toBe(true) - expect(supportsProjectExtendedFields('github.com')).toBe(true) - expect(supportsProjectExtendedFields('github.example.com')).toBe(false) - }) }) diff --git a/src/main/github/project-view/project-error-classification.ts b/src/main/github/project-view/project-error-classification.ts index ca65f6d59db9..49d5fb90eb7d 100644 --- a/src/main/github/project-view/project-error-classification.ts +++ b/src/main/github/project-view/project-error-classification.ts @@ -33,18 +33,16 @@ export function errorsIndicateParentField(errors: GhGraphqlError[], stderr: stri return true } return errors.some((e) => { - const type = (e.type ?? '').toUpperCase() - if (type === 'FIELD_NOT_FOUND' || type === 'UNDEFINED_FIELD' || type === 'FIELD_ERRORS') { - const tail = e.path?.at(-1) - if (tail === 'parent') { - return true - } - // FIELD_ERRORS often omits `path`; match on message for the parent field. - if ((e.message ?? '').toLowerCase().includes('parent')) { - return true - } + const code = (e.type ?? e.extensions?.code ?? '').replace(/_/g, '').toUpperCase() + if (!['FIELDNOTFOUND', 'UNDEFINEDFIELD', 'FIELDERRORS', 'UNDEFINEDTYPE'].includes(code)) { + return false } - return false + const tail = e.path?.at(-1) + return ( + tail === 'parent' || + tail === 'subIssuesSummary' || + /\b(parent|subIssuesSummary|ProjectV2ItemFieldPullRequestValue)\b/i.test(e.message ?? '') + ) }) } diff --git a/src/main/github/project-view/project-view-field-normalization.ts b/src/main/github/project-view/project-view-field-normalization.ts index a1f767d38abe..9483a4b4381c 100644 --- a/src/main/github/project-view/project-view-field-normalization.ts +++ b/src/main/github/project-view/project-view-field-normalization.ts @@ -114,7 +114,6 @@ export type RawFieldValue = { users?: { nodes?: RawUser[] } pullRequests?: { totalCount?: number - pageInfo?: { hasNextPage?: boolean } nodes?: ({ number?: number; title?: string; url?: string } | null)[] } } @@ -194,9 +193,7 @@ export function normalizeFieldValue( typeof raw.pullRequests?.totalCount === 'number' ? raw.pullRequests.totalCount : pullRequests.length - const truncated = - raw.pullRequests?.pageInfo?.hasNextPage === true || totalCount > pullRequests.length - return { kind: 'pull-requests', fieldId, pullRequests, truncated, totalCount } + return { kind: 'pull-requests', fieldId, pullRequests, totalCount } } case undefined: default: diff --git a/src/main/github/project-view/project-view-item-page.ts b/src/main/github/project-view/project-view-item-page.ts index b42b82e94bf2..8faaadaea6df 100644 --- a/src/main/github/project-view/project-view-item-page.ts +++ b/src/main/github/project-view/project-view-item-page.ts @@ -21,8 +21,7 @@ import type { RawItem } from './project-view-item-normalization' import { FIELD_CONFIG_FRAGMENT, fieldValuesSelection, - itemContentSelection, - supportsProjectExtendedFields + itemContentSelection } from './project-view-query-fragments' export type RawItemsPage = { @@ -69,9 +68,9 @@ export async function fetchItemsPageWithRaw(args: { type updatedAt content { - ${itemContentSelection(args.includeParent, supportsProjectExtendedFields(args.host))} + ${itemContentSelection(args.includeParent)} } - ${fieldValuesSelection(supportsProjectExtendedFields(args.host))} + ${fieldValuesSelection(args.includeParent)} } } } diff --git a/src/main/github/project-view/project-view-items.ts b/src/main/github/project-view/project-view-items.ts index a99f7943f836..02818f6b557c 100644 --- a/src/main/github/project-view/project-view-items.ts +++ b/src/main/github/project-view/project-view-items.ts @@ -85,7 +85,7 @@ export async function fetchAllItems(args: { parentFieldDropped = true if (!hasParentFieldWarningLogged(scopeKey)) { console.warn( - `[project-view] Issue.parent is not available for ${args.owner} on this token — retrying without the parent selection.` + `[project-view] Optional project item fields are not available for ${args.owner} on this token — retrying without those selections.` ) markParentFieldWarningLogged(scopeKey) } diff --git a/src/main/github/project-view/project-view-query-fragments.ts b/src/main/github/project-view/project-view-query-fragments.ts index 8b9258490614..29cfc7f7e344 100644 --- a/src/main/github/project-view/project-view-query-fragments.ts +++ b/src/main/github/project-view/project-view-query-fragments.ts @@ -22,21 +22,9 @@ fragment FieldConfig on ProjectV2FieldConfiguration { } ` -export function supportsProjectExtendedFields(host?: string): boolean { - const hostname = host - ?.toLowerCase() - .replace(/^https?:\/\//, '') - .replace(/\/$/, '') - // Why: older GitHub Enterprise schemas may not expose these GitHub.com fields. - return !hostname || hostname === 'github.com' -} - -export function itemContentSelection( - includeParent: boolean, - includeSubIssuesSummary: boolean -): string { +export function itemContentSelection(includeParent: boolean): string { const parentFrag = includeParent ? 'parent { number title url }' : '' - const subIssuesSummaryFrag = includeSubIssuesSummary + const subIssuesSummaryFrag = includeParent ? 'subIssuesSummary { completed total percentCompleted }' : '' return ` @@ -70,6 +58,7 @@ export function itemContentSelection( ` } +// At 100 items × 100 fields, ten linked PRs add at most 100k nodes to the 500k query budget. export function fieldValuesSelection(includeLinkedPullRequests: boolean): string { const linkedPullRequestsFrag = includeLinkedPullRequests ? ` @@ -77,7 +66,6 @@ export function fieldValuesSelection(includeLinkedPullRequests: boolean): string field { ...FieldConfig } pullRequests(first:10) { totalCount - pageInfo { hasNextPage } nodes { number title url } } } diff --git a/src/renderer/src/components/github-project/ProjectCell.test.tsx b/src/renderer/src/components/github-project/ProjectCell.test.tsx index 69185dc2201d..6948640debd3 100644 --- a/src/renderer/src/components/github-project/ProjectCell.test.tsx +++ b/src/renderer/src/components/github-project/ProjectCell.test.tsx @@ -1,77 +1,212 @@ // @vitest-environment happy-dom import { cleanup, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it } from 'vitest' -import type { - GitHubProjectField, - GitHubProjectFieldValue, - GitHubProjectRow -} from '../../../../shared/github/project-types' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + normalizeItem, + type RawItem +} from '../../../../main/github/project-view/project-view-item-normalization' +import { fetchItemsPageWithRaw } from '../../../../main/github/project-view/project-view-item-page' +import { ghExecFileAsync } from '../../../../main/github/project-view/internals' +import type { GitHubProjectRow } from '../../../../shared/github/project-types' import ProjectCell from './ProjectCell' +import { fetchAllItems } from '../../../../main/github/project-view/project-view-items' +import { _resetProjectViewCachesForTests } from '../../../../main/github/project-view/project-view-cache' -function row( - fieldValue?: GitHubProjectFieldValue, - subIssuesProgress?: GitHubProjectRow['content']['subIssuesProgress'] -): GitHubProjectRow { - return { - id: 'item-1', - itemType: 'ISSUE', - content: { - number: 42, - title: 'Parent issue', - body: null, - url: 'https://github.com/o/r/issues/42', - state: 'OPEN', - stateReason: null, - isDraft: null, - repository: 'o/r', - assignees: [], - labels: [], - parentIssue: null, - issueType: null, - subIssuesProgress - }, - fieldValuesByFieldId: fieldValue ? { [fieldValue.fieldId]: fieldValue } : {}, - updatedAt: '2026-10-07T00:00:00Z', - position: 0 +vi.mock('../../../../main/github/project-view/internals', () => ({ + acquire: vi.fn(), + release: vi.fn(), + ghExecFileAsync: vi.fn(), + projectHostAuthenticationError: vi.fn().mockResolvedValue(null), + projectGhExecOptions: (host?: string) => ({ host }), + repositoryRateLimitGuard: () => ({ blocked: false }), + noteRepositoryRateLimitSpend: vi.fn() +})) +vi.mock('../../../../main/github/project-view/project-view-config', () => ({ + ownerQueryRoot: () => 'organization' +})) + +const item: RawItem = { + id: 'item-1', + type: 'ISSUE', + content: { + __typename: 'Issue', + number: 42, + title: 'Parent issue', + subIssuesSummary: { completed: 1, total: 2, percentCompleted: 50 } + }, + fieldValues: { + nodes: [ + { + __typename: 'ProjectV2ItemFieldPullRequestValue', + field: { id: 'field-pr', name: 'Linked pull requests', dataType: 'LINKED_PULL_REQUESTS' }, + pullRequests: { + totalCount: 12, + nodes: Array.from({ length: 10 }, (_, index) => ({ + number: index + 1, + title: `Change ${index + 1}`, + url: `https://github.com/o/r/pull/${index + 1}` + })) + } + } + ] } } +const args = { + owner: 'o', + ownerType: 'organization', + projectNumber: 1, + query: '', + first: 50, + after: null, + includeParent: true, + host: 'acme.ghe.com' +} as const -function field(dataType: 'LINKED_PULL_REQUESTS' | 'SUB_ISSUES_PROGRESS'): GitHubProjectField { - return { kind: 'field', id: 'field-1', name: dataType, dataType } -} +beforeEach(() => { + vi.clearAllMocks() + _resetProjectViewCachesForTests() + vi.mocked(ghExecFileAsync).mockResolvedValue({ + stdout: JSON.stringify({ + data: { + organization: { + projectV2: { + items: { + totalCount: 1, + pageInfo: { hasNextPage: false }, + nodes: [item] + } + } + } + } + }), + stderr: '' + }) +}) +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) -afterEach(cleanup) +function renderColumns(raw: RawItem): void { + const result = normalizeItem(raw, 0) + if (!result.ok) { + throw new Error('Expected a project row') + } + renderRowColumns(result.row) +} -describe('ProjectCell extended values', () => { - it('shows linked PRs and how many were omitted from the first page', () => { - const value: GitHubProjectFieldValue = { - kind: 'pull-requests', - fieldId: 'field-1', - pullRequests: [{ number: 12, title: 'Fix', url: 'https://github.com/o/r/pull/12' }], - truncated: true, - totalCount: 3 - } +function renderRowColumns(row: GitHubProjectRow): void { + for (const [id, dataType] of [ + ['field-pr', 'LINKED_PULL_REQUESTS'], + ['field-progress', 'SUB_ISSUES_PROGRESS'] + ] as const) { render( ) - expect(screen.getByText('#12 +2').textContent).toBe('#12 +2') + } +} + +describe('Project columns from the items response', () => { + it.each(['#1, #2, #3, #4, #5, #6, #7, #8, #9, #10 +2', '1/2 (50%)'])( + 'renders %s from the existing items request', + async (expectedText) => { + const page = await fetchItemsPageWithRaw(args) + if (!page.ok || !page.page.nodes?.[0]) { + throw new Error('Expected an items page') + } + renderColumns(page.page.nodes[0]) + expect(screen.getByText(expectedText).textContent).toBe(expectedText) + expect(ghExecFileAsync).toHaveBeenCalledTimes(1) + const query = vi.mocked(ghExecFileAsync).mock.calls[0][0].join(' ') + expect(query).toContain('... on ProjectV2ItemFieldPullRequestValue') + expect(query).toContain('pullRequests(first:10)') + expect(query).toContain('subIssuesSummary { completed total percentCompleted }') + expect(query).not.toContain('ProjectV2ItemFieldProgressValue') + } + ) + + it('keeps unsupported or absent summaries blank for old hosts, drafts and empty parents', () => { + renderColumns({ id: 'old-host', type: 'ISSUE', content: { title: 'Old host' } }) + renderColumns({ id: 'draft', type: 'DRAFT_ISSUE', content: { title: 'Draft' } }) + renderColumns({ + id: 'empty', + type: 'ISSUE', + content: { + subIssuesSummary: { total: 0, completed: 0, percentCompleted: 0 } + } + }) + expect(document.body.textContent).toBe('') }) - it('shows the Issue sub-issues summary in its project column', () => { - render( - - ) - expect(screen.getByText('1/2 (50%)').textContent).toBe('1/2 (50%)') + it.each([ + { + extensions: { code: 'undefinedField' }, + message: "Field 'subIssuesSummary' doesn't exist on type 'Issue'" + }, + { + extensions: { code: 'undefinedType' }, + message: + "No such type ProjectV2ItemFieldPullRequestValue, so it can't be a fragment condition" + }, + { type: 'FIELD_NOT_FOUND', path: ['parent'] } + ])('retries an unsupported optional selection once: %j', async (error) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.mocked(ghExecFileAsync) + .mockResolvedValueOnce({ + stdout: JSON.stringify({ errors: [error] }), + stderr: '' + }) + .mockResolvedValue({ + stdout: JSON.stringify({ + data: { + organization: { + projectV2: { + items: { + totalCount: 1, + pageInfo: { hasNextPage: false }, + nodes: [{ id: 'old-server', type: 'ISSUE', content: { title: 'Old server' } }] + } + } + } + } + }), + stderr: '' + }) + const result = await fetchAllItems(args) + if (!result.ok) { + throw new Error('Expected the fallback items query to succeed') + } + expect(result.parentFieldDropped).toBe(true) + renderRowColumns(result.rows[0]) + expect(document.body.textContent).toBe('') + expect(ghExecFileAsync).toHaveBeenCalledTimes(2) + const queries = vi + .mocked(ghExecFileAsync) + .mock.calls.map(([arguments_]) => arguments_.join(' ')) + expect(queries[0]).toContain('subIssuesSummary') + expect(queries[0]).toContain('ProjectV2ItemFieldPullRequestValue') + expect(queries[1]).not.toContain('subIssuesSummary') + expect(queries[1]).not.toContain('ProjectV2ItemFieldPullRequestValue') + expect(queries[1]).not.toContain('parent {') + await fetchAllItems(args) + expect(ghExecFileAsync).toHaveBeenCalledTimes(3) + expect(vi.mocked(ghExecFileAsync).mock.calls[2][0].join(' ')).not.toContain('subIssuesSummary') + }) + + it('keeps unrelated API failures instead of treating them as schema capabilities', async () => { + vi.mocked(ghExecFileAsync).mockResolvedValueOnce({ + stdout: JSON.stringify({ + errors: [{ type: 'FORBIDDEN', message: 'Cannot access subIssuesSummary' }] + }), + stderr: '' + }) + expect(await fetchAllItems(args)).toMatchObject({ ok: false }) + expect(ghExecFileAsync).toHaveBeenCalledTimes(1) }) }) diff --git a/src/renderer/src/components/github-project/ProjectCell.tsx b/src/renderer/src/components/github-project/ProjectCell.tsx index aa028122d26e..0ba11c456dbb 100644 --- a/src/renderer/src/components/github-project/ProjectCell.tsx +++ b/src/renderer/src/components/github-project/ProjectCell.tsx @@ -99,8 +99,8 @@ export default function ProjectCell({ } const labels = value.pullRequests.map((pr) => `#${pr.number}`) const overflow = - value.truncated || value.totalCount > value.pullRequests.length - ? ` +${Math.max(value.totalCount - value.pullRequests.length, 1)}` + value.totalCount > value.pullRequests.length + ? ` +${value.totalCount - value.pullRequests.length}` : '' return ( diff --git a/src/renderer/src/components/github-project/group-sort.test.ts b/src/renderer/src/components/github-project/group-sort.test.ts index 96d2c6c6c3fe..f3401de42f20 100644 --- a/src/renderer/src/components/github-project/group-sort.test.ts +++ b/src/renderer/src/components/github-project/group-sort.test.ts @@ -442,3 +442,29 @@ it('uses the first iteration ordering and metadata when legacy field IDs repeat' completed: true }) }) + +it('preserves position and unsupported grouping for linked PR relation values', () => { + const field: GitHubProjectField = { + kind: 'field', + id: 'linked', + name: 'Linked pull requests', + dataType: 'LINKED_PULL_REQUESTS' + } + const rows = [ + makeRow('empty', 1, {}), + makeRow('linked', 0, { + linked: { + kind: 'pull-requests', + fieldId: 'linked', + totalCount: 1, + pullRequests: [{ number: 42, title: 'Change', url: 'https://github.com/o/r/pull/42' }] + } + }) + ] + const table = makeTable( + { ...makeView(field, { field, direction: 'DESC' }), groupByFields: [field] }, + rows + ) + expect(sortRows(table, rows).map((row) => row.id)).toEqual(['linked', 'empty']) + expect(groupRows(table, rows)).toMatchObject([{ key: '__empty__', rows }]) +}) diff --git a/src/shared/github/project-group-sort.ts b/src/shared/github/project-group-sort.ts index 3330c4ea37a0..a3a49e879898 100644 --- a/src/shared/github/project-group-sort.ts +++ b/src/shared/github/project-group-sort.ts @@ -22,12 +22,14 @@ export const EMPTY_PROJECT_GROUP_KEY = '__empty__' type ProjectFieldValue = GitHubProjectRow['fieldValuesByFieldId'][string] -/** False for anything that renders as an empty cell — absent, or present with a blank payload. */ +/** Read-only relations stay outside grouping/sorting; absent and blank values sort last. */ function hasNonEmptyFieldValue(value: ProjectFieldValue | undefined): boolean { if (!value) { return false } switch (value.kind) { + case 'pull-requests': + return false case 'users': return Boolean(value.users[0]?.login) case 'labels': @@ -116,6 +118,8 @@ function labelForEmpty(field: GitHubProjectField): string { function deriveStringValue(value: GitHubProjectRow['fieldValuesByFieldId'][string]): string { switch (value.kind) { + case 'pull-requests': + return '' case 'text': return value.text case 'number': diff --git a/src/shared/github/project-types.ts b/src/shared/github/project-types.ts index 9bd16c720a65..365405d6ae49 100644 --- a/src/shared/github/project-types.ts +++ b/src/shared/github/project-types.ts @@ -140,7 +140,6 @@ export type GitHubProjectFieldValue = kind: 'pull-requests' fieldId: string pullRequests: { number: number; title: string; url: string }[] - truncated: boolean totalCount: number } From 07bd34b7d28d0ddd1ce8292c6047726ddd0bc46f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:14:58 -0700 Subject: [PATCH 3/8] fix(github-project): preserve independently supported project fields --- .../github/project-view-field-values.test.ts | 8 +- .../project-error-classification.ts | 53 +++- .../github/project-view/project-view-cache.ts | 24 +- .../project-view-field-normalization.ts | 46 +-- .../project-view-item-normalization.ts | 8 + .../project-view/project-view-item-page.ts | 7 +- .../github/project-view/project-view-items.ts | 146 ++++----- .../project-view-query-fragments.ts | 7 +- .../github-project/ProjectCell.test.tsx | 289 +++++++++++++----- .../components/github-project/ProjectCell.tsx | 9 +- .../github-project/group-sort.test.ts | 26 -- src/shared/github/project-group-sort.ts | 6 +- src/shared/github/project-types.ts | 12 +- 13 files changed, 383 insertions(+), 258 deletions(-) diff --git a/src/main/github/project-view-field-values.test.ts b/src/main/github/project-view-field-values.test.ts index 6d2f23f6530c..5b1b6cd36344 100644 --- a/src/main/github/project-view-field-values.test.ts +++ b/src/main/github/project-view-field-values.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest' -import { normalizeFieldValue } from './project-view/project-view-field-normalization' -describe('normalizeFieldValue linked PR values', () => { +import { normalizeLinkedPullRequests } from './project-view/project-view-field-normalization' +describe('normalizeLinkedPullRequests linked PR values', () => { it('normalizes linked pull requests with a visible overflow count', () => { - const value = normalizeFieldValue({ + const value = normalizeLinkedPullRequests({ __typename: 'ProjectV2ItemFieldPullRequestValue', field: { id: 'field-pr', name: 'Linked pull requests', dataType: 'LINKED_PULL_REQUESTS' }, pullRequests: { @@ -11,8 +11,6 @@ describe('normalizeFieldValue linked PR values', () => { } }) expect(value).toEqual({ - kind: 'pull-requests', - fieldId: 'field-pr', pullRequests: [{ number: 12, title: 'Fix', url: 'https://github.com/o/r/pull/12' }], totalCount: 12 }) diff --git a/src/main/github/project-view/project-error-classification.ts b/src/main/github/project-view/project-error-classification.ts index 49d5fb90eb7d..9e2f4488bdcb 100644 --- a/src/main/github/project-view/project-error-classification.ts +++ b/src/main/github/project-view/project-error-classification.ts @@ -1,3 +1,4 @@ +import type { OptionalProjectItemField } from './project-view-cache' import type { GitHubProjectViewError } from '../../../shared/github/project-result-types' import { githubProjectHost } from '../../../shared/github/project-identity' @@ -5,7 +6,7 @@ export type GhGraphqlError = { type?: string message?: string path?: (string | number)[] - extensions?: { code?: string } + extensions?: { code?: string; fieldName?: string; typeName?: string } } export function extractGraphqlErrors(stderr: string, stdout: string): GhGraphqlError[] { @@ -27,23 +28,43 @@ export function extractGraphqlErrors(stderr: string, stdout: string): GhGraphqlE return [] } -export function errorsIndicateParentField(errors: GhGraphqlError[], stderr: string): boolean { - const lower = stderr.toLowerCase() - if (lower.includes('preview') && lower.includes('parent')) { - return true +export function unsupportedItemFieldsFromErrors( + errors: GhGraphqlError[], + stderr: string +): OptionalProjectItemField[] { + const unsupported = new Set() + if (/preview/i.test(stderr) && /\bparent\b/i.test(stderr)) { + unsupported.add('parent') } - return errors.some((e) => { - const code = (e.type ?? e.extensions?.code ?? '').replace(/_/g, '').toUpperCase() - if (!['FIELDNOTFOUND', 'UNDEFINEDFIELD', 'FIELDERRORS', 'UNDEFINEDTYPE'].includes(code)) { - return false + for (const error of errors) { + const code = (error.type ?? error.extensions?.code ?? '').replace(/_/g, '').toUpperCase() + const message = error.message ?? '' + const missing = + /doesn't exist|does not exist|cannot query field|unknown field|undefined field|no such type/i.test( + message + ) + if ( + !['FIELDNOTFOUND', 'UNDEFINEDFIELD', 'FIELDERRORS', 'UNDEFINEDTYPE'].includes(code) && + !(code === '' && missing) + ) { + continue + } + for (const field of ['parent', 'subIssuesSummary', 'linkedPullRequests'] as const) { + const name = field === 'linkedPullRequests' ? 'ProjectV2ItemFieldPullRequestValue' : field + if ( + error.path?.at(-1) === name || + error.extensions?.fieldName === name || + error.extensions?.typeName === name || + message + .toLowerCase() + .split(/[^a-z0-9_]+/) + .includes(name.toLowerCase()) + ) { + unsupported.add(field) + } } - const tail = e.path?.at(-1) - return ( - tail === 'parent' || - tail === 'subIssuesSummary' || - /\b(parent|subIssuesSummary|ProjectV2ItemFieldPullRequestValue)\b/i.test(e.message ?? '') - ) - }) + } + return [...unsupported] } export function classifyProjectError( diff --git a/src/main/github/project-view/project-view-cache.ts b/src/main/github/project-view/project-view-cache.ts index 36110d9e5ae5..008a85285813 100644 --- a/src/main/github/project-view/project-view-cache.ts +++ b/src/main/github/project-view/project-view-cache.ts @@ -34,7 +34,8 @@ function getProjectViewCacheEntry(cache: Map, key: K): V | undefined // Module reloads must discard stale capability results. const ownerTypeCache = new Map() // One owner's unsupported parent field must not poison another owner's capability. -const parentFieldRetriedByOwner = new Map() +export type OptionalProjectItemField = 'parent' | 'subIssuesSummary' | 'linkedPullRequests' +const unsupportedItemFieldsByOwner = new Map>() const parentFieldWarningLoggedByOwner = new Map() // Share first-page capability probes per owner. export const parentFieldProbeInFlight = new Map>() @@ -68,12 +69,25 @@ export function getCachedOwnerType( return getProjectViewCacheEntry(ownerTypeCache, ownerTypeCacheKey(owner, host)) } +export function markItemFieldsUnsupported( + scopeKey: string, + fields: readonly OptionalProjectItemField[] +): void { + const unsupported = new Set(getUnsupportedItemFields(scopeKey)) + fields.forEach((field) => unsupported.add(field)) + rememberProjectViewCacheEntry(unsupportedItemFieldsByOwner, scopeKey, unsupported) +} + +export function getUnsupportedItemFields(scopeKey: string): ReadonlySet { + return getProjectViewCacheEntry(unsupportedItemFieldsByOwner, scopeKey) ?? new Set() +} + export function markParentFieldRetried(scopeKey: string): void { - rememberProjectViewCacheEntry(parentFieldRetriedByOwner, scopeKey, true) + markItemFieldsUnsupported(scopeKey, ['parent']) } export function hasParentFieldRetried(scopeKey: string): boolean { - return getProjectViewCacheEntry(parentFieldRetriedByOwner, scopeKey) === true + return getUnsupportedItemFields(scopeKey).has('parent') } export function markParentFieldWarningLogged(scopeKey: string): void { @@ -86,7 +100,7 @@ export function hasParentFieldWarningLogged(scopeKey: string): boolean { export function _resetProjectViewCachesForTests(): void { ownerTypeCache.clear() - parentFieldRetriedByOwner.clear() + unsupportedItemFieldsByOwner.clear() parentFieldWarningLoggedByOwner.clear() parentFieldProbeInFlight.clear() } @@ -99,7 +113,7 @@ export function _getProjectViewCacheSizesForTests(): { } { return { ownerTypes: ownerTypeCache.size, - parentFieldRetries: parentFieldRetriedByOwner.size, + parentFieldRetries: unsupportedItemFieldsByOwner.size, parentFieldWarnings: parentFieldWarningLoggedByOwner.size, parentFieldProbes: parentFieldProbeInFlight.size } diff --git a/src/main/github/project-view/project-view-field-normalization.ts b/src/main/github/project-view/project-view-field-normalization.ts index 9483a4b4381c..5c73cd59e825 100644 --- a/src/main/github/project-view/project-view-field-normalization.ts +++ b/src/main/github/project-view/project-view-field-normalization.ts @@ -1,6 +1,7 @@ import type { GitHubProjectField, GitHubProjectFieldValue, + GitHubProjectLinkedPullRequests, GitHubProjectIteration, GitHubProjectLabel, GitHubProjectSingleSelectOption, @@ -176,28 +177,35 @@ export function normalizeFieldValue( .filter((u): u is GitHubProjectUser => u !== null) return { kind: 'users', fieldId, users } } - case 'ProjectV2ItemFieldPullRequestValue': { - const pullRequests = (raw.pullRequests?.nodes ?? []) - .map((node) => { - if (!node || typeof node.number !== 'number') { - return null - } - return { - number: node.number, - title: typeof node.title === 'string' ? node.title : '', - url: typeof node.url === 'string' ? node.url : '' - } - }) - .filter((pr): pr is { number: number; title: string; url: string } => pr !== null) - const totalCount = - typeof raw.pullRequests?.totalCount === 'number' - ? raw.pullRequests.totalCount - : pullRequests.length - return { kind: 'pull-requests', fieldId, pullRequests, totalCount } - } case undefined: default: // Ignore future field types rather than treating compatible schema additions as drift. return null } } + +export function normalizeLinkedPullRequests( + raw: RawFieldValue +): GitHubProjectLinkedPullRequests | null { + if (raw.__typename !== 'ProjectV2ItemFieldPullRequestValue') { + return null + } + const pullRequests = (raw.pullRequests?.nodes ?? []).flatMap((node) => + !node || typeof node.number !== 'number' + ? [] + : [ + { + number: node.number, + title: typeof node.title === 'string' ? node.title : '', + url: typeof node.url === 'string' ? node.url : '' + } + ] + ) + return { + pullRequests, + totalCount: + typeof raw.pullRequests?.totalCount === 'number' + ? raw.pullRequests.totalCount + : pullRequests.length + } +} diff --git a/src/main/github/project-view/project-view-item-normalization.ts b/src/main/github/project-view/project-view-item-normalization.ts index 6b668cfdb5c5..63f1704fde8e 100644 --- a/src/main/github/project-view/project-view-item-normalization.ts +++ b/src/main/github/project-view/project-view-item-normalization.ts @@ -1,6 +1,7 @@ import type { GitHubProjectFieldValue, GitHubProjectLabel, + GitHubProjectLinkedPullRequests, GitHubProjectRow, GitHubProjectRowItemType, GitHubProjectUser @@ -10,6 +11,7 @@ import { driftError } from './project-error-classification' import { normalizeFieldValue, normalizeLabel, + normalizeLinkedPullRequests, normalizeUser, type RawFieldValue, type RawLabel, @@ -124,8 +126,13 @@ export function normalizeItem(raw: RawItem, position: number): NormalizedItemOut typeof content.issueType.description === 'string' ? content.issueType.description : null } : null + let linkedPullRequests: GitHubProjectLinkedPullRequests | null = null const fieldValuesByFieldId: Record = {} for (const fv of raw.fieldValues?.nodes ?? []) { + if (fv.__typename === 'ProjectV2ItemFieldPullRequestValue') { + linkedPullRequests = normalizeLinkedPullRequests(fv) + continue + } const normalized = normalizeFieldValue(fv) if (normalized) { fieldValuesByFieldId[normalized.fieldId] = normalized @@ -155,6 +162,7 @@ export function normalizeItem(raw: RawItem, position: number): NormalizedItemOut assignees, labels, parentIssue, + linkedPullRequests, subIssuesProgress, issueType }, diff --git a/src/main/github/project-view/project-view-item-page.ts b/src/main/github/project-view/project-view-item-page.ts index 8faaadaea6df..cb726a112433 100644 --- a/src/main/github/project-view/project-view-item-page.ts +++ b/src/main/github/project-view/project-view-item-page.ts @@ -1,3 +1,4 @@ +import type { OptionalProjectItemField } from './project-view-cache' import type { GitHubProjectOwnerType } from '../../../shared/github/project-types' import type { GitHubProjectViewError } from '../../../shared/github/project-result-types' import { @@ -38,7 +39,7 @@ export async function fetchItemsPageWithRaw(args: { query: string first: number after: string | null - includeParent: boolean + unsupportedFields: ReadonlySet host?: string }): Promise< | { ok: true; page: RawItemsPage } @@ -68,9 +69,9 @@ export async function fetchItemsPageWithRaw(args: { type updatedAt content { - ${itemContentSelection(args.includeParent)} + ${itemContentSelection(!args.unsupportedFields.has('parent'), !args.unsupportedFields.has('subIssuesSummary'))} } - ${fieldValuesSelection(args.includeParent)} + ${fieldValuesSelection(!args.unsupportedFields.has('linkedPullRequests'))} } } } diff --git a/src/main/github/project-view/project-view-items.ts b/src/main/github/project-view/project-view-items.ts index 02818f6b557c..8e03d96d5b4d 100644 --- a/src/main/github/project-view/project-view-items.ts +++ b/src/main/github/project-view/project-view-items.ts @@ -1,11 +1,11 @@ import type { GitHubProjectOwnerType, GitHubProjectRow } from '../../../shared/github/project-types' import type { GitHubProjectViewError } from '../../../shared/github/project-result-types' import { projectGhExecOptions, runGraphql } from './internals' -import { driftError, errorsIndicateParentField } from './project-error-classification' +import { driftError, unsupportedItemFieldsFromErrors } from './project-error-classification' import { - hasParentFieldRetried, + getUnsupportedItemFields, hasParentFieldWarningLogged, - markParentFieldRetried, + markItemFieldsUnsupported, markParentFieldWarningLogged, ownerScopeKey, parentFieldProbeInFlight @@ -32,74 +32,56 @@ export async function fetchAllItems(args: { if (inFlight) { await inFlight.catch(() => {}) } - let includeParent = !hasParentFieldRetried(scopeKey) - let parentFieldDropped = !includeParent - // Register the shared parent probe synchronously so concurrent callers cannot duplicate it. - let first: Awaited> - let probePromise: Promise>> | null = null - if (includeParent && !parentFieldProbeInFlight.has(scopeKey)) { - let resolveProbe: () => void = () => {} - const probe = new Promise((resolve) => { - resolveProbe = resolve - }) - parentFieldProbeInFlight.set(scopeKey, probe) - probePromise = (async () => { - try { - const result = await fetchItemsPageWithRaw({ - owner: args.owner, - ownerType: args.ownerType, - projectNumber: args.projectNumber, - query: args.query, - first: ITEM_PAGE_SIZE, - after: null, - includeParent: true, - host: args.host - }) - // Publish unsupported capability before releasing probe waiters. - if (!result.ok && errorsIndicateParentField(result.rawErrors, result.stderr)) { - markParentFieldRetried(scopeKey) - } - return result - } finally { - resolveProbe() - parentFieldProbeInFlight.delete(scopeKey) - } - })() - first = await probePromise - } else { - first = await fetchItemsPageWithRaw({ - owner: args.owner, - ownerType: args.ownerType, - projectNumber: args.projectNumber, - query: args.query, + const unsupportedFields = new Set(getUnsupportedItemFields(scopeKey)) + const fetchPage = (after: string | null) => + fetchItemsPageWithRaw({ + ...args, first: ITEM_PAGE_SIZE, - after: null, - includeParent, - host: args.host + after, + unsupportedFields }) - } - if (!first.ok && includeParent && errorsIndicateParentField(first.rawErrors, first.stderr)) { - // Retry only this owner without parent; other owner scopes retain capability. - markParentFieldRetried(scopeKey) - includeParent = false - parentFieldDropped = true - if (!hasParentFieldWarningLogged(scopeKey)) { - console.warn( - `[project-view] Optional project item fields are not available for ${args.owner} on this token — retrying without those selections.` + const fetchFirstPage = async () => { + let result = await fetchPage(null) + while (!result.ok) { + const missing = unsupportedItemFieldsFromErrors(result.rawErrors, result.stderr).filter( + (field) => !unsupportedFields.has(field) ) - markParentFieldWarningLogged(scopeKey) + if (missing.length === 0) { + break + } + missing.forEach((field) => unsupportedFields.add(field)) + markItemFieldsUnsupported(scopeKey, missing) + if (missing.includes('parent') && !hasParentFieldWarningLogged(scopeKey)) { + console.warn( + `[project-view] Issue.parent is not available for ${args.owner} on this token — retrying without the parent selection.` + ) + markParentFieldWarningLogged(scopeKey) + } + // Each validation retry removes at least one of the three optional selections. + result = await fetchPage(null) } - first = await fetchItemsPageWithRaw({ - owner: args.owner, - ownerType: args.ownerType, - projectNumber: args.projectNumber, - query: args.query, - first: ITEM_PAGE_SIZE, - after: null, - includeParent: false, - host: args.host - }) + return result } + let first: Awaited> + if (!parentFieldProbeInFlight.has(scopeKey)) { + let resolveProbe: () => void = () => {} + parentFieldProbeInFlight.set( + scopeKey, + new Promise((resolve) => { + resolveProbe = resolve + }) + ) + try { + first = await fetchFirstPage() + } finally { + resolveProbe() + parentFieldProbeInFlight.delete(scopeKey) + } + } else { + first = await fetchFirstPage() + } + const parentFieldDropped = unsupportedFields.has('parent') + if (!first.ok) { return { ok: false, error: first.error } } @@ -146,24 +128,15 @@ export async function fetchAllItems(args: { let hasNext = first.page.pageInfo.hasNextPage === true let cursor: string | null | undefined = first.page.pageInfo.endCursor - if (hasNext && typeof cursor !== 'string') { - return { - ok: false, - error: driftError('items.pageInfo.endCursor missing with hasNextPage=true'), - totalCount - } - } while (hasNext) { - const next = await fetchItemsPageWithRaw({ - owner: args.owner, - ownerType: args.ownerType, - projectNumber: args.projectNumber, - query: args.query, - first: ITEM_PAGE_SIZE, - after: cursor as string, - includeParent, - host: args.host - }) + if (typeof cursor !== 'string') { + return { + ok: false, + error: driftError('items.pageInfo.endCursor missing with hasNextPage=true'), + totalCount + } + } + const next = await fetchPage(cursor) if (!next.ok) { return { ok: false, error: next.error, totalCount } } @@ -183,13 +156,6 @@ export async function fetchAllItems(args: { } hasNext = next.page.pageInfo.hasNextPage === true cursor = next.page.pageInfo.endCursor - if (hasNext && typeof cursor !== 'string') { - return { - ok: false, - error: driftError('items.pageInfo.endCursor missing with hasNextPage=true'), - totalCount - } - } } return { ok: true, rows, totalCount, parentFieldDropped } } diff --git a/src/main/github/project-view/project-view-query-fragments.ts b/src/main/github/project-view/project-view-query-fragments.ts index 29cfc7f7e344..a28b76cc109c 100644 --- a/src/main/github/project-view/project-view-query-fragments.ts +++ b/src/main/github/project-view/project-view-query-fragments.ts @@ -22,9 +22,12 @@ fragment FieldConfig on ProjectV2FieldConfiguration { } ` -export function itemContentSelection(includeParent: boolean): string { +export function itemContentSelection( + includeParent: boolean, + includeSubIssuesSummary: boolean +): string { const parentFrag = includeParent ? 'parent { number title url }' : '' - const subIssuesSummaryFrag = includeParent + const subIssuesSummaryFrag = includeSubIssuesSummary ? 'subIssuesSummary { completed total percentCompleted }' : '' return ` diff --git a/src/renderer/src/components/github-project/ProjectCell.test.tsx b/src/renderer/src/components/github-project/ProjectCell.test.tsx index 6948640debd3..c74710f8f13e 100644 --- a/src/renderer/src/components/github-project/ProjectCell.test.tsx +++ b/src/renderer/src/components/github-project/ProjectCell.test.tsx @@ -7,11 +7,14 @@ import { type RawItem } from '../../../../main/github/project-view/project-view-item-normalization' import { fetchItemsPageWithRaw } from '../../../../main/github/project-view/project-view-item-page' +import { fetchAllItems } from '../../../../main/github/project-view/project-view-items' +import { + _resetProjectViewCachesForTests, + type OptionalProjectItemField +} from '../../../../main/github/project-view/project-view-cache' import { ghExecFileAsync } from '../../../../main/github/project-view/internals' import type { GitHubProjectRow } from '../../../../shared/github/project-types' import ProjectCell from './ProjectCell' -import { fetchAllItems } from '../../../../main/github/project-view/project-view-items' -import { _resetProjectViewCachesForTests } from '../../../../main/github/project-view/project-view-cache' vi.mock('../../../../main/github/project-view/internals', () => ({ acquire: vi.fn(), @@ -26,13 +29,15 @@ vi.mock('../../../../main/github/project-view/project-view-config', () => ({ ownerQueryRoot: () => 'organization' })) +const parent = { number: 10, title: 'Parent', url: 'https://github.com/o/r/issues/10' } const item: RawItem = { id: 'item-1', type: 'ISSUE', content: { __typename: 'Issue', number: 42, - title: 'Parent issue', + title: 'Issue', + parent, subIssuesSummary: { completed: 1, total: 2, percentCompleted: 50 } }, fieldValues: { @@ -57,46 +62,79 @@ const args = { ownerType: 'organization', projectNumber: 1, query: '', - first: 50, + first: 100, after: null, - includeParent: true, + unsupportedFields: new Set(), host: 'acme.ghe.com' } as const +const prText = '#1, #2, #3, #4, #5, #6, #7, #8, #9, #10 +2' +const missingSummary = { + extensions: { code: 'undefinedField', typeName: 'Issue', fieldName: 'subIssuesSummary' }, + message: "Field 'subIssuesSummary' doesn't exist on type 'Issue'" +} +const missingPrs = { + extensions: { code: 'undefinedType', typeName: 'ProjectV2ItemFieldPullRequestValue' }, + message: "No such type ProjectV2ItemFieldPullRequestValue, so it can't be a fragment condition" +} +const missingParent = { type: 'FIELD_NOT_FOUND', path: ['parent'] } -beforeEach(() => { - vi.clearAllMocks() - _resetProjectViewCachesForTests() - vi.mocked(ghExecFileAsync).mockResolvedValue({ +function response(nodes: RawItem[]) { + return { stdout: JSON.stringify({ data: { organization: { projectV2: { items: { - totalCount: 1, + totalCount: nodes.length, pageInfo: { hasNextPage: false }, - nodes: [item] + nodes } } } } }), stderr: '' - }) + } +} +function selectedResponse(arguments_: string[]) { + const query = arguments_.join(' ') + const content = { ...item.content } + if (!query.includes('parent {')) { + delete content.parent + } + if (!query.includes('subIssuesSummary {')) { + delete content.subIssuesSummary + } + return response([ + { + ...item, + content, + fieldValues: query.includes('... on ProjectV2ItemFieldPullRequestValue') + ? item.fieldValues + : { nodes: [] } + } + ]) +} +beforeEach(() => { + vi.clearAllMocks() + _resetProjectViewCachesForTests() + vi.mocked(ghExecFileAsync) + .mockReset() + .mockImplementation(async (arguments_) => selectedResponse(arguments_)) }) afterEach(() => { cleanup() vi.restoreAllMocks() }) -function renderColumns(raw: RawItem): void { +function normalized(raw: RawItem): GitHubProjectRow { const result = normalizeItem(raw, 0) if (!result.ok) { throw new Error('Expected a project row') } - renderRowColumns(result.row) + return result.row } - -function renderRowColumns(row: GitHubProjectRow): void { +function renderColumns(row: GitHubProjectRow): void { for (const [id, dataType] of [ ['field-pr', 'LINKED_PULL_REQUESTS'], ['field-progress', 'SUB_ISSUES_PROGRESS'] @@ -113,100 +151,197 @@ function renderRowColumns(row: GitHubProjectRow): void { } describe('Project columns from the items response', () => { - it.each(['#1, #2, #3, #4, #5, #6, #7, #8, #9, #10 +2', '1/2 (50%)'])( - 'renders %s from the existing items request', + it.each([prText, '1/2 (50%)'])( + 'renders %s through one bounded items request on a named cloud host', async (expectedText) => { const page = await fetchItemsPageWithRaw(args) if (!page.ok || !page.page.nodes?.[0]) { throw new Error('Expected an items page') } - renderColumns(page.page.nodes[0]) + const row = normalized(page.page.nodes[0]) + renderColumns(row) expect(screen.getByText(expectedText).textContent).toBe(expectedText) + expect(row.fieldValuesByFieldId).toEqual({}) // Older sort/group consumers never receive a new value discriminant. expect(ghExecFileAsync).toHaveBeenCalledTimes(1) const query = vi.mocked(ghExecFileAsync).mock.calls[0][0].join(' ') - expect(query).toContain('... on ProjectV2ItemFieldPullRequestValue') expect(query).toContain('pullRequests(first:10)') expect(query).toContain('subIssuesSummary { completed total percentCompleted }') expect(query).not.toContain('ProjectV2ItemFieldProgressValue') } ) - it('keeps unsupported or absent summaries blank for old hosts, drafts and empty parents', () => { - renderColumns({ id: 'old-host', type: 'ISSUE', content: { title: 'Old host' } }) - renderColumns({ id: 'draft', type: 'DRAFT_ISSUE', content: { title: 'Draft' } }) - renderColumns({ - id: 'empty', - type: 'ISSUE', - content: { - subIssuesSummary: { total: 0, completed: 0, percentCompleted: 0 } + it.each([ + { completed: 0, total: 2, percentCompleted: 0 }, + { completed: 2, total: 2, percentCompleted: 100 } + ])('preserves zero and complete counters: %j', (summary) => { + renderColumns(normalized({ ...item, content: { subIssuesSummary: summary } })) + expect( + screen.getByText(`${summary.completed}/2 (${summary.percentCompleted}%)`).textContent + ).toBeTruthy() + }) + + it('keeps old-host, draft, PR, redacted and zero-total rows blank', () => { + for (const raw of [ + { id: 'old', type: 'ISSUE', content: {} }, + { id: 'draft', type: 'DRAFT_ISSUE', content: {} }, + { id: 'pr', type: 'PULL_REQUEST', content: {} }, + { id: 'redacted', type: 'REDACTED', content: null }, + { + id: 'empty', + type: 'ISSUE', + content: { subIssuesSummary: { total: 0, completed: 0, percentCompleted: 0 } } } - }) + ]) { + renderColumns(normalized(raw)) + } expect(document.body.textContent).toBe('') }) it.each([ + { errors: [missingSummary], parentDropped: false, summary: false, prs: true }, + { errors: [missingPrs], parentDropped: false, summary: true, prs: false }, + { errors: [missingParent], parentDropped: true, summary: true, prs: true }, + { errors: [missingSummary, missingPrs], parentDropped: false, summary: false, prs: false }, { - extensions: { code: 'undefinedField' }, - message: "Field 'subIssuesSummary' doesn't exist on type 'Issue'" - }, - { - extensions: { code: 'undefinedType' }, - message: - "No such type ProjectV2ItemFieldPullRequestValue, so it can't be a fragment condition" - }, - { type: 'FIELD_NOT_FOUND', path: ['parent'] } - ])('retries an unsupported optional selection once: %j', async (error) => { + errors: [{ message: "Cannot query field 'subIssuesSummary' on type 'Issue'." }], + parentDropped: false, + summary: false, + prs: true + } + ])('omits only unsupported selections: %j', async ({ errors, parentDropped, summary, prs }) => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.mocked(ghExecFileAsync).mockResolvedValueOnce({ + stdout: JSON.stringify({ errors }), + stderr: '' + }) + const result = await fetchAllItems(args) + if (!result.ok) { + throw new Error('Expected compatibility fallback to succeed') + } + expect(result.parentFieldDropped).toBe(parentDropped) + expect(result.rows[0].content.parentIssue).toEqual(parentDropped ? null : parent) + expect(warning).toHaveBeenCalledTimes(parentDropped ? 1 : 0) + renderColumns(result.rows[0]) + expect(Boolean(screen.queryByText('1/2 (50%)'))).toBe(summary) + expect(Boolean(screen.queryByText(prText))).toBe(prs) + expect(ghExecFileAsync).toHaveBeenCalledTimes(2) + const query = vi.mocked(ghExecFileAsync).mock.calls[1][0].join(' ') + expect(query.includes('parent {')).toBe(!parentDropped) + expect(query.includes('subIssuesSummary {')).toBe(summary) + expect(query.includes('... on ProjectV2ItemFieldPullRequestValue')).toBe(prs) + await fetchAllItems(args) + expect(ghExecFileAsync).toHaveBeenCalledTimes(3) + await fetchAllItems({ ...args, owner: 'another-owner' }) + expect(vi.mocked(ghExecFileAsync).mock.calls[3][0].join(' ')).toContain('subIssuesSummary {') + }) + + it('bounds sequential missing-field retries by the three optional selections', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.mocked(ghExecFileAsync) - .mockResolvedValueOnce({ + for (const error of [missingSummary, missingPrs, missingParent]) { + vi.mocked(ghExecFileAsync).mockResolvedValueOnce({ stdout: JSON.stringify({ errors: [error] }), stderr: '' }) - .mockResolvedValue({ - stdout: JSON.stringify({ - data: { - organization: { - projectV2: { - items: { - totalCount: 1, - pageInfo: { hasNextPage: false }, - nodes: [{ id: 'old-server', type: 'ISSUE', content: { title: 'Old server' } }] - } - } - } - } - }), + } + expect(await fetchAllItems(args)).toMatchObject({ ok: true, parentFieldDropped: true }) + expect(ghExecFileAsync).toHaveBeenCalledTimes(4) + }) + + it.each(['FORBIDDEN', 'UNAUTHORIZED', 'RATE_LIMITED', 'NETWORK_ERROR'])( + 'never caches unrelated %s failures', + async (type) => { + vi.mocked(ghExecFileAsync).mockResolvedValueOnce({ + stdout: JSON.stringify({ errors: [{ type, message: 'Cannot access subIssuesSummary' }] }), stderr: '' }) - const result = await fetchAllItems(args) - if (!result.ok) { - throw new Error('Expected the fallback items query to succeed') + expect(await fetchAllItems(args)).toMatchObject({ ok: false }) + expect(ghExecFileAsync).toHaveBeenCalledTimes(1) + expect(await fetchAllItems(args)).toMatchObject({ ok: true, parentFieldDropped: false }) + expect(vi.mocked(ghExecFileAsync).mock.calls[1][0].join(' ')).toContain('subIssuesSummary {') } - expect(result.parentFieldDropped).toBe(true) - renderRowColumns(result.rows[0]) - expect(document.body.textContent).toBe('') - expect(ghExecFileAsync).toHaveBeenCalledTimes(2) - const queries = vi - .mocked(ghExecFileAsync) - .mock.calls.map(([arguments_]) => arguments_.join(' ')) - expect(queries[0]).toContain('subIssuesSummary') - expect(queries[0]).toContain('ProjectV2ItemFieldPullRequestValue') - expect(queries[1]).not.toContain('subIssuesSummary') - expect(queries[1]).not.toContain('ProjectV2ItemFieldPullRequestValue') - expect(queries[1]).not.toContain('parent {') - await fetchAllItems(args) + ) + + it('shares a pending owner capability probe between concurrent callers', async () => { + let entered = () => {} + let release = () => {} + const started = new Promise((resolve) => { + entered = resolve + }) + const pending = new Promise((resolve) => { + release = resolve + }) + vi.mocked(ghExecFileAsync).mockImplementationOnce(async () => { + entered() + await pending + return { stdout: JSON.stringify({ errors: [missingSummary] }), stderr: '' } + }) + const first = fetchAllItems(args) + await started + const second = fetchAllItems(args) + expect(ghExecFileAsync).toHaveBeenCalledTimes(1) + release() + const results = await Promise.all([first, second]) + expect(results).toEqual([ + expect.objectContaining({ ok: true, parentFieldDropped: false }), + expect.objectContaining({ ok: true, parentFieldDropped: false }) + ]) expect(ghExecFileAsync).toHaveBeenCalledTimes(3) - expect(vi.mocked(ghExecFileAsync).mock.calls[2][0].join(' ')).not.toContain('subIssuesSummary') + expect(vi.mocked(ghExecFileAsync).mock.calls[2][0].join(' ')).not.toContain( + 'subIssuesSummary {' + ) }) - it('keeps unrelated API failures instead of treating them as schema capabilities', async () => { + it('keeps supported fields and the cursor on pages after a capability retry', async () => { + vi.mocked(ghExecFileAsync).mockResolvedValueOnce({ + stdout: JSON.stringify({ errors: [missingSummary] }), + stderr: '' + }) + const firstPage = JSON.parse( + selectedResponse(['parent {', '... on ProjectV2ItemFieldPullRequestValue']).stdout + ) + firstPage.data.organization.projectV2.items.pageInfo = { hasNextPage: true, endCursor: 'next' } + firstPage.data.organization.projectV2.items.totalCount = 2 vi.mocked(ghExecFileAsync).mockResolvedValueOnce({ - stdout: JSON.stringify({ - errors: [{ type: 'FORBIDDEN', message: 'Cannot access subIssuesSummary' }] - }), + stdout: JSON.stringify(firstPage), stderr: '' }) - expect(await fetchAllItems(args)).toMatchObject({ ok: false }) + expect(await fetchAllItems(args)).toMatchObject({ + ok: true, + rows: [expect.objectContaining({ position: 0 }), expect.objectContaining({ position: 1 })] + }) + const last = vi.mocked(ghExecFileAsync).mock.calls[2][0] + expect(last).toContain('after=next') + expect(last.join(' ')).not.toContain('subIssuesSummary {') + expect(last.join(' ')).toContain('parent {') + expect(last.join(' ')).toContain('... on ProjectV2ItemFieldPullRequestValue') + }) + + it.each([10, 12])('shows exact counts for a linked PR list with total %i', (totalCount) => { + const row = normalized(item) + if (!row.content.linkedPullRequests) { + throw new Error('Expected linked PR content') + } + row.content.linkedPullRequests.totalCount = totalCount + renderColumns(row) + expect( + screen.getByText(totalCount === 12 ? prText : prText.replace(' +2', '')).textContent + ).toBeTruthy() + }) + + it.each([1, 10])('keeps %i returned items in one request', async (count) => { + vi.mocked(ghExecFileAsync).mockResolvedValueOnce( + response(Array.from({ length: count }, (_, i) => ({ ...item, id: `item-${i}` }))) + ) + expect(await fetchAllItems(args)).toMatchObject({ + ok: true, + rows: Array.from({ length: count }, () => + expect.objectContaining({ + content: expect.objectContaining({ + linkedPullRequests: expect.objectContaining({ totalCount: 12 }) + }) + }) + ) + }) expect(ghExecFileAsync).toHaveBeenCalledTimes(1) }) }) diff --git a/src/renderer/src/components/github-project/ProjectCell.tsx b/src/renderer/src/components/github-project/ProjectCell.tsx index 0ba11c456dbb..e7e3f59589a5 100644 --- a/src/renderer/src/components/github-project/ProjectCell.tsx +++ b/src/renderer/src/components/github-project/ProjectCell.tsx @@ -94,13 +94,14 @@ export default function ProjectCell({ ) } if (field.dataType === 'LINKED_PULL_REQUESTS') { - if (value?.kind !== 'pull-requests') { + const linked = row.content.linkedPullRequests + if (!linked) { return } - const labels = value.pullRequests.map((pr) => `#${pr.number}`) + const labels = linked.pullRequests.map((pr) => `#${pr.number}`) const overflow = - value.totalCount > value.pullRequests.length - ? ` +${value.totalCount - value.pullRequests.length}` + linked.totalCount > linked.pullRequests.length + ? ` +${linked.totalCount - linked.pullRequests.length}` : '' return ( diff --git a/src/renderer/src/components/github-project/group-sort.test.ts b/src/renderer/src/components/github-project/group-sort.test.ts index f3401de42f20..96d2c6c6c3fe 100644 --- a/src/renderer/src/components/github-project/group-sort.test.ts +++ b/src/renderer/src/components/github-project/group-sort.test.ts @@ -442,29 +442,3 @@ it('uses the first iteration ordering and metadata when legacy field IDs repeat' completed: true }) }) - -it('preserves position and unsupported grouping for linked PR relation values', () => { - const field: GitHubProjectField = { - kind: 'field', - id: 'linked', - name: 'Linked pull requests', - dataType: 'LINKED_PULL_REQUESTS' - } - const rows = [ - makeRow('empty', 1, {}), - makeRow('linked', 0, { - linked: { - kind: 'pull-requests', - fieldId: 'linked', - totalCount: 1, - pullRequests: [{ number: 42, title: 'Change', url: 'https://github.com/o/r/pull/42' }] - } - }) - ] - const table = makeTable( - { ...makeView(field, { field, direction: 'DESC' }), groupByFields: [field] }, - rows - ) - expect(sortRows(table, rows).map((row) => row.id)).toEqual(['linked', 'empty']) - expect(groupRows(table, rows)).toMatchObject([{ key: '__empty__', rows }]) -}) diff --git a/src/shared/github/project-group-sort.ts b/src/shared/github/project-group-sort.ts index a3a49e879898..3330c4ea37a0 100644 --- a/src/shared/github/project-group-sort.ts +++ b/src/shared/github/project-group-sort.ts @@ -22,14 +22,12 @@ export const EMPTY_PROJECT_GROUP_KEY = '__empty__' type ProjectFieldValue = GitHubProjectRow['fieldValuesByFieldId'][string] -/** Read-only relations stay outside grouping/sorting; absent and blank values sort last. */ +/** False for anything that renders as an empty cell — absent, or present with a blank payload. */ function hasNonEmptyFieldValue(value: ProjectFieldValue | undefined): boolean { if (!value) { return false } switch (value.kind) { - case 'pull-requests': - return false case 'users': return Boolean(value.users[0]?.login) case 'labels': @@ -118,8 +116,6 @@ function labelForEmpty(field: GitHubProjectField): string { function deriveStringValue(value: GitHubProjectRow['fieldValuesByFieldId'][string]): string { switch (value.kind) { - case 'pull-requests': - return '' case 'text': return value.text case 'number': diff --git a/src/shared/github/project-types.ts b/src/shared/github/project-types.ts index 365405d6ae49..d0b6f496c6af 100644 --- a/src/shared/github/project-types.ts +++ b/src/shared/github/project-types.ts @@ -113,6 +113,11 @@ export type GitHubIssueType = { description: string | null } +export type GitHubProjectLinkedPullRequests = { + pullRequests: { number: number; title: string; url: string }[] + totalCount: number +} + export type GitHubProjectFieldValue = | { kind: 'single-select' @@ -136,12 +141,6 @@ export type GitHubProjectFieldValue = | { kind: 'date'; fieldId: string; date: string; fieldName?: string } | { kind: 'labels'; fieldId: string; labels: GitHubProjectLabel[] } | { kind: 'users'; fieldId: string; users: GitHubProjectUser[] } - | { - kind: 'pull-requests' - fieldId: string - pullRequests: { number: number; title: string; url: string }[] - totalCount: number - } export type GitHubProjectRowItemType = 'ISSUE' | 'PULL_REQUEST' | 'DRAFT_ISSUE' | 'REDACTED' @@ -165,6 +164,7 @@ export type GitHubProjectRow = { assignees: GitHubProjectUser[] labels: GitHubProjectLabel[] parentIssue: GitHubProjectParentIssue | null + linkedPullRequests?: GitHubProjectLinkedPullRequests | null /** Present when the ProjectV2Item content is an Issue and GitHub returned its summary. */ subIssuesProgress?: { completed: number; total: number; percentCompleted: number } | null /** Issue.issueType when set; null on PRs/drafts/redacted or when unset. */ From 5f5735dbc5147a8e1644d7f90981fa75265a27ed Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:29:04 -0700 Subject: [PATCH 4/8] Preserve nullable project values and unsupported fetch concurrency --- .../github/project-view/project-view-cache.ts | 12 +- .../project-view-field-normalization.ts | 7 +- .../project-view-item-normalization.ts | 4 +- .../github/project-view/project-view-items.ts | 4 +- .../project-view-query-fragments.ts | 1 - .../github-project/ProjectCell.test.tsx | 217 ++++++++++++++++-- 6 files changed, 204 insertions(+), 41 deletions(-) diff --git a/src/main/github/project-view/project-view-cache.ts b/src/main/github/project-view/project-view-cache.ts index 008a85285813..7f1bad822cd7 100644 --- a/src/main/github/project-view/project-view-cache.ts +++ b/src/main/github/project-view/project-view-cache.ts @@ -82,14 +82,6 @@ export function getUnsupportedItemFields(scopeKey: string): ReadonlySet !node || typeof node.number !== 'number' ? [] diff --git a/src/main/github/project-view/project-view-item-normalization.ts b/src/main/github/project-view/project-view-item-normalization.ts index 63f1704fde8e..2cb40f6f388f 100644 --- a/src/main/github/project-view/project-view-item-normalization.ts +++ b/src/main/github/project-view/project-view-item-normalization.ts @@ -47,7 +47,7 @@ export type RawItem = { updatedAt?: string content?: RawContent | null fieldValues?: { - nodes?: RawFieldValue[] + nodes?: (RawFieldValue | null)[] pageInfo?: { hasNextPage?: boolean } } } @@ -129,7 +129,7 @@ export function normalizeItem(raw: RawItem, position: number): NormalizedItemOut let linkedPullRequests: GitHubProjectLinkedPullRequests | null = null const fieldValuesByFieldId: Record = {} for (const fv of raw.fieldValues?.nodes ?? []) { - if (fv.__typename === 'ProjectV2ItemFieldPullRequestValue') { + if (fv?.__typename === 'ProjectV2ItemFieldPullRequestValue') { linkedPullRequests = normalizeLinkedPullRequests(fv) continue } diff --git a/src/main/github/project-view/project-view-items.ts b/src/main/github/project-view/project-view-items.ts index 8e03d96d5b4d..3c55cf0819ca 100644 --- a/src/main/github/project-view/project-view-items.ts +++ b/src/main/github/project-view/project-view-items.ts @@ -29,7 +29,7 @@ export async function fetchAllItems(args: { > { const scopeKey = ownerScopeKey(args.owner, args.ownerType, args.host) const inFlight = parentFieldProbeInFlight.get(scopeKey) - if (inFlight) { + if (inFlight && getUnsupportedItemFields(scopeKey).size < 3) { await inFlight.catch(() => {}) } const unsupportedFields = new Set(getUnsupportedItemFields(scopeKey)) @@ -63,7 +63,7 @@ export async function fetchAllItems(args: { return result } let first: Awaited> - if (!parentFieldProbeInFlight.has(scopeKey)) { + if (unsupportedFields.size < 3 && !parentFieldProbeInFlight.has(scopeKey)) { let resolveProbe: () => void = () => {} parentFieldProbeInFlight.set( scopeKey, diff --git a/src/main/github/project-view/project-view-query-fragments.ts b/src/main/github/project-view/project-view-query-fragments.ts index a28b76cc109c..f117eed2af41 100644 --- a/src/main/github/project-view/project-view-query-fragments.ts +++ b/src/main/github/project-view/project-view-query-fragments.ts @@ -66,7 +66,6 @@ export function fieldValuesSelection(includeLinkedPullRequests: boolean): string const linkedPullRequestsFrag = includeLinkedPullRequests ? ` ... on ProjectV2ItemFieldPullRequestValue { - field { ...FieldConfig } pullRequests(first:10) { totalCount nodes { number title url } diff --git a/src/renderer/src/components/github-project/ProjectCell.test.tsx b/src/renderer/src/components/github-project/ProjectCell.test.tsx index c74710f8f13e..117077e58317 100644 --- a/src/renderer/src/components/github-project/ProjectCell.test.tsx +++ b/src/renderer/src/components/github-project/ProjectCell.test.tsx @@ -13,7 +13,9 @@ import { type OptionalProjectItemField } from '../../../../main/github/project-view/project-view-cache' import { ghExecFileAsync } from '../../../../main/github/project-view/internals' -import type { GitHubProjectRow } from '../../../../shared/github/project-types' +import type { GitHubProjectRow, GitHubProjectTable } from '../../../../shared/github/project-types' +import { sortRows, groupRows } from '../../../../shared/github/project-group-sort' +import * as fieldNormalization from '../../../../main/github/project-view/project-view-field-normalization' import ProjectCell from './ProjectCell' vi.mock('../../../../main/github/project-view/internals', () => ({ @@ -78,15 +80,22 @@ const missingPrs = { } const missingParent = { type: 'FIELD_NOT_FOUND', path: ['parent'] } -function response(nodes: RawItem[]) { +function response( + nodes: RawItem[], + totalCount = nodes.length, + pageInfo: { hasNextPage: boolean; endCursor: string | null } = { + hasNextPage: false, + endCursor: null + } +) { return { stdout: JSON.stringify({ data: { organization: { projectV2: { items: { - totalCount: nodes.length, - pageInfo: { hasNextPage: false }, + totalCount, + pageInfo, nodes } } @@ -154,6 +163,24 @@ describe('Project columns from the items response', () => { it.each([prText, '1/2 (50%)'])( 'renders %s through one bounded items request on a named cloud host', async (expectedText) => { + vi.mocked(ghExecFileAsync).mockResolvedValueOnce( + response([ + { + ...item, + fieldValues: { + nodes: [ + null, + { + __typename: 'ProjectV2ItemFieldTextValue', + field: { id: 'notes' }, + text: 'Keep this too' + }, + ...(item.fieldValues?.nodes ?? []) + ] + } + } + ]) + ) const page = await fetchItemsPageWithRaw(args) if (!page.ok || !page.page.nodes?.[0]) { throw new Error('Expected an items page') @@ -161,7 +188,9 @@ describe('Project columns from the items response', () => { const row = normalized(page.page.nodes[0]) renderColumns(row) expect(screen.getByText(expectedText).textContent).toBe(expectedText) - expect(row.fieldValuesByFieldId).toEqual({}) // Older sort/group consumers never receive a new value discriminant. + expect(row.fieldValuesByFieldId).toEqual({ + notes: { kind: 'text', fieldId: 'notes', text: 'Keep this too' } + }) expect(ghExecFileAsync).toHaveBeenCalledTimes(1) const query = vi.mocked(ghExecFileAsync).mock.calls[0][0].join(' ') expect(query).toContain('pullRequests(first:10)') @@ -291,6 +320,49 @@ describe('Project columns from the items response', () => { ) }) + it('fetches unrelated projects concurrently when all optional selections are unsupported', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.mocked(ghExecFileAsync).mockResolvedValueOnce({ + stdout: JSON.stringify({ errors: [missingParent, missingSummary, missingPrs] }), + stderr: '' + }) + expect(await fetchAllItems(args)).toMatchObject({ ok: true, parentFieldDropped: true }) + vi.mocked(ghExecFileAsync).mockClear() + let entered = () => {} + let release = () => {} + const started = new Promise((resolve) => { + entered = resolve + }) + const pending = new Promise((resolve) => { + release = resolve + }) + vi.mocked(ghExecFileAsync).mockImplementationOnce(async (arguments_) => { + entered() + await pending + return selectedResponse(arguments_) + }) + const first = fetchAllItems(args) + await started + const second = fetchAllItems({ ...args, projectNumber: 2 }) + // Flush the normal request's async auth boundary without releasing the first response. + await new Promise((resolve) => setTimeout(resolve, 0)) + const concurrentCalls = vi.mocked(ghExecFileAsync).mock.calls.slice() + release() + expect(await Promise.all([first, second])).toEqual([ + expect.objectContaining({ ok: true, parentFieldDropped: true }), + expect.objectContaining({ ok: true, parentFieldDropped: true }) + ]) + expect(concurrentCalls).toHaveLength(2) + expect( + concurrentCalls.map(([arguments_]) => arguments_.find((arg) => arg.startsWith('num='))) + ).toEqual(['num=1', 'num=2']) + for (const [arguments_] of concurrentCalls) { + expect(arguments_.join(' ')).not.toMatch( + /parent \{|subIssuesSummary \{|\.\.\. on ProjectV2ItemFieldPullRequestValue/ + ) + } + }) + it('keeps supported fields and the cursor on pages after a capability retry', async () => { vi.mocked(ghExecFileAsync).mockResolvedValueOnce({ stdout: JSON.stringify({ errors: [missingSummary] }), @@ -328,20 +400,125 @@ describe('Project columns from the items response', () => { ).toBeTruthy() }) - it.each([1, 10])('keeps %i returned items in one request', async (count) => { - vi.mocked(ghExecFileAsync).mockResolvedValueOnce( - response(Array.from({ length: count }, (_, i) => ({ ...item, id: `item-${i}` }))) - ) - expect(await fetchAllItems(args)).toMatchObject({ - ok: true, - rows: Array.from({ length: count }, () => - expect.objectContaining({ - content: expect.objectContaining({ - linkedPullRequests: expect.objectContaining({ totalCount: 12 }) - }) - }) - ) - }) - expect(ghExecFileAsync).toHaveBeenCalledTimes(1) + it('preserves populated and legacy rows through shared sorting, grouping and cells', async () => { + const result = await fetchAllItems(args) + if (!result.ok) { + throw new Error('Expected rows') + } + const populated = result.rows[0] + populated.fieldValuesByFieldId.points = { kind: 'number', fieldId: 'points', number: 2 } + const legacy = normalized({ id: 'legacy', type: 'ISSUE', content: { title: 'Older host' } }) + delete legacy.content.linkedPullRequests + delete legacy.content.subIssuesProgress + legacy.fieldValuesByFieldId.points = { kind: 'number', fieldId: 'points', number: 1 } + const points = { kind: 'field', id: 'points', name: 'Points', dataType: 'NUMBER' } as const + const prs = { + kind: 'field', + id: 'field-pr', + name: 'Linked PRs', + dataType: 'LINKED_PULL_REQUESTS' + } as const + const progress = { + kind: 'field', + id: 'field-progress', + name: 'Progress', + dataType: 'SUB_ISSUES_PROGRESS' + } as const + const table: GitHubProjectTable = { + project: { + id: 'P', + owner: 'o', + ownerType: 'organization', + number: 1, + title: 'Project', + url: '' + }, + selectedView: { + id: 'V', + number: 1, + name: 'Table', + layout: 'TABLE_LAYOUT', + filter: '', + fields: [points, prs, progress], + groupByFields: [points], + sortByFields: [{ field: points, direction: 'ASC' }] + }, + rows: [populated, legacy], + totalCount: 2, + parentFieldDropped: false + } + const sorted = sortRows(table, table.rows) + expect(sorted.map((row) => row.id)).toEqual(['legacy', 'item-1']) + const groups = groupRows(table, sorted) + expect(groups.map((group) => group.label)).toEqual(['1', '2']) + renderColumns(groups[1].rows[0]) + expect(screen.getByText(prText)).toBeTruthy() + expect(screen.getByText('1/2 (50%)')).toBeTruthy() + cleanup() + renderColumns(groups[0].rows[0]) + expect(document.body.textContent).toBe('') + cleanup() + // Existing builtin ordering still uses the field map, with no new relation value kind. + for (const field of [prs, progress]) { + const relationTable = { + ...table, + selectedView: { + ...table.selectedView, + groupByFields: [field], + sortByFields: [{ field, direction: 'ASC' as const }] + } + } + expect(sortRows(relationTable, table.rows).map((row) => row.id)).toEqual(['item-1', 'legacy']) + expect(groupRows(relationTable, table.rows).map((group) => group.key)).toEqual(['__empty__']) + } }) + + it.each([50, 500])( + 'normalizes %i ten-PR rows with linear work and page requests', + async (count) => { + let prNodeReads = 0 + const normalize = fieldNormalization.normalizeLinkedPullRequests + const normalizer = vi + .spyOn(fieldNormalization, 'normalizeLinkedPullRequests') + .mockImplementation((raw) => { + for (const node of raw.pullRequests?.nodes ?? []) { + if (node) { + const number = node.number + Object.defineProperty(node, 'number', { + get() { + prNodeReads++ + return number + } + }) + } + } + return normalize(raw) + }) + const corpus = Array.from({ length: count }, (_, i) => ({ ...item, id: `item-${i}` })) + vi.mocked(ghExecFileAsync).mockImplementation(async (arguments_) => { + const after = arguments_.find((arg) => arg.startsWith('after=')) + const offset = after ? Number(after.slice('after='.length)) : 0 + expect(offset).toBe((vi.mocked(ghExecFileAsync).mock.calls.length - 1) * 100) + const end = Math.min(offset + 100, count) + return response(corpus.slice(offset, end), count, { + hasNextPage: end < count, + endCursor: end < count ? String(end) : null + }) + }) + const result = await fetchAllItems(args) + if (!result.ok) { + throw new Error('Expected paginated rows') + } + expect(result.rows).toHaveLength(count) + expect(result.rows.at(-1)?.position).toBe(count - 1) + expect(normalizer).toHaveBeenCalledTimes(count) + expect(prNodeReads).toBe(count * 10 * 2) // Validation and copying each returned PR number. + expect(ghExecFileAsync).toHaveBeenCalledTimes(Math.ceil(count / 100)) + for (const [arguments_] of vi.mocked(ghExecFileAsync).mock.calls) { + expect(arguments_.join(' ')).toContain('pullRequests(first:10)') + } + renderColumns(result.rows[count - 1]) + expect(screen.getByText(prText)).toBeTruthy() + } + ) }) From 1c6cdc6874620c7d9703f9bb04bdf0cc7c2dee3a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:36:02 -0700 Subject: [PATCH 5/8] Exercise project relation payloads through unchanged consumers --- .../task-project-board-reply-schema.test.ts | 36 ++++++++++ src/main/runtime/rpc/methods/github.test.ts | 9 ++- .../ProjectCell.test-fixture.tsx | 17 +++++ .../github/project-field-mutations.test.ts | 15 ++++ ...ithub-project-request-coordination.test.ts | 67 +++++++++++++++++- .../github/project-relations.test-fixture.ts | 69 +++++++++++++++++++ 6 files changed, 210 insertions(+), 3 deletions(-) create mode 100644 src/renderer/src/components/github-project/ProjectCell.test-fixture.tsx create mode 100644 src/shared/github/project-relations.test-fixture.ts diff --git a/mobile/src/tasks/task-project-board-reply-schema.test.ts b/mobile/src/tasks/task-project-board-reply-schema.test.ts index ced934e68c18..83b9a1b28201 100644 --- a/mobile/src/tasks/task-project-board-reply-schema.test.ts +++ b/mobile/src/tasks/task-project-board-reply-schema.test.ts @@ -1,4 +1,11 @@ import { describe, expect, it } from 'vitest' +import { projectRelationsTableFixture } from '../../../src/shared/github/project-relations.test-fixture' +import type { GitHubProjectTable } from '../../../src/shared/github/project-types' +import { sortRows, groupRows } from '../../../src/shared/github/project-group-sort' +import { + normalizeProjectTableForMobileSort, + projectFieldDisplayLabel +} from './mobile-tasks-project-fields' import { taskProjectAccessibleListSchema, taskProjectAssignableUserListSchema, @@ -121,6 +128,35 @@ describe('the board table', () => { expect(parsed.success).toBe(true) }) + it('preserves new and legacy content through schema, mobile projection and visible labels', () => { + const table = projectRelationsTableFixture() + const parsed = taskProjectViewTableSchema.parse( + JSON.parse(JSON.stringify({ ok: true, data: table })) + ) + if (!parsed.ok) { + throw new Error('Expected accepted table') + } + expect(parsed.data).toEqual(table) + // SAFETY: exact equality above proves the loose schema retained this fully typed fixture. + const decoded = parsed.data as unknown as GitHubProjectTable + const projected = normalizeProjectTableForMobileSort(decoded, decoded.rows, null) + const groups = groupRows(projected, sortRows(projected, projected.rows)) + expect(groups.map((group) => group.label)).toEqual(['1', '2']) + const rows = groups.flatMap((group) => group.rows) + expect(rows.map((row) => row.id)).toEqual(['legacy', 'populated']) + expect(rows[1].content).toEqual(table.rows[0].content) + expect(rows[0].content).not.toHaveProperty('linkedPullRequests') + expect(rows[0].content).not.toHaveProperty('subIssuesProgress') + expect( + rows.map((row) => + projected.selectedView.fields.map((field) => projectFieldDisplayLabel(row, field)) + ) + ).toEqual([ + ['1', 'Empty', 'Empty'], + ['2', 'Empty', 'Empty'] + ]) + }) + it('refuses a table with no selectedView, which was a read on undefined', () => { const parsed = taskProjectViewTableSchema.safeParse({ ok: true, diff --git a/src/main/runtime/rpc/methods/github.test.ts b/src/main/runtime/rpc/methods/github.test.ts index bd333234cd0a..a6b876689496 100644 --- a/src/main/runtime/rpc/methods/github.test.ts +++ b/src/main/runtime/rpc/methods/github.test.ts @@ -4,6 +4,7 @@ import { RpcDispatcher } from '../dispatcher' import type { RpcRequest } from '../core' import type { OrcaRuntimeService } from '../../orca-runtime' import { GITHUB_METHODS } from './github' +import { projectRelationsTableFixture } from '../../../../shared/github/project-relations.test-fixture' function makeRequest(method: string, params?: unknown): RpcRequest { return { id: 'req-1', authToken: 'tok', method, params } @@ -762,9 +763,10 @@ describe('github RPC methods', () => { }) it('fetches GitHub project tables on the runtime server', async () => { + const table = projectRelationsTableFixture() const runtime = { getRuntimeId: () => 'test-runtime', - getGitHubProjectViewTable: vi.fn().mockResolvedValue({ ok: true, data: { rows: [] } }) + getGitHubProjectViewTable: vi.fn().mockResolvedValue({ ok: true, data: table }) } as unknown as OrcaRuntimeService const dispatcher = new RpcDispatcher({ runtime, methods: GITHUB_METHODS }) @@ -787,7 +789,10 @@ describe('github RPC methods', () => { viewName: undefined, queryOverride: 'is:open' }) - expect(response).toMatchObject({ ok: true, result: { ok: true, data: { rows: [] } } }) + if (!response.ok) { + throw new Error('Expected successful RPC response') + } + expect(response.result).toEqual({ ok: true, data: projectRelationsTableFixture() }) }) it('fetches GitHub project work item details by slug on the runtime server', async () => { diff --git a/src/renderer/src/components/github-project/ProjectCell.test-fixture.tsx b/src/renderer/src/components/github-project/ProjectCell.test-fixture.tsx new file mode 100644 index 000000000000..f6599709315d --- /dev/null +++ b/src/renderer/src/components/github-project/ProjectCell.test-fixture.tsx @@ -0,0 +1,17 @@ +import React from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import type { GitHubProjectRow } from '../../../../shared/github/project-types' +import ProjectCell from './ProjectCell' + +export function projectRelationCellText(row: GitHubProjectRow): string[] { + return ['LINKED_PULL_REQUESTS', 'SUB_ISSUES_PROGRESS'].map((dataType) => + renderToStaticMarkup( + + ).replace(/<[^>]*>/g, '') + ) +} diff --git a/src/renderer/src/store/github/project-field-mutations.test.ts b/src/renderer/src/store/github/project-field-mutations.test.ts index 74be7944da70..5fcbb47b59f3 100644 --- a/src/renderer/src/store/github/project-field-mutations.test.ts +++ b/src/renderer/src/store/github/project-field-mutations.test.ts @@ -6,6 +6,8 @@ import { } from '../slices/github-slice-test-harness' import { projectViewCacheKey } from './cache-identity' import type { GitHubProjectTable } from '../../../../shared/github/project-types' +import { projectRelationsTableFixture } from '../../../../shared/github/project-relations.test-fixture' +import { projectRelationCellText } from '../../components/github-project/ProjectCell.test-fixture' import type { GitHubProjectMutationResult } from '../../../../shared/github/project-result-types' const key = projectViewCacheKey('user', 'owner', 1, 'view') @@ -109,6 +111,16 @@ beforeEach(() => { describe('project field writes', () => { it('keeps rapid moves optimistic and sends update then clear in order', async () => { const store = setup() + const table = fixture() + table.rows[0].content = projectRelationsTableFixture().rows[0].content + store.setState({ projectViewCache: { [key]: { data: table, fetchedAt: 1 } } }) + const visibleRelations = () => { + const row = store.getState().projectViewCache[key]?.data?.rows[0] + if (!row) { + throw new Error('Expected cached row') + } + return projectRelationCellText(row) + } const first = deferred() mockApi.gh.updateProjectItemField.mockReturnValueOnce(first.promise) mockApi.gh.clearProjectItemField.mockResolvedValueOnce({ ok: true }) @@ -116,14 +128,17 @@ describe('project field writes', () => { .getState() .updateProjectFieldValue(key, 'row', 'status', { kind: 'single-select', optionId: 'done' }) expect(field(store)).toMatchObject({ optionId: 'done', name: 'Done', color: 'PURPLE' }) + expect(visibleRelations()).toEqual(['#12 +2', '1/2 (50%)']) const clear = store.getState().clearProjectFieldValue(key, 'row', 'status') expect(field(store)).toBeUndefined() + expect(visibleRelations()).toEqual(['#12 +2', '1/2 (50%)']) await vi.waitFor(() => expect(mockApi.gh.updateProjectItemField).toHaveBeenCalledTimes(1)) expect(mockApi.gh.clearProjectItemField).not.toHaveBeenCalled() first.resolve({ ok: true }) await Promise.all([update, clear]) expect(mockApi.gh.clearProjectItemField).toHaveBeenCalledTimes(1) expect(field(store)).toBeUndefined() + expect(visibleRelations()).toEqual(['#12 +2', '1/2 (50%)']) }) it.each([true, false])( diff --git a/src/renderer/src/store/slices/github-project-request-coordination.test.ts b/src/renderer/src/store/slices/github-project-request-coordination.test.ts index 3c818c088419..c2f417f8392e 100644 --- a/src/renderer/src/store/slices/github-project-request-coordination.test.ts +++ b/src/renderer/src/store/slices/github-project-request-coordination.test.ts @@ -2,7 +2,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { GitHubProjectTable } from '../../../../shared/github/project-types' import type { GetProjectViewTableResult } from '../../../../shared/github/project-result-types' import { projectViewCacheKey } from '../github/cache-identity' -import { createTestStore, mockApi, resetRemoteRuntimeMocks } from './github-slice-test-harness' +import { + createTestStore, + mockApi, + resetRemoteRuntimeMocks, + runtimeEnvironmentCall +} from './github-slice-test-harness' +import { projectRelationsTableFixture } from '../../../../shared/github/project-relations.test-fixture' +import { projectRelationCellText } from '../../components/github-project/ProjectCell.test-fixture' +import { sortRows, groupRows } from '../../../../shared/github/project-group-sort' +import { projectViewSourceScope } from '../github/cache-identity' function makeTable(title = 'Roadmap'): GitHubProjectTable { return { @@ -59,6 +68,62 @@ describe('createGitHubSlice.fetchProjectViewTable coordination', () => { expect(mockApi.gh.getProjectViewTable).not.toHaveBeenCalled() }) + it.each([{ kind: 'local' }, { kind: 'environment', environmentId: 'env-board' }] as const)( + 'preserves populated and legacy cells through the $kind cache', + async (target) => { + const table = projectRelationsTableFixture() + const store = createTestStore() + const envelope = { ok: true, data: table } + if (target.kind === 'local') { + mockApi.gh.getProjectViewTable.mockResolvedValueOnce(envelope) + } else { + runtimeEnvironmentCall.mockResolvedValueOnce({ + id: 'rpc-project', + ok: true, + result: envelope, + _meta: { runtimeId: 'remote-runtime' } + }) + } + expect(await store.getState().fetchProjectViewTable(target, request)).toEqual(envelope) + const key = projectViewCacheKey( + 'organization', + 'acme', + 1, + 'view-1', + undefined, + projectViewSourceScope(target) + ) + const cached = store.getState().projectViewCache[key]?.data + if (!cached) { + throw new Error('Expected cached table') + } + expect(cached).toEqual(table) + const groups = groupRows(cached, sortRows(cached, cached.rows)) + expect(groups.map((group) => group.label)).toEqual(['1', '2']) + expect(groups.flatMap((group) => group.rows.map(projectRelationCellText))).toEqual([ + ['', ''], + ['#12 +2', '1/2 (50%)'] + ]) + expect(cached.rows[1].content).not.toHaveProperty('linkedPullRequests') + expect(cached.rows[1].content).not.toHaveProperty('subIssuesProgress') + expect(await store.getState().fetchProjectViewTable(target, request)).toEqual(envelope) + if (target.kind === 'local') { + expect(mockApi.gh.getProjectViewTable).toHaveBeenCalledTimes(1) + expect(runtimeEnvironmentCall).not.toHaveBeenCalled() + } else { + expect(mockApi.gh.getProjectViewTable).not.toHaveBeenCalled() + expect(runtimeEnvironmentCall).toHaveBeenCalledTimes(1) + expect(runtimeEnvironmentCall).toHaveBeenCalledWith( + expect.objectContaining({ + selector: 'env-board', + method: 'github.project.viewTable', + params: request + }) + ) + } + } + ) + it('deduplicates identical non-forced in-flight requests', async () => { const store = createTestStore() const pending = Promise.withResolvers() diff --git a/src/shared/github/project-relations.test-fixture.ts b/src/shared/github/project-relations.test-fixture.ts new file mode 100644 index 000000000000..bcc02c00fe64 --- /dev/null +++ b/src/shared/github/project-relations.test-fixture.ts @@ -0,0 +1,69 @@ +import type { GitHubProjectRow, GitHubProjectTable } from './project-types' + +export function projectRelationsTableFixture(): GitHubProjectTable { + const row = (id: string, position: number, points: number): GitHubProjectRow => ({ + id, + itemType: 'ISSUE', + position, + updatedAt: '', + content: { + number: position + 1, + title: id, + body: null, + url: null, + state: 'OPEN', + stateReason: null, + isDraft: null, + repository: 'acme/repo', + assignees: [], + labels: [], + parentIssue: null, + issueType: null + }, + fieldValuesByFieldId: { points: { kind: 'number', fieldId: 'points', number: points } } + }) + const populated = row('populated', 0, 2) + populated.content.linkedPullRequests = { + pullRequests: [{ number: 12, title: 'Change', url: 'https://github.com/acme/repo/pull/12' }], + totalCount: 3 + } + populated.content.subIssuesProgress = { completed: 1, total: 2, percentCompleted: 50 } + const points = { kind: 'field', id: 'points', name: 'Points', dataType: 'NUMBER' } as const + return { + project: { + id: 'project-1', + owner: 'acme', + ownerType: 'organization', + number: 1, + title: 'Roadmap', + url: 'https://github.com/orgs/acme/projects/1' + }, + selectedView: { + id: 'view-1', + number: 1, + name: 'Table', + layout: 'TABLE_LAYOUT', + filter: '', + fields: [ + points, + { + kind: 'field', + id: 'prs', + name: 'Linked pull requests', + dataType: 'LINKED_PULL_REQUESTS' + }, + { + kind: 'field', + id: 'progress', + name: 'Sub-issues progress', + dataType: 'SUB_ISSUES_PROGRESS' + } + ], + groupByFields: [points], + sortByFields: [{ field: points, direction: 'ASC' }] + }, + rows: [populated, row('legacy', 1, 1)], + totalCount: 2, + parentFieldDropped: false + } +} From 7a6df0daad0ee67df07201daa4d4677c56eb91ba Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:47:22 -0700 Subject: [PATCH 6/8] Combine project coordination test cache imports --- .../store/slices/github-project-request-coordination.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/renderer/src/store/slices/github-project-request-coordination.test.ts b/src/renderer/src/store/slices/github-project-request-coordination.test.ts index c2f417f8392e..72cb784d6f47 100644 --- a/src/renderer/src/store/slices/github-project-request-coordination.test.ts +++ b/src/renderer/src/store/slices/github-project-request-coordination.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { GitHubProjectTable } from '../../../../shared/github/project-types' import type { GetProjectViewTableResult } from '../../../../shared/github/project-result-types' -import { projectViewCacheKey } from '../github/cache-identity' +import { projectViewCacheKey, projectViewSourceScope } from '../github/cache-identity' import { createTestStore, mockApi, @@ -11,7 +11,6 @@ import { import { projectRelationsTableFixture } from '../../../../shared/github/project-relations.test-fixture' import { projectRelationCellText } from '../../components/github-project/ProjectCell.test-fixture' import { sortRows, groupRows } from '../../../../shared/github/project-group-sort' -import { projectViewSourceScope } from '../github/cache-identity' function makeTable(title = 'Roadmap'): GitHubProjectTable { return { From fb71713a4a4baf755370dc7252644d7d1f1e8cdc Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:53:34 -0700 Subject: [PATCH 7/8] Use checked project payload types in consumer tests --- mobile/src/tasks/task-project-board-reply-schema.test.ts | 7 +++---- src/main/runtime/rpc/methods/github.test.ts | 5 +++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/mobile/src/tasks/task-project-board-reply-schema.test.ts b/mobile/src/tasks/task-project-board-reply-schema.test.ts index 83b9a1b28201..5eb94ee2cd1d 100644 --- a/mobile/src/tasks/task-project-board-reply-schema.test.ts +++ b/mobile/src/tasks/task-project-board-reply-schema.test.ts @@ -1,6 +1,6 @@ +import { deepStrictEqual } from 'node:assert/strict' import { describe, expect, it } from 'vitest' import { projectRelationsTableFixture } from '../../../src/shared/github/project-relations.test-fixture' -import type { GitHubProjectTable } from '../../../src/shared/github/project-types' import { sortRows, groupRows } from '../../../src/shared/github/project-group-sort' import { normalizeProjectTableForMobileSort, @@ -136,9 +136,8 @@ describe('the board table', () => { if (!parsed.ok) { throw new Error('Expected accepted table') } - expect(parsed.data).toEqual(table) - // SAFETY: exact equality above proves the loose schema retained this fully typed fixture. - const decoded = parsed.data as unknown as GitHubProjectTable + const decoded = parsed.data + deepStrictEqual(decoded, table) const projected = normalizeProjectTableForMobileSort(decoded, decoded.rows, null) const groups = groupRows(projected, sortRows(projected, projected.rows)) expect(groups.map((group) => group.label)).toEqual(['1', '2']) diff --git a/src/main/runtime/rpc/methods/github.test.ts b/src/main/runtime/rpc/methods/github.test.ts index a6b876689496..ffb5f210b580 100644 --- a/src/main/runtime/rpc/methods/github.test.ts +++ b/src/main/runtime/rpc/methods/github.test.ts @@ -763,11 +763,12 @@ describe('github RPC methods', () => { }) it('fetches GitHub project tables on the runtime server', async () => { - const table = projectRelationsTableFixture() const runtime = { getRuntimeId: () => 'test-runtime', - getGitHubProjectViewTable: vi.fn().mockResolvedValue({ ok: true, data: table }) + getGitHubProjectViewTable: vi.fn().mockResolvedValue({ ok: true, data: { rows: [] } }) } as unknown as OrcaRuntimeService + const table = projectRelationsTableFixture() + vi.mocked(runtime.getGitHubProjectViewTable).mockResolvedValueOnce({ ok: true, data: table }) const dispatcher = new RpcDispatcher({ runtime, methods: GITHUB_METHODS }) const response = await dispatcher.dispatch( From ab14acb2f2a2bfbaa1cbff8a29f85bdc76d555bb Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:08:11 -0700 Subject: [PATCH 8/8] Place project provider column contract in cross-layer tests --- .../ProjectCell.test-fixture.tsx | 1 - ...thub-project-provider-columns.unit.test.ts | 35 ++++++++++--------- 2 files changed, 18 insertions(+), 18 deletions(-) rename src/renderer/src/components/github-project/ProjectCell.test.tsx => tests/e2e/github-project-provider-columns.unit.test.ts (94%) diff --git a/src/renderer/src/components/github-project/ProjectCell.test-fixture.tsx b/src/renderer/src/components/github-project/ProjectCell.test-fixture.tsx index f6599709315d..f9b1d6d74bbd 100644 --- a/src/renderer/src/components/github-project/ProjectCell.test-fixture.tsx +++ b/src/renderer/src/components/github-project/ProjectCell.test-fixture.tsx @@ -1,4 +1,3 @@ -import React from 'react' import { renderToStaticMarkup } from 'react-dom/server' import type { GitHubProjectRow } from '../../../../shared/github/project-types' import ProjectCell from './ProjectCell' diff --git a/src/renderer/src/components/github-project/ProjectCell.test.tsx b/tests/e2e/github-project-provider-columns.unit.test.ts similarity index 94% rename from src/renderer/src/components/github-project/ProjectCell.test.tsx rename to tests/e2e/github-project-provider-columns.unit.test.ts index 117077e58317..0d382fdd9c64 100644 --- a/src/renderer/src/components/github-project/ProjectCell.test.tsx +++ b/tests/e2e/github-project-provider-columns.unit.test.ts @@ -1,24 +1,25 @@ // @vitest-environment happy-dom +import { createElement } from 'react' import { cleanup, render, screen } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { normalizeItem, type RawItem -} from '../../../../main/github/project-view/project-view-item-normalization' -import { fetchItemsPageWithRaw } from '../../../../main/github/project-view/project-view-item-page' -import { fetchAllItems } from '../../../../main/github/project-view/project-view-items' +} from '../../src/main/github/project-view/project-view-item-normalization' +import { fetchItemsPageWithRaw } from '../../src/main/github/project-view/project-view-item-page' +import { fetchAllItems } from '../../src/main/github/project-view/project-view-items' import { _resetProjectViewCachesForTests, type OptionalProjectItemField -} from '../../../../main/github/project-view/project-view-cache' -import { ghExecFileAsync } from '../../../../main/github/project-view/internals' -import type { GitHubProjectRow, GitHubProjectTable } from '../../../../shared/github/project-types' -import { sortRows, groupRows } from '../../../../shared/github/project-group-sort' -import * as fieldNormalization from '../../../../main/github/project-view/project-view-field-normalization' -import ProjectCell from './ProjectCell' +} from '../../src/main/github/project-view/project-view-cache' +import { ghExecFileAsync } from '../../src/main/github/project-view/internals' +import type { GitHubProjectRow, GitHubProjectTable } from '../../src/shared/github/project-types' +import { sortRows, groupRows } from '../../src/shared/github/project-group-sort' +import * as fieldNormalization from '../../src/main/github/project-view/project-view-field-normalization' +import ProjectCell from '../../src/renderer/src/components/github-project/ProjectCell' -vi.mock('../../../../main/github/project-view/internals', () => ({ +vi.mock('../../src/main/github/project-view/internals', () => ({ acquire: vi.fn(), release: vi.fn(), ghExecFileAsync: vi.fn(), @@ -27,7 +28,7 @@ vi.mock('../../../../main/github/project-view/internals', () => ({ repositoryRateLimitGuard: () => ({ blocked: false }), noteRepositoryRateLimitSpend: vi.fn() })) -vi.mock('../../../../main/github/project-view/project-view-config', () => ({ +vi.mock('../../src/main/github/project-view/project-view-config', () => ({ ownerQueryRoot: () => 'organization' })) @@ -149,12 +150,12 @@ function renderColumns(row: GitHubProjectRow): void { ['field-progress', 'SUB_ISSUES_PROGRESS'] ] as const) { render( - + createElement(ProjectCell, { + row, + field: { kind: 'field', id, name: dataType, dataType }, + editable: false, + sourceTarget: { kind: 'local' } + }) ) } }