diff --git a/src/main/github/client-issue-source.test.ts b/src/main/github/client-issue-source.test.ts index 449449e1d..d1e3f9618 100644 --- a/src/main/github/client-issue-source.test.ts +++ b/src/main/github/client-issue-source.test.ts @@ -223,6 +223,59 @@ describe('GitHub issue source split', () => { expect(item?.type).toBe('pr') }) + it('surfaces a 403 from upstream issues through the listWorkItems envelope', async () => { + // Why: parent design doc §3 / acceptance criterion 2 — the IPC envelope + // must carry a classified error for the failing side so the renderer can + // swap the empty-state for a retryable banner. `sources` must stay + // populated so the banner copy can name the repo that failed. + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) + ghExecFileAsyncMock + .mockRejectedValueOnce(new Error('HTTP 403: Resource not accessible by integration')) + .mockResolvedValueOnce({ stdout: '[]' }) + + const result = await listWorkItems('/repo-root', 10) + + expect(result.items).toEqual([]) + expect(result.sources).toEqual({ + issues: { owner: 'stablyai', repo: 'orca' }, + prs: { owner: 'fork', repo: 'orca' } + }) + expect(result.errors?.issues?.type).toBe('permission_denied') + }) + + it('returns partial results when upstream issues fail but origin PRs succeed', async () => { + // Why: parent design doc §2 partial-failure rule — a failing source must + // not zero out the succeeding source. The UI renders origin PRs with a + // banner above the list, not an empty state. Ensures the IPC shape + // carries both the successful items and the error for the failing side. + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'fork', repo: 'orca' }) + ghExecFileAsyncMock + .mockRejectedValueOnce(new Error('HTTP 403: Resource not accessible by integration')) + .mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + number: 42, + title: 'Fork PR', + state: 'open', + html_url: 'https://github.com/fork/orca/pull/42', + labels: [], + updated_at: '2026-03-31T00:00:00Z', + user: { login: 'octocat' }, + draft: false, + head: { ref: 'feature' }, + base: { ref: 'main' } + } + ]) + }) + + const result = await listWorkItems('/repo-root', 10) + + expect(result.items.map((i) => i.id)).toEqual(['pr:42']) + expect(result.errors?.issues?.type).toBe('permission_denied') + }) + it('raw number lookup does not fall through on transient upstream errors', async () => { // Why: with issue source split, a non-404 upstream failure must not silently // route to origin's PR #N — that would return an unrelated item. diff --git a/src/main/github/client-work-items.test.ts b/src/main/github/client-work-items.test.ts index 72ddfb494..b098ceade 100644 --- a/src/main/github/client-work-items.test.ts +++ b/src/main/github/client-work-items.test.ts @@ -80,7 +80,11 @@ describe('listWorkItems', () => { } ]) }) - const items = await listWorkItems('/repo-root', 10, 'assignee:@me') + const { items, sources } = await listWorkItems('/repo-root', 10, 'assignee:@me') + expect(sources).toEqual({ + issues: { owner: 'acme', repo: 'widgets' }, + prs: { owner: 'acme', repo: 'widgets' } + }) expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 1, [ @@ -160,7 +164,7 @@ describe('listWorkItems', () => { } ]) }) - const items = await listWorkItems('/repo-root', 10, 'is:pr is:draft') + const { items } = await listWorkItems('/repo-root', 10, 'is:pr is:draft') expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) expect(ghExecFileAsyncMock).toHaveBeenCalledWith( [ @@ -246,7 +250,7 @@ describe('listWorkItems', () => { } ]) }) - const items = await listWorkItems('/repo-root', 10, 'is:open') + const { items } = await listWorkItems('/repo-root', 10, 'is:open') expect(ghExecFileAsyncMock).toHaveBeenCalledWith( [ 'issue', diff --git a/src/main/github/client.ts b/src/main/github/client.ts index bbd8a1f91..794c83f0e 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -1,6 +1,8 @@ /* eslint-disable max-lines -- Why: co-locating all GitHub client functions keeps the concurrency acquire/release pattern and error handling consistent across operations. */ import type { + ClassifiedError, + ListWorkItemsResult, PRInfo, PRMergeableState, PRCheckDetail, @@ -21,6 +23,7 @@ import { getOwnerRepo, getIssueOwnerRepo, classifyGhError, + classifyListIssuesError, type OwnerRepo } from './gh-utils' export { _resetOwnerRepoCache } from './gh-utils' @@ -341,14 +344,27 @@ function buildWorkItemListArgs(args: { return out } +// Why: internal shape shared by listRecentWorkItems / listQueriedWorkItems so +// listWorkItems can lift per-side errors into the IPC envelope. The issue-side +// error is the specific new class of silent wrongness introduced by #1076 — +// PR-side errors existed before and are explicitly out of scope for this +// feature per the parent design doc §6. +type PartialWorkItemsResult = { + items: MainWorkItem[] + issuesError?: ClassifiedError +} + async function listRecentWorkItems( repoPath: string, issueOwnerRepo: OwnerRepo | null, prOwnerRepo: OwnerRepo | null, limit: number -): Promise { +): Promise { if (issueOwnerRepo || prOwnerRepo) { - const [issuesResult, prsResult] = await Promise.all([ + // Why: allSettled so a 403 on upstream issues doesn't zero out the origin + // PR half — the UI renders partial results plus a banner for the failing + // side, matching the parent design doc's partial-failure rule (§2). + const [issuesSettled, prsSettled] = await Promise.allSettled([ issueOwnerRepo ? ghExecFileAsync( [ @@ -397,20 +413,61 @@ async function listRecentWorkItems( ) ]) - const issues = (JSON.parse(issuesResult.stdout) as Record[]) - // Why: the GitHub issues REST endpoint also returns pull requests with a - // `pull_request` marker. The new-workspace task picker needs distinct - // issue vs PR buckets, so drop PR-shaped issue rows here before merging. - .filter((item) => !('pull_request' in item)) - .map(mapIssueWorkItem) + let issues: MainWorkItem[] = [] + let issuesError: ClassifiedError | undefined + if (issuesSettled.status === 'fulfilled') { + issues = (JSON.parse(issuesSettled.value.stdout) as Record[]) + // Why: the GitHub issues REST endpoint also returns pull requests with a + // `pull_request` marker. The new-workspace task picker needs distinct + // issue vs PR buckets, so drop PR-shaped issue rows here before merging. + .filter((item) => !('pull_request' in item)) + .map(mapIssueWorkItem) + } else { + const stderr = + issuesSettled.reason instanceof Error + ? issuesSettled.reason.message + : String(issuesSettled.reason) + issuesError = classifyListIssuesError(stderr) + } - const prs = (JSON.parse(prsResult.stdout) as Record[]).map((item) => - mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null) - ) + let prs: MainWorkItem[] = [] + if (prsSettled.status === 'fulfilled') { + prs = (JSON.parse(prsSettled.value.stdout) as Record[]).map((item) => + mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null) + ) + } else { + // Why: PR-side failures must preserve the pre-diff behavior of + // Promise.all by re-throwing so the rejection propagates up through + // listWorkItems to the renderer's cross-repo aggregator (which counts + // the repo as failed). This feature is scoped to the issue-side silent + // wrongness from #1076; PR errors must not be silently swallowed here. + // Why: if the issue side ALSO failed, the classified issuesError would + // otherwise be silently dropped when we throw the PR reason. Log it so + // debugging both-sides-failed scenarios (e.g. 403 on both endpoints) + // isn't blind to the issue-side classification. + if (issuesError) { + console.warn( + 'listRecentWorkItems: both issue and PR sides failed; issuesError was classified:', + issuesError.type, + issuesError.message + ) + } + throw prsSettled.reason + } - return sortWorkItemsByUpdatedAt([...issues, ...prs]).slice(0, limit) + return { + items: sortWorkItemsByUpdatedAt([...issues, ...prs]).slice(0, limit), + issuesError + } } + // Why: the fallback path (non-GitHub remote — neither issueOwnerRepo nor + // prOwnerRepo resolved) intentionally stays on Promise.all rather than the + // Promise.allSettled + per-side classification used above. There are no + // `sources` to surface on this branch and nothing for the partial-failure + // banner to render, so a single-side failure here means the whole call is + // effectively unusable for the feature — reject-all matches reality. If + // non-GitHub remotes ever grow source metadata, revisit this symmetry. const [issuesResult, prsResult] = await Promise.all([ ghExecFileAsync( [ @@ -447,7 +504,9 @@ async function listRecentWorkItems( mapPullRequestWorkItem(item, null) ) - return sortWorkItemsByUpdatedAt([...issues, ...prs]).slice(0, limit) + return { + items: sortWorkItemsByUpdatedAt([...issues, ...prs]).slice(0, limit) + } } async function listQueriedWorkItems( @@ -457,55 +516,62 @@ async function listQueriedWorkItems( query: ParsedTaskQuery, limit: number, before?: string -): Promise { - const fetchers: Promise[] = [] +): Promise { const issueScope = query.scope !== 'pr' const prScope = query.scope !== 'issue' - if (issueScope) { - fetchers.push( - (async () => { - const args = buildWorkItemListArgs({ - kind: 'issue', - ownerRepo: issueOwnerRepo, - limit, - query, - before - }) - try { - const { stdout } = await ghExecFileAsync(args, { cwd: repoPath }) - return (JSON.parse(stdout) as Record[]).map(mapIssueWorkItem) - } catch { - return [] - } - })() - ) - } + // Why: run the issue and PR fetches in parallel but surface the + // issue-side error separately so the IPC envelope can carry it up. PR-side + // failures retain the prior swallow-and-log behavior per parent doc §6. + const issueFetch = (async (): Promise => { + if (!issueScope) { + return { items: [] } + } + const args = buildWorkItemListArgs({ + kind: 'issue', + ownerRepo: issueOwnerRepo, + limit, + query, + before + }) + try { + const { stdout } = await ghExecFileAsync(args, { cwd: repoPath }) + return { + items: (JSON.parse(stdout) as Record[]).map(mapIssueWorkItem) + } + } catch (err) { + const stderr = err instanceof Error ? err.message : String(err) + return { items: [], issuesError: classifyListIssuesError(stderr) } + } + })() - if (prScope) { - fetchers.push( - (async () => { - const args = buildWorkItemListArgs({ - kind: 'pr', - ownerRepo: prOwnerRepo, - limit, - query, - before - }) - try { - const { stdout } = await ghExecFileAsync(args, { cwd: repoPath }) - return (JSON.parse(stdout) as Record[]).map((item) => - mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null) - ) - } catch { - return [] - } - })() - ) - } + const prFetch = (async (): Promise => { + if (!prScope) { + return [] + } + const args = buildWorkItemListArgs({ + kind: 'pr', + ownerRepo: prOwnerRepo, + limit, + query, + before + }) + try { + const { stdout } = await ghExecFileAsync(args, { cwd: repoPath }) + return (JSON.parse(stdout) as Record[]).map((item) => + mapPullRequestWorkItem(item, prOwnerRepo?.owner ?? null) + ) + } catch (err) { + console.warn('listQueriedWorkItems PRs partial failure:', err) + return [] + } + })() - const results = await Promise.all(fetchers) - return sortWorkItemsByUpdatedAt(results.flat()).slice(0, limit) + const [issueResult, prItems] = await Promise.all([issueFetch, prFetch]) + return { + items: sortWorkItemsByUpdatedAt([...issueResult.items, ...prItems]).slice(0, limit), + issuesError: issueResult.issuesError + } } export async function listWorkItems( @@ -513,7 +579,7 @@ export async function listWorkItems( limit = 24, query?: string, before?: string -): Promise { +): Promise> { const [issueOwnerRepo, prOwnerRepo] = await Promise.all([ getIssueOwnerRepo(repoPath), getOwnerRepo(repoPath) @@ -525,19 +591,23 @@ export async function listWorkItems( // count this repo as failed and surface the partial-failure banner. A // catch-all here would make an auth/network failure indistinguishable from // an empty result and silently under-report per-repo failures. - if (!trimmedQuery) { - return await listRecentWorkItems(repoPath, issueOwnerRepo, prOwnerRepo, limit) - } + const partial = !trimmedQuery + ? await listRecentWorkItems(repoPath, issueOwnerRepo, prOwnerRepo, limit) + : await listQueriedWorkItems( + repoPath, + issueOwnerRepo, + prOwnerRepo, + parseTaskQuery(trimmedQuery), + limit, + before + ) - const parsedQuery = parseTaskQuery(trimmedQuery) - return await listQueriedWorkItems( - repoPath, - issueOwnerRepo, - prOwnerRepo, - parsedQuery, - limit, - before - ) + const errors = partial.issuesError ? { issues: partial.issuesError } : undefined + return { + items: partial.items, + sources: { issues: issueOwnerRepo, prs: prOwnerRepo }, + ...(errors ? { errors } : {}) + } } finally { release() } diff --git a/src/main/github/gh-utils.ts b/src/main/github/gh-utils.ts index 095ead81a..e60cd026d 100644 --- a/src/main/github/gh-utils.ts +++ b/src/main/github/gh-utils.ts @@ -1,7 +1,7 @@ import { execFile } from 'child_process' import { promisify } from 'util' import { gitExecFileAsync, ghExecFileAsync } from '../git/runner' -import type { ClassifiedError } from '../../shared/types' +import type { ClassifiedError, GitHubOwnerRepo } from '../../shared/types' // Why: legacy generic execFile wrapper — only used by callers that don't need // WSL-aware routing (e.g. non-repo-scoped gh commands). Repo-scoped callers @@ -46,7 +46,12 @@ export function classifyGhError(stderr: string): ClassifiedError { message: "You don't have permission to edit this issue. Check your GitHub token scopes." } } - if (s.includes('http 404') || s.includes('could not resolve')) { + // Why: the full gh message is "Could not resolve to a Repository with the + // name ...". Matching the substring 'could not resolve' alone would also + // capture DNS failures like "could not resolve host: api.github.com" and + // misclassify them as not_found. Anchor on the 'repository' qualifier so + // DNS errors fall through to the network_error branch below. + if (s.includes('http 404') || s.includes('could not resolve to a repository')) { return { type: 'not_found', message: 'Issue not found — it may have been deleted.' } } if (s.includes('http 422') || s.includes('validation failed')) { @@ -58,14 +63,45 @@ export function classifyGhError(stderr: string): ClassifiedError { message: 'GitHub rate limit hit. Try again in a few minutes.' } } - if (s.includes('timeout') || s.includes('no such host') || s.includes('network')) { + if ( + s.includes('timeout') || + s.includes('no such host') || + s.includes('network') || + s.includes('could not resolve host') + ) { return { type: 'network_error', message: 'Network error — check your connection.' } } return { type: 'unknown', message: `Failed to update issue: ${stderr.trim()}` } } +// Why: classifyGhError's copy is phrased for edit/update operations, but +// `listIssues` is a read op and the renderer interpolates err.message verbatim +// into a read-context banner. Rewrite the message for read contexts while +// keeping the typed classification so callers/telemetry are unaffected. +export function classifyListIssuesError(stderr: string): ClassifiedError { + const c = classifyGhError(stderr) + const trimmed = stderr.trim() + // Why: provide an explicit entry for every `ClassifiedError['type']` value + // (even when the copy matches the generic fallback) so the read-context + // rewrite is complete and any newly added error type surfaces as a + // TypeScript error rather than silently falling through to edit-phrased copy. + const readMessages: Record = { + permission_denied: + "You don't have permission to read issues for this repository. Check your GitHub token scopes.", + not_found: 'Repository not found.', + validation_error: `Invalid request — ${trimmed}`, + rate_limited: 'GitHub rate limit hit. Try again in a few minutes.', + network_error: 'Network error — check your connection.', + unknown: `Failed to load issues: ${trimmed}` + } + return { type: c.type, message: readMessages[c.type] } +} + // ── Owner/repo resolution for gh api --cache ────────────────────────── -export type OwnerRepo = { owner: string; repo: string } +// Why: alias the shared shape so `src/shared/types.ts#GitHubOwnerRepo` remains +// the single source of truth while main-side call sites can keep using the +// short local name `OwnerRepo`. +export type OwnerRepo = GitHubOwnerRepo const ownerRepoCache = new Map() diff --git a/src/main/github/issues.test.ts b/src/main/github/issues.test.ts index ab3640495..d82e7933b 100644 --- a/src/main/github/issues.test.ts +++ b/src/main/github/issues.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as GhUtils from './gh-utils' const { ghExecFileAsyncMock, getIssueOwnerRepoMock, acquireMock, releaseMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn(), @@ -7,12 +8,16 @@ const { ghExecFileAsyncMock, getIssueOwnerRepoMock, acquireMock, releaseMock } = releaseMock: vi.fn() })) -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: ghExecFileAsyncMock, - getIssueOwnerRepo: getIssueOwnerRepoMock, - acquire: acquireMock, - release: releaseMock -})) +vi.mock('./gh-utils', async () => { + const actual = await vi.importActual('./gh-utils') + return { + ...actual, + ghExecFileAsync: ghExecFileAsyncMock, + getIssueOwnerRepo: getIssueOwnerRepoMock, + acquire: acquireMock, + release: releaseMock + } +}) import { createIssue, getIssue, listIssues } from './issues' @@ -48,7 +53,7 @@ describe('issue source operations', () => { getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }) - await listIssues('/repo-root', 5) + await expect(listIssues('/repo-root', 5)).resolves.toEqual({ items: [] }) expect(ghExecFileAsyncMock).toHaveBeenCalledWith( [ @@ -61,6 +66,21 @@ describe('issue source operations', () => { ) }) + it('surfaces a classified permission_denied error instead of collapsing to empty', async () => { + // Why: parent design doc §3 — a 403 on a private upstream must not + // masquerade as "No issues". The envelope carries an error the UI can + // render as a banner with retry, not a silent empty list. + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock.mockRejectedValueOnce( + new Error('HTTP 403: Resource not accessible by integration') + ) + + const result = await listIssues('/repo-root', 5) + + expect(result.items).toEqual([]) + expect(result.error?.type).toBe('permission_denied') + }) + it('creates issues in the issue owner/repo', async () => { getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) ghExecFileAsyncMock.mockResolvedValueOnce({ diff --git a/src/main/github/issues.ts b/src/main/github/issues.ts index 739498b7b..46e79296d 100644 --- a/src/main/github/issues.ts +++ b/src/main/github/issues.ts @@ -1,4 +1,5 @@ import type { + ClassifiedError, GitHubAssignableUser, GitHubCommentResult, GitHubIssueUpdate, @@ -6,7 +7,13 @@ import type { PRComment } from '../../shared/types' import { mapIssueInfo } from './mappers' -import { ghExecFileAsync, acquire, release, getIssueOwnerRepo, classifyGhError } from './gh-utils' +// prettier-ignore +import { ghExecFileAsync, acquire, release, getIssueOwnerRepo, classifyGhError, classifyListIssuesError } from './gh-utils' + +// Why: distinguishes a successful-empty listing from a failed fetch. The +// previous `catch { return [] }` conflated a 403 on a private upstream with an +// empty backlog. Callers decide how to surface `error`. +export type IssueListResult = { items: IssueInfo[]; error?: ClassifiedError } /** * Get a single issue by number. @@ -46,8 +53,15 @@ export async function getIssue(repoPath: string, issueNumber: number): Promise { +export async function listIssues(repoPath: string, limit = 20): Promise { const ownerRepo = await getIssueOwnerRepo(repoPath) await acquire() try { @@ -61,8 +75,16 @@ export async function listIssues(repoPath: string, limit = 20): Promise mapIssueInfo(d as Parameters[0])) + const data = JSON.parse(stdout) as Record[] + // Why: the GitHub REST `/repos/{owner}/{repo}/issues` endpoint returns + // pull requests alongside issues (PRs carry a `pull_request` key). + // Strip them here so `listIssues` only returns true issues, matching the + // filter applied in `listRecentWorkItems` (src/main/github/client.ts). + return { + items: data + .filter((d) => !('pull_request' in d)) + .map((d) => mapIssueInfo(d as Parameters[0])) + } } // Fallback for non-GitHub remotes const { stdout } = await ghExecFileAsync( @@ -70,9 +92,10 @@ export async function listIssues(repoPath: string, limit = 20): Promise mapIssueInfo(d as Parameters[0])) - } catch { - return [] + return { items: data.map((d) => mapIssueInfo(d as Parameters[0])) } + } catch (err) { + const stderr = err instanceof Error ? err.message : String(err) + return { items: [], error: classifyListIssuesError(stderr) } } finally { release() } diff --git a/src/main/ipc/github.test.ts b/src/main/ipc/github.test.ts index 3b27c64f7..5b762d46f 100644 --- a/src/main/ipc/github.test.ts +++ b/src/main/ipc/github.test.ts @@ -85,17 +85,46 @@ describe('registerGitHubHandlers', () => { expect(getIssueMock).not.toHaveBeenCalled() }) - it('forwards listIssues for registered repositories', async () => { - listIssuesMock.mockResolvedValue([]) + it('forwards listIssues for registered repositories and unwraps items', async () => { + listIssuesMock.mockResolvedValue({ items: [] }) registerGitHubHandlers(store as never, stats as never) - await handlers['gh:listIssues'](null, { + const result = await handlers['gh:listIssues'](null, { repoPath: '/workspace/repo', limit: 5 }) expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5) + expect(result).toEqual([]) + }) + + it('drops the error field from listIssues envelope at the IPC boundary', async () => { + // Why: src/main/ipc/github.ts intentionally unwraps the { items, error? } + // envelope to just `items` to preserve the pre-feature-1 + // `Promise` contract for `gh:listIssues`. Feature 1's UI + // consumes the richer envelope through `gh:listWorkItems` instead. This + // test locks in that intentional drop so a future change that starts + // propagating the error through this channel (or that throws when an + // error is present) is caught. + listIssuesMock.mockResolvedValue({ + items: [], + error: { + type: 'permission_denied', + message: + "You don't have permission to read issues for this repository. Check your GitHub token scopes." + } + }) + + registerGitHubHandlers(store as never, stats as never) + + const result = await handlers['gh:listIssues'](null, { + repoPath: '/workspace/repo', + limit: 5 + }) + + expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5) + expect(result).toEqual([]) }) it('forwards the authenticated viewer lookup', async () => { diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts index cf379f4f8..a75e1b66e 100644 --- a/src/main/ipc/github.ts +++ b/src/main/ipc/github.ts @@ -67,7 +67,10 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi ipcMain.handle('gh:listIssues', (_event, args: { repoPath: string; limit?: number }) => { const repo = assertRegisteredRepo(args.repoPath, store) - return listIssues(repo.path, args.limit) + // Why: listIssues now returns { items, error? }. The IPC handler unwraps to + // the items array for the existing contract; feature 1's UI consumes the + // richer envelope through `gh:listWorkItems` instead. + return listIssues(repo.path, args.limit).then((r) => r.items) }) ipcMain.handle( diff --git a/src/main/rate-limits/service.ts b/src/main/rate-limits/service.ts index fc63a49e3..ef827a820 100644 --- a/src/main/rate-limits/service.ts +++ b/src/main/rate-limits/service.ts @@ -37,7 +37,12 @@ type InternalRateLimitState = { } export class RateLimitService { - private state: InternalRateLimitState = { claude: null, codex: null, gemini: null, opencodeGo: null } + private state: InternalRateLimitState = { + claude: null, + codex: null, + gemini: null, + opencodeGo: null + } private pollInterval: number = DEFAULT_POLL_MS private timer: ReturnType | null = null private lastFetchAt = 0 diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index e1e8fb6ca..0c5af49e5 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -25,6 +25,7 @@ import type { GitHubWorkItem, GitHubWorkItemDetails, GitHubViewer, + ListWorkItemsResult, IssueInfo, LinearViewer, LinearConnectionStatus, @@ -429,7 +430,7 @@ export type PreloadApi = { limit?: number query?: string before?: string - }) => Promise[]> + }) => Promise>> prChecks: (args: { repoPath: string prNumber: number diff --git a/src/preload/index.ts b/src/preload/index.ts index d5b8f36e9..1b6b9ae8f 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -12,7 +12,9 @@ import type { FsChangedPayload, GitHubAssignableUser, GitHubCommentResult, + GitHubWorkItem, GhosttyImportPreview, + ListWorkItemsResult, MemorySnapshot, NotificationDispatchResult, SearchResult @@ -433,7 +435,8 @@ const api = { limit?: number query?: string before?: string - }): Promise => ipcRenderer.invoke('gh:listWorkItems', args), + }): Promise>> => + ipcRenderer.invoke('gh:listWorkItems', args), prChecks: (args: { repoPath: string diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index 78460aa57..ea8f3dfe7 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -62,8 +62,9 @@ import { } from '@/lib/pr-comment-groups' import { useAppStore } from '@/store' import { useRepoLabels, useRepoAssignees, useImmediateMutation } from '@/hooks/useIssueMetadata' - +import IssueSourceIndicator, { sameGitHubOwnerRepo } from '@/components/github/IssueSourceIndicator' import type { + GitHubOwnerRepo, GitHubPRFile, GitHubPRFileContents, GitHubWorkItem, @@ -72,6 +73,29 @@ import type { GitHubReaction, PRComment } from '../../../shared/types' +import { PER_REPO_FETCH_LIMIT } from '../../../shared/work-items' + +// Why: the GH item dialog can be opened from any work-item list surface and +// doesn't have the full owner/repo context the list's cache entry carries. +// Parsing the canonical `https://github.com/{owner}/{repo}/...` URL is the +// simplest reliable source — the URL is already present on every work item +// and survives the main-process → IPC boundary. Non-GitHub hosts return null, +// which matches the indicator's suppression rule. +function parseOwnerRepoFromItemUrl(url: string): GitHubOwnerRepo | null { + try { + const parsed = new URL(url) + if (parsed.hostname !== 'github.com') { + return null + } + const segments = parsed.pathname.split('/').filter(Boolean) + if (segments.length < 2) { + return null + } + return { owner: segments[0], repo: segments[1] } + } catch { + return null + } +} // Why: the editor's DiffViewer loads Monaco, which is heavy and should not be // pulled into the dialog's bundle until the user actually opens the Files tab. @@ -2061,6 +2085,68 @@ function GHCommentComposer({ ) } +// Why: the dialog doesn't carry the resolved PR-source slug the Tasks view's +// list cache carries, so we reach into workItemsCache to recover it. We scope +// the lookup to the dialog's own `repoPath` via the public +// `getWorkItemsAnySourcesForRepo` selector keyed by (repoPath, limit) — +// scanning the whole cache risks picking a sibling repo's PR-source when two +// selected repos share the same issue-source (e.g. two forks of the same +// upstream), producing an incorrect "Issues from" chip or incorrectly +// suppressing it. The selector keys primarily on the first-page entry +// (PER_REPO_FETCH_LIMIT, empty query) because sources are repo-level and +// don't vary by search query. If that slot is empty — e.g. the Tasks view is +// filtering by a typed query and only populated the query-keyed entry — the +// selector falls back to scanning cache entries prefixed by this same +// `repoPath::` and reuses sources from the first match. Falling back to hiding +// the indicator when we still can't find a match matches the parent design +// doc §1 rule: hide when either side is unknown rather than guessing. +function WorkItemIssueSourceIndicator({ + url, + repoPath +}: { + url: string + repoPath: string | null +}): React.JSX.Element | null { + // Why: subscribe to a single store-side selector that returns the resolved + // sources for this repo — either the primary `(repoPath, PER_REPO_FETCH_LIMIT, '')` + // entry or the first sibling cache entry that has sources (the Tasks view may + // write cache entries keyed by a user-typed search query, so the primary slot + // can be empty even when sources are known). Sources are repo-level + // (query-independent), so any sibling entry is safe. When the primary slot + // is populated its reference is stable across unrelated cache writes; when + // the fallback path is used a sibling cache rewrite may produce a new + // `sources` object and trigger a harmless extra render. That's cheap — the + // indicator is small and the cache rewrite rate is bounded by user-initiated + // refresh/search actions. + const sources = useAppStore((s) => + s.getWorkItemsAnySourcesForRepo(repoPath ?? '', PER_REPO_FETCH_LIMIT) + ) + const issues = useMemo(() => { + const fromUrl = parseOwnerRepoFromItemUrl(url) + if (!fromUrl) { + return null + } + // Prefer the cache's resolved issue-source when it matches the URL-derived + // slug — the cache entry is authoritative (canonicalized by the main + // process) while the URL parse is a best-effort fallback. + const cachedIssues = sources?.issues + if (cachedIssues && sameGitHubOwnerRepo(cachedIssues, fromUrl)) { + return cachedIssues + } + return fromUrl + }, [url, sources]) + const prs = sources?.prs ?? null + + if (!issues || !prs || sameGitHubOwnerRepo(issues, prs)) { + return null + } + return ( +
+ +
+ ) +} + export default function GitHubItemDialog({ workItem, repoPath, @@ -2260,6 +2346,9 @@ export default function GitHubItemDialog({ )} + {workItem.type === 'issue' && ( + + )}
diff --git a/src/renderer/src/components/TaskPage.tsx b/src/renderer/src/components/TaskPage.tsx index 441413ec9..a2555244c 100644 --- a/src/renderer/src/components/TaskPage.tsx +++ b/src/renderer/src/components/TaskPage.tsx @@ -24,6 +24,11 @@ import { toast } from 'sonner' import { useAppStore } from '@/store' import { useRepoMap } from '@/store/selectors' +import { + workItemsCacheKey, + type WorkItemsCacheSources, + type WorkItemsCacheError +} from '@/store/slices/github' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { @@ -52,6 +57,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover import RepoMultiCombobox from '@/components/ui/repo-multi-combobox' import TeamMultiCombobox from '@/components/ui/team-multi-combobox' import RepoDotLabel from '@/components/repo/RepoDotLabel' +import IssueSourceIndicator, { sameGitHubOwnerRepo } from '@/components/github/IssueSourceIndicator' import { stripRepoQualifiers } from '../../../shared/task-query' import GitHubItemDialog from '@/components/GitHubItemDialog' import LinearItemDrawer from '@/components/LinearItemDrawer' @@ -66,7 +72,12 @@ import type { LinkedWorkItemSummary } from '@/lib/new-workspace' import { launchWorkItemDirect } from '@/lib/launch-work-item-direct' import { isGitRepoKind } from '../../../shared/repo-kind' import { useTeamStates } from '@/hooks/useIssueMetadata' -import type { GitHubWorkItem, LinearIssue, TaskViewPresetId } from '../../../shared/types' +import type { + GitHubOwnerRepo, + GitHubWorkItem, + LinearIssue, + TaskViewPresetId +} from '../../../shared/types' import { shouldSuppressEnterSubmit } from '@/lib/new-workspace-enter-guard' type TaskSource = 'github' | 'linear' @@ -604,6 +615,26 @@ function PaginationBar({ ) } +// Why: feature 1 — shape of the per-repo view derived from `workItemsCache`, +// used by both the indicator render and the `hasDivergentSources` guard. +// Hoisted to module scope so the type isn't re-parsed per render and so the +// guard below can narrow it without a forward reference. +type RepoSourceState = { + repoId: string + repoPath: string + sources: WorkItemsCacheSources | null + error: WorkItemsCacheError | null +} + +// Why: type-guard predicate used to filter `perRepoSourceState` down to rows +// whose issue-source and PR-source slugs differ. Hoisted to module scope so +// the predicate isn't re-allocated on every TaskPage render. +const hasDivergentSources = ( + s: RepoSourceState +): s is RepoSourceState & { + sources: { issues: GitHubOwnerRepo; prs: GitHubOwnerRepo } +} => !!s.sources?.issues && !!s.sources.prs && !sameGitHubOwnerRepo(s.sources.issues, s.sources.prs) + export default function TaskPage(): React.JSX.Element { const settings = useAppStore((s) => s.settings) const pageData = useAppStore((s) => s.taskPageData) @@ -780,7 +811,10 @@ export default function TaskPage(): React.JSX.Element { // this dialog for a read/review surface. The dialog's "Use" button routes // through the same direct-launch flow as the row-level "Use" CTA so // behavior is consistent regardless of entry point. - const [dialogWorkItemId, setDialogWorkItemId] = useState(null) + const [dialogWorkItemKey, setDialogWorkItemKey] = useState<{ + id: string + repoId: string + } | null>(null) const [dialogWorkItemFallback, setDialogWorkItemFallback] = useState(null) const workItemsCache = useAppStore((s) => s.workItemsCache) @@ -790,23 +824,92 @@ export default function TaskPage(): React.JSX.Element { // Why: derive the dialog's work item from the store cache so it reflects // optimistic patches (e.g. table-cell status toggle). Falls back to the // snapshot stored at click time for newly-created stubs not yet in the cache. + // Disambiguates by repoId so issues with the same number fetched from + // multiple repos (e.g. fork + non-fork, both routed through the same + // upstream) resolve to the clicked row's repo, not the first one scanned. const dialogWorkItem = useMemo(() => { - if (!dialogWorkItemId) { + if (!dialogWorkItemKey) { return null } for (const entry of Object.values(workItemsCache)) { - const found = entry?.data?.find((wi) => wi.id === dialogWorkItemId) + const found = entry?.data?.find( + (wi) => wi.id === dialogWorkItemKey.id && wi.repoId === dialogWorkItemKey.repoId + ) if (found) { return found } } return dialogWorkItemFallback - }, [dialogWorkItemId, workItemsCache, dialogWorkItemFallback]) + }, [dialogWorkItemKey, workItemsCache, dialogWorkItemFallback]) const setDialogWorkItem = useCallback((item: GitHubWorkItem | null) => { - setDialogWorkItemId(item?.id ?? null) + setDialogWorkItemKey(item ? { id: item.id, repoId: item.repoId } : null) setDialogWorkItemFallback(item) }, []) + + // Why: feature 1 — render the "Issues from {owner}/{repo}" indicator per + // selected repo whose issue-source and PR-source slugs differ, and surface + // a per-repo retryable banner when the issue-side fetch failed. Both derive + // from the same `workItemsCache` entry the list already consumes, so no + // extra IPC round-trip is needed. The `RepoSourceState` shape itself lives + // at module scope so the type isn't re-parsed per render. + // Why: subscribe to `workItemsCache` directly (already bound above) and + // memoize the derived per-repo view. The alternative — + // `useAppStore(useShallow(...))` — doesn't help here because the selector + // would allocate a wrapper object per repo and zustand's shallow compare + // uses `Object.is` on each element, so every cache mutation would still + // force a re-render. Memoizing over stable inputs re-derives only when the + // cache, selection, or query changes. The dialog's `WorkItemIssueSourceIndicator` + // subscribes to a single `getWorkItemsAnySourcesForRepo(repoPath, limit)` + // selector that returns a stable `WorkItemsCacheSources | null` reference, + // so it doesn't need `useShallow` — unrelated cache writes don't force a + // re-render because the selector result's reference identity is preserved + // between unchanged entries. + const perRepoSourceState = useMemo(() => { + const appliedQ = stripRepoQualifiers(appliedTaskSearch.trim()) + return selectedRepos.map((r) => { + const key = workItemsCacheKey(r.path, PER_REPO_FETCH_LIMIT, appliedQ) + const entry = workItemsCache[key] + return { + repoId: r.id, + repoPath: r.path, + sources: entry?.sources ?? null, + error: entry?.error ?? null + } + }) + }, [selectedRepos, appliedTaskSearch, workItemsCache]) + + // Why: on a partial-failure retry the cache still holds successful-side + // data, so `tasksLoading` (which is gated on `anyUncached`) never flips + // true and the Retry button would otherwise give no feedback. Track + // retry-in-flight per repo (keyed by `repoPath`) so that clicking Retry + // on one banner only flips that banner's button into its "Retrying…" + // state — other still-failing banners stay in their "Retry" state rather + // than misleadingly flipping in lockstep. The fetch effect clears the set + // when the nonce-driven refresh settles. + const [retryingRepoPaths, setRetryingRepoPaths] = useState>(() => new Set()) + + const handleRetryIssuesFetch = useCallback( + (repoPath: string) => { + const repo = selectedRepos.find((r) => r.path === repoPath) + if (!repo) { + return + } + // Why: bumping the shared refresh nonce reuses the Tasks list's + // single fetch path — nonce changes are treated as force=true so + // retry doesn't silently dedupe onto a still-failing in-flight request. + // The nonce bump refreshes ALL selected repos, but the Retrying… + // state is scoped to the clicked repo so other banners stay in their + // "Retry" state rather than misleadingly flipping to "Retrying…". + setRetryingRepoPaths((prev) => { + const next = new Set(prev) + next.add(repoPath) + return next + }) + setTaskRefreshNonce((n) => n + 1) + }, + [selectedRepos] + ) const [newIssueOpen, setNewIssueOpen] = useState(false) const [newIssueTitle, setNewIssueTitle] = useState('') const [newIssueBody, setNewIssueBody] = useState('') @@ -1030,10 +1133,17 @@ export default function TaskPage(): React.JSX.Element { }, [taskSearchInput]) useEffect(() => { + // Why: both early-return branches must clear `retryingRepoPaths` — if the + // user clicks Retry and then switches `taskSource` away from 'github' (or + // somehow ends up with zero repos selected) before the fetch dispatches, + // neither the `.then` nor the `.catch` below will fire, and the Retry + // button would stay stuck in its disabled/Retrying state indefinitely. if (taskSource !== 'github') { + setRetryingRepoPaths(new Set()) return } if (selectedRepos.length === 0) { + setRetryingRepoPaths(new Set()) return } // unreachable — multi-combobox forbids empty @@ -1078,10 +1188,32 @@ export default function TaskPage(): React.JSX.Element { lastFetchedNonceRef.current = taskRefreshNonce const repoArgs = selectedRepos.map((r) => ({ repoId: r.id, path: r.path })) + // Why: snapshot the retrying paths at effect-dispatch so overlapping + // retries don't clear each other's pending state. An earlier cancelled + // effect settling after a newer retry starts would otherwise wipe the + // newer retry's repo from the set. Clearing only the paths captured + // when this effect dispatched preserves later additions. + const dispatchedRetryPaths = retryingRepoPaths void fetchWorkItemsAcrossRepos(repoArgs, PER_REPO_FETCH_LIMIT, CROSS_REPO_DISPLAY_LIMIT, q, { force: forceRefresh && taskRefreshNonce > 0 }) .then(({ items, failedCount: failed }) => { + // Why: clear only the repos this effect was responsible for + // retrying (the snapshot captured at dispatch time). Overlapping + // retries — a second click while a prior fetch is still in flight + // — must not clear the newer repo from the set, so we can't just + // reset the whole set here. The early-return branches above reset + // the whole set because those branches won't dispatch a fetch. + setRetryingRepoPaths((prev) => { + if (dispatchedRetryPaths.size === 0) { + return prev + } + const next = new Set(prev) + for (const p of dispatchedRetryPaths) { + next.delete(p) + } + return next + }) if (cancelled) { return } @@ -1093,6 +1225,22 @@ export default function TaskPage(): React.JSX.Element { .catch((err) => { // Why: fetchWorkItemsAcrossRepos swallows per-repo failures, so a // reject here means an IPC-level or programmer error — surface it. + // Clear only the repos this effect was responsible for retrying + // (the snapshot captured at dispatch time). Overlapping retries — + // a second click while a prior fetch is still in flight — must + // not clear the newer repo from the set, so we can't just reset + // the whole set here. The early-return branches above reset the + // whole set because those branches won't dispatch a fetch. + setRetryingRepoPaths((prev) => { + if (dispatchedRetryPaths.size === 0) { + return prev + } + const next = new Set(prev) + for (const p of dispatchedRetryPaths) { + next.delete(p) + } + return next + }) if (cancelled) { return } @@ -1777,6 +1925,50 @@ export default function TaskPage(): React.JSX.Element { ) : null}
+ + {(() => { + // Why: compute the visible list once so the visibility + // gate and the map don't re-run the same predicate. + // `hasDivergentSources` lives at module scope so the + // predicate isn't re-allocated on every render; the + // narrowed return type means `sources.issues` and + // `sources.prs` are known non-null inside the map. + const visibleRepoSources = perRepoSourceState.filter(hasDivergentSources) + if (visibleRepoSources.length === 0) { + return null + } + // Why: per parent design doc §2, the indicator lives near + // the filter row. It's the self-announcing surface that + // makes the convention-based routing in #1076 legitimate + // — without it, a fork contributor filing a personal TODO + // against `upstream` has no way to tell before submit. + return ( +
+ {visibleRepoSources.map((s) => { + // Why: when multiple repos are selected, attach the + // local dot-label so readers can tell which chip + // describes which repo. Single-repo views omit it — + // the repo is already unambiguous from context. + const repo = + selectedRepos.length > 1 + ? selectedRepos.find((r) => r.id === s.repoId) + : undefined + return ( + + ) + })} +
+ ) + })()} ) : linearStatus.connected ? (
@@ -1927,6 +2119,53 @@ export default function TaskPage(): React.JSX.Element {
) : null} + {perRepoSourceState + .filter((s) => s.error) + .map((s) => { + const err = s.error! + // Why: parent design doc §2 — when the issue fetch fails + // (e.g. a 403 on a private upstream) we render a retryable + // banner with slug-qualified copy instead of a silent + // empty list. The [Retry] action re-invokes the fetch + // with force=true via the shared refresh nonce so any + // still-failing in-flight request is invalidated first. + return ( +
+ + Couldn't load issues from{' '} + + {err.source.owner}/{err.source.repo} + {' '} + — {err.message} + + +
+ ) + })} + {tasksLoading && filteredWorkItems.length === 0 ? ( // Why: shimmer skeleton stands in for the first ~3 rows while // the initial fetch is in flight, so the card is never empty @@ -1962,7 +2201,17 @@ export default function TaskPage(): React.JSX.Element { ) : null} - {!tasksLoading && filteredWorkItems.length === 0 ? ( + {/* Why: suppress the generic empty state when any error banner is + visible (IPC reject via tasksError, cross-repo partial failure + via failedCount, or per-repo issue-side error). Showing + "No matching GitHub work" next to "Couldn't load issues from X/Y" + is contradictory and misleads the user into thinking they + typed the wrong query. */} + {!tasksLoading && + filteredWorkItems.length === 0 && + !tasksError && + failedCount === 0 && + perRepoSourceState.every((s) => !s.error) ? (

No matching GitHub work

@@ -1982,7 +2231,12 @@ export default function TaskPage(): React.JSX.Element { //