diff --git a/src/main/github/client/lookup/pr-for-branch-outcome.ts b/src/main/github/client/lookup/pr-for-branch-outcome.ts index 05db157f287..21ce9490d09 100644 --- a/src/main/github/client/lookup/pr-for-branch-outcome.ts +++ b/src/main/github/client/lookup/pr-for-branch-outcome.ts @@ -12,7 +12,13 @@ import { hostedReviewLocalGitOptionArgs, githubPRStackExecutionScope } from './. import type { GitHubPRBranchLookupOptions } from './pull-request-lookup-data' import { prRefreshUpstreamError } from './../gh-error-predicates' import { resolvePRForBranchOutcome } from './branch-lookup-resolution' -import { readRecentOpenPROutcome, recordPRLastOutcome, startPRLookup } from './pr-last-outcome' +import { + readPacedPROutcome, + readRecentOpenPROutcome, + recordPRLastOutcome, + startPRLookup +} from './pr-last-outcome' +import type { PRAutoRefreshCadence } from '../../../../shared/review-refresh-policy' const reads: CoalescedProbes = new Map() function prLookupScope( @@ -79,6 +85,40 @@ export async function readRecentPhonePROutcome( ) } +/** A paired client's timed read on a host with a slower cadence: the last answer, while still due. */ +export async function readPacedClientPROutcome( + repoPath: string, + branch: string, + linkedPRNumber: number | null, + connectionId: string | null, + fallbackPRNumber: number | null, + options: GitHubPRBranchLookupOptions, + cadence: PRAutoRefreshCadence +): Promise { + if (cadence === 'default' || options.userRefresh === true) { + return null + } + return withGitHubRepoExecution( + repoPath, + connectionId, + hostedReviewLocalGitOptionArgs(options)[0] ?? {}, + async () => + readPacedPROutcome( + lastOutcomeKey( + repoPath, + branch.replace(/^refs\/heads\//, ''), + prLookupScope(repoPath, connectionId, options) + ), + { + linkedPRNumber, + fallbackPRNumber: linkedPRNumber === null ? fallbackPRNumber : null, + currentHeadOid: options.currentHeadOid ?? null + }, + cadence + ) + ) +} + export async function getPRForBranchOutcome( repoPath: string, branch: string, @@ -149,6 +189,7 @@ export async function getPRForBranchOutcome( start, linkedPRNumber: linkedPRNumber ?? null, fallbackPRNumber: fallbackPRNumber ?? null, + headOid: options.currentHeadOid ?? null, outcome: narrowed ? null : outcome }) return outcome diff --git a/src/main/github/client/lookup/pr-last-outcome.test.ts b/src/main/github/client/lookup/pr-last-outcome.test.ts new file mode 100644 index 00000000000..53c183103cc --- /dev/null +++ b/src/main/github/client/lookup/pr-last-outcome.test.ts @@ -0,0 +1,96 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-request-refresh-types' +import type { PRInfo } from '../../../../shared/github/pull-request-types' +import { readPacedPROutcome, recordPRLastOutcome, startPRLookup } from './pr-last-outcome' + +const request = { linkedPRNumber: null, fallbackPRNumber: null, currentHeadOid: 'head-a' } + +function found(overrides: Partial = {}): PRRefreshOutcome { + return { + kind: 'found', + fetchedAt: Date.now(), + pr: { + number: 7, + title: 'PR', + state: 'open', + url: 'https://github.com/acme/repo/pull/7', + checksStatus: 'pending', + updatedAt: '2026-11-01T00:00:00Z', + mergeable: 'MERGEABLE', + headSha: 'head-a', + ...overrides + } + } +} + +function record(key: string, outcome: PRRefreshOutcome | null, headOid = 'head-a'): void { + recordPRLastOutcome(key, { + start: startPRLookup(), + linkedPRNumber: null, + fallbackPRNumber: null, + headOid, + outcome + }) +} + +describe('readPacedPROutcome', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(10_000_000) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('never reuses on the default cadence', () => { + record('k-default', found()) + expect(readPacedPROutcome('k-default', request, 'default')).toBeNull() + }) + + it('reuses the last answer until the host’s stretched interval passes', () => { + const outcome = found() + record('k-reduced', outcome) + vi.advanceTimersByTime(4 * 60_000) + expect(readPacedPROutcome('k-reduced', request, 'reduced')).toBe(outcome) + vi.advanceTimersByTime(60_000) + expect(readPacedPROutcome('k-reduced', request, 'reduced')).toBeNull() + }) + + it('reuses a no-PR answer and keeps reusing any answer when off', () => { + const none: PRRefreshOutcome = { kind: 'no-pr', fetchedAt: Date.now() } + record('k-off', none) + vi.advanceTimersByTime(24 * 60 * 60_000) + expect(readPacedPROutcome('k-off', request, 'off')).toBe(none) + }) + + it('asks GitHub again after a new commit, an error, or a narrowed read', () => { + record('k-head', found(), 'head-old') + expect(readPacedPROutcome('k-head', request, 'off')).toBeNull() + + record('k-error', { + kind: 'upstream-error', + errorType: 'unknown', + message: 'boom', + fetchedAt: Date.now() + }) + expect(readPacedPROutcome('k-error', request, 'off')).toBeNull() + + record('k-narrowed', null) + expect(readPacedPROutcome('k-narrowed', request, 'off')).toBeNull() + }) + + it('asks GitHub again when the request names another PR', () => { + record('k-linked', found()) + expect(readPacedPROutcome('k-linked', { ...request, linkedPRNumber: 9 }, 'off')).toBeNull() + }) + + it('keeps answers older than the phone window for a slower cadence', () => { + const outcome = found() + record('k-old', outcome) + vi.advanceTimersByTime(60_000) + // A later insert used to evict every entry older than 30 s. + record('k-other', found()) + expect(readPacedPROutcome('k-old', request, 'minimal')).toBe(outcome) + }) +}) diff --git a/src/main/github/client/lookup/pr-last-outcome.ts b/src/main/github/client/lookup/pr-last-outcome.ts index f5c7cb383be..bfadf549785 100644 --- a/src/main/github/client/lookup/pr-last-outcome.ts +++ b/src/main/github/client/lookup/pr-last-outcome.ts @@ -1,4 +1,8 @@ import type { PRRefreshOutcome } from '../../../../shared/github/pull-request-refresh-types' +import { + reviewRefreshIntervalMs, + type PRAutoRefreshCadence +} from '../../../../shared/review-refresh-policy' // A phone's re-read right after the desktop's own lookup reuses it instead of asking GitHub again. const PHONE_REUSE_MAX_AGE_MS = 30_000 @@ -10,6 +14,8 @@ type PRLastOutcome = { start: PRLookupStart linkedPRNumber: number | null fallbackPRNumber: number | null + /** The checkout HEAD the lookup was asked about; a new commit may have opened or moved a PR. */ + headOid: string | null // null: the last lookup was narrowed (CI-line watch), so nothing is reusable until a full one. outcome: PRRefreshOutcome | null } @@ -31,15 +37,58 @@ export function recordPRLastOutcome(key: string, entry: PRLastOutcome): void { } lastOutcomes.delete(key) lastOutcomes.set(key, entry) - const now = Date.now() - for (const [oldestKey, oldest] of lastOutcomes) { - if (lastOutcomes.size <= MAX_ENTRIES && now - oldest.start.startedAt < PHONE_REUSE_MAX_AGE_MS) { + // Size-bounded only: a slower host cadence reuses answers far older than the phone window. + for (const oldestKey of lastOutcomes.keys()) { + if (lastOutcomes.size <= MAX_ENTRIES) { break } lastOutcomes.delete(oldestKey) } } +/** With a slower host cadence, a client's timed read reuses the last full answer for the same + * request until this host's own interval for that answer has passed ("off": until an explicit read). */ +export function readPacedPROutcome( + key: string, + request: { + linkedPRNumber: number | null + fallbackPRNumber: number | null + currentHeadOid: string | null + }, + cadence: PRAutoRefreshCadence +): PRRefreshOutcome | null { + if (cadence === 'default') { + return null + } + const entry = lastOutcomes.get(key) + const outcome = entry?.outcome + if ( + !entry || + !outcome || + outcome.kind === 'upstream-error' || + entry.linkedPRNumber !== request.linkedPRNumber || + entry.fallbackPRNumber !== request.fallbackPRNumber || + entry.headOid !== request.currentHeadOid + ) { + return null + } + const pr = outcome.kind === 'found' ? outcome.pr : null + // Selected pacing is the shortest timed interval, so the host never outpaces a selected client. + const interval = reviewRefreshIntervalMs( + { + state: pr?.state ?? null, + checksStatus: pr?.checksStatus ?? null, + hasReview: pr !== null, + selected: true + }, + cadence + ) + if (interval !== null && Date.now() - entry.start.startedAt >= interval) { + return null + } + return outcome +} + /** Only an open PR whose own head is the request's head: a push can't have moved it, and merged or * fallback rules still get a real lookup. */ export function readRecentOpenPROutcome( diff --git a/src/main/github/pr-auto-refresh-cadence-sync.ts b/src/main/github/pr-auto-refresh-cadence-sync.ts new file mode 100644 index 00000000000..562a4c6a8ff --- /dev/null +++ b/src/main/github/pr-auto-refresh-cadence-sync.ts @@ -0,0 +1,27 @@ +import type { RuntimeStore } from '../runtime/construction/runtime-store-contract' +import { + getPRAutoRefreshCadence, + setPRAutoRefreshCadence +} from '../../shared/review-refresh-policy' +import { retimePRRefreshesForCadence } from './pr-refresh-coordinator' + +/** Apply this host's PR auto-refresh setting to every main-process poller, now and on change. + * Runs for desktop and headless `orca serve` alike, so an operator can cap a shared box. */ +export function syncPRAutoRefreshCadence( + store: Pick | null +): void { + if (!store?.getSettings) { + return + } + setPRAutoRefreshCadence(store.getSettings().prAutoRefresh) + store.onSettingsChanged?.((updates, settings) => { + if (!('prAutoRefresh' in updates)) { + return + } + const before = getPRAutoRefreshCadence() + setPRAutoRefreshCadence(settings.prAutoRefresh) + if (getPRAutoRefreshCadence() !== before) { + retimePRRefreshesForCadence() + } + }) +} diff --git a/src/main/github/pr-refresh-coordinator-auto-refresh-cadence.test.ts b/src/main/github/pr-refresh-coordinator-auto-refresh-cadence.test.ts new file mode 100644 index 00000000000..c4bbdde45c1 --- /dev/null +++ b/src/main/github/pr-refresh-coordinator-auto-refresh-cadence.test.ts @@ -0,0 +1,100 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') + return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } +}) + +vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) +vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) +vi.mock('./github-api-repository', () => + moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) +) +vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) + +import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' + +const { getPRForBranchOutcomeMock } = coordinatorMocks + +async function loadCoordinatorWithCadence(cadence: string) { + // resetModules gives each test fresh module state; set the cadence on that same instance. + const policy = await import('../../shared/review-refresh-policy') + policy.setPRAutoRefreshCadence(cadence) + return { policy, coordinator: await import('./pr-refresh-coordinator') } +} + +describe('pr-refresh-coordinator auto-refresh cadence', () => { + beforeEach(() => { + moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) + vi.setSystemTime(1_000) + getPRForBranchOutcomeMock.mockImplementation(async () => ({ + kind: 'found', + pr: makePR({ checksStatus: 'pending' }), + fetchedAt: Date.now() + })) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('keeps the two-minute visible follow-up by default', async () => { + const { coordinator } = await loadCoordinatorWithCadence('default') + coordinator.reportVisiblePRRefreshCandidates([makeCandidate()], 1, 1) + await vi.advanceTimersByTimeAsync(0) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(2 * 60_000 + 1_000) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) + }) + + it('stretches visible follow-ups to ten minutes when reduced', async () => { + const { coordinator } = await loadCoordinatorWithCadence('reduced') + coordinator.reportVisiblePRRefreshCandidates([makeCandidate()], 1, 1) + await vi.advanceTimersByTimeAsync(0) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(9 * 60_000) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(60_000 + 1_000) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) + }) + + it('reads a newly visible PR once and then stops timed reads when off', async () => { + const { coordinator } = await loadCoordinatorWithCadence('off') + coordinator.reportVisiblePRRefreshCandidates([makeCandidate()], 1, 1) + await vi.advanceTimersByTimeAsync(0) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(24 * 60 * 60_000) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + }) + + it('still reads at once on selection when off', async () => { + const { coordinator } = await loadCoordinatorWithCadence('off') + coordinator.enqueuePRRefresh( + makeCandidate({ + cachedFetchedAt: Date.now(), + cachedHasPR: true, + cachedPRState: 'open', + cachedChecksStatus: 'pending' + }), + 'active', + 80 + ) + await vi.advanceTimersByTimeAsync(0) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + }) + + it('drops a queued follow-up when the cadence changes to off', async () => { + const { policy, coordinator } = await loadCoordinatorWithCadence('default') + coordinator.reportVisiblePRRefreshCandidates([makeCandidate()], 1, 1) + await vi.advanceTimersByTimeAsync(0) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + + policy.setPRAutoRefreshCadence('off') + coordinator.retimePRRefreshesForCadence() + await vi.advanceTimersByTimeAsync(60 * 60_000) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/main/github/pr-refresh-coordinator.ts b/src/main/github/pr-refresh-coordinator.ts index 2fbb0d816ef..4b780ebe0b6 100644 --- a/src/main/github/pr-refresh-coordinator.ts +++ b/src/main/github/pr-refresh-coordinator.ts @@ -98,6 +98,12 @@ export function clearVisiblePRRefreshWindow(windowId: number): void { } } +/** A cadence change moves queued visible follow-ups to the new interval; "off" drops them. */ +export function retimePRRefreshesForCadence(): void { + queue.retimeVisible((key, candidate) => visibility.candidate(key, candidate)) + drainer.schedule() +} + export function pruneWorktreePRRefreshAliases(worktreeId: string): void { queue.pruneWorktreeAliases(worktreeId) } diff --git a/src/main/github/pr-refresh-watch-jobs-cadence.test.ts b/src/main/github/pr-refresh-watch-jobs-cadence.test.ts new file mode 100644 index 00000000000..9d0bcb2ea3b --- /dev/null +++ b/src/main/github/pr-refresh-watch-jobs-cadence.test.ts @@ -0,0 +1,31 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type { PRRefreshOutcome } from '../../shared/github/pull-request-refresh-types' +import { setPRAutoRefreshCadence } from '../../shared/review-refresh-policy' +import { makePR } from './pr-refresh-coordinator-test-harness' +import { prWatchNextDueAt } from './pr-refresh-watch-jobs' + +const runningChecks: PRRefreshOutcome = { + kind: 'found', + pr: makePR({ checksStatus: 'pending' }), + fetchedAt: 1_000 +} + +describe('CI-line watch cadence', () => { + afterEach(() => { + setPRAutoRefreshCadence('default') + }) + + it('reads running checks on the background interval by default', () => { + expect(prWatchNextDueAt(runningChecks)).toBe(1_000 + 120_000) + }) + + it('follows a reduced host cadence', () => { + setPRAutoRefreshCadence('reduced') + expect(prWatchNextDueAt(runningChecks)).toBe(1_000 + 10 * 60_000) + }) + + it('slows instead of ending when auto-refresh is off, so the chat still gets its result', () => { + setPRAutoRefreshCadence('off') + expect(prWatchNextDueAt(runningChecks)).toBe(1_000 + 20 * 60_000) + }) +}) diff --git a/src/main/github/pr-refresh-watch-jobs.ts b/src/main/github/pr-refresh-watch-jobs.ts index 861f60efcd1..c00191deed7 100644 --- a/src/main/github/pr-refresh-watch-jobs.ts +++ b/src/main/github/pr-refresh-watch-jobs.ts @@ -3,7 +3,10 @@ import type { PRRefreshOutcome } from '../../shared/github/pull-request-refresh-types' import type { PRInfo } from '../../shared/github/pull-request-types' -import { reviewRefreshIntervalMs } from '../../shared/review-refresh-policy' +import { + getPRAutoRefreshCadence, + reviewRefreshIntervalMs +} from '../../shared/review-refresh-policy' import type { PRRefreshQueue, PRRefreshQueueEntry } from './pr-refresh-queue' import type { PRRefreshRetryState } from './pr-refresh-retry-state' @@ -47,12 +50,17 @@ export function prWatchNextDueAt(outcome: PRRefreshOutcome): number | null { return null } const pr = outcome.kind === 'found' ? outcome.pr : null - const interval = reviewRefreshIntervalMs({ - state: pr?.state ?? null, - checksStatus: pr && !prChecksDone(pr) ? 'pending' : (pr?.checksStatus ?? null), - hasReview: pr !== null, - selected: false - }) + const cadence = getPRAutoRefreshCadence() + // A chat asked for this PR's CI result, so "off" slows the watch rather than ending it unanswered. + const interval = reviewRefreshIntervalMs( + { + state: pr?.state ?? null, + checksStatus: pr && !prChecksDone(pr) ? 'pending' : (pr?.checksStatus ?? null), + hasReview: pr !== null, + selected: false + }, + cadence === 'off' ? 'minimal' : cadence + ) return interval === null ? null : outcome.fetchedAt + interval } diff --git a/src/main/runtime/client/settings/runtime-client-settings-shape.ts b/src/main/runtime/client/settings/runtime-client-settings-shape.ts index c59ee8d22e6..8c94e6a76bb 100644 --- a/src/main/runtime/client/settings/runtime-client-settings-shape.ts +++ b/src/main/runtime/client/settings/runtime-client-settings-shape.ts @@ -41,6 +41,7 @@ export type RuntimeClientSettings = Pick< | 'nativeChatCiResultLines' | 'sourceControlGroupOrder' | 'sourceControlCompareAgainstUpstream' + | 'prAutoRefresh' | 'diffShowWhitespace' > & { /** Always set; older hosts omit it, so clients must not write it to them (settings.update is strict). */ @@ -86,4 +87,5 @@ export type RuntimeClientSettingsUpdate = Pick< | 'nativeChatPermissionMode' | 'nativeChatAutoContinueAfterUsageLimit' | 'workspaceCleanupPolicy' + | 'prAutoRefresh' > diff --git a/src/main/runtime/client/settings/runtime-client-settings.ts b/src/main/runtime/client/settings/runtime-client-settings.ts index 4008aa9c0ad..fe3f027f21b 100644 --- a/src/main/runtime/client/settings/runtime-client-settings.ts +++ b/src/main/runtime/client/settings/runtime-client-settings.ts @@ -26,6 +26,7 @@ import { applyAgentStatusHooksEnabled } from '../../../agent-hooks/installation/ import { isWslHostOrcadProcess } from '../../../ipc/wsl-guest-windows-drive-path' import { isAgentStatusHooksEnabledForAgent } from '../../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import type { RuntimeStore } from '../../construction/runtime-store-contract' +import { normalizePRAutoRefreshCadence } from '../../../../shared/review-refresh-policy' import { agentLaunchSettingsMutationUpdates, projectAgentLaunchSettings, @@ -100,6 +101,7 @@ export class RuntimeClientSettingsController { // Paired clients order their Source Control lists the way this desktop does. sourceControlGroupOrder: normalizeSourceControlGroupOrder(settings.sourceControlGroupOrder), sourceControlCompareAgainstUpstream: settings.sourceControlCompareAgainstUpstream === true, + prAutoRefresh: normalizePRAutoRefreshCadence(settings.prAutoRefresh), diffShowWhitespace: settings.diffShowWhitespace === true, // Omitted without a service: clients treat absence as "ask the host", which names the real cause. ...(this.sharingServices?.artifacts() === false diff --git a/src/main/runtime/construction/runtime-store-contract.ts b/src/main/runtime/construction/runtime-store-contract.ts index f80776e8be8..94fda1a3f4c 100644 --- a/src/main/runtime/construction/runtime-store-contract.ts +++ b/src/main/runtime/construction/runtime-store-contract.ts @@ -175,6 +175,7 @@ export type RuntimeStore = { prBotAuthorOverrides?: GlobalSettings['prBotAuthorOverrides'] sourceControlGroupOrder?: GlobalSettings['sourceControlGroupOrder'] sourceControlCompareAgainstUpstream?: GlobalSettings['sourceControlCompareAgainstUpstream'] + prAutoRefresh?: GlobalSettings['prAutoRefresh'] diffShowWhitespace?: GlobalSettings['diffShowWhitespace'] artifactSharingEnabled?: GlobalSettings['artifactSharingEnabled'] terminalQuickCommands?: GlobalSettings['terminalQuickCommands'] diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts b/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts index 47bfa21315c..2975e78024d 100644 --- a/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts +++ b/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts @@ -16,11 +16,16 @@ import type { Repo } from '../../../../shared/repo-types' import type { DeviceScope } from '../../../../shared/runtime-session-contracts' import { getPRForBranchOutcome, + readPacedClientPROutcome, readRecentPhonePROutcome } from '../../../github/client/lookup/pr-for-branch-outcome' import { getRepoSlug, getRepoUpstream } from '../../../github/client/fetch/repo-slug-upstream' import type { GitHubPRBranchLookupOptions } from '../../../github/client/lookup/pull-request-lookup-data' -import { admissionTierForRefreshReason } from '../../../github/pr-refresh-candidate-policy' +import { + admissionTierForRefreshReason, + isBudgetedBackground +} from '../../../github/pr-refresh-candidate-policy' +import { getPRAutoRefreshCadence } from '../../../../shared/review-refresh-policy' import { runHostedPRRead } from '../../../github/pr-refresh-coordinator' import type { GitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' import { hostedReviewForBranchReply } from '../../../../shared/source-control/hosted-review/hosted-review-contracts' @@ -112,6 +117,21 @@ export class RuntimeHostedReviewCommands { return recent } } + // This host's cadence caps every client's timed reads, so more clients add no GitHub calls. + if (reason !== undefined && isBudgetedBackground(reason)) { + const paced = await readPacedClientPROutcome( + repo.path, + branch, + linkedPRNumber ?? null, + connectionId, + fallbackPRNumber ?? null, + lookupOptions, + getPRAutoRefreshCadence() + ) + if (paced) { + return paced + } + } // Through the coordinator, so a client's read also serves this server's CI-line watches. return runHostedPRRead( { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 9156fdd5865..686d0cec97e 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -5,6 +5,7 @@ import { installRuntimeLinearCommandSurface } from './integrations/linear/runtim import { publishNativeChatPreferenceChanges } from './agent-session/launch/runtime-native-chat-preference-events' import { publishSettingsChanges } from './client/settings/runtime-settings-change-events' import { publishWorkspaceViewChanges } from './sidebar-inputs/runtime-workspace-view-change-events' +import { syncPRAutoRefreshCadence } from '../github/pr-auto-refresh-cadence-sync' import { OrcaRuntimeWithSidebarTemporal, sidebarFactsRuntime @@ -204,6 +205,7 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { publishWorkspaceViewChanges(this.store, (event) => this.emitClientEvent(event)) publishNativeChatPreferenceChanges(this.store, (event) => this.emitClientEvent(event)) publishSettingsChanges(this.store, (event) => this.emitClientEvent(event)) + syncPRAutoRefreshCadence(this.store) } /** What mobileRelay.hosts.list answers changed. */ diff --git a/src/main/source-control/hosted-review-branch-cache.test.ts b/src/main/source-control/hosted-review-branch-cache.test.ts index e833fa2dfca..e84ce8f1c5e 100644 --- a/src/main/source-control/hosted-review-branch-cache.test.ts +++ b/src/main/source-control/hosted-review-branch-cache.test.ts @@ -5,6 +5,7 @@ import { invalidateHostedReviewBranchCache, withHostedReviewBranchCache } from './hosted-review-branch-cache' +import { setPRAutoRefreshCadence } from '../../shared/review-refresh-policy' import { HOSTED_REVIEW_LOOKUP_DEADLINE_MS, LOOKUP_BACKOFF_MAX_MS, @@ -751,4 +752,41 @@ describe('hosted review branch cache (#11532)', () => { expect(next).toHaveBeenCalledTimes(1) }) }) + + describe('host PR auto-refresh cadence', () => { + afterEach(() => { + setPRAutoRefreshCadence('default') + }) + + it('re-reads a found review after a minute by default', async () => { + const lookup = vi.fn(async () => openReview) + await withHostedReviewBranchCache(identity, { headOid: null }, lookup) + vi.advanceTimersByTime(60_000) + await withHostedReviewBranchCache(identity, { headOid: null }, lookup) + expect(lookup).toHaveBeenCalledTimes(2) + }) + + it('keeps a found review five times longer when reduced', async () => { + setPRAutoRefreshCadence('reduced') + const lookup = vi.fn(async () => openReview) + await withHostedReviewBranchCache(identity, { headOid: null }, lookup) + vi.advanceTimersByTime(4 * 60_000) + await withHostedReviewBranchCache(identity, { headOid: null }, lookup) + expect(lookup).toHaveBeenCalledTimes(1) + vi.advanceTimersByTime(60_000) + await withHostedReviewBranchCache(identity, { headOid: null }, lookup) + expect(lookup).toHaveBeenCalledTimes(2) + }) + + it('serves the cached answer until a forced or user read when off', async () => { + setPRAutoRefreshCadence('off') + const lookup = vi.fn(async () => openReview) + await withHostedReviewBranchCache(identity, { headOid: null }, lookup) + vi.advanceTimersByTime(24 * 60 * 60_000) + await withHostedReviewBranchCache(identity, { headOid: null }, lookup) + expect(lookup).toHaveBeenCalledTimes(1) + await withHostedReviewBranchCache(identity, { headOid: null, userRefresh: true }, lookup) + expect(lookup).toHaveBeenCalledTimes(2) + }) + }) }) diff --git a/src/main/source-control/hosted-review-branch-cache.ts b/src/main/source-control/hosted-review-branch-cache.ts index ea11461c5f4..825c9e81624 100644 --- a/src/main/source-control/hosted-review-branch-cache.ts +++ b/src/main/source-control/hosted-review-branch-cache.ts @@ -46,6 +46,7 @@ import { noteFailure } from './hosted-review-lookup-backoff' import { observeProviderRead } from './hosted-review-provider-read' +import { scaleReviewRefreshInterval } from '../../shared/review-refresh-policy' import { ACTIVE_REFRESH_INTERVAL_MS, HOSTED_REVIEW_LOOKUP_DEADLINE_MS, @@ -84,10 +85,14 @@ function isHeadSensitive(entry: CacheEntry): boolean { } function refreshIntervalMs(entry: CacheEntry, active: boolean): number { - if (entry.review !== null) { - return FOUND_REVIEW_TTL_MS - } - return active ? ACTIVE_REFRESH_INTERVAL_MS : NO_REVIEW_REFRESH_INTERVAL_MS + const base = + entry.review !== null + ? FOUND_REVIEW_TTL_MS + : active + ? ACTIVE_REFRESH_INTERVAL_MS + : NO_REVIEW_REFRESH_INTERVAL_MS + // A slower host cadence keeps answers longer; forced, user and newly selected reads still ask. + return scaleReviewRefreshInterval(base) ?? Number.POSITIVE_INFINITY } function isFresh(entry: CacheEntry, headOid: string | null, active: boolean): boolean { diff --git a/src/renderer/src/app-shell/use-visible-review-refresh-reporting.ts b/src/renderer/src/app-shell/use-visible-review-refresh-reporting.ts index e80c181e486..1ba5943676e 100644 --- a/src/renderer/src/app-shell/use-visible-review-refresh-reporting.ts +++ b/src/renderer/src/app-shell/use-visible-review-refresh-reporting.ts @@ -8,6 +8,7 @@ import { getVisibleHostedReviewWorkspaces } from '../store/slices/hosted-review/ import { shouldCoordinateVisibleGitHubReview } from '../store/slices/hosted-review/refresh/visible-hosted-review-refresh-ownership' import { getPRRefreshRuntimeRepoTarget } from '../store/github/repositories/repository-routing' import { + getPRAutoRefreshCadence, reviewRefreshIntervalMs, REVIEW_REFRESH_COOLDOWN_MS } from '../../../shared/review-refresh-policy' @@ -32,6 +33,8 @@ export function visibleReviewWorktreeIdsForState(state: AppState): string[] { function reportIdentity(state: AppState): string { return JSON.stringify([ + // A new cadence re-reports, so main re-plans each visible PR's next read at the new interval. + getPRAutoRefreshCadence(), state.activeWorktreeId, rightSidebarShowsPullRequestData(state), state.sshConnectedGeneration, diff --git a/src/renderer/src/components/settings/page/settings-git-task-section-renderers.tsx b/src/renderer/src/components/settings/page/settings-git-task-section-renderers.tsx index 1400fab36b9..07fe6f219e7 100644 --- a/src/renderer/src/components/settings/page/settings-git-task-section-renderers.tsx +++ b/src/renderer/src/components/settings/page/settings-git-task-section-renderers.tsx @@ -47,6 +47,8 @@ export function renderGitSettingsSection( ) : null} diff --git a/src/renderer/src/components/settings/source-control/GitProviderApiBudgetPane.tsx b/src/renderer/src/components/settings/source-control/GitProviderApiBudgetPane.tsx index 16567ec5530..d297fa85f6a 100644 --- a/src/renderer/src/components/settings/source-control/GitProviderApiBudgetPane.tsx +++ b/src/renderer/src/components/settings/source-control/GitProviderApiBudgetPane.tsx @@ -6,22 +6,37 @@ import { GitHubRateLimitPanel } from '../../github/github-rate-limit-display' import { GitLabRateLimitPanel } from '../../gitlab/gitlab-rate-limit-display' import { useTranslate } from '@/i18n/use-translate' import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' +import { PRAutoRefreshSetting } from './PRAutoRefreshSetting' +import { prAutoRefreshMatchesSearch } from './pr-auto-refresh-search' type GitProviderApiBudgetPaneProps = { settingsSearchQuery?: string /** The host chosen at the top of Settings; budgets come from that host's CLI. */ target: RuntimeClientTarget + settings: GlobalSettings + updateSettings: (updates: Partial) => void | Promise } export function GitProviderApiBudgetPane({ settingsSearchQuery, - target + target, + settings, + updateSettings }: GitProviderApiBudgetPaneProps): React.JSX.Element | null { const t = useTranslate() const storeSearchQuery = useAppStore((s) => s.settingsSearchQuery) const searchQuery = settingsSearchQuery ?? storeSearchQuery const visibleSections = [ + prAutoRefreshMatchesSearch(searchQuery, t) ? ( + + ) : null, matchesSettingsSearch(searchQuery, { title: t('auto.components.settings.GitPane.fdbcd676b0', 'GitHub API budget'), description: t( diff --git a/src/renderer/src/components/settings/source-control/PRAutoRefreshSetting.tsx b/src/renderer/src/components/settings/source-control/PRAutoRefreshSetting.tsx new file mode 100644 index 00000000000..c93a76a7f8b --- /dev/null +++ b/src/renderer/src/components/settings/source-control/PRAutoRefreshSetting.tsx @@ -0,0 +1,162 @@ +import { useEffect, useState } from 'react' +import { toast } from 'sonner' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' +import { + normalizePRAutoRefreshCadence, + type PRAutoRefreshCadence +} from '../../../../../shared/review-refresh-policy' +import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' +import { useTranslate, type Translate } from '@/i18n/use-translate' +import { SearchableSetting } from '../section-layout/SearchableSetting' +import { SettingsRow, SettingsSegmentedControl } from '../form-controls/SettingsFormControls' +import { + getPRAutoRefreshDescription, + getPRAutoRefreshTitle, + PR_AUTO_REFRESH_KEYWORDS +} from './pr-auto-refresh-search' + +type HostCadence = { environmentId: string; cadence: PRAutoRefreshCadence } + +/** The cadence belongs to the host that runs the GitHub reads, so a remote host is read and + * written through its own settings. */ +function usePRAutoRefreshHostCadence( + target: RuntimeClientTarget, + localSettings: GlobalSettings, + updateLocalSettings: (updates: Partial) => void | Promise, + t: Translate +): { + cadence: PRAutoRefreshCadence | null + update: (cadence: PRAutoRefreshCadence) => Promise +} { + const environmentId = target.kind === 'environment' ? target.environmentId : null + const [remote, setRemote] = useState(null) + + useEffect(() => { + if (!environmentId) { + return + } + let current = true + void callRuntimeRpc<{ settings: Partial }>( + { kind: 'environment', environmentId }, + 'settings.get', + undefined, + { timeoutMs: 15_000 } + ).then( + (result) => { + if (current) { + setRemote({ + environmentId, + cadence: normalizePRAutoRefreshCadence(result.settings.prAutoRefresh) + }) + } + }, + (error: unknown) => console.error('Failed to load host PR auto-refresh setting:', error) + ) + return () => { + current = false + } + }, [environmentId]) + + if (!environmentId) { + return { + cadence: normalizePRAutoRefreshCadence(localSettings.prAutoRefresh), + update: async (cadence) => { + await updateLocalSettings({ prAutoRefresh: cadence }) + } + } + } + return { + cadence: remote?.environmentId === environmentId ? remote.cadence : null, + update: async (cadence) => { + try { + const result = await callRuntimeRpc<{ settings: Partial }>( + { kind: 'environment', environmentId }, + 'settings.update', + { prAutoRefresh: cadence }, + { timeoutMs: 15_000 } + ) + setRemote({ + environmentId, + cadence: normalizePRAutoRefreshCadence(result.settings.prAutoRefresh) + }) + } catch (error) { + toast.error( + t( + 'auto.components.settings.GitPane.prAutoRefreshUpdateFailed', + 'Could not update PR auto-refresh on this host.' + ), + { description: error instanceof Error ? error.message : String(error) } + ) + } + } + } +} + +export function PRAutoRefreshSetting({ + target, + settings, + updateSettings +}: { + target: RuntimeClientTarget + settings: GlobalSettings + updateSettings: (updates: Partial) => void | Promise +}): React.JSX.Element { + const t = useTranslate() + const title = getPRAutoRefreshTitle(t) + const description = getPRAutoRefreshDescription(t) + const { cadence, update } = usePRAutoRefreshHostCadence(target, settings, updateSettings, t) + + return ( + + + value={cadence ?? 'default'} + onChange={(next) => { + if (cadence !== null && next !== cadence) { + void update(next) + } + }} + ariaLabel={title} + size="sm" + options={[ + { + value: 'default', + label: t('auto.components.settings.GitPane.prAutoRefreshDefault', 'Default'), + // Unknown until the remote host answers. + disabled: cadence === null + }, + { + value: 'reduced', + label: t('auto.components.settings.GitPane.prAutoRefreshReduced', 'Reduced'), + // Unknown until the remote host answers. + disabled: cadence === null + }, + { + value: 'minimal', + label: t('auto.components.settings.GitPane.prAutoRefreshMinimal', 'Minimal'), + // Unknown until the remote host answers. + disabled: cadence === null + }, + { + value: 'off', + label: t('auto.components.settings.GitPane.prAutoRefreshOff', 'Off'), + // Unknown until the remote host answers. + disabled: cadence === null + } + ]} + /> + } + /> + + ) +} diff --git a/src/renderer/src/components/settings/source-control/git-provider-api-budget-search.ts b/src/renderer/src/components/settings/source-control/git-provider-api-budget-search.ts index 3e260c34a51..6af6664dc29 100644 --- a/src/renderer/src/components/settings/source-control/git-provider-api-budget-search.ts +++ b/src/renderer/src/components/settings/source-control/git-provider-api-budget-search.ts @@ -1,8 +1,18 @@ import { translate } from '@/i18n/i18n' import { translateSearchKeyword } from '../search/settings-search-keywords' import { createLocalizedCatalog } from '@/i18n/localized-catalog' +import { + getPRAutoRefreshDescription, + getPRAutoRefreshTitle, + PR_AUTO_REFRESH_KEYWORDS +} from './pr-auto-refresh-search' export const getGitProviderApiBudgetSearchEntries = createLocalizedCatalog(() => [ + { + title: getPRAutoRefreshTitle(), + description: getPRAutoRefreshDescription(), + keywords: PR_AUTO_REFRESH_KEYWORDS + }, { title: translate('auto.components.settings.git.search.52d52b099d', 'GitHub API budget'), description: translate( diff --git a/src/renderer/src/components/settings/source-control/pr-auto-refresh-search.ts b/src/renderer/src/components/settings/source-control/pr-auto-refresh-search.ts new file mode 100644 index 00000000000..5ba5096d37a --- /dev/null +++ b/src/renderer/src/components/settings/source-control/pr-auto-refresh-search.ts @@ -0,0 +1,34 @@ +import { translate } from '@/i18n/i18n' +import type { Translate } from '@/i18n/use-translate' +import { matchesSettingsSearch } from '../search/settings-search' + +export const PR_AUTO_REFRESH_KEYWORDS = [ + 'pull request', + 'pr', + 'checks', + 'polling', + 'refresh interval', + 'background refresh', + 'github enterprise', + 'cpu', + 'gh' +] + +export function getPRAutoRefreshTitle(t: Translate = translate): string { + return t('auto.components.settings.GitPane.prAutoRefreshTitle', 'PR Auto-Refresh') +} + +export function getPRAutoRefreshDescription(t: Translate = translate): string { + return t( + 'auto.components.settings.GitPane.prAutoRefreshDescription', + 'How often this host re-reads pull request and checks status on a timer. Default refreshes the selected workspace every minute and other visible ones every 2 minutes; Reduced uses 5 and 10 minutes; Minimal uses 10 and 20 minutes; Off only refreshes when you select a workspace, push, return to the window, or refresh manually. On a server, this also limits how often connected clients can make it refresh.' + ) +} + +export function prAutoRefreshMatchesSearch(searchQuery: string, t?: Translate): boolean { + return matchesSettingsSearch(searchQuery, { + title: getPRAutoRefreshTitle(t), + description: getPRAutoRefreshDescription(t), + keywords: PR_AUTO_REFRESH_KEYWORDS + }) +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 972067fb0b8..8ec87508135 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -8904,7 +8904,14 @@ "f2765fbbf6": "GitLab API budget", "8cdbaf4b03": "Jira key casing", "fdbcd676b0": "GitHub API budget", - "074f7aa0d6": "Default compare base" + "074f7aa0d6": "Default compare base", + "prAutoRefreshUpdateFailed": "Could not update PR auto-refresh on this host.", + "prAutoRefreshDefault": "Default", + "prAutoRefreshReduced": "Reduced", + "prAutoRefreshMinimal": "Minimal", + "prAutoRefreshOff": "Off", + "prAutoRefreshTitle": "PR Auto-Refresh", + "prAutoRefreshDescription": "How often this host re-reads pull request and checks status on a timer. Default refreshes the selected workspace every minute and other visible ones every 2 minutes; Reduced uses 5 and 10 minutes; Minimal uses 10 and 20 minutes; Off only refreshes when you select a workspace, push, return to the window, or refresh manually. On a server, this also limits how often connected clients can make it refresh." }, "HiddenExperimentalGroup": { "7c4e18d2f6": "Arms the bold-glitch capture gestures on this machine: {{samplingShortcut}} starts a sampling burst; {{captureShortcut}} captures pane evidence to disk.", diff --git a/src/renderer/src/store/github/refresh/pr-auto-refresh-cadence-observer.test.ts b/src/renderer/src/store/github/refresh/pr-auto-refresh-cadence-observer.test.ts new file mode 100644 index 00000000000..f24a55b96b1 --- /dev/null +++ b/src/renderer/src/store/github/refresh/pr-auto-refresh-cadence-observer.test.ts @@ -0,0 +1,48 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type { GlobalSettings } from '../../../../../shared/global-settings-types' +import { + getPRAutoRefreshCadence, + setPRAutoRefreshCadence +} from '../../../../../shared/review-refresh-policy' +import { installPRAutoRefreshCadenceObserver } from './pr-auto-refresh-cadence-observer' + +type State = { settings: Pick | null } + +function fakeStore(initial: State) { + let state = initial + const listeners = new Set<(next: State, previous: State) => void>() + return { + getState: () => state, + subscribe: (listener: (next: State, previous: State) => void) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } + }, + set(next: State) { + const previous = state + state = next + for (const listener of listeners) { + listener(state, previous) + } + } + } +} + +describe('installPRAutoRefreshCadenceObserver', () => { + afterEach(() => { + setPRAutoRefreshCadence('default') + }) + + it('applies the loaded setting and follows later changes', () => { + const store = fakeStore({ settings: null }) + installPRAutoRefreshCadenceObserver(store) + expect(getPRAutoRefreshCadence()).toBe('default') + + store.set({ settings: { prAutoRefresh: 'minimal' } }) + expect(getPRAutoRefreshCadence()).toBe('minimal') + + store.set({ settings: { prAutoRefresh: 'off' } }) + expect(getPRAutoRefreshCadence()).toBe('off') + }) +}) diff --git a/src/renderer/src/store/github/refresh/pr-auto-refresh-cadence-observer.ts b/src/renderer/src/store/github/refresh/pr-auto-refresh-cadence-observer.ts new file mode 100644 index 00000000000..3ea6746fb66 --- /dev/null +++ b/src/renderer/src/store/github/refresh/pr-auto-refresh-cadence-observer.ts @@ -0,0 +1,20 @@ +import type { GlobalSettings } from '../../../../../shared/global-settings-types' +import { setPRAutoRefreshCadence } from '../../../../../shared/review-refresh-policy' + +type CadenceState = { settings: Pick | null } + +type CadenceStoreHost = { + getState: () => CadenceState + subscribe: (listener: (state: CadenceState, previous: CadenceState) => void) => () => void +} + +/** Every renderer review scheduler reads the shared cadence; set it before their own subscribers + * recompute targets on the same settings change. */ +export function installPRAutoRefreshCadenceObserver(store: CadenceStoreHost): void { + setPRAutoRefreshCadence(store.getState().settings?.prAutoRefresh) + store.subscribe((state, previous) => { + if (state.settings?.prAutoRefresh !== previous.settings?.prAutoRefresh) { + setPRAutoRefreshCadence(state.settings?.prAutoRefresh) + } + }) +} diff --git a/src/renderer/src/store/store-observer-installers.ts b/src/renderer/src/store/store-observer-installers.ts index df211cc0ac3..5c859d8b86c 100644 --- a/src/renderer/src/store/store-observer-installers.ts +++ b/src/renderer/src/store/store-observer-installers.ts @@ -1,5 +1,7 @@ import type { AppState } from './types' import { installTerminalParkingInputs } from './terminals/terminal-parking-input-transitions' +import { installPRAutoRefreshCadenceObserver } from './github/refresh/pr-auto-refresh-cadence-observer' +import { installPRAutoRefreshCadenceObserver } from './github/refresh/pr-auto-refresh-cadence-observer' export type StoreObserverHost = { getState: () => AppState @@ -10,5 +12,6 @@ export type StoreObserverHost = { export type StoreObserverInstaller = (store: StoreObserverHost) => void export const STORE_OBSERVER_INSTALLERS: readonly StoreObserverInstaller[] = [ - installTerminalParkingInputs + installTerminalParkingInputs, + installPRAutoRefreshCadenceObserver ] diff --git a/src/shared/default-global-settings.ts b/src/shared/default-global-settings.ts index fe3326a7219..cf02ad65cb5 100644 --- a/src/shared/default-global-settings.ts +++ b/src/shared/default-global-settings.ts @@ -172,6 +172,7 @@ export function buildDefaultSettings(args: { sourceControlViewMode: 'list', sourceControlGroupOrder: DEFAULT_SOURCE_CONTROL_GROUP_ORDER, sourceControlCompareAgainstUpstream: false, + prAutoRefresh: 'default', showTitlebarAppName: true, showTasksButton: true, showAutomationsButton: true, diff --git a/src/shared/global-settings-types.ts b/src/shared/global-settings-types.ts index 0051f482fe2..0327e28fe84 100644 --- a/src/shared/global-settings-types.ts +++ b/src/shared/global-settings-types.ts @@ -1,3 +1,4 @@ +import type { PRAutoRefreshCadence } from './review-refresh-policy' import type { AgentLaunchChoices } from './agent-launch/choices/agent-launch-choices' import type { TelemetrySettings } from './telemetry-settings-types' import type { BrowserProfileScope } from './browser/profiles/browser-profile-scope' @@ -243,6 +244,8 @@ export type GlobalSettings = GlobalSettingsBase & { sourceControlGroupOrder: SourceControlGroupOrder /** Compare base defaults to the branch upstream instead of the repo default; affects only the compare/diff view, not the PR/rebase target. Per-user. */ sourceControlCompareAgainstUpstream: boolean + /** Timed PR/review/checks refresh cadence on this host; absent means 'default'. */ + prAutoRefresh?: PRAutoRefreshCadence /** Whether to show the Orca app name in the titlebar. */ showTitlebarAppName: boolean /** Hides the Tasks sidebar button (also removes it from keyboard navigation). */ diff --git a/src/shared/review-refresh-policy.test.ts b/src/shared/review-refresh-policy.test.ts new file mode 100644 index 00000000000..c0c5db97747 --- /dev/null +++ b/src/shared/review-refresh-policy.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + getPRAutoRefreshCadence, + normalizePRAutoRefreshCadence, + reviewRefreshIntervalMs, + scaleReviewRefreshInterval, + setPRAutoRefreshCadence +} from './review-refresh-policy' + +describe('review refresh cadence', () => { + afterEach(() => { + setPRAutoRefreshCadence('default') + }) + + it('keeps today’s intervals by default', () => { + expect(reviewRefreshIntervalMs({ state: 'open', selected: true })).toBe(60_000) + expect(reviewRefreshIntervalMs({ state: 'open', selected: false })).toBe(120_000) + expect(reviewRefreshIntervalMs({ hasReview: false, selected: false })).toBe(15 * 60_000) + }) + + it('stretches every timed interval for reduced and minimal', () => { + expect(reviewRefreshIntervalMs({ state: 'open', selected: true }, 'reduced')).toBe(5 * 60_000) + expect(reviewRefreshIntervalMs({ state: 'open', selected: false }, 'reduced')).toBe(10 * 60_000) + expect(reviewRefreshIntervalMs({ state: 'open', selected: true }, 'minimal')).toBe(10 * 60_000) + expect(reviewRefreshIntervalMs({ state: 'open', selected: false }, 'minimal')).toBe(20 * 60_000) + }) + + it('turns every timed interval off, and keeps settled merged reviews stopped', () => { + expect(reviewRefreshIntervalMs({ state: 'open', selected: true }, 'off')).toBeNull() + expect(reviewRefreshIntervalMs({ hasReview: false, selected: true }, 'off')).toBeNull() + expect( + reviewRefreshIntervalMs({ state: 'merged', checksStatus: 'success' }, 'reduced') + ).toBeNull() + expect(scaleReviewRefreshInterval(null, 'minimal')).toBeNull() + }) + + it('follows the process cadence when no cadence is passed', () => { + setPRAutoRefreshCadence('minimal') + expect(getPRAutoRefreshCadence()).toBe('minimal') + expect(reviewRefreshIntervalMs({ state: 'open', selected: true })).toBe(10 * 60_000) + }) + + it('treats unknown or missing values as default', () => { + expect(normalizePRAutoRefreshCadence(undefined)).toBe('default') + expect(normalizePRAutoRefreshCadence('sometimes')).toBe('default') + setPRAutoRefreshCadence(42) + expect(getPRAutoRefreshCadence()).toBe('default') + }) +}) diff --git a/src/shared/review-refresh-policy.ts b/src/shared/review-refresh-policy.ts index 3905c261b1c..d245073d99a 100644 --- a/src/shared/review-refresh-policy.ts +++ b/src/shared/review-refresh-policy.ts @@ -4,7 +4,49 @@ import type { CheckStatus } from './github/pull-request-types' export const REVIEW_REFRESH_COOLDOWN_MS = 10_000 export const CLOSED_REVIEW_REFRESH_INTERVAL_MS = 15 * 60_000 -export function reviewRefreshIntervalMs(input: { +/** How often PR/review state refreshes on a timer. Selecting a worktree, pushing, returning to the + * window and manual refresh still read at once in every mode. */ +export const PR_AUTO_REFRESH_CADENCES = ['default', 'reduced', 'minimal', 'off'] as const +export type PRAutoRefreshCadence = (typeof PR_AUTO_REFRESH_CADENCES)[number] + +const CADENCE_INTERVAL_FACTOR: Record, number> = { + default: 1, + reduced: 5, + minimal: 10 +} + +function isPRAutoRefreshCadence(value: unknown): value is PRAutoRefreshCadence { + return PR_AUTO_REFRESH_CADENCES.some((cadence) => cadence === value) +} + +export function normalizePRAutoRefreshCadence(value: unknown): PRAutoRefreshCadence { + return isPRAutoRefreshCadence(value) ? value : 'default' +} + +// Why process-wide: every renderer/main caller of the policy must follow the same setting, and each +// process applies its own host's setting once rather than threading it through every scheduler. +let processCadence: PRAutoRefreshCadence = 'default' + +export function setPRAutoRefreshCadence(value: unknown): void { + processCadence = normalizePRAutoRefreshCadence(value) +} + +export function getPRAutoRefreshCadence(): PRAutoRefreshCadence { + return processCadence +} + +/** Stretch a timed interval by the cadence; null means no timed refresh. */ +export function scaleReviewRefreshInterval( + intervalMs: number | null, + cadence: PRAutoRefreshCadence = processCadence +): number | null { + if (intervalMs === null || cadence === 'off') { + return null + } + return intervalMs * CADENCE_INTERVAL_FACTOR[cadence] +} + +function defaultReviewRefreshIntervalMs(input: { state?: HostedReviewState | null checksStatus?: CheckStatus | null hasReview?: boolean | null @@ -22,3 +64,15 @@ export function reviewRefreshIntervalMs(input: { } return input.selected ? 60_000 : 120_000 } + +export function reviewRefreshIntervalMs( + input: { + state?: HostedReviewState | null + checksStatus?: CheckStatus | null + hasReview?: boolean | null + selected?: boolean + }, + cadence: PRAutoRefreshCadence = processCadence +): number | null { + return scaleReviewRefreshInterval(defaultReviewRefreshIntervalMs(input), cadence) +} diff --git a/src/shared/rpc-contract/client-settings-params.ts b/src/shared/rpc-contract/client-settings-params.ts index 69f038dd21e..97b3270891d 100644 --- a/src/shared/rpc-contract/client-settings-params.ts +++ b/src/shared/rpc-contract/client-settings-params.ts @@ -12,6 +12,7 @@ import { normalizePRBotAuthorOverrides } from '../source-control/review-comments import { WorktreeVisibilityDefaultsUpdate } from './worktree-visibility-defaults-params' import { WorkspaceCleanupRulesParam } from './workspace-cleanup-policy-params' import { AGENT_CHAT_PERMISSION_MODES } from '../agent-launch/permissions/agent-chat-permission-mode' +import { PR_AUTO_REFRESH_CADENCES } from '../review-refresh-policy' export const TaskProviderParam = z.custom(isTaskProvider, { message: 'Unknown task provider' @@ -132,7 +133,8 @@ export const SettingsUpdate = z .optional(), nativeChatAutoContinueAfterUsageLimit: z.boolean().optional(), nativeChatPermissionMode: z.enum(AGENT_CHAT_PERMISSION_MODES).optional(), - workspaceCleanupPolicy: WorkspaceCleanupRulesParam.optional() + workspaceCleanupPolicy: WorkspaceCleanupRulesParam.optional(), + prAutoRefresh: z.enum(PR_AUTO_REFRESH_CADENCES).optional() }) .strict() .default({})