diff --git a/README.md b/README.md index 70010dbb..29057ef6 100644 --- a/README.md +++ b/README.md @@ -30,12 +30,16 @@ It will sync the open issues and pull requests to the local filesystem under `.g pulls/ 00042-add-cache.md 00042-add-cache.patch + 00042-add-cache/ + checks.json closed/ 00043-release-cleanup.md ``` Then you can view them offline, or ask your local agent to summarize them for you. +The **Checks** tab (`h`) shows synced check runs and commit statuses. Open PR checks refresh on each sync. + ## Web UI `ghfs` ships a local web UI for browsing and acting on the synced mirror. diff --git a/playwright.config.ts b/playwright.config.ts index 7927a6f7..e9a038ce 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -29,6 +29,19 @@ export default defineConfig({ }, ], webServer: [ + { + command: `node ./dist/cli.mjs ui --port 7914 --no-open --no-portless --cwd ${JSON.stringify(resolve(fixtures, 'checks'))}`, + port: 7914, + timeout: 60_000, + reuseExistingServer: false, + stdout: 'pipe', + stderr: 'pipe', + env: { + ...process.env as Record, + GH_TOKEN: 'fake-for-tests', + AI_GATEWAY_API_KEY: '', + }, + }, { command: `node ./dist/cli.mjs ui --port 7910 --no-open --no-portless --cwd ${JSON.stringify(resolve(fixtures, 'single'))}`, port: 7910, diff --git a/src/execute/index.test.ts b/src/execute/index.test.ts index a91b0097..b9893caf 100644 --- a/src/execute/index.test.ts +++ b/src/execute/index.test.ts @@ -577,6 +577,7 @@ function createMockProvider(overrides: Partial = {}): Reposi requestedReviewers: [], })), fetchPullPatch: vi.fn(async () => ''), + fetchPullChecks: vi.fn(async () => ({ headSha: 'head-sha', fetchedAt: '2026-01-01T00:00:00.000Z', checkRuns: [], statuses: [] })), fetchPullCommits: vi.fn(async () => []), fetchReviewComments: vi.fn(async () => []), fetchTimeline: vi.fn(async () => []), diff --git a/src/providers/github/checks.test.ts b/src/providers/github/checks.test.ts new file mode 100644 index 00000000..3f403b4c --- /dev/null +++ b/src/providers/github/checks.test.ts @@ -0,0 +1,76 @@ +import { Octokit } from 'octokit' +import { describe, expect, it, vi } from 'vitest' +import { fetchPullChecks } from './checks' + +describe('fetchPullChecks', () => { + it('pins both paginated APIs to the PR head and keeps the latest status per context', async () => { + const fetch = vi.fn(async (input: string | URL | Request) => { + const url = new URL(String(input)) + if (url.pathname.endsWith('/pulls/42')) + return jsonResponse(String(input), { head: { sha: 'head-sha' } }) + const secondPage = url.searchParams.get('page') === '2' + const headers: Record = secondPage ? {} : { link: `<${url.href}&page=2>; rel="next"` } + if (url.pathname.endsWith('/check-runs')) { + return jsonResponse(String(input), { + total_count: 2, + check_runs: [{ + id: secondPage ? 2 : 1, + name: secondPage ? 'lint' : 'test', + status: secondPage ? 'in_progress' : 'completed', + conclusion: secondPage ? null : 'neutral', + details_url: 'https://ci.example/run', + started_at: null, + completed_at: null, + }], + }, { headers }) + } + return jsonResponse(String(input), secondPage + ? [ + { id: 1, context: 'build', state: 'failure', description: null, target_url: null, created_at: 'old', updated_at: 'old' }, + { id: 2, context: 'deploy', state: 'pending', description: null, target_url: null, created_at: 'now', updated_at: 'now' }, + ] + : [{ id: 3, context: 'build', state: 'success', description: 'passed', target_url: 'https://ci.example/build', created_at: 'now', updated_at: 'now' }], { headers }) + }) + const octokit = new Octokit({ request: { fetch } }) + const bump = vi.fn() + const checks = await fetchPullChecks(octokit, 'owner', 'repo', 42, bump) + expect(checks.headSha).toBe('head-sha') + expect(Number.isNaN(Date.parse(checks.fetchedAt))).toBe(false) + expect(checks.checkRuns).toEqual([ + { id: 1, name: 'test', status: 'completed', conclusion: 'neutral', detailsUrl: 'https://ci.example/run', startedAt: null, completedAt: null }, + { id: 2, name: 'lint', status: 'in_progress', conclusion: null, detailsUrl: 'https://ci.example/run', startedAt: null, completedAt: null }, + ]) + expect(checks.statuses.map(status => [status.context, status.state])).toEqual([['build', 'success'], ['deploy', 'pending']]) + expect(checks.statuses[0].targetUrl).toBe('https://ci.example/build') + expect(bump).toHaveBeenCalledTimes(5) + for (const [input] of fetch.mock.calls.slice(1)) + expect(String(input)).toContain('/commits/head-sha/') + expect(String(fetch.mock.calls[1][0])).toContain('filter=latest') + }) + + it('represents a commit without checks as empty arrays', async () => { + const fetch = vi.fn(async (input: string | URL | Request) => { + const path = new URL(String(input)).pathname + return jsonResponse(String(input), path.endsWith('/pulls/42') + ? { head: { sha: 'another-sha' } } + : path.endsWith('/check-runs') ? { total_count: 0, check_runs: [] } : []) + }) + const checks = await fetchPullChecks(new Octokit({ request: { fetch } }), 'owner', 'repo', 42, vi.fn()) + expect(checks).toMatchObject({ headSha: 'another-sha', checkRuns: [], statuses: [] }) + }) + + it('propagates permission errors instead of reporting empty or successful checks', async () => { + const fetch = vi.fn(async (input: string | URL | Request) => { + if (String(input).endsWith('/pulls/42')) + return jsonResponse(String(input), { head: { sha: 'head-sha' } }) + return jsonResponse(String(input), { message: 'Resource not accessible by integration' }, { status: 403 }) + }) + await expect(fetchPullChecks(new Octokit({ request: { fetch } }), 'owner', 'repo', 42, vi.fn())).rejects.toMatchObject({ status: 403 }) + }) +}) + +function jsonResponse(url: string, body: unknown, init?: ResponseInit): Response { + const response = Response.json(body, init) + Object.defineProperty(response, 'url', { value: url }) + return response +} diff --git a/src/providers/github/checks.ts b/src/providers/github/checks.ts new file mode 100644 index 00000000..f841fb09 --- /dev/null +++ b/src/providers/github/checks.ts @@ -0,0 +1,64 @@ +import type { Octokit } from 'octokit' +import type { ProviderPullChecks } from '../../types/provider' + +export async function fetchPullChecks( + octokit: Octokit, + owner: string, + repo: string, + number: number, + bumpRequestCount: () => void, +): Promise { + bumpRequestCount() + const { data: pull } = await octokit.rest.pulls.get({ owner, repo, pull_number: number }) + const headSha = pull.head.sha + const fetchedAt = new Date().toISOString() + const checkRuns: ProviderPullChecks['checkRuns'] = [] + const statuses: ProviderPullChecks['statuses'] = [] + + for await (const page of octokit.paginate.iterator(octokit.rest.checks.listForRef, { + owner, + repo, + ref: headSha, + filter: 'latest', + per_page: 100, + })) { + bumpRequestCount() + for (const run of page.data) { + checkRuns.push({ + id: run.id, + name: run.name, + status: run.status, + conclusion: run.conclusion, + detailsUrl: run.details_url, + startedAt: run.started_at, + completedAt: run.completed_at, + }) + } + } + + const contexts = new Set() + for await (const page of octokit.paginate.iterator(octokit.rest.repos.listCommitStatusesForRef, { + owner, + repo, + ref: headSha, + per_page: 100, + })) { + bumpRequestCount() + for (const status of page.data) { + if (contexts.has(status.context)) + continue + contexts.add(status.context) + statuses.push({ + id: status.id, + context: status.context, + state: status.state, + description: status.description, + targetUrl: status.target_url, + createdAt: status.created_at, + updatedAt: status.updated_at, + }) + } + } + + return { headSha, fetchedAt, checkRuns, statuses } +} diff --git a/src/providers/github/provider.ts b/src/providers/github/provider.ts index ef9d51ed..bde11895 100644 --- a/src/providers/github/provider.ts +++ b/src/providers/github/provider.ts @@ -28,6 +28,7 @@ import { randomHexColor } from '../../utils/color' import { formatIssueNumber } from '../../utils/format' import { createEmptyReactions, isReactionContent, normalizeReactions, reactionKeyFromContent } from '../../utils/reactions' import { collectPages, iteratePages } from '../helpers' +import { fetchPullChecks } from './checks' import { createGitHubClient } from './client' type BumpRequestCount = () => void @@ -61,6 +62,7 @@ export function createGitHubProvider(options: CreateGitHubProviderOptions): Repo fetchComments: number => fetchComments(octokit, owner, repo, number, bumpRequestCount), fetchPullMetadata: number => fetchPullMetadata(octokit, owner, repo, number, bumpRequestCount), fetchPullPatch: number => fetchPullPatch(octokit, owner, repo, number, bumpRequestCount), + fetchPullChecks: number => fetchPullChecks(octokit, owner, repo, number, bumpRequestCount), fetchPullCommits: number => fetchPullCommits(octokit, owner, repo, number, bumpRequestCount), fetchReviewComments: number => fetchReviewComments(octokit, owner, repo, number, bumpRequestCount), fetchTimeline: number => fetchTimeline(octokit, owner, repo, number, bumpRequestCount), diff --git a/src/server/ui-state.ts b/src/server/ui-state.ts index 78ad635e..84f9fec4 100644 --- a/src/server/ui-state.ts +++ b/src/server/ui-state.ts @@ -3,7 +3,7 @@ import { join } from 'pathe' export const UI_STATE_FILE = '.ui.json' -export type PrTabId = 'conversation' | 'commits' | 'changes' +export type PrTabId = 'conversation' | 'commits' | 'changes' | 'checks' export interface UserOverride { login?: string @@ -74,7 +74,7 @@ function normalizeNumberArray(value: unknown): number[] | undefined { } function normalizePrTab(value: unknown): PrTabId | undefined { - if (value === 'conversation' || value === 'commits' || value === 'changes') + if (value === 'conversation' || value === 'commits' || value === 'changes' || value === 'checks') return value return undefined } diff --git a/src/sync/checks.ts b/src/sync/checks.ts new file mode 100644 index 00000000..2ab730e8 --- /dev/null +++ b/src/sync/checks.ts @@ -0,0 +1,58 @@ +import type { SyncContext } from './sync-repository-types' +import { readdir, rmdir } from 'node:fs/promises' +import { join } from 'pathe' +import { CLOSED_DIR_NAME, PULL_DIR_NAME } from '../constants' +import { removePath, writeFileEnsured } from '../utils/fs' +import { getItemFileName } from './paths' + +export async function refreshPullChecks(context: SyncContext, selectedNumbers: Set, targeted: boolean): Promise { + if (!context.config.sync.pulls) + return + for (const tracked of Object.values(context.syncState.items)) { + if (tracked.kind !== 'pull') + continue + if (targeted ? !selectedNumbers.has(tracked.number) : tracked.state !== 'open' && !selectedNumbers.has(tracked.number)) + continue + tracked.data.checks = await context.provider.fetchPullChecks(tracked.number) + tracked.lastSyncedAt = context.syncedAt + } +} + +export async function materializePullChecks(context: SyncContext): Promise { + if (!context.config.sync.pulls) + return + for (const tracked of Object.values(context.syncState.items)) { + if (tracked.kind !== 'pull' || !tracked.data.checks) + continue + const directory = join( + context.storageDirAbsolute, + PULL_DIR_NAME, + tracked.state === 'closed' ? CLOSED_DIR_NAME : '', + getItemFileName(tracked.number, tracked.data.item.title).replace(/\.md$/, ''), + ) + await writeFileEnsured(join(directory, 'checks.json'), `${JSON.stringify(tracked.data.checks, null, 2)}\n`) + await removePullChecks(context.storageDirAbsolute, tracked.number, directory) + } +} + +export async function removePullChecks(storageDir: string, number: number, keepDirectory?: string): Promise { + const prefix = `${String(number).padStart(5, '0')}-` + for (const stateDirectory of ['', CLOSED_DIR_NAME]) { + const parent = join(storageDir, PULL_DIR_NAME, stateDirectory) + const entries = await readdir(parent, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') + return [] + throw error + }) + for (const entry of entries) { + const directory = join(parent, entry.name) + if (!entry.isDirectory() || !entry.name.startsWith(prefix) || directory === keepDirectory) + continue + await removePath(join(directory, 'checks.json')) + await rmdir(directory).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOTEMPTY' && error.code !== 'ENOENT') + throw error + }) + } + } +} diff --git a/src/sync/index.test.ts b/src/sync/index.test.ts index 14ab4644..4c844f32 100644 --- a/src/sync/index.test.ts +++ b/src/sync/index.test.ts @@ -10,6 +10,106 @@ import { syncRepository } from './index' import { getSyncStatePath, loadSyncState } from './state' describe('syncRepository', () => { + it('refreshes CI-only changes during incremental sync without refetching comments or patches', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'ghfs-checks-test-')) + try { + const item = createIssue({ number: 42, kind: 'pull', state: 'open', title: 'Add cache', updatedAt: '2026-01-01T00:00:00.000Z' }) + const fetchPullChecks = vi.fn() + .mockResolvedValueOnce({ headSha: 'first', fetchedAt: '2026-01-01T00:00:00Z', checkRuns: [{ status: 'in_progress', conclusion: null }], statuses: [] }) + .mockResolvedValueOnce({ headSha: 'second', fetchedAt: '2026-01-01T00:01:00Z', checkRuns: [{ status: 'completed', conclusion: 'success' }], statuses: [] }) + const provider = createMockProvider({ + paginateItems: vi.fn().mockImplementationOnce(async function* () { + yield [item] + }).mockImplementation(async function* () { yield [] }), + fetchPullChecks, + }) + const options = { config: createConfig(cwd), repo: 'owner/repo', token: 'test-token', provider } + await syncRepository(options) + vi.mocked(provider.fetchComments).mockClear() + vi.mocked(provider.fetchPullPatch).mockClear() + await syncRepository(options) + const path = join(cwd, '.ghfs/pulls/00042-add-cache/checks.json') + expect(JSON.parse(await readFile(path, 'utf8'))).toMatchObject({ headSha: 'second', checkRuns: [{ conclusion: 'success' }] }) + expect((await loadSyncState(join(cwd, '.ghfs'))).items['42'].data.checks?.headSha).toBe('second') + expect(fetchPullChecks).toHaveBeenCalledTimes(2) + expect(provider.fetchComments).not.toHaveBeenCalled() + expect(provider.fetchPullPatch).not.toHaveBeenCalled() + } + finally { + await rm(cwd, { recursive: true, force: true }) + } + }) + + it('limits check refresh to targeted numbers and respects disabled pull sync', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'ghfs-checks-test-')) + try { + const items = [1, 2].map(number => createIssue({ number, kind: 'pull', state: 'open', title: `PR ${number}`, updatedAt: '2026-01-01T00:00:00.000Z' })) + const provider = createMockProvider({ + async* paginateItems() { yield items }, + fetchItemsByNumbers: vi.fn(async numbers => items.filter(item => numbers.includes(item.number))), + }) + const options = { config: createConfig(cwd), repo: 'owner/repo', token: 'test-token', provider } + await syncRepository(options) + vi.mocked(provider.fetchPullChecks).mockClear() + await syncRepository({ ...options, numbers: [1] }) + expect(provider.fetchPullChecks).toHaveBeenCalledExactlyOnceWith(1) + vi.mocked(provider.fetchPullChecks).mockClear() + await syncRepository({ ...options, config: createConfig(cwd, { pulls: false }) }) + expect(provider.fetchPullChecks).not.toHaveBeenCalled() + } + finally { + await rm(cwd, { recursive: true, force: true }) + } + }) + + it('moves checks after title/state changes and removes checks when closed pulls are pruned', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'ghfs-checks-test-')) + try { + let item = createIssue({ number: 42, kind: 'pull', state: 'open', title: 'Old title', updatedAt: '2026-01-01T00:00:00.000Z' }) + const provider = createMockProvider({ async* paginateItems() { + yield [item] + } }) + const options = { config: createConfig(cwd, { closed: true }), repo: 'owner/repo', token: 'test-token', provider } + await syncRepository(options) + item = { ...item, title: 'New title', updatedAt: '2026-01-02T00:00:00.000Z' } + await syncRepository(options) + await expect(stat(join(cwd, '.ghfs/pulls/00042-old-title/checks.json'))).rejects.toMatchObject({ code: 'ENOENT' }) + await expect(stat(join(cwd, '.ghfs/pulls/00042-new-title/checks.json'))).resolves.toBeDefined() + item = { ...item, state: 'closed', updatedAt: '2026-01-03T00:00:00.000Z' } + await syncRepository(options) + await expect(stat(join(cwd, '.ghfs/pulls/00042-new-title/checks.json'))).rejects.toMatchObject({ code: 'ENOENT' }) + await expect(stat(join(cwd, '.ghfs/pulls/closed/00042-new-title/checks.json'))).resolves.toBeDefined() + await syncRepository({ ...options, config: createConfig(cwd, { closed: false }) }) + await expect(stat(join(cwd, '.ghfs/pulls/closed/00042-new-title/checks.json'))).rejects.toMatchObject({ code: 'ENOENT' }) + expect((await loadSyncState(join(cwd, '.ghfs'))).items['42']).toBeUndefined() + } + finally { + await rm(cwd, { recursive: true, force: true }) + } + }) + + it('leaves the saved snapshot intact when fetching checks fails', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'ghfs-checks-test-')) + try { + const item = createIssue({ number: 42, kind: 'pull', state: 'open', title: 'PR', updatedAt: '2026-01-01T00:00:00.000Z' }) + const provider = createMockProvider({ async* paginateItems() { + yield [item] + } }) + const options = { config: createConfig(cwd), repo: 'owner/repo', token: 'test-token', provider } + await syncRepository(options) + const path = join(cwd, '.ghfs/pulls/00042-pr/checks.json') + const before = await readFile(path, 'utf8') + const beforeState = await readFile(getSyncStatePath(join(cwd, '.ghfs')), 'utf8') + vi.mocked(provider.fetchPullChecks).mockRejectedValueOnce(new Error('permission denied')) + await expect(syncRepository(options)).rejects.toThrow('permission denied') + expect(await readFile(path, 'utf8')).toBe(before) + expect(await readFile(getSyncStatePath(join(cwd, '.ghfs')), 'utf8')).toBe(beforeState) + } + finally { + await rm(cwd, { recursive: true, force: true }) + } + }) + afterEach(() => { vi.clearAllMocks() }) @@ -472,6 +572,7 @@ function createMockProvider(overrides: Partial = {}): Reposi requestedReviewers: [], })), fetchPullPatch: vi.fn(async () => ''), + fetchPullChecks: vi.fn(async () => ({ headSha: 'head-sha', fetchedAt: '2026-01-01T00:00:00.000Z', checkRuns: [], statuses: [] })), fetchPullCommits: vi.fn(async () => []), fetchReviewComments: vi.fn(async () => []), fetchTimeline: vi.fn(async () => []), diff --git a/src/sync/sync-repository-item.ts b/src/sync/sync-repository-item.ts index 5a21fe11..936bfaf5 100644 --- a/src/sync/sync-repository-item.ts +++ b/src/sync/sync-repository-item.ts @@ -7,6 +7,7 @@ import { diagnostics } from '../logger' import { formatIssueNumber } from '../utils/format' import { movePath, pathExists, removePatchIfExists, removePath, writeFileEnsured } from '../utils/fs' import { normalizeReactions } from '../utils/reactions' +import { removePullChecks } from './checks' import { renderIssueMarkdown } from './markdown' import { getExistingMarkdownPaths, @@ -90,8 +91,10 @@ export async function materializePreparedIssue(context: SyncContext, candidate: await removePath(markdownPath) let patchesDeleted = 0 - if (kind === 'pull') + if (kind === 'pull') { patchesDeleted += await removePatchIfExists(context.storageDirAbsolute, number) + await removePullChecks(context.storageDirAbsolute, number) + } return { kind, diff --git a/src/sync/sync-repository-provider.test.ts b/src/sync/sync-repository-provider.test.ts index fb9a293b..55e7f3b4 100644 --- a/src/sync/sync-repository-provider.test.ts +++ b/src/sync/sync-repository-provider.test.ts @@ -118,6 +118,7 @@ function createContext(overrides: { requestedReviewers: [], })), fetchPullPatch: vi.fn(async () => ''), + fetchPullChecks: vi.fn(async () => ({ headSha: 'head-sha', fetchedAt: '2026-01-01T00:00:00.000Z', checkRuns: [], statuses: [] })), fetchPullCommits: vi.fn(async () => []), fetchTimeline: vi.fn(async () => []), fetchItemSnapshot: vi.fn(async number => ({ diff --git a/src/sync/sync-repository-snapshot.test.ts b/src/sync/sync-repository-snapshot.test.ts index e6572225..58ac2f4b 100644 --- a/src/sync/sync-repository-snapshot.test.ts +++ b/src/sync/sync-repository-snapshot.test.ts @@ -243,6 +243,7 @@ function createProviderMock(overrides: Partial = {}): Reposi requestedReviewers: [], })), fetchPullPatch: vi.fn(async () => ''), + fetchPullChecks: vi.fn(async () => ({ headSha: 'head-sha', fetchedAt: '2026-01-01T00:00:00.000Z', checkRuns: [], statuses: [] })), fetchPullCommits: vi.fn(async () => []), fetchReviewComments: vi.fn(async () => []), fetchTimeline: vi.fn(async () => []), diff --git a/src/sync/sync-repository-storage.ts b/src/sync/sync-repository-storage.ts index f5ff6a0c..4aaaac7b 100644 --- a/src/sync/sync-repository-storage.ts +++ b/src/sync/sync-repository-storage.ts @@ -4,6 +4,7 @@ import { readdir, rm } from 'node:fs/promises' import { isAbsolute, join } from 'pathe' import { CLOSED_DIR_NAME, ISSUE_DIR_NAME, PULL_DIR_NAME } from '../constants' import { movePath, pathExists, removePatchIfExists, removePath } from '../utils/fs' +import { removePullChecks } from './checks' import { getItemMarkdownPath, getPrPatchPath, @@ -57,8 +58,10 @@ export async function handleClosedIssueByPolicy(input: ClosedIssuePolicyInput): await removePath(markdownPath) let patchesDeleted = 0 - if (kind === 'pull') + if (kind === 'pull') { patchesDeleted += await removePatchIfExists(context.storageDirAbsolute, number) + await removePullChecks(context.storageDirAbsolute, number) + } delete context.syncState.items[String(number)] return { @@ -249,8 +252,10 @@ export async function pruneTrackedClosedItems(storageDirAbsolute: string, syncSt if (!shouldSyncKind(sync, item.kind)) continue await removePath(resolveTrackedPathOrJoin(storageDirAbsolute, item.filePath)) - if (item.kind === 'pull') + if (item.kind === 'pull') { patchesDeleted += await removePatchIfExists(storageDirAbsolute, item.number) + await removePullChecks(storageDirAbsolute, item.number) + } delete syncState.items[String(item.number)] } @@ -269,8 +274,10 @@ export async function pruneMissingOpenTrackedItems(storageDirAbsolute: string, s continue await removePath(resolveTrackedPathOrJoin(storageDirAbsolute, item.filePath)) - if (item.kind === 'pull') + if (item.kind === 'pull') { patchesDeleted += await removePatchIfExists(storageDirAbsolute, item.number) + await removePullChecks(storageDirAbsolute, item.number) + } delete syncState.items[String(item.number)] } diff --git a/src/sync/sync-repository.ts b/src/sync/sync-repository.ts index 196cb32f..20b24951 100644 --- a/src/sync/sync-repository.ts +++ b/src/sync/sync-repository.ts @@ -7,6 +7,7 @@ import { GHFS_VERSION } from '../meta' import { createRepositoryProvider } from '../providers/factory' import { formatIssueNumber } from '../utils/format' import { normalizeIssueNumbers, resolveSince } from '../utils/sync' +import { materializePullChecks, refreshPullChecks } from './checks' import { loadSyncState, saveSyncState } from './state' import { materializePreparedIssue, @@ -156,6 +157,7 @@ export async function syncRepository(options: SyncOptions): Promise message: `${formatIssueNumber(issue.number, { repo: options.repo, kind: issue.kind })} ${prepared.kind} ${prepared.action}`, }) } + await refreshPullChecks(syncContext, new Set(candidates.issues.map(issue => issue.number)), Boolean(targetNumbers)) }) syncContext.syncState.repo = options.repo @@ -169,6 +171,7 @@ export async function syncRepository(options: SyncOptions): Promise await runStage('materialize', 'Materialize local files', async () => { for (const prepared of preparedCandidates) addItemStats(counters, await materializePreparedIssue(syncContext, prepared)) + await materializePullChecks(syncContext) }) await runStage('prune', 'Prune stale local artifacts', async () => { diff --git a/src/types/provider.ts b/src/types/provider.ts index 617bdbdc..a16984c9 100644 --- a/src/types/provider.ts +++ b/src/types/provider.ts @@ -46,6 +46,29 @@ export interface ProviderComment { export type ProviderReviewDecision = 'approved' | 'changes_requested' | 'review_required' +export interface ProviderPullChecks { + headSha: string + fetchedAt: string + checkRuns: Array<{ + id: number + name: string + status: string + conclusion: string | null + detailsUrl: string | null + startedAt: string | null + completedAt: string | null + }> + statuses: Array<{ + id: number + context: string + state: string + description: string | null + targetUrl: string | null + createdAt: string + updatedAt: string + }> +} + export interface ProviderPullMetadata { isDraft: boolean merged: boolean @@ -274,6 +297,7 @@ export interface RepositoryProvider { fetchComments: (number: number) => Promise fetchPullMetadata: (number: number) => Promise fetchPullPatch: (number: number) => Promise + fetchPullChecks: (number: number) => Promise fetchPullCommits: (number: number) => Promise fetchReviewComments: (number: number) => Promise fetchTimeline: (number: number) => Promise diff --git a/src/types/sync-state.ts b/src/types/sync-state.ts index 626c4ebf..bb8a448d 100644 --- a/src/types/sync-state.ts +++ b/src/types/sync-state.ts @@ -1,6 +1,6 @@ import type { ExecutionResult } from './execution' import type { IssueKind, IssueState } from './issue' -import type { ProviderComment, ProviderCommit, ProviderItem, ProviderPullMetadata, ProviderReviewComment, ProviderTimelineEvent } from './provider' +import type { ProviderComment, ProviderCommit, ProviderItem, ProviderPullChecks, ProviderPullMetadata, ProviderReviewComment, ProviderTimelineEvent } from './provider' export type SyncRunStage = 'metadata' | 'pagination' | 'fetch' | 'materialize' | 'prune' | 'save' @@ -35,6 +35,7 @@ export interface SyncItemCanonicalData { commits?: ProviderCommit[] timeline?: ProviderTimelineEvent[] reviewComments?: ProviderReviewComment[] + checks?: ProviderPullChecks } export interface SyncItemState { diff --git a/tests/e2e/_support/build-fixture.ts b/tests/e2e/_support/build-fixture.ts index 28bb50c6..69d4b6a0 100644 --- a/tests/e2e/_support/build-fixture.ts +++ b/tests/e2e/_support/build-fixture.ts @@ -1,4 +1,5 @@ import type { SyncItemState, SyncState } from '../../../src/types' +import type { ProviderPullChecks } from '../../../src/types/provider' import { mkdir, writeFile } from 'node:fs/promises' import { join } from 'pathe' import { GHFS_VERSION } from '../../../src/meta' @@ -13,6 +14,7 @@ export interface FixtureItemInput { author?: string labels?: string[] assignees?: string[] + checks?: ProviderPullChecks comments?: Array<{ id: number, author: string, body: string }> } @@ -103,6 +105,7 @@ function buildItemState( lastSyncedAt: syncedAt, filePath: relativePath, data: { + checks: input.checks, item: { number: input.number, kind, diff --git a/tests/e2e/_support/checks-fixture.ts b/tests/e2e/_support/checks-fixture.ts new file mode 100644 index 00000000..b2b69172 --- /dev/null +++ b/tests/e2e/_support/checks-fixture.ts @@ -0,0 +1,59 @@ +import { mkdir, rm } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import { dirname, join } from 'pathe' +import { buildRepoFixture } from './build-fixture' + +const here = dirname(fileURLToPath(import.meta.url)) +const FIXTURES_ROOT = join(here, '..', 'fixtures') + +export async function setupChecksFixture(): Promise { + const dir = join(FIXTURES_ROOT, 'checks') + await rm(dir, { recursive: true, force: true }) + await mkdir(dir, { recursive: true }) + await buildRepoFixture({ + cwd: dir, + repo: 'ghfs-test/checks', + items: [ + { + number: 1, + kind: 'issue', + title: 'First single-repo issue', + body: 'Body of the first issue.', + labels: ['bug'], + }, + { + number: 10, + kind: 'pull', + title: 'First pull request', + body: 'PR description body.', + labels: ['enhancement'], + checks: { + headSha: 'abc1234567890', + fetchedAt: '2026-01-01T12:00:00.000Z', + checkRuns: [ + { id: 1, name: 'Unit tests', status: 'completed', conclusion: 'success', detailsUrl: 'https://example.com/ci/tests', startedAt: null, completedAt: null }, + { id: 2, name: 'Lint', status: 'completed', conclusion: 'failure', detailsUrl: 'https://example.com/ci/lint', startedAt: null, completedAt: null }, + { id: 3, name: 'Build', status: 'in_progress', conclusion: null, detailsUrl: null, startedAt: null, completedAt: null }, + { id: 4, name: 'Optional checks', status: 'completed', conclusion: 'neutral', detailsUrl: null, startedAt: null, completedAt: null }, + ], + statuses: [ + { id: 1, context: 'deploy/preview', state: 'pending', description: 'Waiting for deployment', targetUrl: 'https://example.com/preview', createdAt: '2026-01-01T12:00:00.000Z', updatedAt: '2026-01-01T12:00:00.000Z' }, + ], + }, + }, + { + number: 11, + kind: 'pull', + title: 'Second pull request', + checks: { headSha: 'def1234567890', fetchedAt: '2026-01-01T12:00:00.000Z', checkRuns: [], statuses: [] }, + }, + { + number: 12, + kind: 'pull', + title: 'Pull request awaiting first check sync', + }, + ], + executeMd: '# example queue file\n', + executeYml: '[]\n', + }) +} diff --git a/tests/e2e/_support/global-setup.ts b/tests/e2e/_support/global-setup.ts index 0c52c348..33c36f91 100644 --- a/tests/e2e/_support/global-setup.ts +++ b/tests/e2e/_support/global-setup.ts @@ -2,6 +2,7 @@ import { mkdir, rm } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { dirname, join } from 'pathe' import { buildRepoFixture } from './build-fixture' +import { setupChecksFixture } from './checks-fixture' const here = dirname(fileURLToPath(import.meta.url)) const FIXTURES_ROOT = join(here, '..', 'fixtures') @@ -124,5 +125,6 @@ async function setupHubFixtures(): Promise { export default async function globalSetup(): Promise { await mkdir(FIXTURES_ROOT, { recursive: true }) await setupSingleFixture() + await setupChecksFixture() await setupHubFixtures() } diff --git a/tests/e2e/checks.spec.ts b/tests/e2e/checks.spec.ts new file mode 100644 index 00000000..52d069fb --- /dev/null +++ b/tests/e2e/checks.spec.ts @@ -0,0 +1,64 @@ +import type { Page } from '@playwright/test' +import { expect, test } from '@playwright/test' + +test('PR checks show saved results and links, support keyboard navigation and survive reload', async ({ page }) => { + const errors: string[] = [] + page.on('pageerror', error => errors.push(error.message)) + await page.goto('http://127.0.0.1:7914/') + await selectPull(page, 10) + await page.getByTestId('pr-checks-tab').click() + const checks = page.getByTestId('pr-checks') + await expect(checks.getByTestId('pr-check-row')).toHaveCount(5) + await expect(checks).toContainText('success') + await expect(checks).toContainText('failure') + await expect(checks).toContainText('in progress') + await expect(checks).toContainText('neutral') + await expect(checks).toContainText('pending') + await expect(checks).toContainText('Waiting for deployment') + await expect(checks.getByTestId('pr-checks-sha')).toHaveText('abc1234') + await expect(checks.getByRole('link', { name: 'Unit tests: open details' })).toHaveAttribute('href', 'https://example.com/ci/tests') + await expect(checks.getByRole('link', { name: 'deploy/preview: open details' })).toHaveAttribute('href', 'https://example.com/preview') + await checks.getByRole('link', { name: 'Unit tests: open details' }).focus() + await expect(checks.getByRole('link', { name: 'Unit tests: open details' })).toBeFocused() + await page.context().route('https://example.com/ci/tests', route => route.fulfill({ body: 'CI details' })) + const popupPromise = page.waitForEvent('popup') + await checks.getByRole('link', { name: 'Unit tests: open details' }).press('Enter') + const popup = await popupPromise + await expect(popup).toHaveURL('https://example.com/ci/tests') + await popup.close() + await page.getByRole('tab', { name: /Conversation/ }).click() + await page.keyboard.press('h') + await expect(page.getByTestId('pr-checks-tab')).toHaveAttribute('data-state', 'active') + await expect.poll(async () => { + const { readFile } = await import('node:fs/promises') + const saved = await readFile('tests/e2e/fixtures/checks/.ghfs/.ui.json', 'utf8').catch(() => '{}') + return JSON.parse(saved).lastPrTab + }).toBe('checks') + await page.reload() + await selectPull(page, 10) + await expect(checks.getByTestId('pr-check-row')).toHaveCount(5) + await page.setViewportSize({ width: 390, height: 844 }) + await expect(checks.getByRole('link', { name: 'Unit tests: open details' })).toBeVisible() + await expect.poll(() => page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true) + expect(errors).toEqual([]) +}) + +test('PR checks distinguish an empty snapshot from checks that have not synced', async ({ page }) => { + await page.goto('http://127.0.0.1:7914/') + await selectPull(page, 11) + await page.getByTestId('pr-checks-tab').click() + await expect(page.getByTestId('pr-checks-empty')).toBeVisible() + await expect(page.getByTestId('pr-checks-unsynced')).toHaveCount(0) + await selectPull(page, 12) + await page.getByTestId('pr-checks-tab').click() + await expect(page.getByTestId('pr-checks-unsynced')).toBeVisible() + await expect(page.getByTestId('pr-checks-empty')).toHaveCount(0) + await page.getByRole('button', { name: /^Issues/ }).click() + await page.locator('[data-testid="item-row"][data-item-number="1"]').click() + await expect(page.getByTestId('pr-checks-tab')).toHaveCount(0) +}) + +async function selectPull(page: Page, number: number) { + await page.getByRole('button', { name: /^Pulls/ }).click() + await page.locator(`[data-testid="item-row"][data-item-number="${number}"]`).click() +} diff --git a/ui/components/panel/Detail.vue b/ui/components/panel/Detail.vue index 67602aec..b7d6308f 100644 --- a/ui/components/panel/Detail.vue +++ b/ui/components/panel/Detail.vue @@ -28,6 +28,7 @@ import PanelDetailComposer from './DetailComposer.vue' import PanelDetailConversationTab from './DetailConversationTab.vue' import PanelDetailLabelEditor from './DetailLabelEditor.vue' import PanelDetailPrChangesTab from './DetailPrChangesTab.vue' +import PanelDetailPrChecksTab from './DetailPrChecksTab.vue' import PanelDetailPrCommitsTab from './DetailPrCommitsTab.vue' const props = withDefaults(defineProps<{ @@ -79,7 +80,7 @@ const hasAi = computed(() => state.payload.value?.repo.hasAi ?? false) const { suggesting: suggestingLabels } = useLabelSuggestions() const assignees = computed(() => item.value?.assignees ?? []) -type PrTab = 'conversation' | 'commits' | 'changes' +type PrTab = 'conversation' | 'commits' | 'changes' | 'checks' const prTab = computed({ get() { return ui.uiState.lastPrTab ?? 'conversation' @@ -398,7 +399,7 @@ async function discardThisItem() { v-model="prTab" class="flex-1 flex flex-col min-h-0" > - + + + + Checks + {{ selected.data.checks.checkRuns.length + selected.data.checks.statuses.length }} + +
@@ -445,6 +452,9 @@ async function discardThisItem() { + + +
diff --git a/ui/components/panel/DetailPrChecksTab.vue b/ui/components/panel/DetailPrChecksTab.vue new file mode 100644 index 00000000..8daab21f --- /dev/null +++ b/ui/components/panel/DetailPrChecksTab.vue @@ -0,0 +1,107 @@ + + + diff --git a/ui/composables/useAppCommands.ts b/ui/composables/useAppCommands.ts index 74f6e960..228b7b1a 100644 --- a/ui/composables/useAppCommands.ts +++ b/ui/composables/useAppCommands.ts @@ -651,6 +651,15 @@ export function createAppCommands(): Command[] { run: () => ui.setLastPrTab('changes'), }, + { + id: 'pr.tab.checks', + title: 'PR: Checks tab', + category: 'PR detail', + keybindings: ['h'], + when: 'activeItemKind == "pull"', + run: () => ui.setLastPrTab('checks'), + }, + // ─── Overlays ─────────────────────────────────────────────────────── { id: 'panel.close', diff --git a/ui/composables/useUiState.ts b/ui/composables/useUiState.ts index 5ad9f224..a67ba7c4 100644 --- a/ui/composables/useUiState.ts +++ b/ui/composables/useUiState.ts @@ -4,7 +4,7 @@ import { useDebounceFn } from '@vueuse/core' import { diagnostics } from '../utils/logger' import { useRpc } from './useRpc' -type PrTabId = 'conversation' | 'commits' | 'changes' +type PrTabId = 'conversation' | 'commits' | 'changes' | 'checks' const uiState = reactive({ drafts: {} }) const helpOpen = ref(false) @@ -40,7 +40,7 @@ function ensureSaver(): () => void { } function normalizePrTab(value: unknown): PrTabId | undefined { - if (value === 'conversation' || value === 'commits' || value === 'changes') + if (value === 'conversation' || value === 'commits' || value === 'changes' || value === 'checks') return value return undefined }