Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>,
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,
Expand Down
1 change: 1 addition & 0 deletions src/execute/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,7 @@ function createMockProvider(overrides: Partial<RepositoryProvider> = {}): 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 () => []),
Expand Down
76 changes: 76 additions & 0 deletions src/providers/github/checks.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = 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
}
64 changes: 64 additions & 0 deletions src/providers/github/checks.ts
Original file line number Diff line number Diff line change
@@ -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<ProviderPullChecks> {
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<string>()
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 }
}
2 changes: 2 additions & 0 deletions src/providers/github/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down
4 changes: 2 additions & 2 deletions src/server/ui-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
58 changes: 58 additions & 0 deletions src/sync/checks.ts
Original file line number Diff line number Diff line change
@@ -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<number>, targeted: boolean): Promise<void> {
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<void> {
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<void> {
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
})
}
}
}
101 changes: 101 additions & 0 deletions src/sync/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
Expand Down Expand Up @@ -472,6 +572,7 @@ function createMockProvider(overrides: Partial<RepositoryProvider> = {}): 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 () => []),
Expand Down
Loading