Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(github): pull request CI and mergeability, read once per repository
review93b0794be951
diff --git a/src/core/github/client.ts b/src/core/github/client.tsindex 65262421a..6245a3a4d 100644--- a/src/core/github/client.ts+++ b/src/core/github/client.ts@@ -12,6 +12,17 @@ import type {UpdateIssueInput} from '../../shared/github-issues'import { parseGitHubRepository } from './config'+import type { GitHubPullChecksResult } from '../../shared/github-pull-status'+import {+ GraphQLShapeError,+ PULL_CHECKS_QUERY,+ PULL_STATUS_QUERY,+ graphQLErrors,+ parsePullChecksResponse,+ parsePullStatusResponse,+ rateLimitFrom,+ type PullStatusRead+} from './graphql-pulls'const API_ORIGIN = 'https://api.github.com'const API_VERSION = '2022-11-28'@@ -23,7 +34,11 @@ export class GitHubClientError extends Error {readonly code: 'invalid-request' | 'malformed-response' | 'response-too-large' |'request-failed' | 'rate-limited' | 'insufficient-permission',readonly status?: number,- readonly retryAt?: number+ readonly retryAt?: number,+ /** Which rate budget a PRIMARY limit belongs to (`x-ratelimit-resource`). `graphql` and `core`+ * are separate budgets, so a spent `graphql` budget must not hold REST issue sync. Absent for a+ * secondary limit, which GitHub applies to the whole account. */+ readonly resource?: string) {super(code)}@@ -419,6 +434,65 @@ export class GitHubIssuesClient {return { id: Number(value.id) }}+ /**+ * Every open pull request's head, CI rollup, mergeability and closing issues, plus the recently+ * merged/closed ones — one GraphQL read (see graphql-pulls.ts for the measured cost). A field the+ * token may not read comes back as `access: false`, not as an empty value.+ */+ async pullRequestStatuses(repository: string): Promise<PullStatusRead> {+ const [owner, name] = safeRepository(repository).split('/')+ const body = await this.graphql(PULL_STATUS_QUERY, { owner, name })+ try {+ return parsePullStatusResponse(body, repository)+ } catch (error) {+ if (error instanceof GraphQLShapeError) throw new GitHubClientError('malformed-response')+ throw error+ }+ }++ /** Per-check detail for one PR — read only when someone opens that PR. */+ async pullRequestChecks(repository: string, pullNumber: number): Promise<GitHubPullChecksResult> {+ const [owner, name] = safeRepository(repository).split('/')+ if (!positiveInteger(pullNumber, 2_147_483_647)) throw new GitHubClientError('invalid-request')+ const body = await this.graphql(PULL_CHECKS_QUERY, { owner, name, number: pullNumber })+ try {+ return parsePullChecksResponse(body)+ } catch (error) {+ if (error instanceof GraphQLShapeError) throw new GitHubClientError('malformed-response')+ throw error+ }+ }++ /**+ * One GraphQL request. It goes through the same `request()` as every REST call, so its+ * `x-ratelimit-*` headers (resource `graphql`) reach the coordinator's budget.+ *+ * GraphQL reports an exhausted budget as a 200 whose `errors[].type` is `RATE_LIMITED` — a body+ * that is otherwise shaped like an answer. It is turned into the same `rate-limited` error a REST+ * refusal produces, tagged with the `graphql` resource.+ */+ private async graphql(query: string, variables: Record<string, string | number>): Promise<unknown> {+ const response = await this.request('/graphql', {+ method: 'POST',+ body: JSON.stringify({ query, variables })+ })+ const body = await this.json(response)+ let errors: ReturnType<typeof graphQLErrors>+ try {+ errors = graphQLErrors(body)+ } catch {+ throw new GitHubClientError('malformed-response')+ }+ if (errors.some((error) => error.type === 'RATE_LIMITED')) {+ const header = Number(response.headers.get('x-ratelimit-reset')) * 1_000+ const retryAt = Number.isFinite(header) && header > 0+ ? header+ : rateLimitFrom(body)?.resetAt ?? Date.now() + 60_000+ throw new GitHubClientError('rate-limited', response.status, retryAt, 'graphql')+ }+ return body+ }+async listRepositoryLabels(repository: string,options: { page: number; perPage: number; etag?: string }@@ -520,7 +594,9 @@ export class GitHubIssuesClient {if (secondary && !(Number.isFinite(retryAfter) && retryAfter > 0)) {this.secondaryBackoffMs = Math.min(this.secondaryBackoffMs * 2, 60_000)}- throw new GitHubClientError('rate-limited', response.status, retryAt)+ const resource = primary ? response.headers.get('x-ratelimit-resource') ?? undefined : undefined+ throw new GitHubClientError('rate-limited', response.status, retryAt,+ resource && /^[a-z_]{1,32}$/.test(resource) ? resource : undefined)}if (!response.ok) throw new GitHubClientError('request-failed', response.status)return responsediff --git a/src/core/github/graphql-pulls.test.ts b/src/core/github/graphql-pulls.test.tsnew file mode 100644index 000000000..c52a100bd--- /dev/null+++ b/src/core/github/graphql-pulls.test.ts@@ -0,0 +1,206 @@+import { describe, expect, it } from 'vitest'+import { GitHubIssuesClient, GitHubClientError } from './client'+import {+ GraphQLShapeError,+ PULL_STATUS_QUERY,+ parsePullChecksResponse,+ parsePullStatusResponse+} from './graphql-pulls'++const REPO = 'eneskirca/nodeterm'+const HEAD = 'a'.repeat(40)++/** One open-PR node in the shape GitHub returned for this repository on 2026-09-28. */+function node(number: number, over: Record<string, unknown> = {}) {+ return {+ number,+ headRefName: `feat/${number}`,+ headRefOid: HEAD,+ isDraft: false,+ mergeable: 'MERGEABLE',+ mergeStateStatus: 'CLEAN',+ closingIssuesReferences: { nodes: [] },+ commits: { nodes: [{ commit: { oid: HEAD, statusCheckRollup: { state: 'SUCCESS' } } }] },+ ...over+ }+}++function body(nodes: unknown[], over: { errors?: unknown[]; totalCount?: number; recent?: unknown[] } = {}) {+ return {+ data: {+ rateLimit: { cost: 1, remaining: 4820, limit: 5000, resetAt: '2026-09-28T21:01:03Z' },+ repository: {+ open: { totalCount: over.totalCount ?? nodes.length, nodes },+ recent: { nodes: over.recent ?? [] }+ }+ },+ ...(over.errors ? { errors: over.errors } : {})+ }+}++describe('parsePullStatusResponse', () => {+ it('decodes open pull requests, the rate limit and recent merges', () => {+ const read = parsePullStatusResponse(body([node(1)], {+ recent: [{ number: 9, headRefName: 'feat/9', state: 'MERGED' }]+ }), REPO)+ expect(read.open).toEqual([{+ number: 1, headRefName: 'feat/1', headRefOid: HEAD, isDraft: false, mergeable: 'MERGEABLE',+ mergeStateStatus: 'CLEAN', rollup: 'SUCCESS', rollupOid: HEAD, closes: []+ }])+ expect(read.recent).toEqual([{ number: 9, headRefName: 'feat/9', lifecycle: 'merged' }])+ expect(read.access).toEqual({ ci: true, merge: true })+ expect(read.rateLimit).toEqual({ cost: 1, remaining: 4820, limit: 5000, resetAt: Date.parse('2026-09-28T21:01:03Z') })+ })++ it('reads a null rollup as no checks when nothing was refused', () => {+ const read = parsePullStatusResponse(body([node(1, {+ commits: { nodes: [{ commit: { oid: HEAD, statusCheckRollup: null } }] }+ })]), REPO)+ expect(read.access.ci).toBe(true)+ expect(read.open[0].rollup).toBeNull()+ })++ it('a rollup the token may not read HIDES checks — it is not "no checks"', () => {+ const read = parsePullStatusResponse(body([node(1, {+ commits: { nodes: [{ commit: { oid: HEAD, statusCheckRollup: null } }] }+ })], {+ errors: [{+ type: 'FORBIDDEN',+ path: ['repository', 'open', 'nodes', 0, 'commits', 'nodes', 0, 'commit', 'statusCheckRollup'],+ message: 'Resource not accessible by personal access token'+ }]+ }), REPO)+ expect(read.access).toEqual({ ci: false, merge: true })+ })++ it('a token without scope for the query hides everything instead of failing', () => {+ const read = parsePullStatusResponse({+ data: null,+ errors: [{ type: 'INSUFFICIENT_SCOPES', message: 'Your token has not been granted the required scopes' }]+ }, REPO)+ expect(read).toMatchObject({ open: [], access: { ci: false, merge: false } })+ })++ it('keeps only issues in the SAME repository a pull request closes', () => {+ const read = parsePullStatusResponse(body([node(1, {+ closingIssuesReferences: { nodes: [+ { number: 4, repository: { nameWithOwner: 'EnesKirca/Nodeterm' } },+ { number: 5, repository: { nameWithOwner: 'someone/else' } }+ ] }+ })]), REPO)+ expect(read.open[0].closes).toEqual([4])+ })++ it('reports a truncated list', () => {+ expect(parsePullStatusResponse(body([node(1)], { totalCount: 60 }), REPO).truncated).toBe(true)+ })++ it('an error it cannot classify is a failed read, never an answer', () => {+ expect(() => parsePullStatusResponse(body([node(1)], {+ errors: [{ type: 'SERVICE_UNAVAILABLE', message: 'try again' }]+ }), REPO)).toThrow(GraphQLShapeError)+ expect(() => parsePullStatusResponse({ data: { repository: null } }, REPO)).toThrow(GraphQLShapeError)+ })++ it('rejects malformed nodes', () => {+ expect(() => parsePullStatusResponse(body([node(1, { headRefOid: 'nothex' })]), REPO)).toThrow()+ expect(() => parsePullStatusResponse(body([node(1, { mergeable: 'MAYBE' })]), REPO)).toThrow()+ expect(() => parsePullStatusResponse(body([node(1, {+ commits: { nodes: [{ commit: { oid: HEAD, statusCheckRollup: { state: 'GREEN' } } }] }+ })]), REPO)).toThrow()+ })+})++describe('parsePullChecksResponse', () => {+ const checks = (commitOid: string, rollup: unknown) => ({+ data: { repository: { pullRequest: {+ headRefOid: HEAD,+ commits: { nodes: [{ commit: { oid: commitOid, statusCheckRollup: rollup } }] }+ } } }+ })++ it('lists checks, failures first, with https links only', () => {+ const result = parsePullChecksResponse(checks(HEAD, { state: 'FAILURE', contexts: { totalCount: 3, nodes: [+ { __typename: 'CheckRun', name: 'quality', status: 'COMPLETED', conclusion: 'SUCCESS',+ detailsUrl: 'https://github.com/x/actions/runs/1' },+ { __typename: 'CheckRun', name: 'windows', status: 'COMPLETED', conclusion: 'FAILURE',+ detailsUrl: 'javascript:alert(1)' },+ { __typename: 'StatusContext', context: 'ci/legacy', state: 'PENDING', targetUrl: 'https://ci.example/1' }+ ] } }))+ expect(result).toEqual({+ status: 'ok', headRefOid: HEAD, truncated: false, checks: [+ { name: 'windows', state: 'failed' },+ { name: 'ci/legacy', state: 'pending', url: 'https://ci.example/1' },+ { name: 'quality', state: 'passed', url: 'https://github.com/x/actions/runs/1' }+ ]+ })+ })++ it('says "no checks" for a null rollup, "moved" for another commit, "hidden" when refused', () => {+ expect(parsePullChecksResponse(checks(HEAD, null))).toEqual({ status: 'no-checks' })+ expect(parsePullChecksResponse(checks('b'.repeat(40), { state: 'SUCCESS', contexts: { totalCount: 0, nodes: [] } })))+ .toEqual({ status: 'moved' })+ expect(parsePullChecksResponse({ ...checks(HEAD, null), errors: [{ type: 'FORBIDDEN', path: ['repository'] }] }))+ .toEqual({ status: 'hidden' })+ })+})++describe('GitHubIssuesClient GraphQL', () => {+ function json(value: unknown, headers: Record<string, string> = {}, status = 200): Response {+ return new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json', ...headers } })+ }++ it('posts one query to the GraphQL endpoint and feeds its budget to the observer', async () => {+ const calls: Array<{ url: string; init: RequestInit }> = []+ const samples: unknown[] = []+ const client = new GitHubIssuesClient({+ token: 'secret',+ onRateLimit: (sample) => samples.push(sample),+ fetch: async (url, init) => {+ calls.push({ url: String(url), init: init ?? {} })+ return json(body([node(1)]), {+ 'x-ratelimit-limit': '5000', 'x-ratelimit-remaining': '4819',+ 'x-ratelimit-reset': '1790629263', 'x-ratelimit-resource': 'graphql'+ })+ }+ })+ const read = await client.pullRequestStatuses(REPO)+ expect(read.open).toHaveLength(1)+ expect(calls).toHaveLength(1)+ expect(calls[0].url).toBe('https://api.github.com/graphql')+ expect(calls[0].init.method).toBe('POST')+ expect(JSON.parse(String(calls[0].init.body))).toEqual({+ query: PULL_STATUS_QUERY, variables: { owner: 'eneskirca', name: 'nodeterm' }+ })+ expect(samples).toEqual([{ resource: 'graphql', limit: 5000, remaining: 4819, resetAt: 1790629263_000 }])+ })++ it('turns a RATE_LIMITED error inside a 200 into a graphql-scoped rate limit', async () => {+ const client = new GitHubIssuesClient({+ token: 'secret',+ fetch: async () => json({ data: null, errors: [{ type: 'RATE_LIMITED', message: 'API rate limit exceeded' }] },+ { 'x-ratelimit-reset': '1790629263', 'x-ratelimit-remaining': '0', 'x-ratelimit-limit': '5000' })+ })+ const error = await client.pullRequestStatuses(REPO).catch((caught: unknown) => caught)+ expect(error).toBeInstanceOf(GitHubClientError)+ expect(error).toMatchObject({ code: 'rate-limited', retryAt: 1790629263_000, resource: 'graphql' })+ })++ it('tags a primary 403 with the budget it belongs to', async () => {+ const client = new GitHubIssuesClient({+ token: 'secret',+ fetch: async () => json({ message: 'API rate limit exceeded' }, {+ 'x-ratelimit-remaining': '0', 'x-ratelimit-limit': '5000',+ 'x-ratelimit-reset': '1790629263', 'x-ratelimit-resource': 'graphql'+ }, 403)+ })+ await expect(client.pullRequestStatuses(REPO)).rejects.toMatchObject({+ code: 'rate-limited', resource: 'graphql'+ })+ })++ it('reports a malformed GraphQL body as malformed', async () => {+ const client = new GitHubIssuesClient({ token: 'secret', fetch: async () => json({ data: { repository: null } }) })+ await expect(client.pullRequestStatuses(REPO)).rejects.toMatchObject({ code: 'malformed-response' })+ })+})diff --git a/src/core/github/graphql-pulls.ts b/src/core/github/graphql-pulls.tsnew file mode 100644index 000000000..232620034--- /dev/null+++ b/src/core/github/graphql-pulls.ts@@ -0,0 +1,307 @@+// The GraphQL reads behind pull request cards: ONE query per repository for every open PR's head,+// CI rollup, mergeability and the issues it closes, and one per-PR query for check detail when a+// PR's modal opens. The REST issues harvest already carries every PR's number/state/labels; these+// add only what that endpoint cannot say.+//+// MEASURED 2026-09-28 against eneskirca/nodeterm (60 open PRs): the list query below costs 1 point+// of the separate `graphql` budget (`x-ratelimit-resource: graphql`, 5000/h), the `recent` block+// included, and returns ~18 KB. The per-PR checks query also costs 1.+//+// The parser is strict in the same way the REST decoder is: anything malformed rejects the read,+// and a field the token may not see is reported as HIDDEN — never decoded as its empty value. That+// difference matters most for `statusCheckRollup`: GitHub answers a token without checks access+// with `null` plus a FORBIDDEN error, and `null` alone means "this commit has no checks".+import {+ checkRunState,+ sortChecks,+ statusContextState,+ type GitHubMergeable,+ type GitHubPullCheck,+ type GitHubPullChecksResult,+ type GitHubRollupState,+ type PullStatusFacts+} from '../../shared/github-pull-status'++export const OPEN_PULLS_PER_READ = 50+export const RECENT_PULLS_PER_READ = 30+const MAX_CLOSING_ISSUES = 10+const MAX_CHECKS = 100++export const PULL_STATUS_QUERY = `query($owner:String!,$name:String!){+ rateLimit{ cost remaining limit resetAt }+ repository(owner:$owner,name:$name){+ open: pullRequests(states:OPEN, first:${OPEN_PULLS_PER_READ}, orderBy:{field:UPDATED_AT,direction:DESC}){+ totalCount+ nodes{+ number headRefName headRefOid isDraft mergeable mergeStateStatus+ closingIssuesReferences(first:${MAX_CLOSING_ISSUES}){ nodes{ number repository{ nameWithOwner } } }+ commits(last:1){ nodes{ commit{ oid statusCheckRollup{ state } } } }+ }+ }+ recent: pullRequests(states:[MERGED,CLOSED], first:${RECENT_PULLS_PER_READ}, orderBy:{field:UPDATED_AT,direction:DESC}){+ nodes{ number headRefName state }+ }+ }+}`++export const PULL_CHECKS_QUERY = `query($owner:String!,$name:String!,$number:Int!){+ rateLimit{ cost remaining limit resetAt }+ repository(owner:$owner,name:$name){+ pullRequest(number:$number){+ headRefOid+ commits(last:1){ nodes{ commit{ oid statusCheckRollup{ state+ contexts(first:${MAX_CHECKS}){ totalCount nodes{+ __typename+ ... on CheckRun{ name status conclusion detailsUrl }+ ... on StatusContext{ context state targetUrl }+ } }+ } } } }+ }+ }+}`++export class GraphQLShapeError extends Error {+ constructor() { super('malformed-response') }+}++/** What one list read established. `access` false = the token may not read that field: hide it. */+export interface PullStatusRead {+ open: PullStatusFacts[]+ /** Recently merged/closed PRs, newest first — enough to keep a session card's branch link (and+ * see it merge) after its PR leaves the open list. */+ recent: Array<{ number: number; headRefName: string; lifecycle: 'merged' | 'closed' }>+ access: { ci: boolean; merge: boolean }+ truncated: boolean+ rateLimit?: GraphQLRateLimit+}++export interface GraphQLRateLimit {+ cost: number+ remaining: number+ limit: number+ /** Epoch ms. */+ resetAt: number+}++type GraphQLError = { type?: string; path?: Array<string | number>; message?: string }++function object(value: unknown): Record<string, unknown> | null {+ return value !== null && typeof value === 'object' && !Array.isArray(value)+ ? value as Record<string, unknown>+ : null+}++function positive(value: unknown): value is number {+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0+}++function nonNegative(value: unknown): value is number {+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0+}++function oid(value: unknown): value is string {+ return typeof value === 'string' && /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(value)+}++function refName(value: unknown): value is string {+ return typeof value === 'string' && value.length > 0 && value.length <= 255 &&+ // eslint-disable-next-line no-control-regex+ !/[\u0000-\u001f\u007f]/.test(value)+}++function list(value: unknown, maximum: number): unknown[] {+ const connection = object(value)+ if (!connection || !Array.isArray(connection.nodes) || connection.nodes.length > maximum) {+ throw new GraphQLShapeError()+ }+ return connection.nodes+}++/** `errors[]`, decoded leniently: only `type` and `path` are read, and nothing here is trusted as+ * more than a classification. */+export function graphQLErrors(body: unknown): GraphQLError[] {+ const value = object(body)+ if (!value || value.errors === undefined) return []+ if (!Array.isArray(value.errors)) throw new GraphQLShapeError()+ return value.errors.slice(0, 100).map((entry) => {+ const error = object(entry) ?? {}+ return {+ ...(typeof error.type === 'string' ? { type: error.type } : {}),+ ...(Array.isArray(error.path) ? { path: error.path.filter((part) =>+ typeof part === 'string' || typeof part === 'number') as Array<string | number> } : {})+ }+ })+}++const PERMISSION_TYPES = new Set(['FORBIDDEN', 'INSUFFICIENT_SCOPES'])++function touches(error: GraphQLError, fields: string[]): boolean {+ return !!error.path?.some((part) => typeof part === 'string' && fields.includes(part))+}++export function rateLimitFrom(body: unknown): GraphQLRateLimit | undefined {+ const rate = object(object(object(body)?.data)?.rateLimit)+ if (!rate || !nonNegative(rate.cost) || !nonNegative(rate.remaining) || !positive(rate.limit) ||+ typeof rate.resetAt !== 'string') return undefined+ const resetAt = Date.parse(rate.resetAt)+ if (!Number.isFinite(resetAt)) return undefined+ return { cost: rate.cost, remaining: rate.remaining, limit: rate.limit, resetAt }+}++/**+ * Decodes the list read. Throws `GraphQLShapeError` for a malformed body, and for errors it cannot+ * classify as a permission answer — those are a failed read (the caller keeps its last snapshot),+ * never a statement about the pull requests.+ */+export function parsePullStatusResponse(body: unknown, repository: string): PullStatusRead {+ const errors = graphQLErrors(body)+ const rateLimit = rateLimitFrom(body)+ const repositoryValue = object(object(object(body)?.data)?.repository)+ const permission = errors.filter((error) => error.type && PERMISSION_TYPES.has(error.type))+ const other = errors.filter((error) => !error.type || !PERMISSION_TYPES.has(error.type))+ if (other.length) throw new GraphQLShapeError()+ if (!repositoryValue) {+ // No repository at all. Only a permission answer makes that an answer; anything else is a read+ // that did not work.+ if (!permission.length) throw new GraphQLShapeError()+ return {+ open: [], recent: [], access: { ci: false, merge: false }, truncated: false,+ ...(rateLimit ? { rateLimit } : {})+ }+ }+ const access = {+ ci: !permission.some((error) => !error.path || touches(error, ['commits', 'statusCheckRollup'])),+ merge: !permission.some((error) => !error.path || touches(error, ['mergeable', 'mergeStateStatus']))+ }+ const openConnection = object(repositoryValue.open)+ if (!openConnection || !nonNegative(openConnection.totalCount)) throw new GraphQLShapeError()+ const repositoryFolded = repository.toLocaleLowerCase('en-US')+ const open = list(openConnection, OPEN_PULLS_PER_READ).map((entry): PullStatusFacts => {+ const node = object(entry)+ if (!node || !positive(node.number) || !refName(node.headRefName) || !oid(node.headRefOid) ||+ typeof node.isDraft !== 'boolean') throw new GraphQLShapeError()+ let mergeable: GitHubMergeable | null = null+ let mergeStateStatus: string | null = null+ if (access.merge) {+ if (node.mergeable !== 'MERGEABLE' && node.mergeable !== 'CONFLICTING' &&+ node.mergeable !== 'UNKNOWN') throw new GraphQLShapeError()+ if (typeof node.mergeStateStatus !== 'string' || !/^[A-Z_]{1,32}$/.test(node.mergeStateStatus)) {+ throw new GraphQLShapeError()+ }+ mergeable = node.mergeable+ mergeStateStatus = node.mergeStateStatus+ }+ let rollup: GitHubRollupState | null = null+ let rollupOid: string | null = null+ if (access.ci) {+ const commits = list(node.commits, 1)+ const commit = object(object(commits[0])?.commit)+ if (commits.length && !commit) throw new GraphQLShapeError()+ if (commit) {+ if (!oid(commit.oid)) throw new GraphQLShapeError()+ rollupOid = commit.oid+ if (commit.statusCheckRollup !== null) {+ const state = object(commit.statusCheckRollup)?.state+ if (state !== 'SUCCESS' && state !== 'FAILURE' && state !== 'ERROR' && state !== 'PENDING' &&+ state !== 'EXPECTED') throw new GraphQLShapeError()+ rollup = state+ }+ }+ }+ const closes = node.closingIssuesReferences === null+ ? []+ : list(node.closingIssuesReferences, MAX_CLOSING_ISSUES).flatMap((reference) => {+ const issue = object(reference)+ const nameWithOwner = object(issue?.repository)?.nameWithOwner+ if (!issue || !positive(issue.number) || typeof nameWithOwner !== 'string') {+ throw new GraphQLShapeError()+ }+ // GitHub also links issues in OTHER repositories. The board has cards only for this one.+ return nameWithOwner.toLocaleLowerCase('en-US') === repositoryFolded ? [issue.number] : []+ })+ return {+ number: node.number,+ headRefName: node.headRefName,+ headRefOid: node.headRefOid,+ isDraft: node.isDraft,+ mergeable,+ mergeStateStatus,+ rollup,+ rollupOid,+ closes: [...new Set(closes)]+ }+ })+ const recent = list(repositoryValue.recent, RECENT_PULLS_PER_READ).map((entry) => {+ const node = object(entry)+ if (!node || !positive(node.number) || !refName(node.headRefName) ||+ (node.state !== 'MERGED' && node.state !== 'CLOSED')) throw new GraphQLShapeError()+ return {+ number: node.number,+ headRefName: node.headRefName,+ lifecycle: node.state === 'MERGED' ? 'merged' as const : 'closed' as const+ }+ })+ return {+ open,+ recent,+ access,+ truncated: openConnection.totalCount > open.length,+ ...(rateLimit ? { rateLimit } : {})+ }+}++function httpsUrl(value: unknown): string | undefined {+ if (typeof value !== 'string' || value.length > 2_048) return undefined+ try {+ const url = new URL(value)+ return url.protocol === 'https:' ? url.toString() : undefined+ } catch {+ return undefined+ }+}++function checkName(value: unknown): string | null {+ return typeof value === 'string' && value.length > 0 && value.length <= 256 ? value : null+}++/** Decodes the per-PR checks read. Throws `GraphQLShapeError` for a malformed body or an error it+ * cannot classify. */+export function parsePullChecksResponse(body: unknown): GitHubPullChecksResult {+ const errors = graphQLErrors(body)+ const permission = errors.filter((error) => error.type && PERMISSION_TYPES.has(error.type))+ if (errors.length > permission.length) throw new GraphQLShapeError()+ if (permission.length) return { status: 'hidden' }+ const pull = object(object(object(object(body)?.data)?.repository)?.pullRequest)+ if (!pull || !oid(pull.headRefOid)) throw new GraphQLShapeError()+ const commit = object(object(list(pull.commits, 1)[0])?.commit)+ if (!commit || !oid(commit.oid)) throw new GraphQLShapeError()+ if (commit.oid !== pull.headRefOid) return { status: 'moved' }+ if (commit.statusCheckRollup === null) return { status: 'no-checks' }+ const rollup = object(commit.statusCheckRollup)+ const contexts = object(rollup?.contexts)+ if (!contexts || !nonNegative(contexts.totalCount)) throw new GraphQLShapeError()+ const checks = list(contexts, MAX_CHECKS).flatMap((entry): GitHubPullCheck[] => {+ const node = object(entry)+ if (!node) throw new GraphQLShapeError()+ if (node.__typename === 'CheckRun') {+ const name = checkName(node.name)+ if (!name || typeof node.status !== 'string' ||+ !(node.conclusion === null || typeof node.conclusion === 'string')) throw new GraphQLShapeError()+ const url = httpsUrl(node.detailsUrl)+ return [{ name, state: checkRunState(node.status, node.conclusion), ...(url ? { url } : {}) }]+ }+ if (node.__typename === 'StatusContext') {+ const name = checkName(node.context)+ if (!name || typeof node.state !== 'string') throw new GraphQLShapeError()+ const url = httpsUrl(node.targetUrl)+ return [{ name, state: statusContextState(node.state), ...(url ? { url } : {}) }]+ }+ return []+ })+ return {+ status: 'ok',+ headRefOid: pull.headRefOid,+ checks: sortChecks(checks),+ truncated: contexts.totalCount > checks.length+ }+}diff --git a/src/core/github/handlers.test.ts b/src/core/github/handlers.test.tsindex 24b5d37ef..9d43527c9 100644--- a/src/core/github/handlers.test.ts+++ b/src/core/github/handlers.test.ts@@ -18,7 +18,15 @@ describe('registerGitHubIssueHandlers', () => {createMissingLabels: async (...args: unknown[]) => {calls.push(['labels', ...args]); return { status: 'confirmed' as const, created: [], remaining: [] }},- clearCache: async (...args: unknown[]) => { calls.push(['clear', ...args]) }+ clearCache: async (...args: unknown[]) => { calls.push(['clear', ...args]) },+ pullStatus: async (...args: unknown[]) => {+ calls.push(['pullStatus', ...args])+ return { pulls: [], stale: false, access: { ci: true, merge: true }, undecided: false, truncated: false }+ },+ chasePulls: async (...args: unknown[]) => { calls.push(['chase', ...args]); return false },+ pullChecks: async (...args: unknown[]) => {+ calls.push(['checks', ...args]); return { status: 'no-checks' as const }+ }}const platform = fakePlatform()registerGitHubIssueHandlers(platform, service)@@ -26,10 +34,16 @@ describe('registerGitHubIssueHandlers', () => {await platform.handlers[IPC.githubIssuesSubscribe](7, { projectId: 'p1' })platform.senderListeners[IPC.githubIssuesUnsubscribe](7, 'p1')await platform.handlers[IPC.githubIssuesQuery]({ projectId: 'p1', columnId: null, pageSize: 50 })+ await platform.handlers[IPC.githubIssuesPullStatus]('p1')+ await platform.handlers[IPC.githubIssuesChasePulls]('p1')+ await platform.handlers[IPC.githubIssuesPullChecks]('p1', 12)expect(calls).toEqual([['subscribe', 7, { projectId: 'p1' }],['unsubscribe', 7, 'p1'],- ['query', { projectId: 'p1', columnId: null, pageSize: 50 }]+ ['query', { projectId: 'p1', columnId: null, pageSize: 50 }],+ ['pullStatus', { projectId: 'p1' }],+ ['chase', { projectId: 'p1' }],+ ['checks', { projectId: 'p1', pullNumber: 12 }]])expect(Object.keys(platform.handlers).some((channel) => channel.startsWith('githubControl:'))).toBe(false)})diff --git a/src/core/github/handlers.ts b/src/core/github/handlers.tsindex cba0f945e..fb0204d10 100644--- a/src/core/github/handlers.ts+++ b/src/core/github/handlers.ts@@ -7,6 +7,7 @@ import type {GitHubIssueQuery,GitHubMutationResult} from '../../shared/github-issues'+import type { GitHubPullBoard, GitHubPullChecksResult } from '../../shared/github-pull-status'export interface GitHubIssueHandlerService {subscribe(uiId: number, request: { projectId: string }): Promise<GitHubIssuePage>@@ -22,6 +23,9 @@ export interface GitHubIssueHandlerService {}): Promise<GitHubMutationResult>createMissingLabels(request: { projectId: string }): Promise<CreateMappedLabelsResult>clearCache(request: { projectId: string }): Promise<void>+ pullStatus(request: { projectId: string }): Promise<GitHubPullBoard>+ chasePulls(request: { projectId: string }): Promise<boolean>+ pullChecks(request: { projectId: string; pullNumber: number }): Promise<GitHubPullChecksResult>}export function registerGitHubIssueHandlers(@@ -40,4 +44,10 @@ export function registerGitHubIssueHandlers(service.createMissingLabels({ projectId }))platform.handle(IPC.githubIssuesClearCache, (projectId: string) =>service.clearCache({ projectId }))+ platform.handle(IPC.githubIssuesPullStatus, (projectId: string) =>+ service.pullStatus({ projectId }))+ platform.handle(IPC.githubIssuesChasePulls, (projectId: string) =>+ service.chasePulls({ projectId }))+ platform.handle(IPC.githubIssuesPullChecks, (projectId: string, pullNumber: number) =>+ service.pullChecks({ projectId, pullNumber }))}diff --git a/src/core/github/pull-status-tracker.test.ts b/src/core/github/pull-status-tracker.test.tsnew file mode 100644index 000000000..a56b39f64--- /dev/null+++ b/src/core/github/pull-status-tracker.test.ts@@ -0,0 +1,159 @@+import { describe, expect, it } from 'vitest'+import { GitHubPullStatusTracker } from './pull-status-tracker'+import { GitHubRequestCoordinator } from './request-coordinator'+import type { PullStatusRead } from './graphql-pulls'+import { PULL_CHASE_MAX } from '../../shared/github-pull-status'+import type { PullStatusFacts } from '../../shared/github-pull-status'++const HEAD = 'a'.repeat(40)+const KEY = 'user-1\0o/r'++function facts(number: number, over: Partial<PullStatusFacts> = {}): PullStatusFacts {+ return {+ number, headRefName: `feat/${number}`, headRefOid: HEAD, isDraft: false, mergeable: 'MERGEABLE',+ mergeStateStatus: 'CLEAN', rollup: 'SUCCESS', rollupOid: HEAD, closes: [], ...over+ }+}++function read(open: PullStatusFacts[], over: Partial<PullStatusRead> = {}): PullStatusRead {+ return { open, recent: [], access: { ci: true, merge: true }, truncated: false, ...over }+}++function tracker(start = 0) {+ let now = start+ const changes: number[][] = []+ const coordinator = new GitHubRequestCoordinator({ now: () => now })+ const subject = new GitHubPullStatusTracker({+ coordinator, now: () => now, onChanged: (_key, numbers) => changes.push(numbers)+ })+ return { subject, coordinator, changes, advance: (ms: number) => { now += ms }, at: () => now }+}++describe('GitHubPullStatusTracker', () => {+ it('publishes open pull requests and recent merges', async () => {+ const { subject } = tracker()+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)], {+ recent: [{ number: 2, headRefName: 'feat/2', lifecycle: 'merged' }]+ }))+ const board = subject.board(KEY)+ expect(board.pulls.map((pull) => [pull.number, pull.lifecycle, pull.ci, pull.merge])).toEqual([+ [1, 'open', 'passed', 'ready'], [2, 'merged', undefined, undefined]+ ])+ expect(board.stale).toBe(false)+ expect(board.observedAt).toBe(0)+ })++ it('a failed read keeps the last snapshot and marks it stale instead of going blank', async () => {+ const { subject, changes } = tracker()+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)]))+ changes.length = 0+ await subject.read(KEY, 'user-1', 'heartbeat', async () => {+ throw Object.assign(new Error('request-failed'), { code: 'request-failed', status: 502 })+ })+ const board = subject.board(KEY)+ expect(board.stale).toBe(true)+ expect(board.pulls.map((pull) => pull.ci)).toEqual(['passed'])+ expect(changes).toEqual([[]])+ // A stale snapshot is worth re-reading at the next heartbeat even when nothing changed.+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: false })).toBe(true)+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)]))+ expect(subject.board(KEY).stale).toBe(false)+ })++ it('reads after a heartbeat only when something changed, once it knows the repository', async () => {+ const { subject } = tracker()+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: false })).toBe(true)+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)]))+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: false })).toBe(false)+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: true, foreground: false })).toBe(true)+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: true })).toBe(true)+ })++ it('chases an undecided PR on the schedule and stops after 12 reads', async () => {+ const { subject, advance } = tracker()+ const undecided = async () => read([facts(1, { mergeable: 'UNKNOWN', mergeStateStatus: 'UNKNOWN' })])+ await subject.read(KEY, 'user-1', 'heartbeat', undecided)+ expect(subject.board(KEY).undecided).toBe(true)+ let reads = 0+ for (let tick = 0; tick < 400; tick++) {+ advance(15_000)+ if (!subject.claimChase(KEY)) continue+ reads += 1+ await subject.read(KEY, 'user-1', 'chase', undecided)+ }+ expect(reads).toBe(PULL_CHASE_MAX)+ expect(subject.board(KEY).undecided).toBe(false)+ })++ it('does not chase before the first delay, and a failed chase read still spends its attempt', async () => {+ const { subject, advance } = tracker()+ await subject.read(KEY, 'user-1', 'heartbeat', async () =>+ read([facts(1, { rollup: 'PENDING' })]))+ advance(29_999)+ expect(subject.claimChase(KEY)).toBe(false)+ advance(1)+ expect(subject.claimChase(KEY)).toBe(true)+ await subject.read(KEY, 'user-1', 'chase', async () => { throw Object.assign(new Error('x'), { code: 'request-failed' }) })+ // The next step is one minute after the failed read, not an immediate retry.+ advance(59_999)+ expect(subject.claimChase(KEY)).toBe(false)+ advance(1)+ expect(subject.claimChase(KEY)).toBe(true)+ })++ it('stops chasing once the PR settles', async () => {+ const { subject, advance } = tracker()+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1, { rollup: 'PENDING' })]))+ advance(30_000)+ expect(subject.claimChase(KEY)).toBe(true)+ await subject.read(KEY, 'user-1', 'chase', async () => read([facts(1)]))+ advance(3_600_000)+ expect(subject.claimChase(KEY)).toBe(false)+ })++ it('a background read the graphql budget holds is skipped and owed; REST budget does not hold it', async () => {+ const { subject, coordinator } = tracker()+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)]))+ coordinator.noteRateSample('user-1', { resource: 'core', limit: 5_000, remaining: 10, resetAt: 60_000 })+ let ran = 0+ await subject.read(KEY, 'user-1', 'heartbeat', async () => { ran += 1; return read([facts(1)]) })+ expect(ran).toBe(1)+ coordinator.noteRateSample('user-1', { resource: 'graphql', limit: 5_000, remaining: 10, resetAt: 60_000 })+ await subject.read(KEY, 'user-1', 'heartbeat', async () => { ran += 1; return read([facts(1)]) })+ expect(ran).toBe(1)+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: false })).toBe(true)+ // The user's own refresh is not held by the floor — only by a hard limit.+ await subject.read(KEY, 'user-1', 'foreground', async () => { ran += 1; return read([facts(1)]) })+ expect(ran).toBe(2)+ coordinator.noteRateSample('user-1', { resource: 'graphql', limit: 5_000, remaining: 0, resetAt: 60_000 })+ await subject.read(KEY, 'user-1', 'foreground', async () => { ran += 1; return read([facts(1)]) })+ expect(ran).toBe(2)+ })++ it('a token without permission hides CI and mergeability instead of marking anything stale', async () => {+ const { subject } = tracker()+ await subject.read(KEY, 'user-1', 'heartbeat', async () => {+ throw Object.assign(new Error('insufficient-permission'), { code: 'insufficient-permission', status: 403 })+ })+ expect(subject.board(KEY)).toMatchObject({ pulls: [], stale: false, access: { ci: false, merge: false } })+ })++ it('a read in flight when the cache is cleared publishes nothing', async () => {+ const { subject } = tracker()+ let release!: (value: PullStatusRead) => void+ const pending = subject.read(KEY, 'user-1', 'heartbeat', () => new Promise((resolve) => { release = resolve }))+ subject.forgetRepository('o/r')+ release(read([facts(1)]))+ await pending+ expect(subject.board(KEY).pulls).toEqual([])+ })++ it('never carries a CI result from an older head across reads', async () => {+ const { subject } = tracker()+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1, { rollup: 'SUCCESS' })]))+ const pushed = 'c'.repeat(40)+ await subject.read(KEY, 'user-1', 'heartbeat', async () =>+ read([facts(1, { headRefOid: pushed, rollup: 'SUCCESS', rollupOid: HEAD })]))+ expect(subject.board(KEY).pulls[0]).toMatchObject({ headRefOid: pushed, ci: 'pending' })+ })+})diff --git a/src/core/github/pull-status-tracker.ts b/src/core/github/pull-status-tracker.tsnew file mode 100644index 000000000..20e7d14a5--- /dev/null+++ b/src/core/github/pull-status-tracker.ts@@ -0,0 +1,223 @@+// Pull request CI + mergeability per repository: when to read it, what the board is told, and how+// an undecided PR is chased without webhooks. The GraphQL read itself is the client's; this module+// owns only the decisions, so each rule can be pressed by a test without a network.+//+// WHEN a read happens — nothing else triggers one:+// 1. The issues heartbeat (Wave 1) reported a change. A push, a merge, a label, a comment all move+// the repository's most recently updated item; a finished check run does NOT, which is why:+// 2. An undecided PR (mergeability UNKNOWN, or a rollup still PENDING) is CHASED — 30 s, 1 min,+// 2 min, then 5 min, at most 12 reads per episode — and only while a board is VISIBLE. The+// renderer asserts visibility by asking (`claimChase`); a hidden or closed board stops asking.+// 3. The first heartbeat of an app run (nothing known yet), a user's own refresh, a snapshot that+// is stale, or a read the rate budget skipped earlier (`owed`).+//+// A read the budget holds is skipped, never queued, and remembered as owed; a failed read keeps the+// last snapshot and marks it stale. Neither blanks what the board shows.+import {+ EMPTY_PULL_BOARD,+ PULL_CHASE_MAX,+ nextPullChase,+ pullChaseDue,+ pullStatusFrom,+ type GitHubPullBoard,+ type GitHubPullStatus,+ type PullChaseState+} from '../../shared/github-pull-status'+import type { PullStatusRead } from './graphql-pulls'+import type { GitHubRequestCoordinator } from './request-coordinator'++export type PullReadReason = 'heartbeat' | 'foreground' | 'chase'++type PullRepositoryState = {+ pulls: GitHubPullStatus[]+ observedAt?: number+ stale: boolean+ access: { ci: boolean; merge: boolean }+ truncated: boolean+ chase: PullChaseState | null+ /** A read was skipped by the rate budget; the next opportunity reads even if nothing changed. */+ owed: boolean+ inFlight?: Promise<void>+ /** Bumped by `forget` so a read in flight when the cache was cleared cannot publish. */+ generation: number+}++type TrackerOptions = {+ coordinator: GitHubRequestCoordinator+ now?: () => number+ /** Something the board shows changed for this repository key. */+ onChanged: (key: string, changedPullNumbers: number[]) => void+}++/** Why a read did not produce a snapshot. `hidden` is an ANSWER (the token may not read these+ * fields), not a failure. */+function errorCode(error: unknown): string | undefined {+ return error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string'+ ? (error as { code: string }).code+ : undefined+}++export class GitHubPullStatusTracker {+ private readonly states = new Map<string, PullRepositoryState>()+ private readonly now: () => number++ constructor(private readonly options: TrackerOptions) {+ this.now = options.now ?? Date.now+ }++ board(key: string): GitHubPullBoard {+ const state = this.states.get(key)+ if (!state) return { ...EMPTY_PULL_BOARD, access: { ...EMPTY_PULL_BOARD.access } }+ return {+ pulls: state.pulls.map((pull) => ({ ...pull, closes: [...pull.closes] })),+ ...(state.observedAt !== undefined ? { observedAt: state.observedAt } : {}),+ stale: state.stale,+ access: { ...state.access },+ undecided: !!state.chase && state.chase.attempts < PULL_CHASE_MAX,+ truncated: state.truncated+ }+ }++ /** Should the heartbeat that just ran be followed by a pull status read? */+ wantsReadAfterHeartbeat(key: string, input: { changed: boolean; foreground: boolean }): boolean {+ const state = this.states.get(key)+ return input.changed || input.foreground || !state || state.observedAt === undefined ||+ state.stale || state.owed+ }++ /**+ * Claims one chase read, synchronously, so two boards asking at once cannot both spend it. True+ * means the caller must now `read(…, 'chase')`. The attempt is counted HERE, before the read: a+ * chase read that fails still spends one of the twelve.+ */+ claimChase(key: string): boolean {+ const state = this.states.get(key)+ if (!state || state.inFlight || !pullChaseDue(state.chase, this.now())) return false+ state.chase = { ...state.chase!, attempts: state.chase!.attempts + 1, lastReadAt: this.now() }+ return true+ }++ /** Drops every repository state for `repository` (a cache clear or revoke). */+ forgetRepository(repository: string): void {+ for (const [key, state] of this.states) {+ if (!key.endsWith(`\0${repository}`)) continue+ state.generation += 1+ this.states.delete(key)+ }+ }++ /**+ * Reads now. `run` performs the GraphQL read (through the coordinator and the caller's epoch+ * checks); `userId` names the identity whose `graphql` budget it spends. Single-flight per key:+ * a read already in flight answers every caller that arrives meanwhile.+ */+ read(+ key: string,+ userId: string,+ reason: PullReadReason,+ run: () => Promise<PullStatusRead>+ ): Promise<void> {+ const state = this.stateFor(key)+ if (state.inFlight) return state.inFlight+ // Background reads (heartbeat, chase) respect the whole budget, including the floor Wave 1 keeps+ // for the user's own tools. A read the user asked for respects only a hard limit.+ const throttle = this.options.coordinator.throttle(userId, this.now(), 'graphql')+ if (throttle && (reason !== 'foreground' || throttle.kind === 'rate-limited')) {+ state.owed = true+ return Promise.resolve()+ }+ const generation = state.generation+ const work = this.perform(key, state, generation, userId, run)+ state.inFlight = work+ void work.finally(() => { if (state.inFlight === work) delete state.inFlight })+ return work+ }++ private async perform(+ key: string,+ state: PullRepositoryState,+ generation: number,+ userId: string,+ run: () => Promise<PullStatusRead>+ ): Promise<void> {+ let result: PullStatusRead+ try {+ result = await run()+ } catch (error) {+ if (generation !== state.generation) return+ const code = errorCode(error)+ if (code === 'configuration-changed') return+ if (code === 'rate-limited') {+ // The coordinator has recorded the hold; nothing was learned about the pull requests.+ state.owed = true+ return+ }+ if (code === 'insufficient-permission') {+ this.publish(key, state, {+ open: [], recent: [], access: { ci: false, merge: false }, truncated: false+ }, userId)+ return+ }+ const wasStale = state.stale+ state.stale = true+ // A failed chase read still waits its turn: the next one follows the schedule, not a retry loop.+ if (state.chase) state.chase = { ...state.chase, lastReadAt: this.now() }+ if (!wasStale) this.options.onChanged(key, [])+ return+ }+ if (generation !== state.generation) return+ this.publish(key, state, result, userId)+ }++ private publish(key: string, state: PullRepositoryState, result: PullStatusRead, userId: string): void {+ const now = this.now()+ if (result.rateLimit) {+ // The body's own reading, in case a proxy stripped the headers the client already fed in.+ this.options.coordinator.noteRateSample(userId, {+ resource: 'graphql',+ limit: result.rateLimit.limit,+ remaining: result.rateLimit.remaining,+ resetAt: result.rateLimit.resetAt+ })+ }+ const previous = new Map(state.pulls.map((pull) => [pull.number, pull]))+ const open = result.open.map((facts) => pullStatusFrom(facts, result.access, previous.get(facts.number)))+ const openNumbers = new Set(open.map((pull) => pull.number))+ const finished = result.recent+ .filter((pull) => !openNumbers.has(pull.number))+ .map((pull): GitHubPullStatus => ({+ number: pull.number, lifecycle: pull.lifecycle, headRefName: pull.headRefName, closes: []+ }))+ const pulls = [...open, ...finished]+ const nextNumbers = new Set(pulls.map((pull) => pull.number))+ const changed = [+ ...pulls.filter((pull) => JSON.stringify(pull) !== JSON.stringify(previous.get(pull.number)))+ .map((pull) => pull.number),+ ...state.pulls.filter((pull) => !nextNumbers.has(pull.number)).map((pull) => pull.number)+ ]+ const accessChanged = state.access.ci !== result.access.ci || state.access.merge !== result.access.merge+ const wasStale = state.stale+ const chaseBefore = state.chase+ state.pulls = pulls+ state.observedAt = now+ state.stale = false+ state.owed = false+ state.access = { ...result.access }+ state.truncated = result.truncated+ state.chase = nextPullChase(state.chase, open, now)+ const chaseChanged = !!chaseBefore !== !!state.chase+ if (changed.length || accessChanged || wasStale || chaseChanged) this.options.onChanged(key, changed)+ }++ private stateFor(key: string): PullRepositoryState {+ let state = this.states.get(key)+ if (!state) {+ state = {+ pulls: [], stale: false, access: { ci: true, merge: true }, truncated: false,+ chase: null, owed: false, generation: 0+ }+ this.states.set(key, state)+ }+ return state+ }+}diff --git a/src/core/github/request-coordinator.test.ts b/src/core/github/request-coordinator.test.tsindex cc81630ae..8cdd84b74 100644--- a/src/core/github/request-coordinator.test.ts+++ b/src/core/github/request-coordinator.test.ts@@ -200,4 +200,37 @@ describe('GitHubRequestCoordinator rate budget', () => {await expect(coordinator.runRead('user-1', async () => 'ok')).rejects.toMatchObject({ code: 'rate-limited' })expect(sleeps.reduce((total, value) => total + value, 0)).toBeLessThanOrEqual(MAX_RATE_WAIT_MS)})++ describe('the graphql budget', () => {+ it('a graphql primary limit holds GraphQL reads but not REST issue sync', async () => {+ const coordinator = new GitHubRequestCoordinator({ now: () => 1_000 })+ await expect(coordinator.runRead('user-1', async () => {+ throw Object.assign(new Error('rate-limited'), {+ code: 'rate-limited', retryAt: 3_600_000, resource: 'graphql'+ })+ })).rejects.toMatchObject({ code: 'rate-limited' })+ expect(coordinator.throttle('user-1', 1_000, 'graphql')).toEqual({ until: 3_600_000, kind: 'rate-limited' })+ expect(coordinator.throttle('user-1', 1_000)).toBeUndefined()+ expect(coordinator.canStart('user-1', 1_000)).toBe(true)+ })++ it('an untagged (secondary) limit still holds the whole identity, graphql included', async () => {+ const coordinator = new GitHubRequestCoordinator({ now: () => 1_000 })+ await expect(coordinator.runRead('user-1', async () => {+ throw Object.assign(new Error('rate-limited'), { code: 'rate-limited', retryAt: 9_000 })+ })).rejects.toMatchObject({ code: 'rate-limited' })+ expect(coordinator.throttle('user-1', 1_000, 'graphql')).toEqual({ until: 9_000, kind: 'rate-limited' })+ expect(coordinator.throttle('user-1', 1_000)).toEqual({ until: 9_000, kind: 'rate-limited' })+ })++ it('meters the graphql budget on its own floor', () => {+ const coordinator = new GitHubRequestCoordinator({ now: () => 1_000 })+ coordinator.noteRateSample('user-1', { resource: 'graphql', limit: 5_000, remaining: 99, resetAt: 60_000 })+ expect(coordinator.throttle('user-1', 1_000, 'graphql')).toEqual({ until: 60_000, kind: 'low-budget' })+ expect(coordinator.throttle('user-1', 1_000)).toBeUndefined()+ coordinator.noteRateSample('user-1', { resource: 'graphql', limit: 5_000, remaining: 0, resetAt: 60_000 })+ expect(coordinator.throttle('user-1', 1_000, 'graphql')).toEqual({ until: 60_000, kind: 'rate-limited' })+ expect(coordinator.canStart('user-1', 1_000)).toBe(true)+ })+ })})diff --git a/src/core/github/request-coordinator.ts b/src/core/github/request-coordinator.tsindex e10e75f7b..9a2a536f3 100644--- a/src/core/github/request-coordinator.ts+++ b/src/core/github/request-coordinator.ts@@ -37,6 +37,8 @@ type IdentityState = {lastMutationAt: numbergeneration: numberretryAt: number+ /** Primary-limit holds for a non-`core` budget (see `noteOperationRateLimit`). */+ resourceRetryAt: Map<string, number>/** Latest budget per resource (`core`, `search`, …), from response headers. */budget: Map<string, GitHubRateStatus>}@@ -48,9 +50,17 @@ type CoordinatorOptions = {function noteOperationRateLimit(state: IdentityState, error: unknown): void {if (!error || typeof error !== 'object') return- const value = error as { code?: unknown; retryAt?: unknown }+ const value = error as { code?: unknown; retryAt?: unknown; resource?: unknown }if (value.code === 'rate-limited' && typeof value.retryAt === 'number' &&Number.isFinite(value.retryAt)) {+ // A PRIMARY limit belongs to one budget. `graphql` and `core` are separate, so a spent `graphql`+ // budget (the user's own `gh pr list` spends it too) holds only GraphQL reads — it must not+ // stall REST issue sync for up to an hour. Untagged (secondary) limits hold the identity.+ if (typeof value.resource === 'string' && value.resource !== 'core') {+ const previous = state.resourceRetryAt.get(value.resource) ?? 0+ state.resourceRetryAt.set(value.resource, Math.max(previous, value.retryAt))+ return+ }state.retryAt = Math.max(state.retryAt, value.retryAt)}}@@ -120,20 +130,25 @@ export class GitHubRequestCoordinator {}}- /** The `core` budget last seen for this identity, while its window is still current. */- rateStatus(identity: string, at = this.now()): GitHubRateStatus | undefined {- const status = this.states.get(identity)?.budget.get('core')+ /** The budget last seen for this identity (`core` unless another resource is named), while its+ * window is still current. */+ rateStatus(identity: string, at = this.now(), resource = 'core'): GitHubRateStatus | undefined {+ const status = this.states.get(identity)?.budget.get(resource)return status && status.resetAt > at ? { ...status } : undefined}/** Why background work for this identity must wait, and until when — or undefined when it may* run. `rate-limited` also holds user-initiated requests (they wait up to MAX_RATE_WAIT_MS, then- * are refused); `low-budget` holds only background polls. */- throttle(identity: string, at = this.now()): GitHubThrottle | undefined {+ * are refused); `low-budget` holds only background polls. `resource` names the budget the work+ * would spend: GraphQL reads spend `graphql`, which GitHub meters separately from `core`. */+ throttle(identity: string, at = this.now(), resource = 'core'): GitHubThrottle | undefined {const state = this.states.get(identity)if (!state) return undefinedif (state.retryAt > at) return { until: state.retryAt, kind: 'rate-limited' }- const status = this.rateStatus(identity, at)+ const resourceRetryAt = state.resourceRetryAt.get(resource) ?? 0+ if (resourceRetryAt > at) return { until: resourceRetryAt, kind: 'rate-limited' }+ const status = this.rateStatus(identity, at, resource)+ if (status && status.remaining === 0) return { until: status.resetAt, kind: 'rate-limited' }if (status && status.remaining < backgroundFloor(status.limit)) {return { until: status.resetAt, kind: 'low-budget' }}@@ -165,6 +180,7 @@ export class GitHubRequestCoordinator {lastMutationAt: Number.NEGATIVE_INFINITY,generation: 0,retryAt: 0,+ resourceRetryAt: new Map(),budget: new Map()}this.states.set(identity, state)diff --git a/src/core/github/service.pulls.test.ts b/src/core/github/service.pulls.test.tsnew file mode 100644index 000000000..ce7bba102--- /dev/null+++ b/src/core/github/service.pulls.test.ts@@ -0,0 +1,165 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { promises as fs } from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { GitHubIssueCache } from './cache'+import { GitHubIssueService, type GitHubIssueServiceContext, type GitHubIssuesClientLike } from './service'+import { GitHubRequestCoordinator } from './request-coordinator'+import type { PullStatusRead } from './graphql-pulls'+import type { GitHubIssue, IssueHeartbeatResult, NormalisedProjectKanbanGitHub } from '../../shared/github-issues'+import type { GitHubPullChecksResult, PullStatusFacts } from '../../shared/github-pull-status'++let userDataDir: string+beforeEach(async () => { userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-github-pulls-')) })+afterEach(async () => { await fs.rm(userDataDir, { recursive: true, force: true }) })++const HEAD = 'a'.repeat(40)+const config: NormalisedProjectKanbanGitHub = {+ repository: 'o/r', columnMappings: [{ columnId: 'done', label: 'done' }], completionColumnId: 'done',+ revision: 'mapping-1'+}++function facts(number: number, over: Partial<PullStatusFacts> = {}): PullStatusFacts {+ return {+ number, headRefName: `feat/${number}`, headRefOid: HEAD, isDraft: false, mergeable: 'MERGEABLE',+ mergeStateStatus: 'CLEAN', rollup: 'SUCCESS', rollupOid: HEAD, closes: [], ...over+ }+}++class PullClient implements GitHubIssuesClientLike {+ /** The heartbeat's answer: flip `changed` to simulate activity in the repository. */+ changed = false+ heartbeats = 0+ statusReads = 0+ checkReads = 0+ open: PullStatusFacts[] = [facts(1)]+ checks: GitHubPullChecksResult = { status: 'no-checks' }+ failChecks?: Error++ async listIssues() { return { items: [] as GitHubIssue[] } }+ async issuesHeartbeat(_repository: string, etag?: string): Promise<IssueHeartbeatResult> {+ this.heartbeats += 1+ if (this.changed || !etag) { this.changed = false; return { notModified: false, etag: `W/"${Math.random()}"` } }+ return { notModified: true, etag }+ }+ async getIssue(): Promise<never> { throw new Error('unused') }+ async updateIssue(): Promise<never> { throw new Error('unused') }+ async listRepositoryLabels() { return { items: [] } }+ async createLabel(): Promise<never> { throw new Error('unused') }+ async createIssue(): Promise<never> { throw new Error('unused') }+ async createIssueComment(): Promise<never> { throw new Error('unused') }+ async pullRequestStatuses(): Promise<PullStatusRead> {+ this.statusReads += 1+ return { open: this.open, recent: [], access: { ci: true, merge: true }, truncated: false }+ }+ async pullRequestChecks(): Promise<GitHubPullChecksResult> {+ this.checkReads += 1+ if (this.failChecks) throw this.failChecks+ return this.checks+ }+}++function context(client: PullClient): GitHubIssueServiceContext {+ return {+ localApprovalId: 'local-1', projectId: 'project-1', repository: 'o/r', config, controlRevision: 1,+ credentialGeneration: 1, userId: 'user-1', client, columnColors: {}, mappingApproved: true+ }+}++/** The poll and the subscribe refresh write the real on-disk cache, so "nothing else happens"+ * needs a real settle, not a few microtask turns. */+async function flush(): Promise<void> {+ await new Promise((resolve) => setTimeout(resolve, 40))+}++function harness(client = new PullClient()) {+ let now = 1_000_000+ let poll: (() => void) | undefined+ let contexts = 0+ const service = new GitHubIssueService({+ cache: new GitHubIssueCache(userDataDir),+ coordinator: new GitHubRequestCoordinator({ now: () => now }),+ contextForProject: async () => { contexts += 1; return context(client) },+ now: () => now,+ setInterval: (fn) => { poll = fn; return 1 },+ clearInterval: () => { poll = undefined }+ })+ return {+ client, service,+ advance: (ms: number) => { now += ms },+ poll: async () => { poll?.(); await flush() },+ contexts: () => contexts+ }+}++describe('GitHubIssueService pull status', () => {+ it('reads pull status on the first heartbeat, then only when the heartbeat reports a change', async () => {+ const h = harness()+ await h.service.subscribe(7, { projectId: 'project-1' })+ await vi.waitFor(() => expect(h.client.statusReads).toBe(1))+ expect((await h.service.pullStatus({ projectId: 'project-1' })).pulls[0]).toMatchObject({ number: 1, ci: 'passed' })++ h.advance(60_000)+ await h.poll()+ // The poll really ran (its heartbeat was sent) and answered 304: no GraphQL read.+ await vi.waitFor(() => expect(h.client.heartbeats).toBe(2))+ await flush()+ expect(h.client.statusReads).toBe(1)++ h.client.changed = true+ h.advance(60_000)+ await h.poll()+ await vi.waitFor(() => expect(h.client.statusReads).toBe(2))+ })++ it('a chase ping costs nothing until a read is due, and never resolves a context early', async () => {+ const h = harness()+ h.client.open = [facts(1, { rollup: 'PENDING' })]+ await h.service.subscribe(7, { projectId: 'project-1' })+ await flush()+ const contextsBefore = h.contexts()+ expect(await h.service.chasePulls({ projectId: 'project-1' })).toBe(false)+ expect(h.contexts()).toBe(contextsBefore)+ h.advance(30_000)+ expect(await h.service.chasePulls({ projectId: 'project-1' })).toBe(true)+ expect(h.client.statusReads).toBe(2)+ })++ it('a chase ping for a project with nothing undecided never reads', async () => {+ const h = harness()+ await h.service.subscribe(7, { projectId: 'project-1' })+ await flush()+ h.advance(3_600_000)+ expect(await h.service.chasePulls({ projectId: 'project-1' })).toBe(false)+ expect(h.client.statusReads).toBe(1)+ })++ it('check detail: hidden for a token that cannot read checks, never a failed board', async () => {+ const h = harness()+ h.client.failChecks = Object.assign(new Error('insufficient-permission'), { code: 'insufficient-permission', status: 403 })+ expect(await h.service.pullChecks({ projectId: 'project-1', pullNumber: 1 })).toEqual({ status: 'hidden' })+ h.client.failChecks = Object.assign(new Error('request-failed'), { code: 'request-failed', status: 502 })+ expect(await h.service.pullChecks({ projectId: 'project-1', pullNumber: 1 })).toEqual({ status: 'unavailable' })+ expect(await h.service.pullChecks({ projectId: 'project-1', pullNumber: -3 })).toEqual({ status: 'unavailable' })+ })++ it('does not ask for check detail once the list read showed the token cannot read checks', async () => {+ const h = harness()+ h.client.pullRequestStatuses = async () => {+ h.client.statusReads += 1+ return { open: [facts(1)], recent: [], access: { ci: false, merge: true }, truncated: false }+ }+ await h.service.subscribe(7, { projectId: 'project-1' })+ await flush()+ expect(await h.service.pullChecks({ projectId: 'project-1', pullNumber: 1 })).toEqual({ status: 'hidden' })+ expect(h.client.checkReads).toBe(0)+ })++ it('clearing the cache forgets pull status', async () => {+ const h = harness()+ await h.service.subscribe(7, { projectId: 'project-1' })+ await flush()+ await h.service.clearCache({ projectId: 'project-1' })+ expect((await h.service.pullStatus({ projectId: 'project-1' })).pulls).toEqual([])+ })+})diff --git a/src/core/github/service.ts b/src/core/github/service.tsindex fba8ace88..c3e00bd38 100644--- a/src/core/github/service.ts+++ b/src/core/github/service.ts@@ -24,6 +24,9 @@ import {} from './cache'import { classifyGitHubFailure } from './failure'import type { GitHubRequestCoordinator } from './request-coordinator'+import type { PullStatusRead } from './graphql-pulls'+import { GitHubPullStatusTracker } from './pull-status-tracker'+import type { GitHubPullBoard, GitHubPullChecksResult } from '../../shared/github-pull-status'const MAX_ISSUES = 10_000const MAX_CACHE_BYTES = 64 * 1024 * 1024@@ -61,6 +64,11 @@ export interface GitHubIssuesClientLike {* report path must never build a second authenticated client of its own. */createIssue(repository: string, input: CreateIssueInput): Promise<GitHubIssue>createIssueComment(repository: string, issueNumber: number, body: string): Promise<{ id: number }>+ /** Pull request CI + mergeability (one GraphQL read). Optional so a client that cannot make+ * GraphQL reads — and every test fake written before them — simply has no pull status: the board+ * then shows none, which is the honest answer. */+ pullRequestStatuses?(repository: string): Promise<PullStatusRead>+ pullRequestChecks?(repository: string, pullNumber: number): Promise<GitHubPullChecksResult>}export interface GitHubIssueProjectContext {@@ -203,6 +211,8 @@ export class GitHubIssueService {private readonly repositoryControls = new Map<string, RepositoryControl>()private readonly statePreparations = new Map<string, Set<Promise<RepositoryState>>>()private readonly refreshFloors = new Map<string, { any: number; full: number }>()+ /** Pull request CI/mergeability per repository key — see pull-status-tracker.ts. */+ private readonly pulls: GitHubPullStatusTrackerprivate operationSequence = 0private readonly now: () => numberprivate readonly schedule: NonNullable<ServiceOptions['setInterval']>@@ -212,6 +222,14 @@ export class GitHubIssueService {this.now = options.now ?? Date.nowthis.schedule = options.setInterval ?? ((fn, milliseconds) => setInterval(fn, milliseconds))this.unschedule = options.clearInterval ?? ((timer) => clearInterval(timer as ReturnType<typeof setInterval>))+ this.pulls = new GitHubPullStatusTracker({+ coordinator: options.coordinator,+ now: this.now,+ onChanged: (key, changed) => {+ const state = this.repositories.get(key)+ if (state) this.emitDelta(state, changed, true)+ }+ })}async subscribe(uiId: number, request: { projectId: string }): Promise<GitHubIssuePage> {@@ -321,7 +339,7 @@ export class GitHubIssueService {const cacheGeneration = state.cacheGenerationconst work = this.refreshRepository(captured, state, request.full === true, cacheGeneration, operationId, repositoryGeneration,- startedAt+ startedAt, background)state.refresh = worktry { await work } finally { if (state.refresh === work) delete state.refresh }@@ -646,6 +664,7 @@ export class GitHubIssueService {...mutations])await this.options.cache.clearBound(context.localApprovalId, context.projectId, context.repository)+ this.pulls.forgetRepository(context.repository)for (const state of this.repositoryStates(context.localApprovalId, context.repository)) {state.cacheGeneration += 1state.snapshot = undefined@@ -659,6 +678,75 @@ export class GitHubIssueService {}}+ /** What the board knows about this project's pull requests beyond the issues harvest. Read from+ * memory only — it never sends a request. */+ async pullStatus(request: { projectId: string }): Promise<GitHubPullBoard> {+ const context = await this.cacheContext(request.projectId)+ const { key } = await this.cachedState(context)+ return this.pulls.board(key)+ }++ /**+ * A VISIBLE board asks this while some PR is undecided. It answers false at the cost of a map+ * lookup unless a chase read is due, so a board may ask as often as it likes: the schedule and the+ * cap of 12 live here, and only a due read resolves a context (which runs the credential chain).+ */+ async chasePulls(request: { projectId: string }): Promise<boolean> {+ const key = this.projectKeys.get(request.projectId)+ if (!key || !this.pulls.claimChase(key)) return false+ let captured: GitHubIssueServiceContext+ try {+ captured = await this.options.contextForProject(request.projectId)+ } catch {+ return false+ }+ if (repositoryKey(captured) !== key || !captured.client.pullRequestStatuses) return false+ await this.pulls.read(key, captured.userId, 'chase', () =>+ this.readWithEpoch(captured, () => captured.client.pullRequestStatuses!(captured.repository)))+ return true+ }++ /** Per-check detail for one PR, read when its modal opens. Never throws: every failure is one of+ * the result's own statuses, so a modal can always say what it knows. */+ async pullChecks(request: { projectId: string; pullNumber: number }): Promise<GitHubPullChecksResult> {+ if (!Number.isSafeInteger(request.pullNumber) || request.pullNumber < 1) {+ return { status: 'unavailable' }+ }+ let captured: GitHubIssueServiceContext+ try {+ captured = await this.options.contextForProject(request.projectId)+ } catch {+ return { status: 'unavailable' }+ }+ if (!captured.client.pullRequestChecks) return { status: 'unavailable' }+ // A token already known to be unable to read checks is not asked again.+ if (!this.pulls.board(repositoryKey(captured)).access.ci) return { status: 'hidden' }+ const throttle = this.options.coordinator.throttle(captured.userId, this.now(), 'graphql')+ if (throttle?.kind === 'rate-limited') return { status: 'unavailable' }+ try {+ return await this.readWithEpoch(captured, () =>+ captured.client.pullRequestChecks!(captured.repository, request.pullNumber))+ } catch (error) {+ // A 403 that is not a rate limit: this token may not read the checks. Say nothing about them.+ return (error as { code?: unknown } | null)?.code === 'insufficient-permission'+ ? { status: 'hidden' }+ : { status: 'unavailable' }+ }+ }++ private readPullStatusAfterHeartbeat(+ captured: GitHubIssueServiceContext,+ changed: boolean,+ foreground: boolean+ ): void {+ const key = repositoryKey(captured)+ if (!captured.client.pullRequestStatuses) return+ if (!this.pulls.wantsReadAfterHeartbeat(key, { changed, foreground })) return+ void this.pulls.read(key, captured.userId, foreground ? 'foreground' : 'heartbeat', () =>+ this.readWithEpoch(captured, () => captured.client.pullRequestStatuses!(captured.repository)))+ .catch(() => undefined)+ }+private state(context: GitHubIssueServiceContext,operationId: number,@@ -787,7 +875,8 @@ export class GitHubIssueService {cacheGeneration: number,operationId: number,repositoryGeneration: number,- refreshStartedAt: number+ refreshStartedAt: number,+ background = false): Promise<void> {const full = forceFull || !state.snapshot ||this.now() - state.snapshot.lastFullReconciliationAt >= FULL_REFRESH_AGE@@ -808,6 +897,9 @@ export class GitHubIssueService {.catch((error: unknown) =>error instanceof ConfigurationChangedError ? null : Promise.reject(error))if (!beat) return+ // The heartbeat is also what decides whether pull request CI/mergeability is worth a GraphQL+ // read. It runs beside the issue scan, not after it: the board's issues never wait on it.+ this.readPullStatusAfterHeartbeat(captured, !beat.notModified, !background)if (beat.notModified && !full && previous && !state.incomplete) returnconst heartbeatEtag = beat.etagconst etags: Record<string, string> = heartbeatEtag ? { [HEARTBEAT_ETAG_KEY]: heartbeatEtag } : {}diff --git a/src/main/remote/relay-project-scope.ts b/src/main/remote/relay-project-scope.tsindex ec0195d44..517372b63 100644--- a/src/main/remote/relay-project-scope.ts+++ b/src/main/remote/relay-project-scope.ts@@ -45,6 +45,9 @@ const EXTRACTORS: Record<string, (args: unknown[]) => unknown> = {[IPC.githubIssuesCreateLabels]: fromFirstArg,[IPC.githubIssuesClearCache]: fromFirstArg,[IPC.githubIssuesUnsubscribe]: fromFirstArg,+ [IPC.githubIssuesPullStatus]: fromFirstArg,+ [IPC.githubIssuesChasePulls]: fromFirstArg,+ [IPC.githubIssuesPullChecks]: fromFirstArg,[IPC.boardLogAppend]: fromFirstArg,[IPC.boardLogRead]: fromFirstArg,[IPC.boardLogSubscribe]: fromFirstArg,diff --git a/src/preload/index.ts b/src/preload/index.tsindex 85d7e3f78..c17aad03f 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -228,6 +228,10 @@ const api: NodeTerminalApi = {moveIssue: (request) => ipcRenderer.invoke(IPC.githubIssuesMove, request),createMissingLabels: (projectId) => ipcRenderer.invoke(IPC.githubIssuesCreateLabels, projectId),clearCache: (projectId) => ipcRenderer.invoke(IPC.githubIssuesClearCache, projectId),+ pullStatus: (projectId) => ipcRenderer.invoke(IPC.githubIssuesPullStatus, projectId),+ chasePulls: (projectId) => ipcRenderer.invoke(IPC.githubIssuesChasePulls, projectId),+ pullChecks: (projectId, pullNumber) =>+ ipcRenderer.invoke(IPC.githubIssuesPullChecks, projectId, pullNumber),projectAvatar: (projectId) => ipcRenderer.invoke(IPC.githubProjectAvatar, projectId),onChanged: (projectId, listener) => {const channel = IPC.githubIssuesChanged(projectId)diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex a8c3fd96d..79536e886 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -454,6 +454,14 @@ export function buildGitHubApi(>,clearCache: (projectId) =>client.request(IPC.githubIssuesClearCache, projectId) as Promise<void>,+ pullStatus: (projectId) =>+ client.request(IPC.githubIssuesPullStatus, projectId) as ReturnType<GitHubIssuesApi['pullStatus']>,+ chasePulls: (projectId) =>+ client.request(IPC.githubIssuesChasePulls, projectId) as Promise<boolean>,+ pullChecks: (projectId, pullNumber) =>+ client.request(IPC.githubIssuesPullChecks, projectId, pullNumber) as ReturnType<+ GitHubIssuesApi['pullChecks']+ >,projectAvatar: (projectId) =>client.request(IPC.githubProjectAvatar, projectId) as ReturnType<GitHubIssuesApi['projectAvatar']diff --git a/src/renderer/state/githubIssues.test.ts b/src/renderer/state/githubIssues.test.tsindex 44dfdf172..3f023243e 100644--- a/src/renderer/state/githubIssues.test.ts+++ b/src/renderer/state/githubIssues.test.ts@@ -32,6 +32,11 @@ function api(): GitHubIssuesApi {moveIssue: vi.fn(async () => ({ status: 'configuration-changed' as const })),createMissingLabels: vi.fn(async () => ({ status: 'confirmed' as const, created: [], remaining: [] })),clearCache: vi.fn(async () => {}),+ pullStatus: vi.fn(async () => ({+ pulls: [], stale: false, access: { ci: true, merge: true }, undecided: false, truncated: false+ })),+ chasePulls: vi.fn(async () => false),+ pullChecks: vi.fn(async () => ({ status: 'no-checks' as const })),projectAvatar: vi.fn(async () => null),onChanged: vi.fn(() => () => {})}diff --git a/src/shared/github-issues.ts b/src/shared/github-issues.tsindex d7ca5af29..b3ef70e6e 100644--- a/src/shared/github-issues.ts+++ b/src/shared/github-issues.ts@@ -1,3 +1,5 @@+import type { GitHubPullBoard, GitHubPullChecksResult } from './github-pull-status'+export interface ProjectKanbanGitHub {repository?: stringcolumnMappings: Array<{@@ -277,6 +279,13 @@ export interface GitHubIssuesApi {}): Promise<GitHubMutationResult>createMissingLabels(projectId: string): Promise<CreateMappedLabelsResult>clearCache(projectId: string): Promise<void>+ /** Pull request CI + mergeability, from memory (no request). */+ pullStatus(projectId: string): Promise<GitHubPullBoard>+ /** A VISIBLE board asks while some PR is undecided; the host decides whether a read is due (30 s,+ * 1 min, 2 min, then 5 min, at most 12 per episode) and answers whether it read. */+ chasePulls(projectId: string): Promise<boolean>+ /** Per-check detail for one PR — read only when its modal opens. */+ pullChecks(projectId: string, pullNumber: number): Promise<GitHubPullChecksResult>onChanged(projectId: string, listener: (changedIssueNumbers: number[]) => void): () => void/** Resolve the project's GitHub org/user avatar (owner derived host-side from the project's own* origin — never a caller-supplied slug). Null when the project has no GitHub origin or thediff --git a/src/shared/github-pull-status.test.ts b/src/shared/github-pull-status.test.tsnew file mode 100644index 000000000..188797ca0--- /dev/null+++ b/src/shared/github-pull-status.test.ts@@ -0,0 +1,194 @@+import { describe, expect, it } from 'vitest'+import {+ PULL_CHASE_MAX,+ PULL_STATUS_GREY_AFTER_MS,+ checkRunState,+ ciState,+ isUndecided,+ mergeState,+ nextPullChase,+ pullChaseDelay,+ pullChaseDue,+ pullStatusFreshness,+ pullStatusFrom,+ sortChecks,+ statusContextState,+ type GitHubPullStatus,+ type PullStatusFacts+} from './github-pull-status'++const HEAD = 'a'.repeat(40)+const OLD = 'b'.repeat(40)+const ALL = { ci: true, merge: true }++function facts(over: Partial<PullStatusFacts> = {}): PullStatusFacts {+ return {+ number: 7,+ headRefName: 'feat/x',+ headRefOid: HEAD,+ isDraft: false,+ mergeable: 'MERGEABLE',+ mergeStateStatus: 'CLEAN',+ rollup: 'SUCCESS',+ rollupOid: HEAD,+ closes: [],+ ...over+ }+}++describe('ci state', () => {+ it('a missing rollup is "no checks", never "passed"', () => {+ expect(ciState(null)).toBe('none')+ expect(pullStatusFrom(facts({ rollup: null, rollupOid: null }), ALL).ci).toBe('none')+ })++ it('maps GitHub status states', () => {+ expect(ciState('SUCCESS')).toBe('passed')+ expect(ciState('FAILURE')).toBe('failed')+ expect(ciState('ERROR')).toBe('failed')+ expect(ciState('PENDING')).toBe('pending')+ expect(ciState('EXPECTED')).toBe('pending')+ })+})++describe('merge state', () => {+ it('MERGEABLE is not ready: only CLEAN is', () => {+ expect(mergeState('MERGEABLE', 'BLOCKED')).toBe('blocked')+ expect(mergeState('MERGEABLE', 'BEHIND')).toBe('behind')+ expect(mergeState('MERGEABLE', 'UNSTABLE')).toBe('unstable')+ expect(mergeState('MERGEABLE', 'HAS_HOOKS')).toBe('hooks')+ expect(mergeState('MERGEABLE', 'CLEAN')).toBe('ready')+ })++ it('conflicts from either field are conflicts', () => {+ expect(mergeState('CONFLICTING', 'DIRTY')).toBe('conflict')+ expect(mergeState('CONFLICTING', 'CLEAN')).toBe('conflict')+ expect(mergeState('MERGEABLE', 'DIRTY')).toBe('conflict')+ })++ it('UNKNOWN in either field is undecided', () => {+ expect(mergeState('UNKNOWN', 'CLEAN')).toBe('undecided')+ expect(mergeState('MERGEABLE', 'UNKNOWN')).toBe('undecided')+ })++ it('an unreadable or unrecognised value claims nothing', () => {+ expect(mergeState(null, 'CLEAN')).toBeUndefined()+ expect(mergeState('MERGEABLE', null)).toBeUndefined()+ expect(mergeState('MERGEABLE', 'SOMETHING_NEW')).toBeUndefined()+ })+})++describe('pullStatusFrom', () => {+ it('ignores a rollup taken at another commit', () => {+ const status = pullStatusFrom(facts({ rollup: 'SUCCESS', rollupOid: OLD }), ALL)+ expect(status.ci).not.toBe('passed')+ expect(status.ci).toBe('pending')+ })++ it('never carries CI from an older head onto a newer one', () => {+ const previous: GitHubPullStatus = {+ number: 7, lifecycle: 'open', headRefName: 'feat/x', headRefOid: OLD, ci: 'passed', closes: []+ }+ const status = pullStatusFrom(facts({ rollup: 'SUCCESS', rollupOid: OLD }), ALL, previous)+ expect(status.ci).toBe('pending')+ })++ it('keeps the previous CI for the SAME head when this read raced a push', () => {+ const previous: GitHubPullStatus = {+ number: 7, lifecycle: 'open', headRefName: 'feat/x', headRefOid: HEAD, ci: 'failed', closes: []+ }+ const status = pullStatusFrom(facts({ rollup: 'SUCCESS', rollupOid: OLD }), ALL, previous)+ expect(status.ci).toBe('failed')+ })++ it('omits ci and merge the token may not read', () => {+ const status = pullStatusFrom(facts(), { ci: false, merge: false })+ expect(status.ci).toBeUndefined()+ expect(status.merge).toBeUndefined()+ expect('ci' in status).toBe(false)+ })++ it('a draft reads as draft', () => {+ expect(pullStatusFrom(facts({ isDraft: true }), ALL).lifecycle).toBe('draft')+ })+})++describe('undecided', () => {+ it('pending CI or undecided mergeability keeps an open PR undecided', () => {+ expect(isUndecided({ lifecycle: 'open', ci: 'pending', merge: 'ready' })).toBe(true)+ expect(isUndecided({ lifecycle: 'open', ci: 'passed', merge: 'undecided' })).toBe(true)+ expect(isUndecided({ lifecycle: 'open', ci: 'none', merge: 'ready' })).toBe(false)+ expect(isUndecided({ lifecycle: 'merged', ci: 'pending', merge: 'undecided' })).toBe(false)+ })+})++describe('chase', () => {+ const pending = (number: number, oid = HEAD): GitHubPullStatus => ({+ number, lifecycle: 'open', headRefName: 'x', headRefOid: oid, ci: 'pending', merge: 'ready', closes: []+ })+ const settled = (number: number): GitHubPullStatus => ({ ...pending(number), ci: 'passed' })++ it('follows 30 s, 1 min, 2 min, then 5 min', () => {+ expect([0, 1, 2, 3, 4, 11].map(pullChaseDelay)).toEqual(+ [30_000, 60_000, 120_000, 300_000, 300_000, 300_000]+ )+ })++ it('caps an episode at 12 reads', () => {+ let chase = nextPullChase(null, [pending(1)], 0)!+ let now = 0+ let reads = 0+ for (let tick = 0; tick < 200; tick++) {+ now += 30_000+ if (!pullChaseDue(chase, now)) continue+ reads += 1+ chase = { ...nextPullChase(chase, [pending(1)], now)!, attempts: chase.attempts + 1 }+ }+ expect(reads).toBe(PULL_CHASE_MAX)+ expect(pullChaseDue(chase, now + 3_600_000)).toBe(false)+ })++ it('is not due before its delay', () => {+ const chase = nextPullChase(null, [pending(1)], 1_000)!+ expect(pullChaseDue(chase, 1_000 + 29_999)).toBe(false)+ expect(pullChaseDue(chase, 1_000 + 30_000)).toBe(true)+ })++ it('ends when nothing is undecided', () => {+ expect(nextPullChase({ keys: ['1@x'], attempts: 3, lastReadAt: 0 }, [settled(1)], 5)).toBeNull()+ })++ it('a new head or a new undecided PR starts a new episode; the same one keeps counting', () => {+ const base = nextPullChase(null, [pending(1)], 0)!+ const spent = { ...base, attempts: 9 }+ expect(nextPullChase(spent, [pending(1)], 10)!.attempts).toBe(9)+ expect(nextPullChase(spent, [pending(1, OLD)], 10)!.attempts).toBe(0)+ expect(nextPullChase(spent, [pending(1), pending(2)], 10)!.attempts).toBe(0)+ })+})++describe('freshness', () => {+ it('a snapshot is fresh until a read fails, then stale, then greyed', () => {+ expect(pullStatusFreshness({ stale: false, observedAt: 0 }, 10 ** 9)).toBe('fresh')+ expect(pullStatusFreshness({ stale: true, observedAt: 1_000 }, 2_000)).toBe('stale')+ expect(pullStatusFreshness({ stale: true, observedAt: 1_000 }, 1_000 + PULL_STATUS_GREY_AFTER_MS))+ .toBe('expired')+ })+})++describe('checks', () => {+ it('maps check runs and status contexts', () => {+ expect(checkRunState('IN_PROGRESS', null)).toBe('pending')+ expect(checkRunState('COMPLETED', 'SUCCESS')).toBe('passed')+ expect(checkRunState('COMPLETED', 'TIMED_OUT')).toBe('failed')+ expect(checkRunState('COMPLETED', 'SKIPPED')).toBe('skipped')+ expect(statusContextState('EXPECTED')).toBe('pending')+ expect(statusContextState('ERROR')).toBe('failed')+ })++ it('sorts failures first', () => {+ expect(sortChecks([+ { name: 'b', state: 'passed' }, { name: 'a', state: 'failed' }, { name: 'c', state: 'pending' }+ ]).map((check) => check.name)).toEqual(['a', 'c', 'b'])+ })+})diff --git a/src/shared/github-pull-status.ts b/src/shared/github-pull-status.tsnew file mode 100644index 000000000..cdb506f26--- /dev/null+++ b/src/shared/github-pull-status.ts@@ -0,0 +1,268 @@+// What a pull request's CI and merge state MEAN on the board — one pure place, shared by core (which+// reads GitHub) and the renderer (which draws it), so the two cannot disagree about a single rule.+//+// Every rule here is a bug that has been shipped somewhere before, and the tests pin each one:+// - a missing check rollup means "no checks", never "passed";+// - "ready to merge" comes from `mergeStateStatus === 'CLEAN'` alone — `mergeable === 'MERGEABLE'`+// is also true for a PR that branch protection is still blocking (measured: 2 of 31 MERGEABLE+// pull requests on this repository were BLOCKED);+// - a rollup counts only when it was taken at the PR's current head commit;+// - a failed read keeps the last snapshot and says it is stale, instead of going blank.++/** The PR's checks, summarised. `none` = GitHub reports no rollup at all: the board shows nothing+ * for CI — not a green tick. */+export type PullCiState = 'passed' | 'failed' | 'pending' | 'none'++/** Whether the PR can merge. Only `ready` means "ready to merge". */+export type PullMergeState =+ | 'ready'+ | 'conflict'+ | 'blocked'+ | 'behind'+ | 'unstable'+ | 'hooks'+ | 'undecided'++/** Where the PR is in its life, as the board needs it. `merged` and `closed` are different facts:+ * only a merge completes the work. */+export type PullLifecycle = 'open' | 'draft' | 'merged' | 'closed'++/** GitHub's `StatusState`, the value a commit's check rollup carries. */+export type GitHubRollupState = 'SUCCESS' | 'FAILURE' | 'ERROR' | 'PENDING' | 'EXPECTED'+/** GitHub's `MergeableState`. */+export type GitHubMergeable = 'MERGEABLE' | 'CONFLICTING' | 'UNKNOWN'++/** One open PR as GitHub reported it in one read. `rollup` is null when GitHub reports no rollup;+ * `rollupOid` is the commit that rollup belongs to. `mergeable`/`mergeStateStatus` are null when+ * the token may not read them (the read is then not an answer about mergeability). */+export interface PullStatusFacts {+ number: number+ headRefName: string+ headRefOid: string+ isDraft: boolean+ mergeable: GitHubMergeable | null+ mergeStateStatus: string | null+ rollup: GitHubRollupState | null+ rollupOid: string | null+ /** Issues in the SAME repository this PR closes on merge (GitHub's own linking). */+ closes: number[]+}++/** One PR's state on the board. `ci`/`merge` are ABSENT when unknown — the token cannot read them,+ * the PR is not open, or the only rollup we have belongs to another commit. Absent renders nothing. */+export interface GitHubPullStatus {+ number: number+ lifecycle: PullLifecycle+ headRefName: string+ /** Open PRs only: the commit the status below was taken at. */+ headRefOid?: string+ ci?: PullCiState+ merge?: PullMergeState+ /** Open PRs only. */+ closes: number[]+}++/** Everything the board knows about a repository's pull requests beyond the issues harvest. */+export interface GitHubPullBoard {+ pulls: GitHubPullStatus[]+ /** Epoch ms of the last read that succeeded. Absent = none yet in this app run. */+ observedAt?: number+ /** The latest read failed: `pulls` is the last snapshot that succeeded, kept on purpose. */+ stale: boolean+ /** False = the token may not read checks (ci) / mergeability (merge): hide that region. */+ access: { ci: boolean; merge: boolean }+ /** Some open PR is still undecided, so the board should keep chasing while it is visible. */+ undecided: boolean+ /** More open PRs exist than one read covers; the oldest-updated ones carry no status. */+ truncated: boolean+}++export const EMPTY_PULL_BOARD: GitHubPullBoard = {+ pulls: [],+ stale: false,+ access: { ci: true, merge: true },+ undecided: false,+ truncated: false+}++export function ciState(rollup: GitHubRollupState | null): PullCiState {+ if (rollup === null) return 'none'+ if (rollup === 'SUCCESS') return 'passed'+ if (rollup === 'FAILURE' || rollup === 'ERROR') return 'failed'+ return 'pending'+}++/** `mergeStateStatus` decides, except that a conflict reported by `mergeable` is a conflict whatever+ * the status says, and an unknown `mergeable` is undecided. `MERGEABLE` alone never yields `ready`. */+export function mergeState(+ mergeable: GitHubMergeable | null,+ mergeStateStatus: string | null+): PullMergeState | undefined {+ if (mergeable === null || mergeStateStatus === null) return undefined+ if (mergeable === 'CONFLICTING') return 'conflict'+ if (mergeable === 'UNKNOWN') return 'undecided'+ switch (mergeStateStatus) {+ case 'CLEAN': return 'ready'+ case 'DIRTY': return 'conflict'+ case 'BLOCKED': return 'blocked'+ case 'BEHIND': return 'behind'+ case 'UNSTABLE': return 'unstable'+ case 'HAS_HOOKS': return 'hooks'+ case 'UNKNOWN': return 'undecided'+ // A value GitHub adds later is not a reason to claim anything, and not a reason to chase.+ default: return undefined+ }+}++/** GitHub is still working something out for this PR, so re-reading soon will likely change it. */+export function isUndecided(status: Pick<GitHubPullStatus, 'lifecycle' | 'ci' | 'merge'>): boolean {+ if (status.lifecycle !== 'open' && status.lifecycle !== 'draft') return false+ return status.merge === 'undecided' || status.ci === 'pending'+}++/**+ * The board status for one open PR, from one read plus the previous status for the same PR.+ *+ * The rollup counts only when it belongs to the head commit. When this read's rollup is for another+ * commit (a read that raced a push), the previous CI is kept ONLY if it was taken at this same head;+ * a CI result from an older head is never carried onto a newer one.+ */+export function pullStatusFrom(+ facts: PullStatusFacts,+ access: { ci: boolean; merge: boolean },+ previous?: GitHubPullStatus+): GitHubPullStatus {+ const lifecycle: PullLifecycle = facts.isDraft ? 'draft' : 'open'+ let ci: PullCiState | undefined+ if (access.ci) {+ if (facts.rollup === null) ci = 'none'+ else if (facts.rollupOid === facts.headRefOid) ci = ciState(facts.rollup)+ else if (previous?.headRefOid === facts.headRefOid && previous.ci !== undefined) ci = previous.ci+ // The only rollup we have is for another commit. Reading again will settle it.+ else ci = 'pending'+ }+ const merge = access.merge ? mergeState(facts.mergeable, facts.mergeStateStatus) : undefined+ return {+ number: facts.number,+ lifecycle,+ headRefName: facts.headRefName,+ headRefOid: facts.headRefOid,+ ...(ci !== undefined ? { ci } : {}),+ ...(merge !== undefined ? { merge } : {}),+ closes: facts.closes+ }+}++/** A key per undecided PR AT ITS HEAD: a push to a stuck PR starts a new chase, while the same stuck+ * PR read again does not restart the count. */+export function undecidedKeys(pulls: GitHubPullStatus[]): string[] {+ return pulls.filter(isUndecided).map((pull) => `${pull.number}@${pull.headRefOid ?? ''}`).sort()+}++// ── Chase: re-read an undecided PR without webhooks ─────────────────────────────────────────────++/** Nothing can call us when GitHub finishes computing, so an undecided PR is re-read on this+ * schedule — 30 s, 1 min, 2 min, then every 5 min — and at most this many times per episode. The+ * first step is 30 s because a first read is what starts GitHub's mergeability computation: on this+ * repository 40 of 50 open PRs read UNKNOWN, and every one had settled 20 s later. */+export const PULL_CHASE_DELAYS_MS = [30_000, 60_000, 120_000, 300_000] as const+export const PULL_CHASE_MAX = 12++export function pullChaseDelay(attempt: number): number {+ return PULL_CHASE_DELAYS_MS[Math.min(attempt, PULL_CHASE_DELAYS_MS.length - 1)]+}++export interface PullChaseState {+ /** `undecidedKeys` of the episode being chased. */+ keys: string[]+ /** Chase reads spent in this episode. */+ attempts: number+ /** When the last read (of any kind) finished. */+ lastReadAt: number+}++/** The chase after a read that SUCCEEDED. A new undecided PR (or a new head) starts a new episode;+ * the same undecided set keeps counting; nothing undecided ends the chase. */+export function nextPullChase(+ previous: PullChaseState | null,+ pulls: GitHubPullStatus[],+ now: number+): PullChaseState | null {+ const keys = undecidedKeys(pulls)+ if (keys.length === 0) return null+ const known = new Set(previous?.keys ?? [])+ const fresh = !previous || keys.some((key) => !known.has(key))+ return { keys, attempts: fresh ? 0 : previous.attempts, lastReadAt: now }+}++/** Is a chase read due? Never past `PULL_CHASE_MAX`, never before the schedule allows. */+export function pullChaseDue(chase: PullChaseState | null, now: number): boolean {+ if (!chase || chase.attempts >= PULL_CHASE_MAX) return false+ return now - chase.lastReadAt >= pullChaseDelay(chase.attempts)+}++// ── Freshness ───────────────────────────────────────────────────────────────────────────────────++/** A stale snapshot is shown as-is (marked stale) until it is this old, then greyed. */+export const PULL_STATUS_GREY_AFTER_MS = 15 * 60_000++export type PullStatusFreshness = 'fresh' | 'stale' | 'expired'++export function pullStatusFreshness(+ board: Pick<GitHubPullBoard, 'stale' | 'observedAt'>,+ now: number+): PullStatusFreshness {+ if (!board.stale) return 'fresh'+ if (board.observedAt === undefined || now - board.observedAt >= PULL_STATUS_GREY_AFTER_MS) {+ return 'expired'+ }+ return 'stale'+}++// ── Per-check detail (fetched only when a PR's modal opens) ─────────────────────────────────────++export type PullCheckState = 'passed' | 'failed' | 'pending' | 'skipped' | 'neutral'++export interface GitHubPullCheck {+ name: string+ state: PullCheckState+ /** https only; absent when GitHub gave none or it was not an https URL. */+ url?: string+}++export type GitHubPullChecksResult =+ | { status: 'ok'; headRefOid: string; checks: GitHubPullCheck[]; truncated: boolean }+ /** GitHub reports no rollup for the head commit: there are no checks to show. */+ | { status: 'no-checks' }+ /** The token may not read checks. Nothing is shown. */+ | { status: 'hidden' }+ /** The read raced a push: the checks belong to another commit. */+ | { status: 'moved' }+ | { status: 'unavailable' }++const CHECK_ORDER: Record<PullCheckState, number> = {+ failed: 0, pending: 1, passed: 2, neutral: 3, skipped: 4+}++/** Failures first, then what is still running: the order someone opening a red PR reads in. */+export function sortChecks(checks: GitHubPullCheck[]): GitHubPullCheck[] {+ return [...checks].sort((a, b) =>+ CHECK_ORDER[a.state] - CHECK_ORDER[b.state] || a.name.localeCompare(b.name))+}++/** A check run's `status` + `conclusion`, or a commit status context's `state`, as one of ours. */+export function checkRunState(status: string, conclusion: string | null): PullCheckState {+ if (status !== 'COMPLETED') return 'pending'+ switch (conclusion) {+ case 'SUCCESS': return 'passed'+ case 'SKIPPED': return 'skipped'+ case 'NEUTRAL': return 'neutral'+ default: return 'failed'+ }+}++export function statusContextState(state: string): PullCheckState {+ if (state === 'SUCCESS') return 'passed'+ if (state === 'PENDING' || state === 'EXPECTED') return 'pending'+ return 'failed'+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 421fda870..e8936655e 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -412,6 +412,9 @@ export const IPC = {githubIssuesMove: 'githubIssues:move',githubIssuesCreateLabels: 'githubIssues:create-labels',githubIssuesClearCache: 'githubIssues:clear-cache',+ githubIssuesPullStatus: 'githubIssues:pull-status',+ githubIssuesChasePulls: 'githubIssues:chase-pulls',+ githubIssuesPullChecks: 'githubIssues:pull-checks',githubIssuesChanged: (projectId: string) => `githubIssues:changed:${projectId}`,githubProjectAvatar: 'github:projectAvatar',githubControlStatus: 'githubControl:status',