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..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,4 +1,11 @@ +import { deepStrictEqual } from 'node:assert/strict' import { describe, expect, it } from 'vitest' +import { projectRelationsTableFixture } from '../../../src/shared/github/project-relations.test-fixture' +import { sortRows, groupRows } from '../../../src/shared/github/project-group-sort' +import { + normalizeProjectTableForMobileSort, + projectFieldDisplayLabel +} from './mobile-tasks-project-fields' import { taskProjectAccessibleListSchema, taskProjectAssignableUserListSchema, @@ -121,6 +128,34 @@ 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') + } + 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']) + 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/github/project-view-field-values.test.ts b/src/main/github/project-view-field-values.test.ts new file mode 100644 index 000000000000..5b1b6cd36344 --- /dev/null +++ b/src/main/github/project-view-field-values.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +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 = normalizeLinkedPullRequests({ + __typename: 'ProjectV2ItemFieldPullRequestValue', + field: { id: 'field-pr', name: 'Linked pull requests', dataType: 'LINKED_PULL_REQUESTS' }, + pullRequests: { + totalCount: 12, + nodes: [{ number: 12, title: 'Fix', url: 'https://github.com/o/r/pull/12' }, null] + } + }) + expect(value).toEqual({ + 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 ca65f6d59db9..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,25 +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 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 + 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) } } - return false - }) + } + 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..7f1bad822cd7 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,17 @@ export function getCachedOwnerType( return getProjectViewCacheEntry(ownerTypeCache, ownerTypeCacheKey(owner, host)) } -export function markParentFieldRetried(scopeKey: string): void { - rememberProjectViewCacheEntry(parentFieldRetriedByOwner, scopeKey, true) +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 hasParentFieldRetried(scopeKey: string): boolean { - return getProjectViewCacheEntry(parentFieldRetriedByOwner, scopeKey) === true +export function getUnsupportedItemFields(scopeKey: string): ReadonlySet { + return getProjectViewCacheEntry(unsupportedItemFieldsByOwner, scopeKey) ?? new Set() } export function markParentFieldWarningLogged(scopeKey: string): void { @@ -86,7 +92,7 @@ export function hasParentFieldWarningLogged(scopeKey: string): boolean { export function _resetProjectViewCachesForTests(): void { ownerTypeCache.clear() - parentFieldRetriedByOwner.clear() + unsupportedItemFieldsByOwner.clear() parentFieldWarningLoggedByOwner.clear() parentFieldProbeInFlight.clear() } @@ -99,7 +105,7 @@ export function _getProjectViewCacheSizesForTests(): { } { return { ownerTypes: ownerTypeCache.size, - parentFieldRetries: parentFieldRetriedByOwner.size, + parentFieldRetries: unsupportedItemFieldsByOwner.size, parentFieldWarnings: parentFieldWarningLoggedByOwner.size, parentFieldProbes: parentFieldProbeInFlight.size } @@ -124,12 +130,12 @@ export function _getProjectViewOwnerTypeForTests( /** @internal - exposed for cache-bound tests only. */ export function _markProjectViewParentFieldRetriedForTests(scopeKey: string): void { - markParentFieldRetried(scopeKey) + markItemFieldsUnsupported(scopeKey, ['parent']) } /** @internal - exposed for cache-bound tests only. */ export function _hasProjectViewParentFieldRetriedForTests(scopeKey: string): boolean { - return hasParentFieldRetried(scopeKey) + return getUnsupportedItemFields(scopeKey).has('parent') } /** @internal - exposed for cache-bound tests only. */ 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..33fc6044cd56 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, @@ -112,6 +113,10 @@ export type RawFieldValue = { date?: string labels?: { nodes?: RawLabel[] } users?: { nodes?: RawUser[] } + pullRequests?: { + totalCount?: number + nodes?: ({ number?: number; title?: string; url?: string } | null)[] + } } export function normalizeFieldValue( @@ -178,3 +183,24 @@ export function normalizeFieldValue( return null } } + +export function normalizeLinkedPullRequests(raw: RawFieldValue): GitHubProjectLinkedPullRequests { + 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 3bcfda9d6bac..2cb40f6f388f 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, @@ -30,6 +32,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 @@ -44,7 +47,7 @@ export type RawItem = { updatedAt?: string content?: RawContent | null fieldValues?: { - nodes?: RawFieldValue[] + nodes?: (RawFieldValue | null)[] pageInfo?: { hasNextPage?: boolean } } } @@ -100,6 +103,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' && @@ -112,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 @@ -143,6 +162,8 @@ export function normalizeItem(raw: RawItem, position: number): NormalizedItemOut assignees, labels, parentIssue, + linkedPullRequests, + 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..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 { @@ -20,7 +21,7 @@ import { ownerQueryRoot } from './project-view-config' import type { RawItem } from './project-view-item-normalization' import { FIELD_CONFIG_FRAGMENT, - FIELD_VALUES_SELECTION, + fieldValuesSelection, itemContentSelection } from './project-view-query-fragments' @@ -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 } @@ -67,8 +68,10 @@ export async function fetchItemsPageWithRaw(args: { id type updatedAt - content { ${itemContentSelection(args.includeParent)} } - ${FIELD_VALUES_SELECTION} + content { + ${itemContentSelection(!args.unsupportedFields.has('parent'), !args.unsupportedFields.has('subIssuesSummary'))} + } + ${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 a99f7943f836..3c55cf0819ca 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 @@ -29,77 +29,59 @@ 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(() => {}) } - 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] Issue.parent is not available for ${args.owner} on this token — retrying without the parent selection.` + 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 (unsupportedFields.size < 3 && !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 dc339442c51b..f117eed2af41 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,14 @@ 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 = includeSubIssuesSummary + ? 'subIssuesSummary { completed total percentCompleted }' + : '' return ` __typename ... on Issue { @@ -38,6 +44,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 +61,19 @@ export function itemContentSelection(includeParent: boolean): string { ` } -export const FIELD_VALUES_SELECTION = ` +// 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 + ? ` + ... on ProjectV2ItemFieldPullRequestValue { + pullRequests(first:10) { + totalCount + nodes { number title url } + } + } + ` + : '' + return ` fieldValues(first:${FIELD_VALUES_PAGE_SIZE}) { pageInfo { hasNextPage } nodes { @@ -66,6 +85,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/main/runtime/rpc/methods/github.test.ts b/src/main/runtime/rpc/methods/github.test.ts index bd333234cd0a..ffb5f210b580 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 } @@ -766,6 +767,8 @@ describe('github RPC methods', () => { getRuntimeId: () => 'test-runtime', 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( @@ -787,7 +790,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..f9b1d6d74bbd --- /dev/null +++ b/src/renderer/src/components/github-project/ProjectCell.test-fixture.tsx @@ -0,0 +1,16 @@ +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/components/github-project/ProjectCell.tsx b/src/renderer/src/components/github-project/ProjectCell.tsx index 6e2459a2a3ff..e7e3f59589a5 100644 --- a/src/renderer/src/components/github-project/ProjectCell.tsx +++ b/src/renderer/src/components/github-project/ProjectCell.tsx @@ -93,6 +93,34 @@ export default function ProjectCell({ ) } + if (field.dataType === 'LINKED_PULL_REQUESTS') { + const linked = row.content.linkedPullRequests + if (!linked) { + return + } + const labels = linked.pullRequests.map((pr) => `#${pr.number}`) + const overflow = + linked.totalCount > linked.pullRequests.length + ? ` +${linked.totalCount - linked.pullRequests.length}` + : '' + 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 ( { 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..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,8 +1,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 { projectViewCacheKey, projectViewSourceScope } from '../github/cache-identity' +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' function makeTable(title = 'Roadmap'): GitHubProjectTable { return { @@ -59,6 +67,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 + } +} diff --git a/src/shared/github/project-types.ts b/src/shared/github/project-types.ts index 05220311325d..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' @@ -159,6 +164,9 @@ 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. */ issueType: GitHubIssueType | null } diff --git a/tests/e2e/github-project-provider-columns.unit.test.ts b/tests/e2e/github-project-provider-columns.unit.test.ts new file mode 100644 index 000000000000..0d382fdd9c64 --- /dev/null +++ b/tests/e2e/github-project-provider-columns.unit.test.ts @@ -0,0 +1,525 @@ +// @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 '../../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 '../../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('../../src/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('../../src/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: 'Issue', + parent, + 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: 100, + after: null, + 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'] } + +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, + pageInfo, + 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 normalized(raw: RawItem): GitHubProjectRow { + const result = normalizeItem(raw, 0) + if (!result.ok) { + throw new Error('Expected a project row') + } + return result.row +} +function renderColumns(row: GitHubProjectRow): void { + for (const [id, dataType] of [ + ['field-pr', 'LINKED_PULL_REQUESTS'], + ['field-progress', 'SUB_ISSUES_PROGRESS'] + ] as const) { + render( + createElement(ProjectCell, { + row, + field: { kind: 'field', id, name: dataType, dataType }, + editable: false, + sourceTarget: { kind: 'local' } + }) + ) + } +} + +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') + } + const row = normalized(page.page.nodes[0]) + renderColumns(row) + expect(screen.getByText(expectedText).textContent).toBe(expectedText) + 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)') + expect(query).toContain('subIssuesSummary { completed total percentCompleted }') + expect(query).not.toContain('ProjectV2ItemFieldProgressValue') + } + ) + + 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 }, + { + 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(() => {}) + for (const error of [missingSummary, missingPrs, missingParent]) { + vi.mocked(ghExecFileAsync).mockResolvedValueOnce({ + stdout: JSON.stringify({ errors: [error] }), + stderr: '' + }) + } + 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: '' + }) + 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 {') + } + ) + + 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 {' + ) + }) + + 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] }), + 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(firstPage), + stderr: '' + }) + 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('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() + } + ) +})