diff --git a/.gitignore b/.gitignore index 92b3d28c4..eca545b53 100644 --- a/.gitignore +++ b/.gitignore @@ -72,7 +72,9 @@ design-docs/ # Local-only design/planning docs (not checked in) docs/*.md +docs/**/*.md !docs/README*.md +!docs/**/README*.md # Stably CLI (only docs/ are tracked) .stably/* diff --git a/src/main/github/client-issue-source.test.ts b/src/main/github/client-issue-source.test.ts index ddeeca3a0..e899b69ef 100644 --- a/src/main/github/client-issue-source.test.ts +++ b/src/main/github/client-issue-source.test.ts @@ -12,6 +12,8 @@ const { getIssueOwnerRepoMock, getOwnerRepoForRemoteMock, resolveIssueSourceMock, + rateLimitGuardMock, + noteRateLimitSpendMock, acquireMock, releaseMock } = vi.hoisted(() => ({ @@ -21,6 +23,8 @@ const { getIssueOwnerRepoMock: vi.fn(), getOwnerRepoForRemoteMock: vi.fn(), resolveIssueSourceMock: vi.fn(), + rateLimitGuardMock: vi.fn(() => ({ blocked: false })), + noteRateLimitSpendMock: vi.fn(), acquireMock: vi.fn(), releaseMock: vi.fn() })) @@ -41,6 +45,11 @@ vi.mock('./gh-utils', async () => { } }) +vi.mock('./rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: noteRateLimitSpendMock +})) + import { countWorkItems, getWorkItem, listWorkItems, _resetOwnerRepoCache } from './client' describe('GitHub issue source split', () => { @@ -51,6 +60,9 @@ describe('GitHub issue source split', () => { getIssueOwnerRepoMock.mockReset() getOwnerRepoForRemoteMock.mockReset() resolveIssueSourceMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() acquireMock.mockReset() releaseMock.mockReset() acquireMock.mockResolvedValue(undefined) diff --git a/src/main/github/client-pr-checks.test.ts b/src/main/github/client-pr-checks.test.ts index 1a3dadf95..669fa7503 100644 --- a/src/main/github/client-pr-checks.test.ts +++ b/src/main/github/client-pr-checks.test.ts @@ -6,6 +6,8 @@ const { getOwnerRepoMock, getIssueOwnerRepoMock, gitExecFileAsyncMock, + rateLimitGuardMock, + noteRateLimitSpendMock, acquireMock, releaseMock } = vi.hoisted(() => ({ @@ -14,6 +16,8 @@ const { getOwnerRepoMock: vi.fn(), getIssueOwnerRepoMock: vi.fn(), gitExecFileAsyncMock: vi.fn(), + rateLimitGuardMock: vi.fn(() => ({ blocked: false })), + noteRateLimitSpendMock: vi.fn(), acquireMock: vi.fn(), releaseMock: vi.fn() })) @@ -37,6 +41,11 @@ vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) +vi.mock('./rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: noteRateLimitSpendMock +})) + import { getPRChecks, _resetOwnerRepoCache } from './client' describe('getPRChecks', () => { @@ -46,6 +55,9 @@ describe('getPRChecks', () => { getOwnerRepoMock.mockReset() getIssueOwnerRepoMock.mockReset() gitExecFileAsyncMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() acquireMock.mockReset() releaseMock.mockReset() acquireMock.mockResolvedValue(undefined) diff --git a/src/main/github/client-work-items.test.ts b/src/main/github/client-work-items.test.ts index 128037ba9..f68e466db 100644 --- a/src/main/github/client-work-items.test.ts +++ b/src/main/github/client-work-items.test.ts @@ -11,6 +11,8 @@ const { getOwnerRepoForRemoteMock, resolveIssueSourceMock, gitExecFileAsyncMock, + rateLimitGuardMock, + noteRateLimitSpendMock, acquireMock, releaseMock } = vi.hoisted(() => ({ @@ -21,6 +23,8 @@ const { getOwnerRepoForRemoteMock: vi.fn(), resolveIssueSourceMock: vi.fn(), gitExecFileAsyncMock: vi.fn(), + rateLimitGuardMock: vi.fn(() => ({ blocked: false })), + noteRateLimitSpendMock: vi.fn(), acquireMock: vi.fn(), releaseMock: vi.fn() })) @@ -48,6 +52,11 @@ vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) +vi.mock('./rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: noteRateLimitSpendMock +})) + import { listWorkItems, _resetOwnerRepoCache } from './client' describe('listWorkItems', () => { @@ -59,6 +68,9 @@ describe('listWorkItems', () => { getOwnerRepoForRemoteMock.mockReset() resolveIssueSourceMock.mockReset() gitExecFileAsyncMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() acquireMock.mockReset() releaseMock.mockReset() acquireMock.mockResolvedValue(undefined) diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index 37b8241d5..e6e647e63 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -1,6 +1,10 @@ /* oxlint-disable max-lines -- Why: GitHub client fixtures cover local and SSH repo identity paths in one suite so mocked CLI behavior stays consistent. */ import { beforeEach, describe, expect, it, vi } from 'vitest' +type RateLimitGuardResult = + | { blocked: false } + | { blocked: true; remaining: number; limit: number; resetAt: number } + const { execFileAsyncMock, ghExecFileAsyncMock, @@ -9,6 +13,8 @@ const { getOwnerRepoForRemoteMock, getRemoteUrlForRepoMock, gitExecFileAsyncMock, + rateLimitGuardMock, + noteRateLimitSpendMock, ghRepoExecOptionsMock, githubRepoContextMock, acquireMock, @@ -21,6 +27,8 @@ const { getOwnerRepoForRemoteMock: vi.fn(), getRemoteUrlForRepoMock: vi.fn(), gitExecFileAsyncMock: vi.fn(), + rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })), + noteRateLimitSpendMock: vi.fn(), ghRepoExecOptionsMock: vi.fn((context) => context.connectionId ? {} : { cwd: context.repoPath } ), @@ -59,7 +67,18 @@ vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) -import { getPRForBranch, getPullRequestPushTarget, _resetOwnerRepoCache } from './client' +vi.mock('./rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: noteRateLimitSpendMock +})) + +import { + getPRComments, + getPRForBranch, + getPullRequestPushTarget, + resolveReviewThread, + _resetOwnerRepoCache +} from './client' describe('getPRForBranch', () => { beforeEach(() => { @@ -70,6 +89,9 @@ describe('getPRForBranch', () => { getOwnerRepoForRemoteMock.mockReset() getRemoteUrlForRepoMock.mockReset() gitExecFileAsyncMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() ghRepoExecOptionsMock.mockClear() githubRepoContextMock.mockClear() acquireMock.mockReset() @@ -422,3 +444,67 @@ describe('getPRForBranch', () => { expect(gitExecFileAsyncMock).not.toHaveBeenCalled() }) }) + +describe('GitHub GraphQL rate-limit guard', () => { + beforeEach(() => { + execFileAsyncMock.mockReset() + ghExecFileAsyncMock.mockReset() + getOwnerRepoMock.mockReset() + getIssueOwnerRepoMock.mockReset() + getOwnerRepoForRemoteMock.mockReset() + getRemoteUrlForRepoMock.mockReset() + gitExecFileAsyncMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() + acquireMock.mockReset() + releaseMock.mockReset() + acquireMock.mockResolvedValue(undefined) + _resetOwnerRepoCache() + }) + + it('skips PR review-thread GraphQL fetch while preserving REST comments', async () => { + rateLimitGuardMock.mockReturnValue({ + blocked: true, + remaining: 4, + limit: 5000, + resetAt: 1_800_000_000 + }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + id: 10, + user: { login: 'octo', avatar_url: 'https://avatar', type: 'User' }, + body: 'top-level', + created_at: '2026-04-01T00:00:00Z', + html_url: 'https://github.com/acme/widgets/pull/7#issuecomment-10' + } + ]) + }) + .mockResolvedValueOnce({ stdout: '[]' }) + + const comments = await getPRComments('/repo-root', 7) + + expect(comments).toHaveLength(1) + expect(comments[0].body).toBe('top-level') + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) + expect(ghExecFileAsyncMock.mock.calls.some((call) => call[0][1] === 'graphql')).toBe(false) + expect(noteRateLimitSpendMock).not.toHaveBeenCalled() + }) + + it('blocks review-thread resolve mutations before spawning gh when GraphQL is low', async () => { + rateLimitGuardMock.mockReturnValue({ + blocked: true, + remaining: 4, + limit: 5000, + resetAt: 1_800_000_000 + }) + + await expect(resolveReviewThread('/repo-root', 'thread-1', true)).resolves.toBe(false) + + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + expect(noteRateLimitSpendMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 6787553a2..4dcf66bf4 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -53,6 +53,7 @@ import { deriveCheckStatus } from './mappers' import { mapGraphQLReactionGroups, type GitHubGraphQLReactionGroup } from './comment-reactions' +import { noteRateLimitSpend, rateLimitGuard } from './rate-limit' const ORCA_REPO = 'stablyai/orca' @@ -1358,12 +1359,13 @@ export async function getPRComments( // permissions, transient network error) doesn't blank out all comments. // Each source is parsed independently; failed sources contribute zero // comments instead of aborting the entire fetch. - const [issueResult, threadsResult, reviewsResult] = await Promise.allSettled([ - ghExecFileAsync( - ['api', ...cacheArgs, `${base}/issues/${prNumber}/comments?per_page=100`], - ghOptions - ), - ghExecFileAsync( + const reviewThreadsGuard = rateLimitGuard('graphql') + let reviewThreadsFetch: Promise<{ stdout: string; stderr: string } | null> + if (reviewThreadsGuard.blocked) { + reviewThreadsFetch = Promise.resolve(null) + } else { + noteRateLimitSpend('graphql') + reviewThreadsFetch = ghExecFileAsync( [ 'api', 'graphql', @@ -1377,7 +1379,14 @@ export async function getPRComments( `pr=${prNumber}` ], ghOptions + ) + } + const [issueResult, threadsResult, reviewsResult] = await Promise.allSettled([ + ghExecFileAsync( + ['api', ...cacheArgs, `${base}/issues/${prNumber}/comments?per_page=100`], + ghOptions ), + reviewThreadsFetch, // Why: review summaries (approve, request changes, general comments) live // under pulls/{n}/reviews, not under issue comments or review threads. // Without this, a reviewer who submits "LGTM" without inline threads @@ -1442,7 +1451,7 @@ export async function getPRComments( reactionGroups?: GitHubGraphQLReactionGroup[] | null } const reviewComments: PRComment[] = [] - if (threadsResult.status === 'fulfilled') { + if (threadsResult.status === 'fulfilled' && threadsResult.value) { const threadsData = JSON.parse(threadsResult.value.stdout) as { data: { repository: { @@ -1494,7 +1503,9 @@ export async function getPRComments( } } } else { - console.warn('Failed to fetch review threads:', threadsResult.reason) + if (threadsResult.status === 'rejected') { + console.warn('Failed to fetch review threads:', threadsResult.reason) + } } // Parse review summaries (REST) — only include reviews with a body, @@ -1572,8 +1583,16 @@ export async function resolveReviewThread( const mutation = resolve ? 'resolveReviewThread' : 'unresolveReviewThread' const query = `mutation($threadId: ID!) { ${mutation}(input: { threadId: $threadId }) { thread { isResolved } } }` const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId)) + const guard = rateLimitGuard('graphql') + if (guard.blocked) { + console.warn( + `${mutation} skipped: GitHub GraphQL rate limit nearly exhausted (${guard.remaining}/${guard.limit})` + ) + return false + } await acquire() try { + noteRateLimitSpend('graphql') await ghExecFileAsync( ['api', 'graphql', '-f', `query=${query}`, '-f', `threadId=${threadId}`], ghOptions diff --git a/src/main/github/work-item-details.test.ts b/src/main/github/work-item-details.test.ts index c8a8c3fa4..30517f8c4 100644 --- a/src/main/github/work-item-details.test.ts +++ b/src/main/github/work-item-details.test.ts @@ -1,5 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +type RateLimitGuardResult = + | { blocked: false } + | { blocked: true; remaining: number; limit: number; resetAt: number } + const { ghExecFileAsyncMock, getOwnerRepoMock, @@ -7,6 +11,8 @@ const { getWorkItemMock, getPRChecksMock, getPRCommentsMock, + rateLimitGuardMock, + noteRateLimitSpendMock, ghRepoExecOptionsMock, githubRepoContextMock, acquireMock, @@ -18,6 +24,8 @@ const { getWorkItemMock: vi.fn(), getPRChecksMock: vi.fn(), getPRCommentsMock: vi.fn(), + rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })), + noteRateLimitSpendMock: vi.fn(), ghRepoExecOptionsMock: vi.fn((context) => context.connectionId ? {} : { cwd: context.repoPath } ), @@ -45,6 +53,11 @@ vi.mock('./client', () => ({ getPRComments: getPRCommentsMock })) +vi.mock('./rate-limit', () => ({ + rateLimitGuard: rateLimitGuardMock, + noteRateLimitSpend: noteRateLimitSpendMock +})) + import { getWorkItemDetails } from './work-item-details' describe('getWorkItemDetails', () => { @@ -55,6 +68,9 @@ describe('getWorkItemDetails', () => { getWorkItemMock.mockReset() getPRChecksMock.mockReset() getPRCommentsMock.mockReset() + rateLimitGuardMock.mockReset() + rateLimitGuardMock.mockReturnValue({ blocked: false }) + noteRateLimitSpendMock.mockReset() ghRepoExecOptionsMock.mockClear() githubRepoContextMock.mockClear() acquireMock.mockReset() @@ -158,6 +174,38 @@ describe('getWorkItemDetails', () => { expect(details?.body).toBe('Issue body') }) + it('skips optional GraphQL issue detail calls when the cached GraphQL budget is low', async () => { + rateLimitGuardMock.mockReturnValue({ + blocked: true, + remaining: 3, + limit: 5000, + resetAt: 1_800_000_000 + }) + getWorkItemMock.mockResolvedValueOnce({ + id: 'issue:923', + type: 'issue', + number: 923, + title: 'Use upstream issues', + state: 'open', + url: 'https://github.com/stablyai/orca/issues/923', + labels: [], + updatedAt: '2026-04-01T00:00:00Z', + author: 'octocat' + }) + getIssueOwnerRepoMock.mockResolvedValue({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ stdout: JSON.stringify({ body: 'Issue body', assignees: [] }) }) + .mockResolvedValueOnce({ stdout: '[]' }) + + const details = await getWorkItemDetails('/repo-root', 923, 'issue') + + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) + expect(ghExecFileAsyncMock.mock.calls.some((call) => call[0][1] === 'graphql')).toBe(false) + expect(noteRateLimitSpendMock).not.toHaveBeenCalled() + expect(details?.body).toBe('Issue body') + expect(details?.participants).toEqual([]) + }) + it('uses SSH connection context for issue details without local cwd', async () => { getWorkItemMock.mockResolvedValueOnce({ id: 'issue:923', diff --git a/src/main/github/work-item-details.ts b/src/main/github/work-item-details.ts index 7d7ab66d7..d417cbe45 100644 --- a/src/main/github/work-item-details.ts +++ b/src/main/github/work-item-details.ts @@ -19,6 +19,7 @@ import { githubRepoContext } from './gh-utils' import { getWorkItem, getPRChecks, getPRComments } from './client' +import { noteRateLimitSpend, rateLimitGuard } from './rate-limit' // Why: a PR "changed file" listing returned by the REST endpoint is paginated // at 100 per page; we cap at a reasonable total so a massive PR cannot starve @@ -112,7 +113,11 @@ async function getIssueDetailsViaGraphQL( if (!ownerRepo) { return null } + if (rateLimitGuard('graphql').blocked) { + return null + } try { + noteRateLimitSpend('graphql') const { stdout } = await ghExecFileAsync( [ 'api', @@ -441,7 +446,11 @@ async function getWorkItemParticipants( if (!ownerRepo) { return [] } + if (rateLimitGuard('graphql').blocked) { + return [] + } try { + noteRateLimitSpend('graphql') const { stdout } = await ghExecFileAsync( [ 'api', @@ -498,6 +507,9 @@ async function getGitHubUsersByLogin( if (uniqueLogins.length === 0) { return [] } + if (rateLimitGuard('graphql').blocked) { + return [] + } const fields = uniqueLogins .map( (login, index) => @@ -505,6 +517,7 @@ async function getGitHubUsersByLogin( ) .join('\n') try { + noteRateLimitSpend('graphql') const { stdout } = await ghExecFileAsync( ['api', 'graphql', '-f', `query=query { ${fields} }`], ghRepoExecOptions(githubRepoContext(repoPath, connectionId)) diff --git a/src/renderer/src/components/github/GitHubRateLimitPill.tsx b/src/renderer/src/components/github/GitHubRateLimitPill.tsx index 714ad1510..532094cbc 100644 --- a/src/renderer/src/components/github/GitHubRateLimitPill.tsx +++ b/src/renderer/src/components/github/GitHubRateLimitPill.tsx @@ -1,228 +1,6 @@ -/** - * Compact GitHub API rate-limit indicator for the TaskPage header. - * - * Why: TaskPage fans out GitHub requests on every preset click, search - * debounce, and repo-selection change (×N selected repos × 2 halves for - * count). Users with large repo selections or heavy usage can exhaust the - * search API's 30/min budget in a few clicks without knowing. - * - * Display policy: stay invisible during normal use. Only render when a - * bucket drops to <25% remaining (warn) or <10% (crit). At healthy levels - * the budget is not actionable information and surfacing it just trains - * users to ignore the pill (or worry needlessly about ambiguous numbers - * like "30/30"). The probe still refreshes while the page is active so we - * can show the pill the moment something becomes actionable. - * - * This is an indicator, not a throttle — we deliberately don't block the - * user from making requests when counts are low. Blocking would hurt the - * hot path (well under quota) more than it helps the cold path (user can - * also just wait for the reset, which is always < 1 hour). - */ -import React, { useCallback, useEffect, useRef, useState } from 'react' -import { Gauge } from 'lucide-react' -import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { cn } from '@/lib/utils' -import { useAppStore } from '@/store' -import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' -import type { GetRateLimitResult, GitHubRateLimitSnapshot } from '../../../../shared/types' - -// Why: 60s client-side cadence. Aligns with typical user action rhythm -// (click → paint → click) without polling faster than GitHub's counters -// move for typical request volumes. The server-side 30s cache absorbs -// any faster-than-this polling. -const REFRESH_INTERVAL_MS = 60_000 - -type BucketKey = 'core' | 'search' | 'graphql' - -type BucketMeta = { - key: BucketKey - label: string - description: string -} - -const BUCKETS: BucketMeta[] = [ - { key: 'core', label: 'REST', description: 'REST API (5000/hr)' }, - { key: 'search', label: 'Search', description: 'Search API (30/min)' }, - { key: 'graphql', label: 'GraphQL', description: 'GraphQL (5000 pts/hr)' } -] - -function formatReset(resetAt: number): string { - // Why: resetAt is seconds, Date.now() is ms. Compute the gap in seconds so - // "<1min" / "in 45s" / "in 12min" reads naturally without cognitive math. - const deltaSec = Math.max(0, resetAt - Math.floor(Date.now() / 1000)) - if (deltaSec < 60) { - return `${deltaSec}s` - } - const mins = Math.round(deltaSec / 60) - return `${mins}m` -} - -function toneFor(remaining: number, limit: number): 'ok' | 'warn' | 'crit' { - if (limit <= 0) { - return 'ok' - } - const pct = remaining / limit - if (pct < 0.1) { - return 'crit' - } - if (pct < 0.25) { - return 'warn' - } - return 'ok' -} - -function worstTone(snapshot: GitHubRateLimitSnapshot): 'ok' | 'warn' | 'crit' { - const tones = BUCKETS.map((b) => toneFor(snapshot[b.key].remaining, snapshot[b.key].limit)) - if (tones.includes('crit')) { - return 'crit' - } - if (tones.includes('warn')) { - return 'warn' - } - return 'ok' -} - -function tightestBucket(snapshot: GitHubRateLimitSnapshot): BucketMeta { - // Why: "N left" in the pill shows the bucket closest to exhaustion by - // ratio — that's the actionable one. Absolute remaining would always - // favor GraphQL (5000 pts) over Search (30) even when Search is 1 away. - let worst = BUCKETS[0] - let worstPct = 1 - for (const b of BUCKETS) { - const { remaining, limit } = snapshot[b.key] - const pct = limit > 0 ? remaining / limit : 1 - if (pct < worstPct) { - worstPct = pct - worst = b - } - } - return worst -} +import React from 'react' +import { GitHubRateLimitCompact } from './github-rate-limit-display' export default function GitHubRateLimitPill(): React.JSX.Element | null { - const [snapshot, setSnapshot] = useState(null) - const [hasError, setHasError] = useState(false) - const settings = useAppStore((s) => s.settings) - // Why: StrictMode double-invokes effects in dev. Without this guard the - // first mount fires two rate_limit IPCs back-to-back — benign (exempt - // endpoint, cached) but noisy in logs. Tracks the latest in-flight token - // so stale responses from an unmounted instance are dropped. - const latestToken = useRef(0) - - const fetchSnapshot = useCallback( - async (force: boolean): Promise => { - const token = ++latestToken.current - try { - const target = getActiveRuntimeTarget(settings) - const params = force ? { force: true } : undefined - const res = - target.kind === 'environment' - ? await callRuntimeRpc(target, 'github.rateLimit', params ?? {}, { - timeoutMs: 30_000 - }) - : ((await window.api.gh.rateLimit(params)) as GetRateLimitResult | undefined) - if (token !== latestToken.current) { - return - } - if (res?.ok) { - setSnapshot(res.snapshot) - setHasError(false) - } else { - setHasError(true) - } - } catch { - if (token !== latestToken.current) { - return - } - setHasError(true) - } - }, - [settings] - ) - - useEffect(() => { - const fetchIfVisible = (): void => { - if (document.visibilityState === 'visible' && document.hasFocus()) { - void fetchSnapshot(false) - } - } - void fetchSnapshot(false) - // Why: rate-limit probes are only useful while the TaskPage is visible. - // Skipping hidden-window ticks avoids spending gh/API work just to keep an - // invisible pill current; focus refreshes restore freshness before use. - const handle = window.setInterval(fetchIfVisible, REFRESH_INTERVAL_MS) - window.addEventListener('focus', fetchIfVisible) - document.addEventListener('visibilitychange', fetchIfVisible) - return () => { - window.clearInterval(handle) - window.removeEventListener('focus', fetchIfVisible) - document.removeEventListener('visibilitychange', fetchIfVisible) - } - }, [fetchSnapshot]) - - // Why: silently render nothing on error or before first load. The pill is - // informational — surfacing a red error here would mislead users into - // thinking their actual gh workflow is broken when only the probe failed. - if (!snapshot || hasError) { - return null - } - - const tone = worstTone(snapshot) - // Why: hide the pill entirely at healthy levels. It only earns screen - // real estate when the user is actually approaching a wall — otherwise - // "30/30" is ambiguous noise that users can't act on. - if (tone === 'ok') { - return null - } - const tight = tightestBucket(snapshot) - const tightBucket = snapshot[tight.key] - - return ( - - - - - -
GitHub API budget
-
- {BUCKETS.map((b) => { - const v = snapshot[b.key] - const t = toneFor(v.remaining, v.limit) - return ( -
- {b.description} - - {v.remaining} of {v.limit} left · resets in {formatReset(v.resetAt)} - -
- ) - })} -
-
Click to refresh
-
-
- ) + return } diff --git a/src/renderer/src/components/github/github-rate-limit-display.tsx b/src/renderer/src/components/github/github-rate-limit-display.tsx new file mode 100644 index 000000000..52fa0d66e --- /dev/null +++ b/src/renderer/src/components/github/github-rate-limit-display.tsx @@ -0,0 +1,267 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react' +import { Gauge, RefreshCw } from 'lucide-react' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import { useAppStore } from '@/store' +import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' +import type { GetRateLimitResult, GitHubRateLimitSnapshot } from '../../../../shared/types' + +const REFRESH_INTERVAL_MS = 60_000 + +type BucketKey = 'core' | 'search' | 'graphql' + +type BucketMeta = { + key: BucketKey + label: string + description: string +} + +const BUCKETS: BucketMeta[] = [ + { key: 'core', label: 'REST', description: 'REST API' }, + { key: 'search', label: 'Search', description: 'Search API' }, + { key: 'graphql', label: 'GraphQL', description: 'GraphQL API' } +] + +export function formatGitHubRateLimitReset(resetAt: number): string { + const deltaSec = Math.max(0, resetAt - Math.floor(Date.now() / 1000)) + if (deltaSec < 60) { + return `${deltaSec}s` + } + const mins = Math.round(deltaSec / 60) + return `${mins}m` +} + +export function toneForGitHubBucket(remaining: number, limit: number): 'ok' | 'warn' | 'crit' { + if (limit <= 0) { + return 'ok' + } + const pct = remaining / limit + if (pct < 0.1) { + return 'crit' + } + if (pct < 0.25) { + return 'warn' + } + return 'ok' +} + +function worstGitHubRateLimitTone(snapshot: GitHubRateLimitSnapshot): 'ok' | 'warn' | 'crit' { + const tones = BUCKETS.map((b) => + toneForGitHubBucket(snapshot[b.key].remaining, snapshot[b.key].limit) + ) + if (tones.includes('crit')) { + return 'crit' + } + if (tones.includes('warn')) { + return 'warn' + } + return 'ok' +} + +function tightestGitHubBucket(snapshot: GitHubRateLimitSnapshot): BucketMeta { + let worst = BUCKETS[0] + let worstPct = 1 + for (const b of BUCKETS) { + const { remaining, limit } = snapshot[b.key] + const pct = limit > 0 ? remaining / limit : 1 + if (pct < worstPct) { + worstPct = pct + worst = b + } + } + return worst +} + +export function useGitHubRateLimitSnapshot(options?: { autoRefresh?: boolean }): { + snapshot: GitHubRateLimitSnapshot | null + hasError: boolean + isFetching: boolean + refresh: (force?: boolean) => Promise +} { + const [snapshot, setSnapshot] = useState(null) + const [hasError, setHasError] = useState(false) + const [isFetching, setIsFetching] = useState(false) + const settings = useAppStore((s) => s.settings) + const latestToken = useRef(0) + const autoRefresh = options?.autoRefresh ?? true + + const refresh = useCallback( + async (force = false): Promise => { + const token = ++latestToken.current + setIsFetching(true) + try { + const target = getActiveRuntimeTarget(settings) + const params = force ? { force: true } : undefined + const res = + target.kind === 'environment' + ? await callRuntimeRpc(target, 'github.rateLimit', params ?? {}, { + timeoutMs: 30_000 + }) + : ((await window.api.gh.rateLimit(params)) as GetRateLimitResult | undefined) + if (token !== latestToken.current) { + return + } + if (res?.ok) { + setSnapshot(res.snapshot) + setHasError(false) + } else { + setHasError(true) + } + } catch { + if (token === latestToken.current) { + setHasError(true) + } + } finally { + if (token === latestToken.current) { + setIsFetching(false) + } + } + }, + [settings] + ) + + useEffect(() => { + if (!autoRefresh) { + return + } + const fetchIfVisible = (): void => { + if (document.visibilityState === 'visible' && document.hasFocus()) { + void refresh(false) + } + } + void refresh(false) + const handle = window.setInterval(fetchIfVisible, REFRESH_INTERVAL_MS) + window.addEventListener('focus', fetchIfVisible) + document.addEventListener('visibilitychange', fetchIfVisible) + return () => { + window.clearInterval(handle) + window.removeEventListener('focus', fetchIfVisible) + document.removeEventListener('visibilitychange', fetchIfVisible) + } + }, [autoRefresh, refresh]) + + return { snapshot, hasError, isFetching, refresh } +} + +function GitHubRateLimitRows({ + snapshot +}: { + snapshot: GitHubRateLimitSnapshot +}): React.JSX.Element { + return ( +
+ {BUCKETS.map((b) => { + const v = snapshot[b.key] + const tone = toneForGitHubBucket(v.remaining, v.limit) + return ( +
+ {b.description} + + {v.remaining} of {v.limit} left · resets in {formatGitHubRateLimitReset(v.resetAt)} + +
+ ) + })} +
+ ) +} + +export function GitHubRateLimitCompact({ + className, + hideHealthy = true, + label = 'GitHub API budget', + tooltipSide = 'top' +}: { + className?: string + hideHealthy?: boolean + label?: string + tooltipSide?: 'top' | 'right' | 'bottom' | 'left' +}): React.JSX.Element | null { + const { snapshot, hasError, refresh } = useGitHubRateLimitSnapshot() + if (!snapshot || hasError) { + return null + } + + const tone = worstGitHubRateLimitTone(snapshot) + if (hideHealthy && tone === 'ok') { + return null + } + const tight = tightestGitHubBucket(snapshot) + const tightBucket = snapshot[tight.key] + + return ( + + + + + +
{label}
+
+ +
+
Click to refresh
+
+
+ ) +} + +export function GitHubRateLimitPanel({ className }: { className?: string }): React.JSX.Element { + const { snapshot, hasError, isFetching, refresh } = useGitHubRateLimitSnapshot() + + return ( +
+
+
+
+ + GitHub API Budget +
+

+ Orca uses REST, Search, and GraphQL through the GitHub CLI. +

+
+ +
+ {hasError ? ( +
GitHub API budget is unavailable.
+ ) : snapshot ? ( + + ) : ( +
Loading GitHub API budget…
+ )} +
+ ) +} diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index a550e2256..e22a31cb6 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -17,6 +17,7 @@ import { } from './checks-panel-content' import { ENTRY_REFRESH_GRACE_MS, shouldEntryRefresh } from './checks-entry-refresh' import type { PRInfo, PRCheckDetail, PRComment } from '../../../../shared/types' +import { toast } from 'sonner' export default function ChecksPanel(): React.JSX.Element { const activeWorktree = useActiveWorktree() @@ -425,6 +426,8 @@ export default function ChecksPanel(): React.JSX.Element { setComments((prev) => prev.map((c) => (c.threadId === threadId ? { ...c, isResolved: resolve } : c)) ) + } else { + toast.error('Could not update review thread. Check the GitHub API budget.') } } ) diff --git a/src/renderer/src/components/right-sidebar/index.tsx b/src/renderer/src/components/right-sidebar/index.tsx index a5a698218..f277f827f 100644 --- a/src/renderer/src/components/right-sidebar/index.tsx +++ b/src/renderer/src/components/right-sidebar/index.tsx @@ -22,6 +22,7 @@ import SourceControl from './SourceControl' import SearchPanel from './Search' import ChecksPanel from './ChecksPanel' import PortsPanel from './PortsPanel' +import { GitHubRateLimitCompact } from '@/components/github/github-rate-limit-display' const MIN_WIDTH = 220 // Why: long file names (e.g. construction drawing sheets, multi-part document @@ -213,6 +214,8 @@ function RightSidebarInner(): React.JSX.Element { const effectiveTab = visibleItems.some((item) => item.id === rightSidebarTab) ? rightSidebarTab : visibleItems[0].id + const showGitHubBudgetInPanel = + !isFolder && (effectiveTab === 'source-control' || effectiveTab === 'checks') const activityBarSideWidth = activityBarPosition === 'side' ? ACTIVITY_BAR_SIDE_WIDTH : 0 const maxWidth = useWindowAwareMaxWidth() @@ -333,6 +336,13 @@ function RightSidebarInner(): React.JSX.Element { )} + {showGitHubBudgetInPanel ? ( + + ) : null} + {panelContent} {/* Resize handle on LEFT side */} diff --git a/src/renderer/src/components/settings/GitPane.tsx b/src/renderer/src/components/settings/GitPane.tsx index 6810ef47c..e7c4d924b 100644 --- a/src/renderer/src/components/settings/GitPane.tsx +++ b/src/renderer/src/components/settings/GitPane.tsx @@ -5,6 +5,7 @@ import { useAppStore } from '../../store' import { GIT_PANE_SEARCH_ENTRIES } from './git-search' import { SearchableSetting } from './SearchableSetting' import { matchesSettingsSearch } from './settings-search' +import { GitHubRateLimitPanel } from '../github/github-rate-limit-display' export { GIT_PANE_SEARCH_ENTRIES } @@ -110,6 +111,21 @@ export function GitPane({ ) : null, + matchesSettingsSearch(searchQuery, { + title: 'GitHub API Budget', + description: 'Current GitHub CLI REST, Search, and GraphQL rate limits.', + keywords: ['github', 'gh', 'graphql', 'rate limit', 'api budget'] + }) ? ( + + + + ) : null, matchesSettingsSearch(searchQuery, { title: 'Orca Attribution', description: 'Add Orca attribution to commits, PRs, and issues.', diff --git a/src/renderer/src/components/settings/git-search.ts b/src/renderer/src/components/settings/git-search.ts index cb66e34ee..e26ee40bb 100644 --- a/src/renderer/src/components/settings/git-search.ts +++ b/src/renderer/src/components/settings/git-search.ts @@ -11,6 +11,11 @@ export const GIT_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [ description: 'Optionally fast-forward local main or master when creating worktrees.', keywords: ['main', 'master', 'origin/main', 'git diff', 'base ref', 'worktree'] }, + { + title: 'GitHub API Budget', + description: 'Current GitHub CLI REST, Search, and GraphQL rate limits.', + keywords: ['github', 'gh', 'graphql', 'rate limit', 'api budget'] + }, { title: 'Orca Attribution', description: 'Add Orca attribution to commits, PRs, and issues.', diff --git a/src/renderer/src/components/status-bar/StatusBar.tsx b/src/renderer/src/components/status-bar/StatusBar.tsx index 418292e0e..c18c1f33e 100644 --- a/src/renderer/src/components/status-bar/StatusBar.tsx +++ b/src/renderer/src/components/status-bar/StatusBar.tsx @@ -38,6 +38,7 @@ import { isStatusBarItemAvailable } from './status-bar-agent-gating' import { PetStatusSegment } from './PetStatusSegment' import { TOGGLE_FLOATING_TERMINAL_EVENT } from '@/lib/floating-terminal' import { FloatingTerminalIconContextMenu } from '@/components/floating-terminal/FloatingTerminalIconContextMenu' +import { GitHubRateLimitCompact } from '@/components/github/github-rate-limit-display' type StatusBarProps = { floatingTerminalOpen: boolean @@ -855,6 +856,7 @@ function StatusBarInner({ floatingTerminalOpen }: StatusBarProps): React.JSX.Ele }} >
+ {showClaude && } {showCodex && } {showGemini && (