diff --git a/src/main/git/repo.ts b/src/main/git/repo.ts index a20b0cd14..40059d3a9 100644 --- a/src/main/git/repo.ts +++ b/src/main/git/repo.ts @@ -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 '' } } diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index 0459cb753..451c41e4b 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -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([]) const [checksLoading, setChecksLoading] = useState(false) const [editingTitle, setEditingTitle] = useState(false) const [titleDraft, setTitleDraft] = useState('') const [titleSaving, setTitleSaving] = useState(false) const titleInputRef = useRef(null) - const pollRef = useRef | null>(null) + const pollRef = useRef | null>(null) + const pollIntervalRef = useRef(30_000) // start at 30s, backs off to 120s + const prevChecksRef = useRef('') // 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]) diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index 327de243d..88e191205 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -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 = { data: T | null @@ -8,12 +8,14 @@ export type CacheEntry = { } 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>() const inflightIssueRequests = new Map>() +const inflightChecksRequests = new Map>() -function isFresh(entry: CacheEntry | undefined): entry is CacheEntry { - return entry !== undefined && Date.now() - entry.fetchedAt < CACHE_TTL +function isFresh(entry: CacheEntry | undefined, ttl = CACHE_TTL): entry is CacheEntry { + return entry !== undefined && Date.now() - entry.fetchedAt < ttl } let saveTimer: ReturnType | null = null @@ -36,8 +38,10 @@ function debouncedSaveCache(state: AppState): void { export type GitHubSlice = { prCache: Record> issueCache: Record> + checksCache: Record> fetchPRForBranch: (repoPath: string, branch: string) => Promise fetchIssue: (repoPath: string, number: number) => Promise + fetchPRChecks: (repoPath: string, prNumber: number) => Promise initGitHubCache: () => Promise refreshAllGitHub: () => void refreshGitHubForWorktree: (worktreeId: string) => void @@ -46,6 +50,7 @@ export type GitHubSlice = { export const createGitHubSlice: StateCreator = (set, get) => ({ prCache: {}, issueCache: {}, + checksCache: {}, initGitHubCache: async () => { try { @@ -133,22 +138,48 @@ export const createGitHubSlice: StateCreator = (s return request }, - refreshAllGitHub: () => { - // Invalidate all cache entries so next fetch bypasses TTL - set((s) => { - const nextPr: Record> = {} - for (const [k, v] of Object.entries(s.prCache)) { - nextPr[k] = { ...v, fetchedAt: 0 } - } - const nextIssue: Record> = {} - 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 = (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) + } } } }