feat: reduce GitHub API usage for checks and improve cache invalidation (#127)

- Fix ChecksPanel memory leak: add cancelled flag to prevent schedulePoll after unmount
- Include status in check signature for proper backoff reset on state transitions
- ChecksPanel lint: use ternary instead of if/else
- Don't cache empty string on gh CLI failure so login detection retries
- Clear checksCache on refreshAllGitHub to ensure fresh data
- Remove dead fetchIssueList code and supporting infrastructure
This commit is contained in:
Jinjing
2026-03-26 16:14:05 -07:00
committed by GitHub
parent d7895d575d
commit 0d58a0bc45
3 changed files with 111 additions and 32 deletions
+16 -3
View File
@@ -85,14 +85,21 @@ function normalizeUsername(value: string): string {
return localPart.replace(/^\d+\+/, '')
}
let cachedGhLogin: string | undefined
function getGhLogin(): string {
if (cachedGhLogin !== undefined) {
return cachedGhLogin
}
try {
const apiLogin = execSync('gh api user -q .login', {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
}).trim()
if (apiLogin) {
return normalizeUsername(apiLogin)
cachedGhLogin = normalizeUsername(apiLogin)
return cachedGhLogin
}
} catch {
// Fall through to auth status parsing
@@ -109,12 +116,18 @@ function getGhLogin(): string {
/Active account:\s+true[\s\S]*?account\s+([A-Za-z0-9-]+)/
)
if (activeAccountMatch?.[1]) {
return normalizeUsername(activeAccountMatch[1])
cachedGhLogin = normalizeUsername(activeAccountMatch[1])
return cachedGhLogin
}
const accountMatch = output.match(/Logged in to github\.com account\s+([A-Za-z0-9-]+)/)
return normalizeUsername(accountMatch?.[1] ?? '')
const login = normalizeUsername(accountMatch?.[1] ?? '')
if (login) {
cachedGhLogin = login
}
return login
} catch {
// Don't cache empty results on failure — allow retry on next call
return ''
}
}
@@ -66,13 +66,17 @@ export default function ChecksPanel(): React.JSX.Element {
const prCache = useAppStore((s) => s.prCache)
const fetchPRForBranch = useAppStore((s) => s.fetchPRForBranch)
const fetchPRChecks = useAppStore((s) => s.fetchPRChecks)
const [checks, setChecks] = useState<PRCheckDetail[]>([])
const [checksLoading, setChecksLoading] = useState(false)
const [editingTitle, setEditingTitle] = useState(false)
const [titleDraft, setTitleDraft] = useState('')
const [titleSaving, setTitleSaving] = useState(false)
const titleInputRef = useRef<HTMLInputElement>(null)
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)
const pollRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const pollIntervalRef = useRef(30_000) // start at 30s, backs off to 120s
const prevChecksRef = useRef<string>('')
// Find active worktree and repo
const { worktree, repo } = useMemo(() => {
@@ -93,37 +97,60 @@ export default function ChecksPanel(): React.JSX.Element {
const prCacheKey = repo && branch ? `${repo.path}::${branch}` : ''
const pr: PRInfo | null = prCacheKey ? (prCache[prCacheKey]?.data ?? null) : null
// Fetch checks
// Fetch checks via cached store method
const fetchChecks = useCallback(async () => {
if (!repo || !pr) {
return
}
setChecksLoading(true)
try {
const result = (await window.api.gh.prChecks({
repoPath: repo.path,
prNumber: pr.number
})) as PRCheckDetail[]
const result = await fetchPRChecks(repo.path, pr.number)
setChecks(result)
// Exponential backoff: if checks haven't changed, double the interval (cap 120s).
// If they changed, reset to 30s.
const signature = JSON.stringify(result.map((c) => `${c.name}:${c.status}:${c.conclusion}`))
pollIntervalRef.current =
signature === prevChecksRef.current
? Math.min(pollIntervalRef.current * 2, 120_000)
: 30_000
prevChecksRef.current = signature
} catch (err) {
console.warn('Failed to fetch PR checks:', err)
setChecks([])
} finally {
setChecksLoading(false)
}
}, [repo, pr])
}, [repo, pr, fetchPRChecks])
// Fetch checks on mount + poll
// Fetch checks on mount + poll with exponential backoff
useEffect(() => {
if (!pr) {
setChecks([])
return
}
// Reset backoff state on PR change
pollIntervalRef.current = 30_000
prevChecksRef.current = ''
let cancelled = false
void fetchChecks()
pollRef.current = setInterval(() => void fetchChecks(), 30_000)
const schedulePoll = (): void => {
pollRef.current = setTimeout(() => {
void fetchChecks().then(() => {
if (!cancelled) {
schedulePoll()
}
})
}, pollIntervalRef.current)
}
schedulePoll()
return () => {
cancelled = true
if (pollRef.current) {
clearInterval(pollRef.current)
clearTimeout(pollRef.current)
}
}
}, [fetchChecks, pr])
+58 -19
View File
@@ -1,6 +1,6 @@
import type { StateCreator } from 'zustand'
import type { AppState } from '../types'
import type { PRInfo, IssueInfo, Worktree } from '../../../../shared/types'
import type { PRInfo, IssueInfo, PRCheckDetail, Worktree } from '../../../../shared/types'
export type CacheEntry<T> = {
data: T | null
@@ -8,12 +8,14 @@ export type CacheEntry<T> = {
}
const CACHE_TTL = 300_000 // 5 minutes (stale data shown instantly, then refreshed)
const CHECKS_CACHE_TTL = 60_000 // 1 minute — checks change more frequently
const inflightPRRequests = new Map<string, Promise<PRInfo | null>>()
const inflightIssueRequests = new Map<string, Promise<IssueInfo | null>>()
const inflightChecksRequests = new Map<string, Promise<PRCheckDetail[]>>()
function isFresh<T>(entry: CacheEntry<T> | undefined): entry is CacheEntry<T> {
return entry !== undefined && Date.now() - entry.fetchedAt < CACHE_TTL
function isFresh<T>(entry: CacheEntry<T> | undefined, ttl = CACHE_TTL): entry is CacheEntry<T> {
return entry !== undefined && Date.now() - entry.fetchedAt < ttl
}
let saveTimer: ReturnType<typeof setTimeout> | null = null
@@ -36,8 +38,10 @@ function debouncedSaveCache(state: AppState): void {
export type GitHubSlice = {
prCache: Record<string, CacheEntry<PRInfo>>
issueCache: Record<string, CacheEntry<IssueInfo>>
checksCache: Record<string, CacheEntry<PRCheckDetail[]>>
fetchPRForBranch: (repoPath: string, branch: string) => Promise<PRInfo | null>
fetchIssue: (repoPath: string, number: number) => Promise<IssueInfo | null>
fetchPRChecks: (repoPath: string, prNumber: number) => Promise<PRCheckDetail[]>
initGitHubCache: () => Promise<void>
refreshAllGitHub: () => void
refreshGitHubForWorktree: (worktreeId: string) => void
@@ -46,6 +50,7 @@ export type GitHubSlice = {
export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (set, get) => ({
prCache: {},
issueCache: {},
checksCache: {},
initGitHubCache: async () => {
try {
@@ -133,22 +138,48 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
return request
},
refreshAllGitHub: () => {
// Invalidate all cache entries so next fetch bypasses TTL
set((s) => {
const nextPr: Record<string, CacheEntry<PRInfo>> = {}
for (const [k, v] of Object.entries(s.prCache)) {
nextPr[k] = { ...v, fetchedAt: 0 }
}
const nextIssue: Record<string, CacheEntry<IssueInfo>> = {}
for (const [k, v] of Object.entries(s.issueCache)) {
nextIssue[k] = { ...v, fetchedAt: 0 }
}
return { prCache: nextPr, issueCache: nextIssue }
})
fetchPRChecks: async (repoPath, prNumber) => {
const cacheKey = `${repoPath}::pr-checks::${prNumber}`
const cached = get().checksCache[cacheKey]
if (isFresh(cached, CHECKS_CACHE_TTL)) {
return cached.data ?? []
}
// Re-fetch all worktrees' PR + issue data
const inflightRequest = inflightChecksRequests.get(cacheKey)
if (inflightRequest) {
return inflightRequest
}
const request = (async () => {
try {
const checks = (await window.api.gh.prChecks({
repoPath,
prNumber
})) as PRCheckDetail[]
set((s) => ({
checksCache: { ...s.checksCache, [cacheKey]: { data: checks, fetchedAt: Date.now() } }
}))
return checks
} catch (err) {
console.error('Failed to fetch PR checks:', err)
return get().checksCache[cacheKey]?.data ?? []
} finally {
inflightChecksRequests.delete(cacheKey)
}
})()
inflightChecksRequests.set(cacheKey, request)
return request
},
refreshAllGitHub: () => {
// Invalidate checks cache so it refreshes on next access
set({ checksCache: {} })
// Only re-fetch PR/issue entries that are already stale — skip fresh ones
const state = get()
const now = Date.now()
for (const worktrees of Object.values(state.worktreesByRepo)) {
for (const wt of worktrees) {
const repo = state.repos.find((r) => r.id === wt.repoId)
@@ -158,10 +189,18 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
const branch = wt.branch.replace(/^refs\/heads\//, '')
if (!wt.isBare) {
void get().fetchPRForBranch(repo.path, branch)
const prKey = `${repo.path}::${branch}`
const prEntry = state.prCache[prKey]
if (!prEntry || now - prEntry.fetchedAt >= CACHE_TTL) {
void get().fetchPRForBranch(repo.path, branch)
}
}
if (wt.linkedIssue) {
void get().fetchIssue(repo.path, wt.linkedIssue)
const issueKey = `${repo.path}::${wt.linkedIssue}`
const issueEntry = state.issueCache[issueKey]
if (!issueEntry || now - issueEntry.fetchedAt >= CACHE_TTL) {
void get().fetchIssue(repo.path, wt.linkedIssue)
}
}
}
}