diff --git a/apps/desktop/src/main/services/prs/prAsync.test.ts b/apps/desktop/src/main/services/prs/prAsync.test.ts index 7b1c9769c9..83beab07ac 100644 --- a/apps/desktop/src/main/services/prs/prAsync.test.ts +++ b/apps/desktop/src/main/services/prs/prAsync.test.ts @@ -125,7 +125,7 @@ describe("prPollingService", () => { service.start(); await vi.advanceTimersByTimeAsync(12_000); - expect(refreshCalls).toEqual([undefined]); + expect(refreshCalls).toEqual([{ background: true }]); expect(events.filter((event) => event.type === "prs-updated")).toHaveLength(1); hotIds = ["pr-1"]; @@ -163,7 +163,7 @@ describe("prPollingService", () => { service.start(); await vi.advanceTimersByTimeAsync(12_000); - expect(refresh).toHaveBeenLastCalledWith(); + expect(refresh).toHaveBeenLastCalledWith({ background: true }); service.reconcilePrs(["pr-1"]); await vi.advanceTimersByTimeAsync(0); @@ -174,7 +174,7 @@ describe("prPollingService", () => { await vi.advanceTimersByTimeAsync(55_000); expect(refresh).toHaveBeenCalledTimes(3); - expect(refresh).toHaveBeenLastCalledWith(); + expect(refresh).toHaveBeenLastCalledWith({ background: true }); }); it("uses webhook reconciliation instead of hot polling while the relay is healthy", async () => { diff --git a/apps/desktop/src/main/services/prs/prPollingService.ts b/apps/desktop/src/main/services/prs/prPollingService.ts index da6c8023d0..81028e8b8e 100644 --- a/apps/desktop/src/main/services/prs/prPollingService.ts +++ b/apps/desktop/src/main/services/prs/prPollingService.ts @@ -433,7 +433,7 @@ export function createPrPollingService({ } else if (hotPrIds.length > 0) { await prService.refresh({ prIds: hotPrIds }); } else { - await prService.refresh(); + await prService.refresh({ background: true }); } const prs = prService.listAll(); try { diff --git a/apps/desktop/src/main/services/prs/prService.test.ts b/apps/desktop/src/main/services/prs/prService.test.ts index 1dd524791d..65963c1cdf 100644 --- a/apps/desktop/src/main/services/prs/prService.test.ts +++ b/apps/desktop/src/main/services/prs/prService.test.ts @@ -4512,6 +4512,71 @@ describe("prService.refresh", () => { }); }); + function countPullReads(githubService: ReturnType, prNumber: number): number { + return (githubService.apiRequest as any).mock.calls + .filter(([args]: [{ path: string }]) => args.path.endsWith(`/pulls/${prNumber}`)) + .length; + } + + it("stops re-reading a row whose background read keeps failing", async () => { + const goneRow = makePrRow({ id: "pr-gone", github_pr_number: 91, state: "open" }); + const okRow = makePrRow({ id: "pr-ok", github_pr_number: 90, state: "open" }); + const githubService = makeRefreshGithubService(new Set([91])); + const { service } = buildService({ db: makeRefreshDb([goneRow, okRow]), githubService }); + + await service.refresh({ background: true }); + await service.refresh({ background: true }); + + // The permanently failing row is inside its cooldown on the second sweep. + expect(countPullReads(githubService, 91)).toBe(1); + // The healthy stale sibling is still read every sweep. + expect(countPullReads(githubService, 90)).toBe(2); + }); + + it("clears a row's backoff after a requested read succeeds", async () => { + const row = makePrRow({ id: "pr-flaky", github_pr_number: 91, state: "open" }); + const failing = new Set([91]); + const githubService = makeRefreshGithubService(failing); + const { service } = buildService({ db: makeRefreshDb([row]), githubService }); + + await service.refresh({ background: true }); + expect(countPullReads(githubService, 91)).toBe(1); + + failing.clear(); + await service.refresh({ prId: "pr-flaky" }); + await service.refresh({ background: true }); + + expect(countPullReads(githubService, 91)).toBe(3); + }); + + it("does not arm the per-row ladder for a rate-limited failure", async () => { + const row = makePrRow({ id: "pr-limited", github_pr_number: 91, state: "open" }); + const githubService = makeGithubService({ + apiRequest: vi.fn(async () => { + const error = new Error("rate limited") as Error & { rateLimitResetAtMs?: number }; + error.rateLimitResetAtMs = Date.now() + 60_000; + throw error; + }), + }); + const { service } = buildService({ db: makeRefreshDb([row]), githubService }); + + await service.refresh({ background: true }); + await service.refresh({ background: true }); + + // Rate limits stay on the global pause machinery, not the per-row ladder. + expect(countPullReads(githubService, 91)).toBe(2); + }); + + it("still rethrows a GitHub-wide failure from a background sweep", async () => { + const row = makePrRow({ id: "pr-outage", github_pr_number: 91, state: "open" }); + const { service } = buildService({ + db: makeRefreshDb([row]), + githubService: makeOutageGithubService("No server is currently available to service your request."), + }); + + await expect(service.refresh({ background: true })).rejects.toThrow(/No server is currently available/); + }); + it("still rejects explicit single-PR refresh failures", async () => { const failingRow = makePrRow({ id: "pr-bad", github_pr_number: 91 }); const { service, logger } = buildService({ diff --git a/apps/desktop/src/main/services/prs/prService.ts b/apps/desktop/src/main/services/prs/prService.ts index ead2a0e192..6862239abe 100644 --- a/apps/desktop/src/main/services/prs/prService.ts +++ b/apps/desktop/src/main/services/prs/prService.ts @@ -1153,15 +1153,26 @@ function isGraphqlUndefinedFieldError(error: unknown): boolean { .test(getErrorMessage(error)); } +/** + * How stale a row must be before a background read, and the floor a failed + * read buys: an active PR is due every couple of minutes, a closed one rarely. + */ +function backgroundRefreshStaleMs(state: string | null | undefined): number { + const normalized = String(state ?? "").toLowerCase(); + return normalized === "open" || normalized === "draft" + ? BACKGROUND_REFRESH_MIN_STALE_MS + : BACKGROUND_REFRESH_CLOSED_STALE_MS; +} + function isBackgroundRefreshCandidate(row: PullRequestRow, nowMs: number): boolean { - const state = String(row.state ?? "").toLowerCase(); - const isActive = state === "open" || state === "draft"; - const staleAfterMs = isActive ? BACKGROUND_REFRESH_MIN_STALE_MS : BACKGROUND_REFRESH_CLOSED_STALE_MS; const lastSyncedAtMs = parseIsoMs(row.last_synced_at); if (lastSyncedAtMs <= 0) return true; - return nowMs - lastSyncedAtMs >= staleAfterMs; + return nowMs - lastSyncedAtMs >= backgroundRefreshStaleMs(row.state); } +/** The per-PR key in the shared GitHub read ladder. */ +const backgroundPrReadKey = (prId: string): string => `pr:${prId}`; + function compareBackgroundRefreshPriority(left: PullRequestRow, right: PullRequestRow): number { const leftState = String(left.state ?? "").toLowerCase(); const rightState = String(right.state ?? "").toLowerCase(); @@ -5902,10 +5913,19 @@ export function createPrService({ return updated; }; - const refreshPrIds = async (prIds: string[]): Promise => { + const refreshPrIds = async ( + prIds: string[], + options: { recordFailures?: boolean } = {}, + ): Promise => { const uniquePrIds = [...new Set(prIds.map((prId) => String(prId ?? "").trim()).filter(Boolean))]; const refreshed: PrSummary[] = []; const failures: Array<{ prId: string; reason: unknown }> = []; + // A failed row never advances `last_synced_at`, so without a ladder it is + // the oldest candidate on every later sweep and is re-read forever. The + // row's state picks the floor: an active PR keeps its couple of minutes. + const stateByPrId = options.recordFailures + ? new Map(listRows().map((row) => [row.id, row.state])) + : null; for (let i = 0; i < uniquePrIds.length; i += REFRESH_CONCURRENCY) { const batchPrIds = uniquePrIds.slice(i, i + REFRESH_CONCURRENCY); const results = await Promise.allSettled(batchPrIds.map((prId) => refreshOne(prId))); @@ -5913,9 +5933,17 @@ export function createPrService({ const prId = batchPrIds[index] ?? ""; if (result.status === "fulfilled") { refreshed.push(result.value); + githubReadBackoff.clear(backgroundPrReadKey(result.value.id)); return; } failures.push({ prId, reason: result.reason }); + if (options.recordFailures && githubRateLimitResetAtMsOf(result.reason) == null) { + githubReadBackoff.record( + backgroundPrReadKey(prId), + result.reason, + backgroundRefreshStaleMs(stateByPrId?.get(prId)), + ); + } logger.warn("prs.refresh_failed", { prId, error: getErrorMessage(result.reason) }); }); } @@ -10534,13 +10562,16 @@ export function createPrService({ getReviewSnapshot, - async refresh(args: { prId?: string; prIds?: string[] } = {}): Promise { + async refresh(args: { prId?: string; prIds?: string[]; background?: boolean } = {}): Promise { const requestedPrIds = [ ...(args.prId ? [args.prId] : []), ...((args.prIds ?? []).map((prId) => String(prId ?? "").trim()).filter(Boolean)), ]; if (requestedPrIds.length > 0) { - return withGithubStackMemberships(await refreshPrIds(requestedPrIds)); + const refreshed = await refreshPrIds(requestedPrIds); + // A requested read that succeeds restores the background sweep. + for (const pr of refreshed) githubReadBackoff.clear(backgroundPrReadKey(pr.id)); + return withGithubStackMemberships(refreshed); } const rows = listRows(); @@ -10548,6 +10579,9 @@ export function createPrService({ const hotPrIds = new Set(getHotRefreshPrIds(nowMs)); const staleCandidates = rows .filter((row) => !hotPrIds.has(row.id) && isBackgroundRefreshCandidate(row, nowMs)) + // A background sweep skips a row still inside its failure cooldown; a + // user-requested refresh reads every row once (the branch above). + .filter((row) => !args.background || !githubReadBackoff.isBackedOff(backgroundPrReadKey(row.id), nowMs)) .sort(compareBackgroundRefreshPriority) .slice(0, BACKGROUND_REFRESH_MAX_PRS); const hotCandidates = rows @@ -10566,7 +10600,10 @@ export function createPrService({ // rethrow would pin a perfectly healthy poller at max backoff forever. // Only a failure that says GitHub itself is unusable counts. try { - await refreshPrIds(candidates.map((row) => row.id)); + await refreshPrIds( + candidates.map((row) => row.id), + args.background ? { recordFailures: true } : {}, + ); } catch (error) { if (isGithubWideFailure(error)) throw error; logger.warn("prs.background_refresh_rows_failed", { error: getErrorMessage(error) });