diff --git a/mobile/app/h/[hostId]/tasks.tsx b/mobile/app/h/[hostId]/tasks.tsx index 191a47038..a9d24ae63 100644 --- a/mobile/app/h/[hostId]/tasks.tsx +++ b/mobile/app/h/[hostId]/tasks.tsx @@ -77,6 +77,15 @@ import { findRepoForGitHubProjectRepository, type GitHubRepoSlugCacheEntry } from '../../../src/tasks/github-project-repo-match' +import { + parseGitHubProjectInput as parseProjectInput, + type GitHubProjectOwnerType, + type GitHubProjectPartialFailure, + type GitHubProjectRef, + type GitHubProjectSettings, + type GitHubProjectSummary, + type GitHubProjectViewSummary +} from '../../../src/tasks/github-project-reference' import { extractGitHubIssueSourceFallback, extractGitHubIssueSourceError, @@ -130,11 +139,16 @@ import { } from '../../../src/tasks/mobile-task-copy-feedback-timer' import type { BaseRefSearchResult, + GitHubOwnerRepo, PersistedTrustedOrcaHooks, SparsePreset, TuiAgent } from '../../../../src/shared/types' import type { SshConnectionState } from '../../../../src/shared/ssh-types' +import { + githubProjectHost, + githubProjectIdentityKey as githubProjectKey +} from '../../../../src/shared/github-project-identity' type RepoSummary = { id: string @@ -148,11 +162,6 @@ type RepoSummary = { type IssueSourcePreference = 'upstream' | 'origin' | 'auto' -type GitHubOwnerRepo = { - owner: string - repo: string -} - type GitHubWorkItem = { id: string type: 'issue' | 'pr' @@ -444,34 +453,6 @@ type LinearStatusResponse = { activeWorkspaceId?: string | null } -type GitHubProjectOwnerType = 'organization' | 'user' -type GitHubProjectRef = { - owner: string - ownerType: GitHubProjectOwnerType - number: number -} -type GitHubProjectSettings = { - pinned: GitHubProjectRef[] - recent: Array - lastViewByProject: Record - activeProject: GitHubProjectRef | null -} -type GitHubProjectSummary = GitHubProjectRef & { - id: string - title: string - url: string - source: string -} -type GitHubProjectPartialFailure = { - owner: string - message: string -} -type GitHubProjectViewSummary = { - id: string - number: number - name: string - layout: 'TABLE_LAYOUT' | 'BOARD_LAYOUT' | 'ROADMAP_LAYOUT' -} type GitHubIssueType = { id: string name: string @@ -951,48 +932,6 @@ function githubKindFromQuery(query: string, fallbackPreset: GitHubPreset): GitHu : 'issues' } -function githubProjectKey(project: GitHubProjectRef): string { - return `${project.ownerType}:${project.owner}:${project.number}` -} - -function parseProjectInput( - input: string -): { owner: string; number: number; viewNumber?: number } | null { - const trimmed = input.trim() - if (!trimmed) { - return null - } - const short = /^([A-Za-z0-9][A-Za-z0-9-]*)\/(\d+)$/.exec(trimmed) - if (short) { - return { owner: short[1]!, number: Number(short[2]) } - } - try { - const url = new URL(trimmed) - if (url.hostname !== 'github.com') { - return null - } - const parts = url.pathname.split('/').filter(Boolean) - if ((parts[0] === 'orgs' || parts[0] === 'users') && parts[2] === 'projects' && parts[3]) { - const number = Number(parts[3]) - if (!Number.isInteger(number) || number < 1) { - return null - } - const viewNumber = - parts[4] === 'views' && parts[5] && Number.isInteger(Number(parts[5])) - ? Number(parts[5]) - : undefined - return { - owner: parts[1]!, - number, - ...(viewNumber && viewNumber > 0 ? { viewNumber } : {}) - } - } - } catch { - return null - } - return null -} - function projectRowType(row: GitHubProjectRow): 'issue' | 'pr' | null { if (row.itemType === 'ISSUE') { return 'issue' @@ -1014,6 +953,11 @@ function splitRepositorySlug(slug: string | null): { owner: string; repo: string return owner && repo ? { owner, repo } : null } +function projectRowGitHubRepository(row: GitHubProjectRow, host: string): GitHubOwnerRepo | null { + const slug = splitRepositorySlug(row.content.repository) + return slug ? { ...slug, host } : null +} + const GITHUB_PROJECT_OPTION_COLORS: Record = { GRAY: '#8b949e', RED: '#f85149', @@ -2468,6 +2412,10 @@ export default function MobileTasksScreen() { tasksSupportState.kind === 'unsupported' && tasksSupportState.client === client const taskUiReady = tasksSupported && taskStateHydrated + const activeGitHubProject = githubProjectSettings.activeProject + const activeGitHubProjectHost = githubProjectHost( + githubProjectTable?.project.host ?? activeGitHubProject?.host + ) const hostedRepos = useMemo(() => repos.filter(isHostedTaskRepo), [repos]) const workspaceRepos = useMemo(() => repos.filter((repo) => repo.kind !== 'folder'), [repos]) const reposById = useMemo(() => new Map(repos.map((repo) => [repo.id, repo])), [repos]) @@ -2483,9 +2431,10 @@ export default function MobileTasksScreen() { findRepoForGitHubProjectRepository( row.content.repository, hostedRepos, - githubRepoSlugCache + githubRepoSlugCache, + activeGitHubProjectHost ) as RepoSummary | null, - [githubRepoSlugCache, hostedRepos] + [activeGitHubProjectHost, githubRepoSlugCache, hostedRepos] ) const githubProjectRepoSlugReady = useMemo( () => @@ -2501,10 +2450,11 @@ export default function MobileTasksScreen() { ? (filterGitHubProjectRowsForRepos( githubProjectTable.rows, hostedRepos, - githubRepoSlugCache + githubRepoSlugCache, + activeGitHubProjectHost ) as GitHubProjectRow[]) : [], - [githubProjectTable, githubRepoSlugCache, hostedRepos] + [activeGitHubProjectHost, githubProjectTable, githubRepoSlugCache, hostedRepos] ) const visibleGitHubProjectGroups = useMemo(() => { if (!githubProjectTable) { @@ -2599,10 +2549,10 @@ export default function MobileTasksScreen() { return { repoId: repo.id, path: repo.path, - slug: result ? `${result.owner}/${result.repo}` : null + repository: result } } catch { - return { repoId: repo.id, path: repo.path, slug: null } + return { repoId: repo.id, path: repo.path, repository: null } } }).then((entries) => { if (cancelled) { @@ -2611,7 +2561,7 @@ export default function MobileTasksScreen() { setGithubRepoSlugCache((current) => { const next = { ...current } for (const entry of entries) { - next[entry.repoId] = { path: entry.path, slug: entry.slug } + next[entry.repoId] = { path: entry.path, repository: entry.repository } } return next }) @@ -2630,7 +2580,6 @@ export default function MobileTasksScreen() { taskStateHydrated, tasksSupported ]) - const activeGitHubProject = githubProjectSettings.activeProject const activeGitHubProjectKey = activeGitHubProject ? githubProjectKey(activeGitHubProject) : null const activeGitHubProjectViewId = activeGitHubProjectKey ? githubProjectSettings.lastViewByProject[activeGitHubProjectKey]?.viewId @@ -3738,7 +3687,9 @@ export default function MobileTasksScreen() { } setGithubProjectError('') setGithubProjectPartialFailures([]) - const response = await client.sendRequest('github.project.listAccessible', {}) + const response = await client.sendRequest('github.project.listAccessible', { + host: 'github.com' + }) if (!isSuccess(response)) { throw new Error(response.error.message) } @@ -3763,6 +3714,7 @@ export default function MobileTasksScreen() { } const response = await client.sendRequest('github.project.listViews', { owner: project.owner, + host: githubProjectHost(project.host), ownerType: project.ownerType, projectNumber: project.number }) @@ -3800,6 +3752,7 @@ export default function MobileTasksScreen() { 'github.project.viewTable', { owner: activeGitHubProject.owner, + host: activeGitHubProjectHost, ownerType: activeGitHubProject.ownerType, projectNumber: activeGitHubProject.number, viewId: activeGitHubProjectViewId, @@ -3838,7 +3791,14 @@ export default function MobileTasksScreen() { setGithubProjectLoading(false) } }, - [activeGitHubProject, activeGitHubProjectViewId, client, connState, tasksSupported] + [ + activeGitHubProject, + activeGitHubProjectHost, + activeGitHubProjectViewId, + client, + connState, + tasksSupported + ] ) const commitGitHubProjectView = useCallback( @@ -3932,7 +3892,8 @@ export default function MobileTasksScreen() { return } const input = githubProjectPasteInput.trim() - if (!parseProjectInput(input)) { + const parsed = parseProjectInput(input) + if (!parsed) { setGithubProjectPasteError('Expected a project URL or owner/number.') return } @@ -3940,7 +3901,10 @@ export default function MobileTasksScreen() { setGithubProjectPasteError('') setGithubProjectError('') try { - const response = await client.sendRequest('github.project.resolveRef', { input }) + const response = await client.sendRequest('github.project.resolveRef', { + input, + host: githubProjectHost(parsed.host) + }) if (!isSuccess(response)) { throw new Error(response.error.message) } @@ -3951,6 +3915,7 @@ export default function MobileTasksScreen() { ownerType: GitHubProjectOwnerType number: number title: string + host?: string viewNumber?: number } | { ok: false; error: { message: string } } @@ -3964,7 +3929,8 @@ export default function MobileTasksScreen() { { owner: result.owner, ownerType: result.ownerType, - number: result.number + number: result.number, + host: githubProjectHost(result.host ?? parsed.host) }, { viewNumber: result.viewNumber } ) @@ -4536,6 +4502,7 @@ export default function MobileTasksScreen() { { owner: slug.owner, repo: slug.repo, + host: activeGitHubProjectHost, number: projectRowItem.content.number, type }, @@ -4610,7 +4577,14 @@ export default function MobileTasksScreen() { return () => { stale = true } - }, [client, githubProjectTable, projectRowDetailRefreshSeq, projectRowItem, tasksSupported]) + }, [ + activeGitHubProjectHost, + client, + githubProjectTable, + projectRowDetailRefreshSeq, + projectRowItem, + tasksSupported + ]) useEffect(() => { const slug = splitRepositorySlug(projectMetadataRepository) @@ -4628,7 +4602,7 @@ export default function MobileTasksScreen() { void client .sendRequest( 'github.project.listLabelsBySlug', - { owner: slug.owner, repo: slug.repo }, + { owner: slug.owner, repo: slug.repo, host: activeGitHubProjectHost }, { timeoutMs: 30_000 } ) .then((response) => { @@ -4660,7 +4634,7 @@ export default function MobileTasksScreen() { return () => { stale = true } - }, [client, projectMetadataRepository, tasksSupported]) + }, [activeGitHubProjectHost, client, projectMetadataRepository, tasksSupported]) useEffect(() => { const slug = splitRepositorySlug(projectMetadataRepository) @@ -4681,6 +4655,7 @@ export default function MobileTasksScreen() { { owner: slug.owner, repo: slug.repo, + host: activeGitHubProjectHost, ...(projectMetadataSeedLogins ? { seedLogins: projectMetadataSeedLogins.split(',') } : {}) }, { timeoutMs: 30_000 } @@ -4716,7 +4691,13 @@ export default function MobileTasksScreen() { return () => { stale = true } - }, [client, projectMetadataRepository, projectMetadataSeedLogins, tasksSupported]) + }, [ + activeGitHubProjectHost, + client, + projectMetadataRepository, + projectMetadataSeedLogins, + tasksSupported + ]) useEffect(() => { const slug = splitRepositorySlug(projectIssueTypeRepository) @@ -4734,7 +4715,7 @@ export default function MobileTasksScreen() { void client .sendRequest( 'github.project.listIssueTypesBySlug', - { owner: slug.owner, repo: slug.repo }, + { owner: slug.owner, repo: slug.repo, host: activeGitHubProjectHost }, { timeoutMs: 30_000 } ) .then((response) => { @@ -4768,7 +4749,7 @@ export default function MobileTasksScreen() { return () => { stale = true } - }, [client, projectIssueTypeRepository, tasksSupported]) + }, [activeGitHubProjectHost, client, projectIssueTypeRepository, tasksSupported]) const getWorkspaceTargetRepo = useCallback( (item: ActionableTaskItem, repoIdOverride?: string): RepoSummary | null => { @@ -5729,6 +5710,7 @@ export default function MobileTasksScreen() { { owner: slug.owner, repo: slug.repo, + host: activeGitHubProjectHost, number: row.content.number, updates }, @@ -5790,7 +5772,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, projectMutating] + [activeGitHubProjectHost, client, projectMutating] ) const addProjectRowComment = useCallback( @@ -5810,6 +5792,7 @@ export default function MobileTasksScreen() { { owner: slug.owner, repo: slug.repo, + host: activeGitHubProjectHost, number: row.content.number, body }, @@ -5838,7 +5821,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, projectCommentDraft, projectMutating] + [activeGitHubProjectHost, client, projectCommentDraft, projectMutating] ) const updateProjectRowComment = useCallback( @@ -5861,6 +5844,7 @@ export default function MobileTasksScreen() { { owner: slug.owner, repo: slug.repo, + host: activeGitHubProjectHost, commentId, body }, @@ -5898,7 +5882,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, projectEditingCommentDraft, projectMutating] + [activeGitHubProjectHost, client, projectEditingCommentDraft, projectMutating] ) const deleteProjectRowComment = useCallback( @@ -5920,6 +5904,7 @@ export default function MobileTasksScreen() { { owner: slug.owner, repo: slug.repo, + host: activeGitHubProjectHost, commentId }, { timeoutMs: 30_000 } @@ -5956,7 +5941,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, projectEditingCommentId, projectMutating] + [activeGitHubProjectHost, client, projectEditingCommentId, projectMutating] ) const toggleProjectGitHubReviewThread = useCallback( @@ -5979,6 +5964,7 @@ export default function MobileTasksScreen() { 'github.resolveReviewThread', { repo: `id:${repo.id}`, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), threadId: comment.threadId, resolve }, @@ -6010,7 +5996,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, findProjectRowRepo, projectMutating] + [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating] ) const replyToProjectGitHubComment = useCallback( @@ -6038,6 +6024,7 @@ export default function MobileTasksScreen() { { repo: `id:${repo.id}`, prNumber: row.content.number, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), commentId: comment.id, body, threadId: comment.threadId, @@ -6051,6 +6038,7 @@ export default function MobileTasksScreen() { { repo: `id:${repo.id}`, number: row.content.number, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), body: `@${commentAuthor(comment)} ${body}`, type: projectRowType(row) ?? 'issue' }, @@ -6092,7 +6080,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, findProjectRowRepo, itemReplyDrafts, projectMutating] + [activeGitHubProjectHost, client, findProjectRowRepo, itemReplyDrafts, projectMutating] ) const mutateProjectRowMetadata = useCallback( @@ -6120,6 +6108,7 @@ export default function MobileTasksScreen() { { owner: slug.owner, repo: slug.repo, + host: activeGitHubProjectHost, number: row.content.number, updates }, @@ -6204,7 +6193,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, projectMutating] + [activeGitHubProjectHost, client, projectMutating] ) const mutateProjectRowField = useCallback( @@ -6223,11 +6212,13 @@ export default function MobileTasksScreen() { value === null ? { projectId: githubProjectTable.project.id, + host: activeGitHubProjectHost, itemId: row.id, fieldId: field.id } : { projectId: githubProjectTable.project.id, + host: activeGitHubProjectHost, itemId: row.id, fieldId: field.id, value @@ -6274,7 +6265,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, githubProjectTable, projectMutating] + [activeGitHubProjectHost, client, githubProjectTable, projectMutating] ) const mutateProjectRowIssueType = useCallback( @@ -6294,6 +6285,7 @@ export default function MobileTasksScreen() { { owner: slug.owner, repo: slug.repo, + host: activeGitHubProjectHost, number: row.content.number, issueTypeId: issueType?.id ?? null }, @@ -6329,7 +6321,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, projectMutating] + [activeGitHubProjectHost, client, projectMutating] ) const requestProjectGitHubReviewers = useCallback( @@ -6350,6 +6342,7 @@ export default function MobileTasksScreen() { { repo: `id:${repo.id}`, prNumber: row.content.number, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), reviewers }, { timeoutMs: 30_000 } @@ -6397,7 +6390,14 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, findProjectRowRepo, projectMutating, projectReviewersDraft, projectRowDetail] + [ + activeGitHubProjectHost, + client, + findProjectRowRepo, + projectMutating, + projectReviewersDraft, + projectRowDetail + ] ) const refreshProjectGitHubChecks = useCallback( @@ -6420,6 +6420,7 @@ export default function MobileTasksScreen() { { repo: `id:${repo.id}`, prNumber: row.content.number, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), headSha: projectRowDetail?.provider === 'github' ? projectRowDetail.headSha : undefined, noCache: true }, @@ -6441,7 +6442,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, findProjectRowRepo, projectMutating, projectRowDetail] + [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating, projectRowDetail] ) const rerunProjectGitHubChecks = useCallback( @@ -6464,6 +6465,7 @@ export default function MobileTasksScreen() { { repo: `id:${repo.id}`, prNumber: row.content.number, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), headSha: projectRowDetail?.provider === 'github' ? projectRowDetail.headSha : undefined, failedOnly }, @@ -6483,7 +6485,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, findProjectRowRepo, projectMutating, projectRowDetail] + [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating, projectRowDetail] ) const toggleProjectGitHubFileViewed = useCallback( @@ -6504,6 +6506,7 @@ export default function MobileTasksScreen() { 'github.setPRFileViewed', { repo: `id:${repo.id}`, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), pullRequestId: projectRowDetail.pullRequestId, path: file.path, viewed @@ -6536,7 +6539,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, findProjectRowRepo, projectMutating, projectRowDetail] + [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating, projectRowDetail] ) const toggleProjectGitHubFileExpansion = useCallback( @@ -6570,6 +6573,7 @@ export default function MobileTasksScreen() { { repo: `id:${repo.id}`, prNumber: row.content.number, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), path: file.path, oldPath: file.oldPath, status: file.status ?? 'modified', @@ -6593,7 +6597,14 @@ export default function MobileTasksScreen() { setPrFileLoadingPath(null) } }, - [client, expandedPrFilePath, findProjectRowRepo, prFileContents, projectRowDetail] + [ + activeGitHubProjectHost, + client, + expandedPrFilePath, + findProjectRowRepo, + prFileContents, + projectRowDetail + ] ) const addProjectGitHubFileReviewComment = useCallback( @@ -6625,6 +6636,7 @@ export default function MobileTasksScreen() { { repo: `id:${repo.id}`, prNumber: row.content.number, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), commitId: projectRowDetail.headSha, path: file.path, line, @@ -6669,7 +6681,14 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, findProjectRowRepo, prFileCommentDrafts, projectMutating, projectRowDetail] + [ + activeGitHubProjectHost, + client, + findProjectRowRepo, + prFileCommentDrafts, + projectMutating, + projectRowDetail + ] ) const mergeProjectGitHubPullRequest = useCallback( @@ -6695,6 +6714,7 @@ export default function MobileTasksScreen() { { repo: `id:${repo.id}`, prNumber: row.content.number, + prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost), method }, { timeoutMs: 60_000 } @@ -6731,7 +6751,7 @@ export default function MobileTasksScreen() { setProjectMutating(false) } }, - [client, findProjectRowRepo, projectMutating] + [activeGitHubProjectHost, client, findProjectRowRepo, projectMutating] ) const toggleGitHubStatus = useCallback( diff --git a/mobile/src/session/github-pr-mutations.ts b/mobile/src/session/github-pr-mutations.ts index 6d615150a..4c52f5a8f 100644 --- a/mobile/src/session/github-pr-mutations.ts +++ b/mobile/src/session/github-pr-mutations.ts @@ -147,48 +147,51 @@ export async function fetchSetPRAutoMerge( export async function fetchUpdatePRState( client: Pick, worktreeId: string, - args: { prNumber: number; state: 'open' | 'closed' } + args: { prNumber: number; state: 'open' | 'closed'; prRepo?: GitHubPrRepoSlug | null } ): Promise { - // updatePRState does NOT accept prRepo (KTD3) — buildGithubPrParams omits it. return sendGithubPrMutation( client, 'github.updatePRState', - buildGithubPrParams('github.updatePRState', worktreeId, { - prNumber: args.prNumber, - updates: { state: args.state } - }) + buildGithubPrParams( + 'github.updatePRState', + worktreeId, + { prNumber: args.prNumber, updates: { state: args.state } }, + { prRepo: args.prRepo } + ) ) } export async function fetchRequestPRReviewers( client: Pick, worktreeId: string, - args: { prNumber: number; reviewers: string[] } + args: { prNumber: number; reviewers: string[]; prRepo?: GitHubPrRepoSlug | null } ): Promise { - // requestPRReviewers does NOT accept prRepo (KTD3). return sendGithubPrMutation( client, 'github.requestPRReviewers', - buildGithubPrParams('github.requestPRReviewers', worktreeId, { - prNumber: args.prNumber, - reviewers: args.reviewers - }) + buildGithubPrParams( + 'github.requestPRReviewers', + worktreeId, + { prNumber: args.prNumber, reviewers: args.reviewers }, + { prRepo: args.prRepo } + ) ) } export async function fetchRemovePRReviewers( client: Pick, worktreeId: string, - args: { prNumber: number; reviewers: string[] } + args: { prNumber: number; reviewers: string[]; prRepo?: GitHubPrRepoSlug | null } ): Promise { - // removePRReviewers does NOT accept prRepo (KTD3). return sendGithubPrMutation( client, 'github.removePRReviewers', - buildGithubPrParams('github.removePRReviewers', worktreeId, { - prNumber: args.prNumber, - reviewers: args.reviewers - }) + buildGithubPrParams( + 'github.removePRReviewers', + worktreeId, + { prNumber: args.prNumber, reviewers: args.reviewers }, + { prRepo: args.prRepo } + ) ) } @@ -262,15 +265,17 @@ export async function fetchAddIssueComment( export async function fetchResolveReviewThread( client: Pick, worktreeId: string, - args: { threadId: string; resolve: boolean } + args: { threadId: string; resolve: boolean; prRepo?: GitHubPrRepoSlug | null } ): Promise { const response = await sendRaw( client, 'github.resolveReviewThread', - buildGithubPrParams('github.resolveReviewThread', worktreeId, { - threadId: args.threadId, - resolve: args.resolve - }) + buildGithubPrParams( + 'github.resolveReviewThread', + worktreeId, + { threadId: args.threadId, resolve: args.resolve }, + { prRepo: args.prRepo } + ) ) if (!response.ok) { return { @@ -315,9 +320,13 @@ export async function fetchDeleteIssueComment( export async function fetchRerunPRChecks( client: Pick, worktreeId: string, - args: { prNumber: number; headSha?: string | null; failedOnly?: boolean } + args: { + prNumber: number + headSha?: string | null + failedOnly?: boolean + prRepo?: GitHubPrRepoSlug | null + } ): Promise { - // rerunPRChecks does NOT accept prRepo (KTD3); headSha is a plain param here. const params: Record = { prNumber: args.prNumber } if (args.failedOnly !== undefined) { params.failedOnly = args.failedOnly @@ -328,6 +337,6 @@ export async function fetchRerunPRChecks( return sendGithubPrMutation( client, 'github.rerunPRChecks', - buildGithubPrParams('github.rerunPRChecks', worktreeId, params) + buildGithubPrParams('github.rerunPRChecks', worktreeId, params, { prRepo: args.prRepo }) ) } diff --git a/mobile/src/session/github-pr-rpc.test.ts b/mobile/src/session/github-pr-rpc.test.ts index 56904e482..767fcbfea 100644 --- a/mobile/src/session/github-pr-rpc.test.ts +++ b/mobile/src/session/github-pr-rpc.test.ts @@ -278,9 +278,17 @@ describe('buildGithubPrParams — method-aware prRepo / headSha', () => { for (const method of [ 'github.prChecks', 'github.prCheckDetails', + 'github.rerunPRChecks', + 'github.resolveReviewThread', + 'github.setPRFileViewed', + 'github.updatePRState', + 'github.requestPRReviewers', + 'github.removePRReviewers', 'github.mergePR', 'github.setPRAutoMerge', - 'github.prComments' + 'github.prComments', + 'github.prFileContents', + 'github.addPRReviewComment' ]) { const params = buildGithubPrParams(method, WORKTREE_ID, { prNumber: 1 }, { prRepo: fork }) expect(params.prRepo).toEqual(fork) @@ -288,13 +296,7 @@ describe('buildGithubPrParams — method-aware prRepo / headSha', () => { }) it('omits prRepo for methods that reject it', () => { - for (const method of [ - 'github.updatePRState', - 'github.requestPRReviewers', - 'github.removePRReviewers', - 'github.listAssignableUsers', - 'github.rerunPRChecks' - ]) { + for (const method of ['github.repoSlug', 'github.prForBranch', 'github.listAssignableUsers']) { const params = buildGithubPrParams(method, WORKTREE_ID, { prNumber: 1 }, { prRepo: fork }) expect('prRepo' in params).toBe(false) } diff --git a/mobile/src/session/github-pr-rpc.ts b/mobile/src/session/github-pr-rpc.ts index 46d6ec2b6..c83b155cb 100644 --- a/mobile/src/session/github-pr-rpc.ts +++ b/mobile/src/session/github-pr-rpc.ts @@ -41,16 +41,22 @@ export function githubPrRepoSlugParam(slug: GitHubPrRepoSlug): Record = { ok: true; result: T } | { ok: false; error: string } -// Why: `prRepo` is method-asymmetric (KTD3). These are the only github.* methods -// whose host schema (SlugRepo on PullRequest/PullRequestChecks/PullRequestCheckDetails) -// accepts it; the rest reject the key. Centralizing the allow-list keeps a fork's -// prRepo from leaking into a schema that would reject it. +// Why: `prRepo` remains method-asymmetric. Keep the RPC schema allow-list here +// so fork/GHES identity reaches every PR-scoped read or mutation that accepts it. const METHODS_ACCEPTING_PR_REPO = new Set([ 'github.prChecks', 'github.prCheckDetails', + 'github.rerunPRChecks', + 'github.resolveReviewThread', + 'github.setPRFileViewed', + 'github.updatePRState', + 'github.requestPRReviewers', + 'github.removePRReviewers', 'github.mergePR', 'github.setPRAutoMerge', - 'github.prComments' + 'github.prComments', + 'github.prFileContents', + 'github.addPRReviewComment' ]) // Why: only github.prChecks declares a `headSha` param (PullRequestCheckDetails diff --git a/mobile/src/session/pr-action-mutation-contract.ts b/mobile/src/session/pr-action-mutation-contract.ts new file mode 100644 index 000000000..a2fcdb271 --- /dev/null +++ b/mobile/src/session/pr-action-mutation-contract.ts @@ -0,0 +1,38 @@ +import type { GitHubPRMergeMethod } from '../../../src/shared/types' +import type { GitHubPrMutationOutcome } from './github-pr-mutations' +import type { GitHubPrRepoSlug } from './github-pr-rpc' + +export type PrActionMutations = { + mergePR: (args: { + prNumber: number + method?: GitHubPRMergeMethod + prRepo?: GitHubPrRepoSlug | null + }) => Promise + setPRAutoMerge: (args: { + prNumber: number + enabled: boolean + method?: GitHubPRMergeMethod + prRepo?: GitHubPrRepoSlug | null + }) => Promise + updatePRState: (args: { + prNumber: number + state: 'open' | 'closed' + prRepo?: GitHubPrRepoSlug | null + }) => Promise + requestReviewers: (args: { + prNumber: number + reviewers: string[] + prRepo?: GitHubPrRepoSlug | null + }) => Promise + removeReviewers: (args: { + prNumber: number + reviewers: string[] + prRepo?: GitHubPrRepoSlug | null + }) => Promise + rerunChecks: (args: { + prNumber: number + headSha?: string | null + failedOnly?: boolean + prRepo?: GitHubPrRepoSlug | null + }) => Promise +} diff --git a/mobile/src/session/pr-actions-engine.test.ts b/mobile/src/session/pr-actions-engine.test.ts index d879454c5..3656b2732 100644 --- a/mobile/src/session/pr-actions-engine.test.ts +++ b/mobile/src/session/pr-actions-engine.test.ts @@ -198,4 +198,43 @@ describe('PrActionsEngine — PR identity changes', () => { await action expect(refetch).not.toHaveBeenCalled() }) + + it('clears in-flight state when only the GitHub host changes', async () => { + const slow = deferred() + const mutations: PrActionMutations = { + mergePR: async () => ({ ok: true }), + setPRAutoMerge: async () => slow.promise, + updatePRState: async () => ({ ok: true }), + requestReviewers: async () => ({ ok: true }), + removeReviewers: async () => ({ ok: true }), + rerunChecks: async () => ({ ok: true }) + } + const refetch = vi.fn() + const onChange = vi.fn() + const baseConfig = { + mutations, + prNumber: 1, + refetch, + onChange + } + const engine = new PrActionsEngine({ + ...baseConfig, + prRepo: { owner: 'acme', repo: 'widgets' } + }) + + const action = engine.setAutoMerge(true) + expect(engine.resolveAutoMerge(false)).toBe(true) + expect(engine.isBusy({ kind: 'autoMerge' })).toBe(true) + + engine.updateConfig({ + ...baseConfig, + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' } + }) + expect(engine.resolveAutoMerge(false)).toBe(false) + expect(engine.busy).toBeNull() + + slow.resolve({ ok: true }) + await action + expect(refetch).not.toHaveBeenCalled() + }) }) diff --git a/mobile/src/session/pr-actions-engine.ts b/mobile/src/session/pr-actions-engine.ts index 7c3495453..ce19c9bbb 100644 --- a/mobile/src/session/pr-actions-engine.ts +++ b/mobile/src/session/pr-actions-engine.ts @@ -1,45 +1,18 @@ import type { GitHubPRMergeMethod, PRState } from '../../../src/shared/types' +import { githubRepoIdentityKey } from '../../../src/shared/github-repository-identity-key' import { classifyPrSidebarFailure } from './mobile-pr-sidebar-state' import { createOptimisticField, type OptimisticField } from './optimistic-write-sequence' import type { GitHubPrMutationOutcome } from './github-pr-mutations' import type { GitHubPrRepoSlug } from './github-pr-rpc' +import type { PrActionMutations } from './pr-action-mutation-contract' + +export type { PrActionMutations } from './pr-action-mutation-contract' // Pure (React-free) engine for the PR mutation actions: owns optimistic fields, // busy/error/blocked state, and the success/transient/permanent routing. The hook // is a thin adapter that subscribes to `onChange` and exposes these methods. Kept // React-free so the U6 action logic is unit-testable with injected fakes. -export type PrActionMutations = { - mergePR: (args: { - prNumber: number - method?: GitHubPRMergeMethod - prRepo?: GitHubPrRepoSlug | null - }) => Promise - setPRAutoMerge: (args: { - prNumber: number - enabled: boolean - method?: GitHubPRMergeMethod - prRepo?: GitHubPrRepoSlug | null - }) => Promise - updatePRState: (args: { - prNumber: number - state: 'open' | 'closed' - }) => Promise - requestReviewers: (args: { - prNumber: number - reviewers: string[] - }) => Promise - removeReviewers: (args: { - prNumber: number - reviewers: string[] - }) => Promise - rerunChecks: (args: { - prNumber: number - headSha?: string | null - failedOnly?: boolean - }) => Promise -} - export type PrActionBusyKey = | { kind: 'merge' } | { kind: 'autoMerge' } @@ -68,7 +41,7 @@ export type PrActionsEngineConfig = { } function prActionsIdentity(cfg: PrActionsEngineConfig): string { - const repo = cfg.prRepo ? `${cfg.prRepo.owner}/${cfg.prRepo.repo}` : '' + const repo = cfg.prRepo ? githubRepoIdentityKey(cfg.prRepo) : '' return `${cfg.prNumber}:${repo}` } @@ -260,7 +233,8 @@ export class PrActionsEngine { try { const outcome = await cfg.mutations.updatePRState({ prNumber: cfg.prNumber, - state + state, + prRepo: cfg.prRepo }) await this.settle(identity, outcome, { onSuccess: () => this.stateField.settleSuccess(seq), @@ -281,7 +255,8 @@ export class PrActionsEngine { try { const outcome = await cfg.mutations.requestReviewers({ prNumber: cfg.prNumber, - reviewers: [login] + reviewers: [login], + prRepo: cfg.prRepo }) await this.settle(identity, outcome, { onSuccess: () => field.settleSuccess(seq), @@ -302,7 +277,8 @@ export class PrActionsEngine { try { const outcome = await cfg.mutations.removeReviewers({ prNumber: cfg.prNumber, - reviewers: [login] + reviewers: [login], + prRepo: cfg.prRepo }) await this.settle(identity, outcome, { onSuccess: () => field.settleSuccess(seq), @@ -322,7 +298,8 @@ export class PrActionsEngine { const outcome = await cfg.mutations.rerunChecks({ prNumber: cfg.prNumber, headSha: cfg.headSha, - failedOnly: true + failedOnly: true, + prRepo: cfg.prRepo }) await this.settle(identity, outcome, { onSuccess: () => {}, onRevert: () => {} }) } finally { diff --git a/mobile/src/session/use-mobile-pr-actions.test.ts b/mobile/src/session/use-mobile-pr-actions.test.ts index e8efa6009..dd022bb25 100644 --- a/mobile/src/session/use-mobile-pr-actions.test.ts +++ b/mobile/src/session/use-mobile-pr-actions.test.ts @@ -10,6 +10,7 @@ import { } from './github-pr-mutations' const WORKTREE_ID = 'repo-42::/path/to/wt' +const ENTERPRISE_PR_REPO = { owner: 'fork', repo: 'proj', host: 'github.acme.test' } function okStatus(): RpcResponse { return { id: 'x', ok: true, result: { ok: true }, _meta: { runtimeId: 'r' } } @@ -46,13 +47,17 @@ function fakeMutations(overrides: Partial = {}): PrActionMuta } } -function makeEngine(mutations: PrActionMutations, refetch = vi.fn(async () => {})) { +function makeEngine( + mutations: PrActionMutations, + refetch = vi.fn(async () => {}), + prRepo: typeof ENTERPRISE_PR_REPO | null = null +) { const onChange = vi.fn() const engine = new PrActionsEngine({ mutations, prNumber: 7, headSha: 'abc123', - prRepo: null, + prRepo, refetch, onChange }) @@ -67,7 +72,7 @@ describe('mutation wrappers — prRepo + param shapes', () => { await fetchMergePR(client, WORKTREE_ID, { prNumber: 7, method: 'squash', - prRepo: { owner: 'fork', repo: 'proj' } + prRepo: ENTERPRISE_PR_REPO }) expect(sendRequest).toHaveBeenCalledWith( 'github.mergePR', @@ -75,17 +80,25 @@ describe('mutation wrappers — prRepo + param shapes', () => { repo: 'id:repo-42', prNumber: 7, method: 'squash', - prRepo: { owner: 'fork', repo: 'proj' } + prRepo: ENTERPRISE_PR_REPO }) ) }) - it('updatePRState close carries NO prRepo and the state update', async () => { + it('updatePRState carries the host-qualified PR repo and state update', async () => { const { client, sendRequest } = mockClient(okStatus()) - await fetchUpdatePRState(client, WORKTREE_ID, { prNumber: 7, state: 'closed' }) + await fetchUpdatePRState(client, WORKTREE_ID, { + prNumber: 7, + state: 'closed', + prRepo: ENTERPRISE_PR_REPO + }) const [, params] = sendRequest.mock.calls[0] - expect(params).toEqual({ repo: 'id:repo-42', prNumber: 7, updates: { state: 'closed' } }) - expect(params).not.toHaveProperty('prRepo') + expect(params).toEqual({ + repo: 'id:repo-42', + prNumber: 7, + updates: { state: 'closed' }, + prRepo: ENTERPRISE_PR_REPO + }) }) it('updatePRState reopen passes state:open', async () => { @@ -95,27 +108,43 @@ describe('mutation wrappers — prRepo + param shapes', () => { expect((params.updates as { state: string }).state).toBe('open') }) - it('request/remove reviewers carry NO prRepo even when a fork is in play', async () => { + it('request/remove reviewers carry the host-qualified PR repo', async () => { const { client, sendRequest } = mockClient(okStatus()) - await fetchRequestPRReviewers(client, WORKTREE_ID, { prNumber: 7, reviewers: ['alice'] }) - await fetchRemovePRReviewers(client, WORKTREE_ID, { prNumber: 7, reviewers: ['bob'] }) - for (const [, params] of sendRequest.mock.calls) { - expect(params).not.toHaveProperty('prRepo') - } - expect(sendRequest.mock.calls[0][1]).toMatchObject({ reviewers: ['alice'] }) - expect(sendRequest.mock.calls[1][1]).toMatchObject({ reviewers: ['bob'] }) + await fetchRequestPRReviewers(client, WORKTREE_ID, { + prNumber: 7, + reviewers: ['alice'], + prRepo: ENTERPRISE_PR_REPO + }) + await fetchRemovePRReviewers(client, WORKTREE_ID, { + prNumber: 7, + reviewers: ['bob'], + prRepo: ENTERPRISE_PR_REPO + }) + expect(sendRequest.mock.calls[0][1]).toMatchObject({ + reviewers: ['alice'], + prRepo: ENTERPRISE_PR_REPO + }) + expect(sendRequest.mock.calls[1][1]).toMatchObject({ + reviewers: ['bob'], + prRepo: ENTERPRISE_PR_REPO + }) }) - it('rerunPRChecks carries failedOnly + headSha and NO prRepo', async () => { + it('rerunPRChecks carries failedOnly, headSha, and the host-qualified PR repo', async () => { const { client, sendRequest } = mockClient(okStatus()) await fetchRerunPRChecks(client, WORKTREE_ID, { prNumber: 7, headSha: 'abc', - failedOnly: true + failedOnly: true, + prRepo: ENTERPRISE_PR_REPO }) const [, params] = sendRequest.mock.calls[0] - expect(params).toMatchObject({ prNumber: 7, failedOnly: true, headSha: 'abc' }) - expect(params).not.toHaveProperty('prRepo') + expect(params).toMatchObject({ + prNumber: 7, + failedOnly: true, + headSha: 'abc', + prRepo: ENTERPRISE_PR_REPO + }) }) it('a host { ok:false, error } result surfaces as a failure outcome', async () => { @@ -155,14 +184,14 @@ describe('PrActionsEngine — auto-merge optimistic revert', () => { const mutations = fakeMutations({ setPRAutoMerge: vi.fn(async () => ({ ok: false as const, error: 'connection lost' })) }) - const { engine } = makeEngine(mutations) + const { engine } = makeEngine(mutations, undefined, ENTERPRISE_PR_REPO) // authoritative = false; user enables. await engine.setAutoMerge(true, 'squash') expect(mutations.setPRAutoMerge).toHaveBeenCalledWith({ prNumber: 7, enabled: true, method: 'squash', - prRepo: null + prRepo: ENTERPRISE_PR_REPO }) // Reverted to authoritative after transient failure. expect(engine.resolveAutoMerge(false)).toBe(false) @@ -182,20 +211,32 @@ describe('PrActionsEngine — auto-merge optimistic revert', () => { describe('PrActionsEngine — updateState close/reopen', () => { it('close fires state:closed and reopen fires state:open', async () => { const mutations = fakeMutations() - const { engine } = makeEngine(mutations) + const { engine } = makeEngine(mutations, undefined, ENTERPRISE_PR_REPO) await engine.updateState('closed') await engine.updateState('open') - expect(mutations.updatePRState).toHaveBeenNthCalledWith(1, { prNumber: 7, state: 'closed' }) - expect(mutations.updatePRState).toHaveBeenNthCalledWith(2, { prNumber: 7, state: 'open' }) + expect(mutations.updatePRState).toHaveBeenNthCalledWith(1, { + prNumber: 7, + state: 'closed', + prRepo: ENTERPRISE_PR_REPO + }) + expect(mutations.updatePRState).toHaveBeenNthCalledWith(2, { + prNumber: 7, + state: 'open', + prRepo: ENTERPRISE_PR_REPO + }) }) }) describe('PrActionsEngine — reviewers', () => { - it('requestReviewer adds via requestReviewers with a single login (no prRepo at engine level)', async () => { + it('requestReviewer adds via requestReviewers with a host-qualified PR repo', async () => { const mutations = fakeMutations() - const { engine } = makeEngine(mutations) + const { engine } = makeEngine(mutations, undefined, ENTERPRISE_PR_REPO) await engine.requestReviewer('alice') - expect(mutations.requestReviewers).toHaveBeenCalledWith({ prNumber: 7, reviewers: ['alice'] }) + expect(mutations.requestReviewers).toHaveBeenCalledWith({ + prNumber: 7, + reviewers: ['alice'], + prRepo: ENTERPRISE_PR_REPO + }) }) it('removeReviewer optimistic revert on transient failure', async () => { @@ -213,12 +254,13 @@ describe('PrActionsEngine — reviewers', () => { describe('PrActionsEngine — rerun checks', () => { it('fires failedOnly:true with headSha and refetches on success', async () => { const mutations = fakeMutations() - const { engine, refetch } = makeEngine(mutations) + const { engine, refetch } = makeEngine(mutations, undefined, ENTERPRISE_PR_REPO) await engine.rerunFailingChecks() expect(mutations.rerunChecks).toHaveBeenCalledWith({ prNumber: 7, headSha: 'abc123', - failedOnly: true + failedOnly: true, + prRepo: ENTERPRISE_PR_REPO }) expect(refetch).toHaveBeenCalledOnce() }) diff --git a/mobile/src/session/use-mobile-pr-comment-actions.ts b/mobile/src/session/use-mobile-pr-comment-actions.ts index b1eb51ad6..38096bad8 100644 --- a/mobile/src/session/use-mobile-pr-comment-actions.ts +++ b/mobile/src/session/use-mobile-pr-comment-actions.ts @@ -30,7 +30,11 @@ export type PrCommentMutations = { line?: number prRepo?: GitHubPrRepoSlug | null }) => Promise - resolveThread: (args: { threadId: string; resolve: boolean }) => Promise + resolveThread: (args: { + threadId: string + resolve: boolean + prRepo?: GitHubPrRepoSlug | null + }) => Promise addRootComment: (args: { prNumber: number body: string @@ -171,9 +175,9 @@ export function useMobilePrCommentActions(input: PrCommentActionsInput) { if (!mutations || !params) { return Promise.resolve(false) } - return run(resolveKey(params.threadId), () => mutations.resolveThread(params)) + return run(resolveKey(params.threadId), () => mutations.resolveThread({ ...params, prRepo })) }, - [mutations, run] + [mutations, prRepo, run] ) const addRootComment = useCallback( diff --git a/mobile/src/tasks/github-project-host-routing-source.test.ts b/mobile/src/tasks/github-project-host-routing-source.test.ts new file mode 100644 index 000000000..05781d9f6 --- /dev/null +++ b/mobile/src/tasks/github-project-host-routing-source.test.ts @@ -0,0 +1,42 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' + +const source = readFileSync(new URL('../../app/h/[hostId]/tasks.tsx', import.meta.url), 'utf8') + +describe('mobile GitHub Project host routing boundary', () => { + it('host-qualifies every Project RPC request', () => { + const calls = [...source.matchAll(/['"](github\.project\.[^'"]+)['"]/g)] + expect(calls.length).toBeGreaterThan(10) + for (const call of calls) { + const request = source.slice(call.index, call.index + 700) + expect(request, `${call[1]} must carry a host`).toMatch(/\bhost\s*:/) + } + }) + + it('pins Project-row PR actions to the row repository identity', () => { + const actions = source.slice(source.indexOf('const toggleProjectGitHubReviewThread')) + for (const method of [ + 'github.resolveReviewThread', + 'github.addPRReviewCommentReply', + 'github.addIssueComment', + 'github.requestPRReviewers', + 'github.prChecks', + 'github.rerunPRChecks', + 'github.setPRFileViewed', + 'github.prFileContents', + 'github.addPRReviewComment', + 'github.mergePR' + ]) { + const offset = actions.indexOf(`'${method}'`) + expect(offset, `${method} must remain wired in the Project action path`).toBeGreaterThan(-1) + expect(actions.slice(offset, offset + 700), `${method} must carry prRepo`).toContain( + 'prRepo: projectRowGitHubRepository(row, activeGitHubProjectHost)' + ) + } + }) + + it('pins discovery to github.com while pasted URLs supply their parsed host', () => { + expect(source).toContain("'github.project.listAccessible', {\n host: 'github.com'") + expect(source).toContain('host: githubProjectHost(parsed.host)') + }) +}) diff --git a/mobile/src/tasks/github-project-reference.test.ts b/mobile/src/tasks/github-project-reference.test.ts new file mode 100644 index 000000000..d083d96cc --- /dev/null +++ b/mobile/src/tasks/github-project-reference.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { parseGitHubProjectInput } from './github-project-reference' + +describe('parseGitHubProjectInput', () => { + it('keeps legacy owner/number input hostless', () => { + expect(parseGitHubProjectInput('Acme/42')).toEqual({ owner: 'Acme', number: 42 }) + }) + + it('preserves GitHub Enterprise hosts and view numbers', () => { + expect( + parseGitHubProjectInput('https://GitHub.Acme-Corp.com:8443/orgs/Acme/projects/42/views/7') + ).toEqual({ + owner: 'Acme', + number: 42, + host: 'github.acme-corp.com:8443', + viewNumber: 7 + }) + }) + + it('accepts github.com user Project URLs', () => { + expect(parseGitHubProjectInput('http://github.com/users/octocat/projects/3')).toEqual({ + owner: 'octocat', + number: 3, + host: 'github.com' + }) + }) + + it('rejects credentials, invalid routes, and unsafe integers', () => { + for (const input of [ + 'https://user:token@github.acme.test/orgs/acme/projects/1', + 'https://github.acme.test/acme/projects/1', + 'https://github.acme.test/orgs/acme/projects/1/files', + 'https://github.acme.test/orgs/acme/projects/9007199254740992', + 'https://github.acme.test/orgs/acme/projects/1/views/0' + ]) { + expect(parseGitHubProjectInput(input)).toBeNull() + } + }) +}) diff --git a/mobile/src/tasks/github-project-reference.ts b/mobile/src/tasks/github-project-reference.ts new file mode 100644 index 000000000..00047f15f --- /dev/null +++ b/mobile/src/tasks/github-project-reference.ts @@ -0,0 +1,84 @@ +import type { GitHubProjectIdentity } from '../../../src/shared/github-project-identity' + +export type GitHubProjectOwnerType = GitHubProjectIdentity['ownerType'] +export type GitHubProjectRef = GitHubProjectIdentity +export type GitHubProjectSettings = { + pinned: GitHubProjectRef[] + recent: Array + lastViewByProject: Record + activeProject: GitHubProjectRef | null +} +export type GitHubProjectSummary = GitHubProjectRef & { + id: string + title: string + url: string + source: string +} +export type GitHubProjectPartialFailure = { owner: string; message: string } +export type GitHubProjectViewSummary = { + id: string + number: number + name: string + layout: 'TABLE_LAYOUT' | 'BOARD_LAYOUT' | 'ROADMAP_LAYOUT' +} + +export type ParsedGitHubProjectInput = { + owner: string + number: number + host?: string + viewNumber?: number +} + +const OWNER_RE = /^[A-Za-z0-9][A-Za-z0-9-]*$/ + +function positiveInteger(value: string | undefined): number | null { + if (!value || !/^\d+$/.test(value)) { + return null + } + const parsed = Number(value) + return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null +} + +export function parseGitHubProjectInput(input: string): ParsedGitHubProjectInput | null { + const trimmed = input.trim() + const short = /^([A-Za-z0-9][A-Za-z0-9-]*)\/(\d+)$/.exec(trimmed) + if (short) { + const number = positiveInteger(short[2]) + return number ? { owner: short[1]!, number } : null + } + + try { + const url = new URL(trimmed) + if ( + (url.protocol !== 'https:' && url.protocol !== 'http:') || + url.username || + url.password || + !url.host + ) { + return null + } + const parts = url.pathname.split('/').filter(Boolean) + const hasView = parts.length === 6 && parts[4] === 'views' + if ( + (parts[0] !== 'orgs' && parts[0] !== 'users') || + !OWNER_RE.test(parts[1] ?? '') || + parts[2] !== 'projects' || + (parts.length !== 4 && !hasView) + ) { + return null + } + const number = positiveInteger(parts[3]) + const viewNumber = hasView ? positiveInteger(parts[5]) : null + if (!number || (hasView && !viewNumber)) { + return null + } + return { + owner: parts[1]!, + number, + host: url.host.toLowerCase(), + ...(viewNumber ? { viewNumber } : {}) + } + } catch { + return null + } +} diff --git a/mobile/src/tasks/github-project-repo-match.test.ts b/mobile/src/tasks/github-project-repo-match.test.ts index 7979f690d..bce71393d 100644 --- a/mobile/src/tasks/github-project-repo-match.test.ts +++ b/mobile/src/tasks/github-project-repo-match.test.ts @@ -20,7 +20,10 @@ describe('GitHub project repo matching', () => { it('matches project rows by resolved repo slug before path/display heuristics', () => { expect( findRepoForGitHubProjectRepository('stablyai/orca', repos, { - 'repo-1': { path: '/Users/me/orca', slug: 'stablyai/orca' } + 'repo-1': { + path: '/Users/me/orca', + repository: { owner: 'stablyai', repo: 'orca' } + } }) ).toBe(repos[0]) }) @@ -28,8 +31,14 @@ describe('GitHub project repo matching', () => { it('does not pick a repo when resolved slugs are ambiguous', () => { expect( findRepoForGitHubProjectRepository('stablyai/orca', repos, { - 'repo-1': { path: '/Users/me/orca', slug: 'stablyai/orca' }, - 'repo-2': { path: '/Users/me/other', slug: 'stablyai/orca' } + 'repo-1': { + path: '/Users/me/orca', + repository: { owner: 'stablyai', repo: 'orca' } + }, + 'repo-2': { + path: '/Users/me/other', + repository: { owner: 'stablyai', repo: 'orca' } + } }) ).toBeNull() }) @@ -56,7 +65,10 @@ describe('GitHub project repo matching', () => { 'stablyai/orca', [{ id: 'repo-1', path: '/Users/me/stablyai/orca', displayName: 'orca' }], { - 'repo-1': { path: '/Users/me/stablyai/orca', slug: 'fork/orca' } + 'repo-1': { + path: '/Users/me/stablyai/orca', + repository: { owner: 'fork', repo: 'orca' } + } } ) ).toBeNull() @@ -71,8 +83,46 @@ describe('GitHub project repo matching', () => { expect( filterGitHubProjectRowsForRepos(rows, repos, { - 'repo-1': { path: '/Users/me/orca', slug: 'stablyai/orca' } + 'repo-1': { + path: '/Users/me/orca', + repository: { owner: 'stablyai', repo: 'orca' } + } }).map((row) => row.id) ).toEqual(['row-1']) }) + + it('matches same-named repositories only on the active Project host', () => { + expect( + findRepoForGitHubProjectRepository( + 'stablyai/orca', + repos, + { + 'repo-1': { + path: '/Users/me/orca', + repository: { owner: 'stablyai', repo: 'orca', host: 'github.com' } + }, + 'repo-2': { + path: '/Users/me/other', + repository: { + owner: 'stablyai', + repo: 'orca', + host: 'github.acme-corp.com' + } + } + }, + 'github.acme-corp.com' + ) + ).toBe(repos[1]) + }) + + it('does not use hostless path heuristics for Enterprise Project rows', () => { + expect( + findRepoForGitHubProjectRepository( + 'stablyai/orca', + [{ id: 'repo-1', path: '/Users/me/stablyai/orca', displayName: 'orca' }], + {}, + 'github.acme-corp.com' + ) + ).toBeNull() + }) }) diff --git a/mobile/src/tasks/github-project-repo-match.ts b/mobile/src/tasks/github-project-repo-match.ts index bf70f71da..c4d1e1d2e 100644 --- a/mobile/src/tasks/github-project-repo-match.ts +++ b/mobile/src/tasks/github-project-repo-match.ts @@ -1,3 +1,8 @@ +import { + githubRepoIdentityKey, + isDefaultGitHubHost +} from '../../../src/shared/github-repository-identity-key' + export type GitHubProjectRepoMatch = { id: string path: string @@ -6,13 +11,13 @@ export type GitHubProjectRepoMatch = { export type GitHubRepoSlugCacheEntry = { path: string - slug: string | null + repository: { owner: string; repo: string; host?: string } | null } type CachedSlugState = | { status: 'missing' } | { status: 'stale' } - | { status: 'resolved'; slug: string | null } + | { status: 'resolved'; repository: GitHubRepoSlugCacheEntry['repository'] } export function normalizeGitHubRepositorySlug(value: string | null | undefined): string | null { const trimmed = value?.trim() @@ -37,13 +42,14 @@ function cachedSlugStateForRepo( if (cached.path !== repo.path) { return { status: 'stale' } } - return { status: 'resolved', slug: normalizeGitHubRepositorySlug(cached.slug) } + return { status: 'resolved', repository: cached.repository } } export function findRepoForGitHubProjectRepository( repository: string | null | undefined, repos: GitHubProjectRepoMatch[], - slugsByRepoId: Record = {} + slugsByRepoId: Record = {}, + projectHost?: string ): GitHubProjectRepoMatch | null { const slug = normalizeGitHubRepositorySlug(repository) if (!slug) { @@ -53,9 +59,18 @@ export function findRepoForGitHubProjectRepository( const slugStates = new Map( repos.map((repo) => [repo.id, cachedSlugStateForRepo(repo, slugsByRepoId)]) ) + const requestedIdentityKey = githubRepoIdentityKey({ + owner: slug.split('/')[0]!, + repo: slug.split('/')[1]!, + ...(projectHost ? { host: projectHost } : {}) + }) const slugMatches = repos.filter((repo) => { const state = slugStates.get(repo.id) - return state?.status === 'resolved' && state.slug === slug + return ( + state?.status === 'resolved' && + state.repository !== null && + githubRepoIdentityKey(state.repository) === requestedIdentityKey + ) }) if (slugMatches.length === 1) { return slugMatches[0]! @@ -64,10 +79,16 @@ export function findRepoForGitHubProjectRepository( return null } + if (!isDefaultGitHubHost(projectHost)) { + // Why: display names and local paths contain no host evidence, so using + // them for GHES rows could bind an Enterprise item to a github.com repo. + return null + } + return ( repos.find((repo) => { const state = slugStates.get(repo.id) - if (state?.status === 'resolved' && state.slug !== null) { + if (state?.status === 'resolved' && state.repository !== null) { return false } const display = repo.displayName.trim().toLowerCase() @@ -82,9 +103,12 @@ export function filterGitHubProjectRowsForRepos< >( rows: readonly Row[], repos: GitHubProjectRepoMatch[], - slugsByRepoId: Record = {} + slugsByRepoId: Record = {}, + projectHost?: string ): Row[] { return rows.filter((row) => - Boolean(findRepoForGitHubProjectRepository(row.content.repository, repos, slugsByRepoId)) + Boolean( + findRepoForGitHubProjectRepository(row.content.repository, repos, slugsByRepoId, projectHost) + ) ) } diff --git a/mobile/src/tasks/smart-source-paste-intent.test.ts b/mobile/src/tasks/smart-source-paste-intent.test.ts index 05c0757a7..4cd34cb00 100644 --- a/mobile/src/tasks/smart-source-paste-intent.test.ts +++ b/mobile/src/tasks/smart-source-paste-intent.test.ts @@ -1,8 +1,9 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { deriveRepoSlug, findRepoMatchingSlug, findRepoMatchingSlugForPaste, + lookupGitHubItemByOwnerRepo, resolvePasteIntent, type PasteRepoCandidate } from './smart-source-paste-intent' @@ -47,6 +48,14 @@ describe('deriveRepoSlug', () => { }) }) + it('preserves an Enterprise upstream host', () => { + expect( + deriveRepoSlug({ + upstream: { owner: 'up', repo: 'stream', host: 'github.corp.example' } + }) + ).toEqual({ owner: 'up', repo: 'stream', host: 'github.corp.example' }) + }) + it('parses an SSH remote URL', () => { expect( deriveRepoSlug({ gitRemoteIdentity: { remoteUrl: 'git@github.com:acme/widgets.git' } }) @@ -78,6 +87,16 @@ describe('findRepoMatchingSlug', () => { expect(findRepoMatchingSlug(repos, { owner: 'other', repo: 'thing' })).toBeNull() }) + it('does not match a GHES link to a same-named github.com repo', () => { + expect( + findRepoMatchingSlug(repos, { + owner: 'acme', + repo: 'widgets', + host: 'github.corp.example' + }) + ).toBeNull() + }) + it('falls back to the host-aware repo slug RPC for SSH and enterprise repos', async () => { const calls: string[] = [] const client = { @@ -86,7 +105,10 @@ describe('findRepoMatchingSlug', () => { calls.push(repo) return { ok: true, - result: repo === 'id:b' ? { owner: 'enterprise', repo: 'widgets' } : null + result: + repo === 'id:b' + ? { owner: 'enterprise', repo: 'widgets', host: 'github.corp.example' } + : null } } } as unknown as RpcClient @@ -94,7 +116,7 @@ describe('findRepoMatchingSlug', () => { findRepoMatchingSlugForPaste( client, repos, - { owner: 'enterprise', repo: 'widgets' }, + { owner: 'enterprise', repo: 'widgets', host: 'github.corp.example' }, new Map() ) ).resolves.toMatchObject({ id: 'b' }) @@ -139,4 +161,26 @@ describe('findRepoMatchingSlug', () => { ) ).resolves.toBeNull() }) + + it('sends the pasted host through the exact owner/repo lookup RPC', async () => { + const sendRequest = vi.fn().mockResolvedValue({ ok: true, result: null }) + const client = { sendRequest } as unknown as RpcClient + + await lookupGitHubItemByOwnerRepo( + client, + 'repo-1', + { owner: 'acme', repo: 'widgets', host: 'github.corp.example' }, + 7, + 'pr' + ) + + expect(sendRequest).toHaveBeenCalledWith('github.workItemByOwnerRepo', { + repo: 'id:repo-1', + owner: 'acme', + ownerRepo: 'widgets', + host: 'github.corp.example', + number: 7, + type: 'pr' + }) + }) }) diff --git a/mobile/src/tasks/smart-source-paste-intent.ts b/mobile/src/tasks/smart-source-paste-intent.ts index 72c23a373..00f4c0d9e 100644 --- a/mobile/src/tasks/smart-source-paste-intent.ts +++ b/mobile/src/tasks/smart-source-paste-intent.ts @@ -9,6 +9,7 @@ import { parseGitLabIssueOrMRLink } from '../../../src/shared/new-workspace/gitl import { isSmartWorkspaceSourceQueryWithinLimit } from '../../../src/shared/new-workspace/smart-workspace-source-results' import type { RpcClient } from '../transport/rpc-client' import type { RpcSuccess } from '../transport/types' +import { githubRepoIdentityKey } from '../../../src/shared/github-repository-identity-key' // A repo the picker can switch to for a cross-repo GitHub paste. Slug is derived // best-effort from the repo's remote metadata. @@ -58,11 +59,15 @@ export function resolvePasteIntent(query: string): PasteIntent { // Pure: derive an owner/repo slug from a repo's remote metadata so a pasted // cross-repo URL can be matched to a locally known repo. export function deriveRepoSlug(repo: { - upstream?: { owner: string; repo: string } | null + upstream?: { owner: string; repo: string; host?: string } | null gitRemoteIdentity?: { remoteUrl?: string; canonicalKey?: string } | null }): RepoSlug | null { if (repo.upstream?.owner && repo.upstream.repo) { - return { owner: repo.upstream.owner, repo: repo.upstream.repo } + return { + owner: repo.upstream.owner, + repo: repo.upstream.repo, + ...(repo.upstream.host ? { host: repo.upstream.host } : {}) + } } const source = repo.gitRemoteIdentity?.remoteUrl ?? repo.gitRemoteIdentity?.canonicalKey ?? '' const match = /(?:github\.com[/:]|^)([^/\s:]+)\/([^/\s]+?)(?:\.git)?$/i.exec(source) @@ -76,9 +81,7 @@ function slugsEqual(a: RepoSlug | null, b: RepoSlug | null): boolean { if (!a || !b) { return false } - return ( - a.owner.toLowerCase() === b.owner.toLowerCase() && a.repo.toLowerCase() === b.repo.toLowerCase() - ) + return githubRepoIdentityKey(a) === githubRepoIdentityKey(b) } export function findRepoMatchingSlug( @@ -148,6 +151,7 @@ export async function lookupGitHubItemByOwnerRepo( repo: `id:${repoId}`, owner: slug.owner, ownerRepo: slug.repo, + ...(slug.host ? { host: slug.host } : {}), number, type }) diff --git a/mobile/src/tasks/use-smart-workspace-source.ts b/mobile/src/tasks/use-smart-workspace-source.ts index 1d0c88daf..42edcd48e 100644 --- a/mobile/src/tasks/use-smart-workspace-source.ts +++ b/mobile/src/tasks/use-smart-workspace-source.ts @@ -22,7 +22,11 @@ const DEBOUNCE_MS = 200 const RESULT_LIMIT = 36 export type SmartCrossRepoPrompt = { - link: { slug: { owner: string; repo: string }; number: number; type: 'issue' | 'pr' } + link: { + slug: { owner: string; repo: string; host?: string } + number: number + type: 'issue' | 'pr' + } matchingRepo: PasteRepoCandidate } @@ -73,7 +77,9 @@ export function useSmartWorkspaceSource(args: UseSmartWorkspaceSourceArgs) { // the mode/repo changes so one provider's rows never render under another tab. const scopeRef = useRef('') const dismissedPasteRef = useRef('') - const repoSlugCacheRef = useRef>(new Map()) + const repoSlugCacheRef = useRef< + Map + >(new Map()) useEffect(() => { if (!client || !enabled || mode === 'text') { @@ -185,7 +191,7 @@ async function runSmartSearch(args: { linearWorkspaceId: string | null | undefined repos: readonly PasteRepoCandidate[] dismissedPasteRef: { current: string } - repoSlugCache: Map + repoSlugCache: Map }): Promise<{ fan: SmartFanOutResult paste: PasteResolved diff --git a/src/main/git/gh-rate-limit-breaker.test.ts b/src/main/git/gh-rate-limit-breaker.test.ts index 787ad3d17..8fa8d667d 100644 --- a/src/main/git/gh-rate-limit-breaker.test.ts +++ b/src/main/git/gh-rate-limit-breaker.test.ts @@ -131,6 +131,21 @@ describe('breaker state', () => { expect(getGhRateLimitBlockedUntilMs('core', now, 'native:ghe-0.example.test')).toBeNull() }) + it('keeps a recently-read active scope when the bounded map evicts', () => { + const now = Date.now() + const hotScope = 'native:active.example.test' + recordGhPrimaryRateLimit('core', now + 60_000, hotScope) + for (let i = 0; i < 1_023; i += 1) { + recordGhPrimaryRateLimit('core', now + 60_000, `native:cold-${i}.example.test`) + } + + expect(getGhRateLimitBlockedUntilMs('core', now, hotScope)).toBe(now + 60_000) + recordGhPrimaryRateLimit('core', now + 60_000, 'native:new.example.test') + + expect(getGhRateLimitBlockedUntilMs('core', now, hotScope)).toBe(now + 60_000) + expect(getGhRateLimitBlockedUntilMs('core', now, 'native:cold-0.example.test')).toBeNull() + }) + it('notifyGhPrimaryRateLimit applies a fallback block and fires the reset probe', () => { const probe = vi.fn() registerGhRateLimitResetProbe(probe) diff --git a/src/main/git/gh-rate-limit-breaker.ts b/src/main/git/gh-rate-limit-breaker.ts index 6da81bab8..8bc427649 100644 --- a/src/main/git/gh-rate-limit-breaker.ts +++ b/src/main/git/gh-rate-limit-breaker.ts @@ -184,6 +184,10 @@ export function getGhRateLimitBlockedUntilMs( blockedUntilMsByScopeAndBucket.delete(key) return null } + // Why: active blocks are hot entries; refresh their insertion order so a + // stream of one-off hostile hosts evicts cold scopes before an active one. + blockedUntilMsByScopeAndBucket.delete(key) + blockedUntilMsByScopeAndBucket.set(key, blockedUntil) return blockedUntil } diff --git a/src/main/git/runner-gh-rate-limit-breaker.test.ts b/src/main/git/runner-gh-rate-limit-breaker.test.ts index a887b70ac..24fd2d5d0 100644 --- a/src/main/git/runner-gh-rate-limit-breaker.test.ts +++ b/src/main/git/runner-gh-rate-limit-breaker.test.ts @@ -108,6 +108,36 @@ describe('ghExecFileAsync rate-limit breaker', () => { expect(execFileMock).toHaveBeenCalledTimes(5) }) + it.each([ + ['separate', ['--hostname', 'github.com']], + ['inline', ['--hostname=github.com']] + ])('scopes an explicit %s hostname ahead of process GH_HOST', async (_name, hostnameArgs) => { + const originalGhHost = process.env.GH_HOST + process.env.GH_HOST = 'github.acme-corp.com' + try { + mockGhFailure(PRIMARY_RATE_LIMIT_STDERR) + await expect(ghExecFileAsync(['api', ...hostnameArgs, 'repos/a/b/pulls'])).rejects.toThrow( + 'rate limit' + ) + + expect(getGhRateLimitBlockedUntilMs('core', Date.now(), 'native:github.com')).not.toBeNull() + expect( + getGhRateLimitBlockedUntilMs('core', Date.now(), 'native:github.acme-corp.com') + ).toBeNull() + + mockGhSuccess('[]') + await expect(ghExecFileAsync(['api', 'repos/a/b/pulls'])).resolves.toMatchObject({ + stdout: '[]' + }) + } finally { + if (originalGhHost === undefined) { + delete process.env.GH_HOST + } else { + process.env.GH_HOST = originalGhHost + } + } + }) + it('scopes a WSL UNC-cwd 403 to the distro runtime and probes that scope', async () => { // Why: a \\wsl.localhost\... cwd routes gh through wsl.exe, so the 403 // belongs to the distro's account — the native scope must stay usable and diff --git a/src/main/git/runner-wsl-gh-fallback.test.ts b/src/main/git/runner-wsl-gh-fallback.test.ts index ee2c1e9f9..4cd81cda2 100644 --- a/src/main/git/runner-wsl-gh-fallback.test.ts +++ b/src/main/git/runner-wsl-gh-fallback.test.ts @@ -193,6 +193,42 @@ describe('ghExecFileAsync WSL fallback', () => { ) }) + it('falls back for repo view with an explicit positional repository', async () => { + execFileMock.mockImplementation((binary, _args, options, callback) => { + if (typeof options === 'function') { + callback = options + } + if (binary === 'wsl.exe') { + callback( + Object.assign(new Error('Command failed: wsl.exe'), { + stdout: '', + stderr: 'bash: line 1: gh: command not found\n' + }) + ) + return + } + callback(null, { stdout: '{"isFork":false}', stderr: '' }) + }) + + await expect( + ghExecFileAsync( + ['repo', 'view', 'github.acme-corp.com/stablyhq/noqa', '--json', 'isFork,parent'], + { + cwd: String.raw`\\wsl.localhost\Ubuntu\home\jinwoo\stably\noqa`, + host: 'github.acme-corp.com' + } + ) + ).resolves.toEqual({ stdout: '{"isFork":false}', stderr: '' }) + + expect(execFileMock).toHaveBeenNthCalledWith( + 2, + 'gh', + ['repo', 'view', 'github.acme-corp.com/stablyhq/noqa', '--json', 'isFork,parent'], + expect.objectContaining({ cwd: undefined }), + expect.any(Function) + ) + }) + it('does not fall back for gh api calls that depend on repo-context placeholders', async () => { execFileMock.mockImplementation((_binary, _args, _options, callback) => { callback( diff --git a/src/main/git/runner.ts b/src/main/git/runner.ts index 0383ebadb..7d72c6848 100644 --- a/src/main/git/runner.ts +++ b/src/main/git/runner.ts @@ -123,6 +123,17 @@ function argsUseGhApiPlaceholders(args: string[]): boolean { ) } +function hasExplicitRepoViewTarget(args: string[]): boolean { + const target = args[2] + return ( + args[0] === 'repo' && + args[1] === 'view' && + typeof target === 'string' && + !target.startsWith('-') && + target.includes('/') + ) +} + function canRunGitHubCliWithoutRepoCwd(args: string[]): boolean { if (hasExplicitRepoArg(args)) { return true @@ -130,7 +141,7 @@ function canRunGitHubCliWithoutRepoCwd(args: string[]): boolean { if (args[0] === 'api') { return !argsUseGhApiPlaceholders(args) } - return args[0] === 'auth' + return args[0] === 'auth' || hasExplicitRepoViewTarget(args) } function isMissingCommandInWsl(stderr: string, command: string): boolean { @@ -1424,13 +1435,39 @@ export function applyGhHostToArgs(args: string[], host?: string): string[] { return qualified } -function ghRateLimitScope(options: GhExecOptions, resolved: ResolvedCommand): string { +function explicitGhHostname(args: readonly string[]): string | undefined { + for (let i = 0; i < args.length; i += 1) { + if (args[i] === '--hostname') { + const value = args[i + 1]?.trim() + return value || undefined + } + if (args[i].startsWith('--hostname=')) { + const value = args[i].slice('--hostname='.length).trim() + return value || undefined + } + } + return undefined +} + +function ghRateLimitScope( + args: readonly string[], + options: GhExecOptions, + resolved: ResolvedCommand +): string { const runtime = resolved.wsl ? `wsl:${resolved.wsl.distro.toLowerCase()}` : 'native' - const host = options.host ?? options.env?.GH_HOST ?? process.env.GH_HOST ?? 'github.com' + // Why: an explicit argv hostname controls the actual gh request even when + // GH_HOST or options.host disagree, so breaker state must follow that host. + const host = + explicitGhHostname(args) ?? + options.host ?? + options.env?.GH_HOST ?? + process.env.GH_HOST ?? + 'github.com' return ghRateLimitScopeKey(runtime, host) } function assertGhRateLimitScopeAvailable( + args: readonly string[], options: GhExecOptions, resolved: ResolvedCommand, bucket: GhRateLimitBucket, @@ -1442,7 +1479,7 @@ function assertGhRateLimitScopeAvailable( const blockedUntilMs = getGhRateLimitBlockedUntilMs( bucket, Date.now(), - ghRateLimitScope(options, resolved) + ghRateLimitScope(args, options, resolved) ) if (blockedUntilMs !== null) { throw createGhRateLimitBlockedError(bucket, blockedUntilMs) @@ -1471,7 +1508,7 @@ export async function ghExecFileAsync( // cannot block one another after an unrelated quota exhaustion. const rateLimitBucket = classifyGhRateLimitBucket(args) const rateLimitProbe = isGhRateLimitProbe(args) - assertGhRateLimitScopeAvailable(options, resolved, rateLimitBucket, rateLimitProbe) + assertGhRateLimitScopeAvailable(args, options, resolved, rateLimitBucket, rateLimitProbe) let lastError: unknown let attemptedHostFallback = false let attemptedDefaultWslFallback = false @@ -1491,7 +1528,7 @@ export async function ghExecFileAsync( lastError = err const { stderr } = extractExecError(err) if (isGhPrimaryRateLimitStderr(stderr)) { - notifyGhPrimaryRateLimit(rateLimitBucket, ghRateLimitScope(options, resolved)) + notifyGhPrimaryRateLimit(rateLimitBucket, ghRateLimitScope(args, options, resolved)) } if ( process.platform === 'win32' && @@ -1507,7 +1544,7 @@ export async function ghExecFileAsync( // global calls like rate_limit/auth do not carry a repo cwd to route by. resolved = wslResolved attemptedDefaultWslFallback = true - assertGhRateLimitScopeAvailable(options, resolved, rateLimitBucket, rateLimitProbe) + assertGhRateLimitScopeAvailable(args, options, resolved, rateLimitBucket, rateLimitProbe) attempt = -1 continue } @@ -1515,7 +1552,7 @@ export async function ghExecFileAsync( if (!attemptedHostFallback && canFallBackToHostGitHubCli('gh', args, resolved, stderr)) { resolved = resolveHostGitHubCli('gh', args) attemptedHostFallback = true - assertGhRateLimitScopeAvailable(options, resolved, rateLimitBucket, rateLimitProbe) + assertGhRateLimitScopeAvailable(args, options, resolved, rateLimitBucket, rateLimitProbe) attempt = -1 continue } diff --git a/src/main/github/client-create-pr.test.ts b/src/main/github/client-create-pr.test.ts index 8cc6806bb..c3efb986b 100644 --- a/src/main/github/client-create-pr.test.ts +++ b/src/main/github/client-create-pr.test.ts @@ -57,7 +57,8 @@ vi.mock('../git/runner', () => ({ })) vi.mock('./github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock + getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, + isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) })) import { createGitHubPullRequest } from './client' diff --git a/src/main/github/client-file-viewed.test.ts b/src/main/github/client-file-viewed.test.ts index d00f34a34..b9a0bc6fc 100644 --- a/src/main/github/client-file-viewed.test.ts +++ b/src/main/github/client-file-viewed.test.ts @@ -40,7 +40,8 @@ vi.mock('./gh-utils', () => ({ })) vi.mock('./github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock + getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, + isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) })) import { setPRFileViewed } from './client' diff --git a/src/main/github/client-pr-local-runtime.test.ts b/src/main/github/client-pr-local-runtime.test.ts index 03c00cd08..c5e28ce0f 100644 --- a/src/main/github/client-pr-local-runtime.test.ts +++ b/src/main/github/client-pr-local-runtime.test.ts @@ -79,7 +79,9 @@ vi.mock('../git/runner', () => ({ })) vi.mock('./github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock + getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, + getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugMock, + isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) })) vi.mock('../providers/ssh-git-dispatch', () => ({ @@ -228,7 +230,7 @@ describe('GitHub PR local runtime routing', () => { await getPRComments('/repo-root', 7, { prRepo }, null, localGitOptions) await expect( - resolveReviewThread('/repo-root', 'thread-1', true, null, localGitOptions) + resolveReviewThread('/repo-root', 'thread-1', true, null, prRepo, localGitOptions) ).resolves.toBe(true) await expect( addPRReviewCommentReply( @@ -249,6 +251,7 @@ describe('GitHub PR local runtime routing', () => { repoPath: '/repo-root', connectionId: null, localGitOptions, + prRepo, prNumber: 7, body: 'Inline', commitId: 'head-oid', @@ -263,13 +266,13 @@ describe('GitHub PR local runtime routing', () => { updatePRDetails('/repo-root', 7, { body: 'New body' }, null, prRepo, localGitOptions) ).resolves.toEqual({ ok: true }) await expect( - updatePRState('/repo-root', 7, { state: 'closed' }, null, localGitOptions) + updatePRState('/repo-root', 7, { state: 'closed' }, null, prRepo, localGitOptions) ).resolves.toEqual({ ok: true }) await expect( - requestPRReviewers('/repo-root', 7, ['octo'], null, localGitOptions) + requestPRReviewers('/repo-root', 7, ['octo'], null, prRepo, localGitOptions) ).resolves.toEqual({ ok: true }) await expect( - removePRReviewers('/repo-root', 7, ['octo'], null, localGitOptions) + removePRReviewers('/repo-root', 7, ['octo'], null, prRepo, localGitOptions) ).resolves.toEqual({ ok: true }) await expect( setPRAutoMerge('/repo-root', 7, true, 'squash', null, prRepo, localGitOptions) @@ -449,9 +452,16 @@ describe('GitHub PR local runtime routing', () => { getPRCheckDetails('/remote/repo', { checkRunId: 88, prRepo: enterpriseRepo }, 'ssh-1') ).resolves.toMatchObject({ name: 'lint', conclusion: 'failure' }) await expect( - rerunPRChecks('/remote/repo', 7, { headSha: 'head-sha', failedOnly: true }, 'ssh-1') + rerunPRChecks( + '/remote/repo', + 7, + { headSha: 'head-sha', failedOnly: true, prRepo: enterpriseRepo }, + 'ssh-1' + ) ).resolves.toEqual({ ok: true, count: 1 }) - await expect(resolveReviewThread('/remote/repo', 'thread-1', true, 'ssh-1')).resolves.toBe(true) + await expect( + resolveReviewThread('/remote/repo', 'thread-1', true, 'ssh-1', enterpriseRepo) + ).resolves.toBe(true) await expect( addPRReviewCommentReply( '/remote/repo', @@ -469,6 +479,7 @@ describe('GitHub PR local runtime routing', () => { addPRReviewComment({ repoPath: '/remote/repo', connectionId: 'ssh-1', + prRepo: enterpriseRepo, prNumber: 7, body: 'Enterprise inline comment', commitId: 'head-sha', @@ -482,13 +493,19 @@ describe('GitHub PR local runtime routing', () => { await expect( updatePRDetails('/remote/repo', 7, { body: 'New body' }, 'ssh-1', enterpriseRepo) ).resolves.toEqual({ ok: true }) - await expect(updatePRState('/remote/repo', 7, { state: 'closed' }, 'ssh-1')).resolves.toEqual({ + await expect( + updatePRState('/remote/repo', 7, { state: 'closed' }, 'ssh-1', enterpriseRepo) + ).resolves.toEqual({ ok: true }) - await expect(requestPRReviewers('/remote/repo', 7, ['octo'], 'ssh-1')).resolves.toEqual({ + await expect( + requestPRReviewers('/remote/repo', 7, ['octo'], 'ssh-1', enterpriseRepo) + ).resolves.toEqual({ ok: true }) - await expect(removePRReviewers('/remote/repo', 7, ['octo'], 'ssh-1')).resolves.toEqual({ + await expect( + removePRReviewers('/remote/repo', 7, ['octo'], 'ssh-1', enterpriseRepo) + ).resolves.toEqual({ ok: true }) await expect( diff --git a/src/main/github/client-work-items-query-paging.test.ts b/src/main/github/client-work-items-query-paging.test.ts index df95e0cbe..b3f819c21 100644 --- a/src/main/github/client-work-items-query-paging.test.ts +++ b/src/main/github/client-work-items-query-paging.test.ts @@ -11,6 +11,9 @@ const { gitExecFileAsyncMock, rateLimitGuardMock, noteRateLimitSpendMock, + repositoryRateLimitGuardMock, + noteRepositoryRateLimitSpendMock, + spendsSharedGitHubComQuotaMock, acquireMock, releaseMock } = vi.hoisted(() => ({ @@ -23,6 +26,11 @@ const { gitExecFileAsyncMock: vi.fn(), rateLimitGuardMock: vi.fn((_bucket?: unknown) => ({ blocked: false })), noteRateLimitSpendMock: vi.fn(), + repositoryRateLimitGuardMock: vi.fn((_repo: unknown, bucket: string) => + rateLimitGuardMock(bucket) + ), + noteRepositoryRateLimitSpendMock: vi.fn(), + spendsSharedGitHubComQuotaMock: vi.fn(() => true), acquireMock: vi.fn(), releaseMock: vi.fn() })) @@ -67,11 +75,9 @@ vi.mock('./rate-limit', () => ({ noteRateLimitSpend: noteRateLimitSpendMock, getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })), // Mirror production: shared-scope calls delegate to the global guard/spend. - repositoryRateLimitGuard: vi.fn((_repo: unknown, bucket: string) => rateLimitGuardMock(bucket)), - noteRepositoryRateLimitSpend: vi.fn((_repo: unknown, bucket: string, cost?: number) => - noteRateLimitSpendMock(bucket, cost) - ), - spendsSharedGitHubComQuota: () => true + repositoryRateLimitGuard: repositoryRateLimitGuardMock, + noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock, + spendsSharedGitHubComQuota: spendsSharedGitHubComQuotaMock })) vi.mock('./github-api-repository', async (importOriginal) => { @@ -135,6 +141,10 @@ describe('listWorkItems query paging', () => { rateLimitGuardMock.mockReset() rateLimitGuardMock.mockReturnValue({ blocked: false }) noteRateLimitSpendMock.mockReset() + repositoryRateLimitGuardMock.mockClear() + noteRepositoryRateLimitSpendMock.mockReset() + spendsSharedGitHubComQuotaMock.mockReset() + spendsSharedGitHubComQuotaMock.mockReturnValue(true) acquireMock.mockReset() releaseMock.mockReset() acquireMock.mockResolvedValue(undefined) @@ -165,6 +175,31 @@ describe('listWorkItems query paging', () => { expect(releaseMock).not.toHaveBeenCalled() }) + it('uses an implicit WSL UNC cwd for search quota accounting', async () => { + const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } + const repoPath = String.raw`\\wsl.localhost\Ubuntu\home\me\widgets` + getIssueOwnerRepoMock.mockResolvedValueOnce(repository) + getOwnerRepoMock.mockResolvedValueOnce(repository) + ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '3' }) + spendsSharedGitHubComQuotaMock.mockReturnValue(false) + + await expect(countWorkItems(repoPath, 'is:issue is:open')).resolves.toBe(3) + + const executionOptions = { cwd: repoPath, host: 'github.com' } + expect(spendsSharedGitHubComQuotaMock).toHaveBeenCalledWith(repository, executionOptions) + expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith( + repository, + 'search', + executionOptions + ) + expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalledWith( + repository, + 'search', + 1, + executionOptions + ) + }) + it('passes review-requested as a --search qualifier (gh CLI has no dedicated flag)', async () => { getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index 5c78ee8b1..cbdcef7a3 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -3690,6 +3690,39 @@ describe('getPRForBranch', () => { ) }) + it('does not confuse same-slug PR repositories across GitHub hosts', async () => { + const enterprise = { owner: 'team', repo: 'orca', host: 'github.acme-corp.com' } + const dotCom = { owner: 'team', repo: 'orca', host: 'github.com' } + resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ + candidates: [enterprise, dotCom], + headRepo: dotCom + }) + getOwnerRepoForRemoteMock.mockResolvedValueOnce(dotCom) + getRemoteUrlForRepoMock.mockResolvedValueOnce('git@github.com:team/orca.git') + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + head: { + ref: 'feature', + repo: { + full_name: 'team/orca', + name: 'orca', + clone_url: 'https://github.acme-corp.com/team/orca.git', + ssh_url: 'git@github.acme-corp.com:team/orca.git', + owner: { login: 'team' } + } + } + }) + }) + + await expect(getPullRequestPushTarget('/repo-root', 7)).resolves.toEqual({ + pushTarget: { + remoteName: 'pr-team-orca', + branchName: 'feature', + remoteUrl: 'git@github.acme-corp.com:team/orca.git' + } + }) + }) + it('probes additional PR repo candidates when the first lookup is not found', async () => { resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ candidates: [ @@ -4271,6 +4304,13 @@ describe('GitHub GraphQL rate-limit guard', () => { }) it('isolates merge metadata for the same slug on different GitHub hosts', async () => { + resolvePRRepositoryCandidatesMock.mockResolvedValue({ + candidates: [ + { owner: 'acme', repo: 'widgets', host: 'github.com' }, + { owner: 'acme', repo: 'widgets', host: 'github.acme-corp.com' } + ], + headRepo: { owner: 'acme', repo: 'widgets', host: 'github.com' } + }) const prView = { number: 7, title: 'PR', @@ -4320,6 +4360,25 @@ describe('GitHub GraphQL rate-limit guard', () => { expect(graphqlCalls[1]?.[1]).toEqual(expect.objectContaining({ host: 'github.acme-corp.com' })) }) + it('rejects explicit work-item lookups outside configured repository candidates', async () => { + resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ + candidates: [{ owner: 'acme', repo: 'widgets', host: 'github.com' }], + headRepo: { owner: 'acme', repo: 'widgets', host: 'github.com' } + }) + + await expect( + getWorkItemByOwnerRepo( + '/repo-root', + { owner: 'victim', repo: 'secrets', host: 'evil.example.test' }, + 7, + 'pr' + ) + ).resolves.toBeNull() + + expect(acquireMock).not.toHaveBeenCalled() + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) + it('returns conflicting file details instead of running gh merge when PR is dirty', async () => { ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: JSON.stringify({ diff --git a/src/main/github/client.ts b/src/main/github/client.ts index c60765b52..0f7531987 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -189,7 +189,7 @@ function pruneRepositoryMergeMetadataCache(now = Date.now()): void { async function assertRateLimitBudget( bucket: RateLimitBucketKind, repository?: GitHubApiRepository | null, - executionOptions?: Pick + executionOptions?: Pick ): Promise { if (spendsSharedGitHubComQuota(repository, executionOptions)) { await getRateLimit() @@ -313,6 +313,7 @@ export async function getPullRequestPushTarget( await acquire() try { let prStdout = '' + let matchedRepository: GitHubApiRepository | null = null for (const candidate of candidates) { try { const { stdout } = await ghExecFileAsync( @@ -320,6 +321,7 @@ export async function getPullRequestPushTarget( { ...ghOptions, ...githubHostExecOptions(candidate) } ) prStdout = stdout + matchedRepository = candidate break } catch (error) { // Why: in fork workflows `origin` is often the contributor fork while @@ -331,7 +333,7 @@ export async function getPullRequestPushTarget( throw error } } - if (!prStdout) { + if (!prStdout || !matchedRepository) { return null } const origin = await getGitHubApiRepositoryForRemote( @@ -366,8 +368,8 @@ export async function getPullRequestPushTarget( } if ( origin && - origin.owner.toLowerCase() === owner.toLowerCase() && - origin.repo.toLowerCase() === repo.toLowerCase() + githubRepoIdentityKey(origin) === + githubRepoIdentityKey({ owner, repo, host: matchedRepository.host }) ) { return { pushTarget: { remoteName: 'origin', branchName }, @@ -1577,7 +1579,7 @@ async function countWorkItemsForQuery( ) // Why: over-counts gh cache hits, which is the safe direction — the search // bucket is only 30/min and the next probe corrects the estimate. - noteRepositoryRateLimitSpend(ownerRepo, 'search', 1, localGitOptions) + noteRepositoryRateLimitSpend(ownerRepo, 'search', 1, ghOptions) return Number.parseInt(stdout.trim(), 10) || 0 } @@ -1629,16 +1631,20 @@ export async function countWorkItems( const parsedQuery = trimmedQuery ? parseTaskQuery(trimmedQuery) : null const effectiveQuery = parsedQuery ?? defaultOpenWorkItemQuery() + const ghOptions = { + ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), + ...githubHostExecOptions(ownerRepo) + } // Why: counts are decorative (pagination totals). The search bucket is only // 30/min, so a multi-repo Tasks page must stop counting when the budget is // gone instead of converting the remaining repos into 403 spawns. getRateLimit // is 30s-cached and single-flight, so priming here is one spawn per window. // Only shared github.com traffic consults the snapshot; other scopes bypass. - if (spendsSharedGitHubComQuota(ownerRepo, localGitOptions)) { + if (spendsSharedGitHubComQuota(ownerRepo, ghOptions)) { await getRateLimit() } - if (repositoryRateLimitGuard(ownerRepo, 'search', localGitOptions).blocked) { + if (repositoryRateLimitGuard(ownerRepo, 'search', ghOptions).blocked) { return 0 } @@ -2142,14 +2148,34 @@ export async function getWorkItemByOwnerRepo( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} ): Promise { + const { candidates } = await resolveGitHubApiRepositoryCandidates( + repoPath, + connectionId, + localGitOptions + ) + const requestedKey = githubRepoIdentityKey(ownerRepo) + const matchedRepository = candidates.find( + (candidate) => githubRepoIdentityKey(candidate) === requestedKey + ) + // Why: this lookup is reachable from pasted links. Restricting it to a + // configured remote prevents gh from sending credentials to an arbitrary host. + if (!matchedRepository) { + return null + } await acquire() try { if (type === 'issue') { - return await fetchIssueWorkItem(repoPath, ownerRepo, number, connectionId, localGitOptions) + return await fetchIssueWorkItem( + repoPath, + matchedRepository, + number, + connectionId, + localGitOptions + ) } return await fetchPullRequestWorkItem( repoPath, - ownerRepo, + matchedRepository, number, connectionId, localGitOptions @@ -4058,13 +4084,17 @@ function parseActionsRunId(url: string | null | undefined): number | undefined { export async function rerunPRChecks( repoPath: string, prNumber: number, - options: { headSha?: string; failedOnly?: boolean } = {}, + options: { + headSha?: string + failedOnly?: boolean + prRepo?: GitHubApiRepository | null + } = {}, connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} ): Promise { const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( repoPath, - undefined, + options.prRepo, connectionId, localGitOptions ) @@ -4452,13 +4482,14 @@ export async function setPRFileViewed(args: { repoPath: string connectionId?: string | null localGitOptions?: LocalGitExecOptions + prRepo?: GitHubApiRepository | null pullRequestId: string path: string viewed: boolean }): Promise { const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( args.repoPath, - undefined, + args.prRepo, args.connectionId, args.localGitOptions ) @@ -4503,13 +4534,14 @@ export async function resolveReviewThread( threadId: string, resolve: boolean, connectionId?: string | null, + prRepo?: GitHubApiRepository | null, localGitOptions: LocalGitExecOptions = {} ): Promise { const mutation = resolve ? 'resolveReviewThread' : 'unresolveReviewThread' const query = `mutation($threadId: ID!) { ${mutation}(input: { threadId: $threadId }) { thread { isResolved } } }` const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( repoPath, - undefined, + prRepo, connectionId, localGitOptions ) @@ -4628,7 +4660,7 @@ export async function addPRReviewComment( ): Promise { const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( args.repoPath, - undefined, + args.prRepo, args.connectionId, args.localGitOptions ) @@ -4956,11 +4988,12 @@ export async function updatePRState( prNumber: number, updates: GitHubPullRequestStateUpdate, connectionId?: string | null, + prRepo?: GitHubApiRepository | null, localGitOptions: LocalGitExecOptions = {} ): Promise<{ ok: true } | { ok: false; error: string }> { const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( repoPath, - undefined, + prRepo, connectionId, localGitOptions ) @@ -4994,6 +5027,7 @@ export async function requestPRReviewers( prNumber: number, reviewers: string[], connectionId?: string | null, + prRepo?: GitHubApiRepository | null, localGitOptions: LocalGitExecOptions = {} ): Promise<{ ok: true } | { ok: false; error: string }> { const logins = reviewers.map((reviewer) => reviewer.trim()).filter(Boolean) @@ -5002,7 +5036,7 @@ export async function requestPRReviewers( } const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( repoPath, - undefined, + prRepo, connectionId, localGitOptions ) @@ -5034,6 +5068,7 @@ export async function removePRReviewers( prNumber: number, reviewers: string[], connectionId?: string | null, + prRepo?: GitHubApiRepository | null, localGitOptions: LocalGitExecOptions = {} ): Promise<{ ok: true } | { ok: false; error: string }> { const logins = reviewers.map((reviewer) => reviewer.trim()).filter(Boolean) @@ -5042,7 +5077,7 @@ export async function removePRReviewers( } const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( repoPath, - undefined, + prRepo, connectionId, localGitOptions ) diff --git a/src/main/github/github-api-repository.test.ts b/src/main/github/github-api-repository.test.ts index 57c94259b..64ff0f8ea 100644 --- a/src/main/github/github-api-repository.test.ts +++ b/src/main/github/github-api-repository.test.ts @@ -1,6 +1,24 @@ -import { describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as GitHubEnterpriseRepository from './github-enterprise-repository' -import { githubHostExecOptions, resolveGitHubRepoExecution } from './github-api-repository' +const { isGitHubHostAuthenticatedMock } = vi.hoisted(() => ({ + isGitHubHostAuthenticatedMock: vi.fn() +})) + +vi.mock('./github-enterprise-repository', async (importOriginal) => ({ + ...(await importOriginal()), + isGitHubHostAuthenticated: isGitHubHostAuthenticatedMock +})) + +import { + githubHostExecOptions, + resolveGitHubApiRepository, + resolveGitHubRepoExecution +} from './github-api-repository' + +beforeEach(() => { + isGitHubHostAuthenticatedMock.mockReset().mockResolvedValue(false) +}) describe('githubHostExecOptions', () => { it('pins every known repository host', () => { @@ -21,6 +39,7 @@ describe('githubHostExecOptions', () => { describe('resolveGitHubRepoExecution', () => { it('combines local repository and GitHub host execution options', async () => { const ownerRepo = { owner: 'acme', repo: 'widgets', host: 'github.acme-corp.com' } + isGitHubHostAuthenticatedMock.mockResolvedValue(true) await expect( resolveGitHubRepoExecution('/repo', ownerRepo, null, { wslDistro: 'Ubuntu' }) @@ -32,6 +51,45 @@ describe('resolveGitHubRepoExecution', () => { host: 'github.acme-corp.com' } }) + expect(isGitHubHostAuthenticatedMock).toHaveBeenCalledWith( + 'github.acme-corp.com', + '/repo', + null, + { wslDistro: 'Ubuntu' } + ) + }) + + it('rejects an explicit Enterprise host absent from the local gh auth inventory', async () => { + await expect( + resolveGitHubApiRepository( + '/remote/repo', + { + owner: 'acme', + repo: 'widgets', + host: 'evil.example.test' + }, + 'ssh-1' + ) + ).resolves.toBeNull() + + expect(isGitHubHostAuthenticatedMock).toHaveBeenCalledWith( + 'evil.example.test', + '/remote/repo', + 'ssh-1', + {} + ) + }) + + it('normalizes github.com without spending an auth inventory probe', async () => { + await expect( + resolveGitHubApiRepository('/repo', { + owner: 'acme', + repo: 'widgets', + host: ' GitHub.COM ' + }) + ).resolves.toEqual({ owner: 'acme', repo: 'widgets', host: 'github.com' }) + + expect(isGitHubHostAuthenticatedMock).not.toHaveBeenCalled() }) it('uses a caller-specific repository resolver without changing its identity', async () => { diff --git a/src/main/github/github-api-repository.ts b/src/main/github/github-api-repository.ts index 596afa003..03e31a9b0 100644 --- a/src/main/github/github-api-repository.ts +++ b/src/main/github/github-api-repository.ts @@ -11,7 +11,8 @@ import { } from './gh-utils' import { getEnterpriseGitHubRepoSlug, - getEnterpriseGitHubRepoSlugForRemote + getEnterpriseGitHubRepoSlugForRemote, + isGitHubHostAuthenticated } from './github-enterprise-repository' export type GitHubApiRepository = GitHubOwnerRepo @@ -241,7 +242,22 @@ export async function resolveGitHubApiRepository( localGitOptions: LocalGitExecOptions = {} ): Promise { if (repository?.host) { - return repository + const host = repository.host.trim().toLowerCase() + if (!host) { + return null + } + if (isDefaultGitHubHost(host)) { + return { ...repository, host } + } + // Why: client-supplied hosts must match gh's local auth inventory before + // they can receive ambient Enterprise credentials from a host-pinned call. + const authenticated = await isGitHubHostAuthenticated( + host, + repoPath, + connectionId, + localGitOptions + ) + return authenticated ? { ...repository, host } : null } const originRepository = await getOriginGitHubApiRepository( repoPath, diff --git a/src/main/github/github-enterprise-repository.test.ts b/src/main/github/github-enterprise-repository.test.ts index a0ab303d9..2cf8914f9 100644 --- a/src/main/github/github-enterprise-repository.test.ts +++ b/src/main/github/github-enterprise-repository.test.ts @@ -15,7 +15,8 @@ vi.mock('../git/runner', () => ({ import { _resetGitHubHostAuthCache, getEnterpriseGitHubRepoSlug, - isGitHubHostAuthenticated + isGitHubHostAuthenticated, + isGitHubHostAuthenticatedForGlobalCli } from './github-enterprise-repository' function mockOriginRemote(url: string): void { @@ -61,12 +62,9 @@ describe('getEnterpriseGitHubRepoSlug', () => { repo: 'orca', host: 'github.acme-corp.com' }) - // The auth probe targets the remote's host, not a hardcoded github.com, and - // scopes any breaker trip to that host via the exec options. - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['auth', 'status', '--hostname', 'github.acme-corp.com'], - { cwd: '/repo', host: 'github.acme-corp.com' } - ) + // Why: inventory configured gh hosts without targeting the untrusted remote; + // passing it as --hostname could expose an ambient enterprise token. + expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], { cwd: '/repo' }) }) it('resolves a GHES SCP-style SSH remote', async () => { @@ -88,10 +86,10 @@ describe('getEnterpriseGitHubRepoSlug', () => { localGitExecOptions: { wslDistro: 'Ubuntu' } }) - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['auth', 'status', '--hostname', 'github.acme-corp.com'], - { cwd: '/repo', wslDistro: 'Ubuntu', host: 'github.acme-corp.com' } - ) + expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], { + cwd: '/repo', + wslDistro: 'Ubuntu' + }) }) it('leaves github.com to getOwnerRepo without probing gh auth', async () => { @@ -136,10 +134,7 @@ describe('isGitHubHostAuthenticated', () => { await expect( isGitHubHostAuthenticated('github.acme-corp.com', '/remote/repo', 'ssh-1') ).resolves.toBe(true) - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['auth', 'status', '--hostname', 'github.acme-corp.com'], - { host: 'github.acme-corp.com' } - ) + expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], {}) }) it('caches per runtime+host so detection polling does not re-spawn gh', async () => { @@ -155,7 +150,12 @@ describe('isGitHubHostAuthenticated', () => { ghExecFileAsyncMock.mockImplementation( () => new Promise((resolve) => { - finishProbe = () => resolve({ stdout: '', stderr: '' }) + finishProbe = () => + resolve({ + stdout: + 'github.acme-corp.com\n ✓ Logged in to github.acme-corp.com account kelora (keyring)', + stderr: '' + }) }) ) @@ -175,6 +175,66 @@ describe('isGitHubHostAuthenticated', () => { expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) }) + it('derives cache scope from an implicit WSL UNC repository path', async () => { + const originalPlatform = process.platform + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + ghExecFileAsyncMock.mockImplementation(async (_args: string[], options: { cwd?: string }) => ({ + stdout: options.cwd?.includes('Ubuntu') + ? 'github.com\n ✓ Logged in to github.com account other (keyring)' + : 'github.acme-corp.com\n ✓ Logged in to github.acme-corp.com account kelora (keyring)', + stderr: '' + })) + + try { + await expect(isGitHubHostAuthenticated('github.acme-corp.com', '/native/repo')).resolves.toBe( + true + ) + await expect( + isGitHubHostAuthenticated( + 'github.acme-corp.com', + String.raw`\\wsl.localhost\Ubuntu\home\me\repo` + ) + ).resolves.toBe(false) + await expect( + isGitHubHostAuthenticated( + 'github.acme-corp.com', + String.raw`\\wsl.localhost\Debian\home\me\repo` + ) + ).resolves.toBe(true) + + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(3) + } finally { + Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) + } + }) + + it('shares the native gh auth probe across SSH connections', async () => { + mockHostAuthenticated() + + await isGitHubHostAuthenticated('github.acme-corp.com', '/remote/a', 'ssh-1') + await isGitHubHostAuthenticated('github.acme-corp.com', '/remote/b', 'ssh-2') + + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + }) + + it('does not target an unconfigured remote host with ambient credentials', async () => { + mockHostAuthenticated('github.acme-corp.com') + + await expect(isGitHubHostAuthenticated('evil.example.test', '/repo')).resolves.toBe(false) + + expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], { cwd: '/repo' }) + expect(ghExecFileAsyncMock.mock.calls.flat()).not.toContain('evil.example.test') + }) + + it('validates a global project host by inventory without targeting it', async () => { + mockHostAuthenticated('github.acme-corp.com') + + await expect(isGitHubHostAuthenticatedForGlobalCli('evil.example.test')).resolves.toBe(false) + + expect(ghExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], {}) + expect(ghExecFileAsyncMock.mock.calls.flat()).not.toContain('evil.example.test') + }) + it('treats a listed host as authenticated even when gh exits non-zero', async () => { ghExecFileAsyncMock.mockRejectedValue( Object.assign(new Error('exit 1'), { diff --git a/src/main/github/github-enterprise-repository.ts b/src/main/github/github-enterprise-repository.ts index bd832a229..35e3cc253 100644 --- a/src/main/github/github-enterprise-repository.ts +++ b/src/main/github/github-enterprise-repository.ts @@ -12,6 +12,7 @@ import { parseGitHubRemoteIdentity, type LocalGitExecOptions } from './github-repository-identity' +import { parseWslPath } from '../wsl' export type GitHubEnterpriseRepoSlug = GitHubOwnerRepo & { host: string } @@ -30,12 +31,11 @@ type HostAuthCacheEntry = { const hostAuthCache = new Map() const hostAuthInFlight = new Map>() -// Why: gh's authenticated hosts live in per-runtime config — a WSL distro and an -// SSH host each carry their own `hosts.yml` — so cache state must be keyed by the -// runtime that executes gh, not shared under one "local" bucket. Mirrors the -// runtime scoping used by owner/repo resolution. -function runtimeCacheKey(connectionId?: string | null, wslDistro?: string): string { - return connectionId ?? `local:${wslDistro ?? 'host'}` +// Why: connection-backed Git operations execute remotely, but gh intentionally +// executes on the native host. Only WSL selects a distinct gh config/runtime. +function runtimeCacheKey(repoPath: string, wslDistro?: string): string { + const resolvedDistro = wslDistro ?? parseWslPath(repoPath)?.distro + return `local:${resolvedDistro?.toLowerCase() ?? 'host'}` } /** @internal - exposed for tests only */ @@ -78,11 +78,10 @@ function ghCommandOutput(error: unknown): string { /** * Whether `gh` is authenticated to `host` from the repository's own runtime. * - * The probe runs `gh auth status --hostname ` with the repo's execution - * options (cwd / WSL distro, or SSH-local like the create path), so a GHES login - * stored only in that runtime's gh config — or a `GH_ENTERPRISE_TOKEN` inferred - * from it — is honored instead of the host/default-distro gh. Cached briefly per - * runtime+host so provider-detection polling does not re-spawn gh each time. + * The probe inventories gh's configured hosts and matches `host` locally. It + * deliberately does not pass an untrusted remote host to gh because ambient + * enterprise tokens could otherwise be sent to that host during validation. + * Cached briefly per runtime+host so provider-detection polling stays cheap. */ export async function isGitHubHostAuthenticated( host: string, @@ -91,7 +90,7 @@ export async function isGitHubHostAuthenticated( localGitOptions: LocalGitExecOptions = {} ): Promise { const normalizedHost = host.toLowerCase() - const cacheKey = `${runtimeCacheKey(connectionId, localGitOptions.wslDistro)}\0${normalizedHost}` + const cacheKey = `${runtimeCacheKey(repoPath, localGitOptions.wslDistro)}\0${normalizedHost}` const now = Date.now() pruneHostAuthCache(now) const cached = hostAuthCache.get(cacheKey) @@ -106,15 +105,14 @@ export async function isGitHubHostAuthenticated( // once; coalesce them so one host never spawns duplicate auth subprocesses. const probe = (async () => { const execOptions = { - ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), - // Why: scope any rate-limit breaker trip from this probe to the probed - // host, not to gh's default account. - host: normalizedHost + ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)) } let authenticated: boolean try { - await ghExecFileAsync(['auth', 'status', '--hostname', normalizedHost], execOptions) - authenticated = true + const { stdout, stderr } = await ghExecFileAsync(['auth', 'status'], execOptions) + authenticated = parseAuthStatus(`${stdout}\n${stderr}`).some( + (account) => account.host.toLowerCase() === normalizedHost + ) } catch (error) { const output = ghCommandOutput(error) if (!output) { @@ -142,6 +140,12 @@ export async function isGitHubHostAuthenticated( } } +/** Safely validate a project-selected host without giving the untrusted host + * to gh. Global project calls have no repository cwd, so they use native gh. */ +export function isGitHubHostAuthenticatedForGlobalCli(host: string): Promise { + return isGitHubHostAuthenticated(host, '', 'project-host-validation') +} + /** * Resolve owner/repo for a GitHub Enterprise Server remote — a custom host the * user is gh-authenticated to. Returns null for github.com (already handled by diff --git a/src/main/github/pr-refresh-coordinator.test.ts b/src/main/github/pr-refresh-coordinator.test.ts index 91692e906..7298c36af 100644 --- a/src/main/github/pr-refresh-coordinator.test.ts +++ b/src/main/github/pr-refresh-coordinator.test.ts @@ -2,6 +2,7 @@ request timestamps, and follow-up scheduling against shared module state. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { GitHubPRRefreshCandidate, PRInfo } from '../../shared/types' +import { isWslUncPath } from '../../shared/wsl-paths' const { sendMock, @@ -117,8 +118,10 @@ describe('pr-refresh-coordinator', () => { repositoryRateLimitGuardMock.mockReturnValue({ blocked: false }) spendsSharedGitHubComQuotaMock.mockReset() spendsSharedGitHubComQuotaMock.mockImplementation( - (repository: { host?: string } | null, options?: { wslDistro?: string }) => - (!repository?.host || repository.host.toLowerCase() === 'github.com') && !options?.wslDistro + (repository: { host?: string } | null, options?: { cwd?: string; wslDistro?: string }) => + (!repository?.host || repository.host.toLowerCase() === 'github.com') && + !options?.wslDistro && + !(options?.cwd && isWslUncPath(options.cwd)) ) getAllWebContentsMock.mockReturnValue([ { @@ -596,12 +599,20 @@ describe('pr-refresh-coordinator', () => { { scope: 'GitHub Enterprise', repository: { owner: 'acme', repo: 'widgets', host: 'github.acme-corp.com' }, + repoPath: '/repo', localGitOptions: undefined }, { scope: 'WSL', repository: { owner: 'acme', repo: 'widgets', host: 'github.com' }, + repoPath: '/repo', localGitOptions: { wslDistro: 'Ubuntu' } + }, + { + scope: 'implicit WSL UNC', + repository: { owner: 'acme', repo: 'widgets', host: 'github.com' }, + repoPath: String.raw`\\wsl.localhost\Ubuntu\home\me\widgets`, + localGitOptions: undefined } ])('bypasses the shared budget for $scope background refreshes', async (testCase) => { const { enqueuePRRefresh } = await import('./pr-refresh-coordinator') @@ -610,9 +621,20 @@ describe('pr-refresh-coordinator', () => { kind: 'no-pr', fetchedAt: Date.now() }) - const executionOptions = testCase.localGitOptions ?? {} + const executionOptions = { + cwd: testCase.repoPath, + ...testCase.localGitOptions + } - enqueuePRRefresh(makeCandidate({ localGitOptions: testCase.localGitOptions }), 'active', 80, 1) + enqueuePRRefresh( + makeCandidate({ + repoPath: testCase.repoPath, + localGitOptions: testCase.localGitOptions + }), + 'active', + 80, + 1 + ) await vi.advanceTimersByTimeAsync(0) diff --git a/src/main/github/pr-refresh-coordinator.ts b/src/main/github/pr-refresh-coordinator.ts index 28d1d1e8b..025940fff 100644 --- a/src/main/github/pr-refresh-coordinator.ts +++ b/src/main/github/pr-refresh-coordinator.ts @@ -772,7 +772,13 @@ async function drainQueue(): Promise { ) if (isBackground(next.reason)) { - const executionOptions = next.candidate.localGitOptions ?? {} + const executionOptions = ghRepoExecOptions( + githubRepoContext( + next.candidate.repoPath, + next.candidate.connectionId, + next.candidate.localGitOptions + ) + ) const repository = await getOriginGitHubApiRepository( next.candidate.repoPath, next.candidate.connectionId, diff --git a/src/main/github/project-view-host-auth.test.ts b/src/main/github/project-view-host-auth.test.ts new file mode 100644 index 000000000..ec426d953 --- /dev/null +++ b/src/main/github/project-view-host-auth.test.ts @@ -0,0 +1,93 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + acquireMock, + releaseMock, + ghExecFileAsyncMock, + hostAuthenticatedMock, + noteRepositoryRateLimitSpendMock +} = vi.hoisted(() => ({ + acquireMock: vi.fn(), + releaseMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + hostAuthenticatedMock: vi.fn(), + noteRepositoryRateLimitSpendMock: vi.fn() +})) + +vi.mock('./gh-utils', () => ({ + acquire: acquireMock, + release: releaseMock +})) + +vi.mock('../git/runner', () => ({ + extractExecError: vi.fn(() => ({ stdout: '', stderr: '' })), + ghExecFileAsync: ghExecFileAsyncMock +})) + +vi.mock('./rate-limit', () => ({ + rateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRateLimitSpend: vi.fn(), + repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock +})) + +vi.mock('./github-enterprise-repository', () => ({ + isGitHubHostAuthenticatedForGlobalCli: hostAuthenticatedMock +})) + +import { runGraphql, runRest } from './project-view/internals' + +describe('project view host authentication boundary', () => { + beforeEach(() => { + acquireMock.mockReset().mockResolvedValue(undefined) + releaseMock.mockReset() + ghExecFileAsyncMock.mockReset() + hostAuthenticatedMock.mockReset() + noteRepositoryRateLimitSpendMock.mockReset() + }) + + it('does not send GraphQL or REST requests to an unconfigured host', async () => { + hostAuthenticatedMock.mockResolvedValue(false) + + const [graphql, rest] = await Promise.all([ + runGraphql('query { viewer { login } }', {}, { host: 'evil.example.test' }), + runRest(['user'], undefined, 'core', { host: 'evil.example.test' }) + ]) + + expect(graphql).toMatchObject({ ok: false, error: { type: 'auth_required' } }) + expect(rest).toMatchObject({ ok: false, error: { type: 'auth_required' } }) + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + expect(acquireMock).not.toHaveBeenCalled() + expect(noteRepositoryRateLimitSpendMock).not.toHaveBeenCalled() + }) + + it('routes a configured Enterprise request to its selected host', async () => { + hostAuthenticatedMock.mockResolvedValue(true) + ghExecFileAsyncMock.mockResolvedValue({ + stdout: '{"data":{"viewer":{"login":"me"}}}', + stderr: '' + }) + + await expect( + runGraphql('query { viewer { login } }', {}, { host: 'github.corp.example' }) + ).resolves.toMatchObject({ ok: true }) + + expect(ghExecFileAsyncMock).toHaveBeenCalledWith(expect.any(Array), { + encoding: 'utf-8', + host: 'github.corp.example' + }) + }) + + it('keeps github.com fast and never probes it as Enterprise', async () => { + ghExecFileAsyncMock.mockResolvedValue({ + stdout: '{"data":{"viewer":{"login":"me"}}}', + stderr: '' + }) + + await expect( + runGraphql('query { viewer { login } }', {}, { host: 'github.com' }) + ).resolves.toMatchObject({ ok: true }) + + expect(hostAuthenticatedMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/github/project-view.test.ts b/src/main/github/project-view.test.ts index edfeffb46..0c1a74728 100644 --- a/src/main/github/project-view.test.ts +++ b/src/main/github/project-view.test.ts @@ -176,6 +176,13 @@ describe('parseProjectPaste', () => { ).toEqual({ kind: 'org', owner: 'acme', number: 7 }) }) + it('rejects credentials and paths that only begin like a Project URL', () => { + expect(parseProjectPaste('https://user:token@github.com/orgs/acme/projects/1')).toBeNull() + expect(parseProjectPaste('https://github.com/orgs/acme/projects/1evil')).toBeNull() + expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/views/2evil')).toBeNull() + expect(parseProjectPaste('https://github.com/orgs/acme/projects/1/files')).toBeNull() + }) + it('returns null for empty input', () => { expect(parseProjectPaste('')).toBeNull() expect(parseProjectPaste(' ')).toBeNull() diff --git a/src/main/github/project-view.ts b/src/main/github/project-view.ts index 82508136f..2cd220c2b 100644 --- a/src/main/github/project-view.ts +++ b/src/main/github/project-view.ts @@ -15,6 +15,7 @@ import { isValidOwnerSlug, assertSlug, assertPositiveInt, + projectHostAuthenticationError, projectGhExecOptions, type GraphqlVars } from './project-view/internals' @@ -887,6 +888,10 @@ async function fetchItemsPageWithRaw(args: { stderr: string } > { + const authError = await projectHostAuthenticationError(args.host) + if (authError) { + return { ok: false, error: authError, rawErrors: [], stderr: '' } + } const root = ownerQueryRoot(args.ownerType) const afterArg = args.after ? `, after: $after` : '' const afterVar = args.after ? `$after:String!, ` : '' @@ -1619,32 +1624,42 @@ export function parseProjectPaste(input: string, host?: string): ParsedPaste | n if (isGitHubProjectRefInputTooLarge(trimmed)) { return null } - // URL forms. Why: GHES project URLs live on the enterprise host — accept it - // alongside github.com when the caller supplies one. - const escapedHost = host ? host.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : null - const urlRe = new RegExp( - `^https?://(?:github\\.com${escapedHost ? `|${escapedHost}` : ''})/(orgs|users)/([^/]+)/projects/(\\d+)(?:/views/(\\d+))?`, - 'i' - ) - const m = trimmed.match(urlRe) - if (m) { - const [, kindSeg, owner, nStr, vStr] = m - const number = Number.parseInt(nStr, 10) - if (!Number.isInteger(number) || number < 1) { + // Why: URL parsing enforces an exact Project path and rejects credentials; + // a prefix regex could silently turn `/projects/1evil` into Project 1. + try { + const url = new URL(trimmed) + const allowedHosts = new Set(['github.com', ...(host ? [host.trim().toLowerCase()] : [])]) + const parts = url.pathname.split('/').filter(Boolean) + const hasView = parts.length === 6 && parts[4] === 'views' + if ( + (url.protocol !== 'https:' && url.protocol !== 'http:') || + url.username || + url.password || + !allowedHosts.has(url.host.toLowerCase()) || + (parts[0] !== 'orgs' && parts[0] !== 'users') || + !isValidOwnerSlug(parts[1]) || + parts[2] !== 'projects' || + (parts.length !== 4 && !hasView) + ) { return null } - if (!isValidOwnerSlug(owner)) { + const number = Number(parts[3]) + const viewNumber = hasView ? Number(parts[5]) : undefined + if ( + !Number.isSafeInteger(number) || + number < 1 || + (hasView && (!Number.isSafeInteger(viewNumber) || (viewNumber ?? 0) < 1)) + ) { return null } - const viewNumber = vStr ? Number.parseInt(vStr, 10) : undefined return { - kind: kindSeg === 'orgs' ? 'org' : 'user', - owner, + kind: parts[0] === 'orgs' ? 'org' : 'user', + owner: parts[1], number, - ...(viewNumber !== undefined && Number.isInteger(viewNumber) && viewNumber >= 1 - ? { viewNumber } - : {}) + ...(viewNumber !== undefined ? { viewNumber } : {}) } + } catch { + // Shorthand parsing below remains available for non-URL input. } // owner/number shorthand — owner alphabet matches OWNER_SLUG_RE. const shortRe = /^([A-Za-z0-9][A-Za-z0-9-]*)\/(\d+)$/ diff --git a/src/main/github/project-view/internals.ts b/src/main/github/project-view/internals.ts index 12db80e7d..10e2c033d 100644 --- a/src/main/github/project-view/internals.ts +++ b/src/main/github/project-view/internals.ts @@ -13,6 +13,8 @@ import { } from '../rate-limit' import type { GitHubProjectViewError } from '../../../shared/github-project-types' import { githubProjectHost } from '../../../shared/github-project-identity' +import { isDefaultGitHubHost } from '../../../shared/github-repository-identity-key' +import { isGitHubHostAuthenticatedForGlobalCli } from '../github-enterprise-repository' import { classifyProjectError, driftError, @@ -42,6 +44,24 @@ export function projectGhExecOptions(host: string | undefined): ProjectGhExecOpt return { host: githubProjectHost(host) } } +export async function projectHostAuthenticationError( + host: string | undefined +): Promise { + const selectedHost = githubProjectHost(host) + if ( + isDefaultGitHubHost(selectedHost) || + (await isGitHubHostAuthenticatedForGlobalCli(selectedHost)) + ) { + return null + } + // Why: never target an unconfigured pasted host with gh; ambient + // GH_ENTERPRISE_TOKEN credentials could otherwise be sent to that server. + return { + type: 'auth_required', + message: `GitHub CLI is not authenticated to ${selectedHost}. Run gh auth login --hostname ${selectedHost}.` + } +} + // ─── Slug validation ────────────────────────────────────────────────── // Why: GitHub usernames/org logins disallow `_`, `.`, leading `-`. Repo names @@ -132,6 +152,10 @@ export async function runGraphql( | { ok: true; data: T } | { ok: false; error: GitHubProjectViewError; raw: { stderr: string; stdout: string } } > { + const authError = await projectHostAuthenticationError(exec?.host) + if (authError) { + return { ok: false, error: authError, raw: { stderr: '', stdout: '' } } + } // Why: GHES traffic runs against its own quota — only github.com requests // consult/debit the shared snapshot. const guard = repositoryRateLimitGuard({ host: exec?.host }, 'graphql') @@ -203,6 +227,10 @@ export async function runRest( bucket: RateLimitBucketKind = 'core', options?: { expectEmpty?: boolean; host?: string } ): Promise<{ ok: true; data: T } | { ok: false; error: GitHubProjectViewError }> { + const authError = await projectHostAuthenticationError(options?.host) + if (authError) { + return { ok: false, error: authError } + } // Why: GHES traffic runs against its own quota — only github.com requests // consult/debit the shared snapshot. const guard = repositoryRateLimitGuard({ host: options?.host }, bucket) diff --git a/src/main/github/project-view/mutations.test.ts b/src/main/github/project-view/mutations.test.ts index fc6c10140..30a00a0f1 100644 --- a/src/main/github/project-view/mutations.test.ts +++ b/src/main/github/project-view/mutations.test.ts @@ -1,14 +1,24 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -const { acquireMock, ghExecFileAsyncMock, releaseMock, runGraphqlMock, runRestMock } = vi.hoisted( - () => ({ - acquireMock: vi.fn(), - ghExecFileAsyncMock: vi.fn(), - releaseMock: vi.fn(), - runGraphqlMock: vi.fn(), - runRestMock: vi.fn() - }) -) +const { + acquireMock, + ghExecFileAsyncMock, + noteRepositoryRateLimitSpendMock, + projectHostAuthenticationErrorMock, + repositoryRateLimitGuardMock, + releaseMock, + runGraphqlMock, + runRestMock +} = vi.hoisted(() => ({ + acquireMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + noteRepositoryRateLimitSpendMock: vi.fn(), + projectHostAuthenticationErrorMock: vi.fn(), + repositoryRateLimitGuardMock: vi.fn(), + releaseMock: vi.fn(), + runGraphqlMock: vi.fn(), + runRestMock: vi.fn() +})) vi.mock('./internals', () => ({ acquire: acquireMock, @@ -20,8 +30,9 @@ vi.mock('./internals', () => ({ ghExecFileAsync: ghExecFileAsyncMock, rateLimitGuard: () => ({ blocked: false }), noteRateLimitSpend: vi.fn(), - repositoryRateLimitGuard: () => ({ blocked: false }), - noteRepositoryRateLimitSpend: vi.fn(), + repositoryRateLimitGuard: repositoryRateLimitGuardMock, + noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock, + projectHostAuthenticationError: projectHostAuthenticationErrorMock, projectGhExecOptions: (host?: string) => (host ? { host } : {}), classifyProjectError: (stderr: string) => ({ type: 'unknown', message: stderr }), rateLimitedError: () => ({ type: 'rate_limited', message: 'rate limited' }), @@ -41,6 +52,9 @@ describe('updateIssueBySlug', () => { beforeEach(() => { acquireMock.mockReset().mockResolvedValue(undefined) ghExecFileAsyncMock.mockReset().mockResolvedValue({ stdout: '', stderr: '' }) + noteRepositoryRateLimitSpendMock.mockReset() + projectHostAuthenticationErrorMock.mockReset().mockResolvedValue(null) + repositoryRateLimitGuardMock.mockReset().mockReturnValue({ blocked: false }) releaseMock.mockReset() runRestMock.mockReset().mockResolvedValue({ ok: true, data: {} }) }) @@ -76,6 +90,58 @@ describe('updateIssueBySlug', () => { expect(runRestMock).not.toHaveBeenCalled() }) + it('rejects an unconfigured Enterprise host before spawning gh', async () => { + projectHostAuthenticationErrorMock.mockResolvedValue({ + type: 'auth_required', + message: 'GitHub host is not authenticated' + }) + + await expect( + updateIssueBySlug({ + owner: 'acme', + repo: 'widgets', + host: 'evil.example.test', + number: 12, + updates: { state: 'closed' } + }) + ).resolves.toMatchObject({ ok: false, error: { type: 'auth_required' } }) + + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + expect(runRestMock).not.toHaveBeenCalled() + }) + + it('guards and accounts state mutations in the selected host quota scope', async () => { + const args = { + owner: 'acme', + repo: 'widgets', + host: 'github.corp.example', + number: 12, + updates: { state: 'closed' as const } + } + + await expect(updateIssueBySlug(args)).resolves.toEqual({ ok: true }) + + expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith(args, 'core') + expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalledWith(args, 'core') + }) + + it('does not spawn a state mutation while that host quota is blocked', async () => { + repositoryRateLimitGuardMock.mockReturnValue({ blocked: true }) + + await expect( + updateIssueBySlug({ + owner: 'acme', + repo: 'widgets', + host: 'github.corp.example', + number: 12, + updates: { state: 'closed' } + }) + ).resolves.toMatchObject({ ok: false, error: { type: 'rate_limited' } }) + + expect(noteRepositoryRateLimitSpendMock).not.toHaveBeenCalled() + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) + it('closes slug-addressed duplicate issues with --duplicate-of', async () => { await expect( updateIssueBySlug({ diff --git a/src/main/github/project-view/mutations.ts b/src/main/github/project-view/mutations.ts index 72929ec4b..ac4b20ed5 100644 --- a/src/main/github/project-view/mutations.ts +++ b/src/main/github/project-view/mutations.ts @@ -12,6 +12,7 @@ import { runRest, validateSlugArgs, assertPositiveInt, + projectHostAuthenticationError, projectGhExecOptions, type GraphqlVars } from './internals' @@ -216,6 +217,10 @@ export async function updateIssueBySlug( return { ok: false, error: duplicate.error } } } + const authError = await projectHostAuthenticationError(args.host) + if (authError) { + return { ok: false, error: authError } + } // Title/body go through PATCH /repos/{owner}/{repo}/issues/{n}. // State uses gh issue close/reopen so duplicate closes can record a target. @@ -223,6 +228,10 @@ export async function updateIssueBySlug( const base = `repos/${args.owner}/${args.repo}/issues/${args.number}` if (state !== undefined) { + const guard = repositoryRateLimitGuard(args, 'core') + if (guard.blocked) { + return { ok: false, error: rateLimitedError(guard) } + } const stateArgs = state === 'closed' ? ['issue', 'close', String(args.number), '--repo', `${args.owner}/${args.repo}`] @@ -237,6 +246,7 @@ export async function updateIssueBySlug( } } await acquire() + noteRepositoryRateLimitSpend(args, 'core') try { await ghExecFileAsync(stateArgs, { encoding: 'utf-8', ...githubHostExecOptions(args) }) } catch (err) { @@ -522,6 +532,10 @@ export async function listLabelsBySlug( if (!v.ok) { return v } + const authError = await projectHostAuthenticationError(args.host) + if (authError) { + return { ok: false, error: authError } + } const guard = repositoryRateLimitGuard(args, 'core') if (guard.blocked) { return { ok: false, error: rateLimitedError(guard) } @@ -557,6 +571,10 @@ export async function listAssignableUsersBySlug( if (!v.ok) { return v } + const authError = await projectHostAuthenticationError(args.host) + if (authError) { + return { ok: false, error: authError } + } // Seed logins merge after the fetch so callers can include currently-visible // assignees even if the repo participant search is sparse. const result: GitHubAssignableUser[] = [] diff --git a/src/main/github/work-item-details-concurrency.test.ts b/src/main/github/work-item-details-concurrency.test.ts new file mode 100644 index 000000000..cef30594b --- /dev/null +++ b/src/main/github/work-item-details-concurrency.test.ts @@ -0,0 +1,147 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + acquireMock, + releaseMock, + ghExecFileAsyncMock, + getWorkItemMock, + getPRCommentsMock, + getPRChecksMock +} = vi.hoisted(() => ({ + acquireMock: vi.fn<() => Promise>(), + releaseMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + getWorkItemMock: vi.fn(), + getPRCommentsMock: vi.fn(), + getPRChecksMock: vi.fn() +})) + +vi.mock('./gh-utils', () => ({ + acquire: acquireMock, + release: releaseMock, + ghExecFileAsync: ghExecFileAsyncMock, + ghRepoExecOptions: (context: { repoPath: string }) => ({ cwd: context.repoPath }), + githubRepoContext: (repoPath: string, connectionId?: string | null) => ({ + repoPath, + connectionId: connectionId ?? null + }) +})) + +vi.mock('./client', () => ({ + getWorkItem: getWorkItemMock, + getPRComments: getPRCommentsMock, + getPRChecks: getPRChecksMock +})) + +vi.mock('./github-api-repository', () => ({ + getIssueGitHubApiRepository: vi.fn(), + getOriginGitHubApiRepository: vi.fn(), + githubHostExecOptions: (repository?: { host?: string } | null) => + repository?.host ? { host: repository.host } : {}, + resolveGitHubRepoExecution: vi.fn() +})) + +vi.mock('./rate-limit', () => ({ + repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), + noteRepositoryRateLimitSpend: vi.fn() +})) + +import { getWorkItemDetails } from './work-item-details' + +describe('getWorkItemDetails concurrency', () => { + beforeEach(() => { + let running = 0 + const queue: (() => void)[] = [] + acquireMock.mockReset() + acquireMock.mockImplementation(() => { + if (running < 4) { + running += 1 + return Promise.resolve() + } + return new Promise((resolve) => + queue.push(() => { + running += 1 + resolve() + }) + ) + }) + releaseMock.mockReset() + releaseMock.mockImplementation(() => { + running -= 1 + queue.shift()?.() + }) + + getWorkItemMock.mockReset() + getWorkItemMock.mockImplementation(async (_repoPath: string, number: number) => ({ + id: `pr:${number}`, + type: 'pr', + number, + title: `PR ${number}`, + state: 'open', + url: `https://github.com/acme/widgets/pull/${number}`, + labels: [], + updatedAt: '2026-07-16T00:00:00Z', + author: null, + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.com' } + })) + + const withNestedPermit = async (value: T): Promise => { + await acquireMock() + try { + return value + } finally { + releaseMock() + } + } + getPRCommentsMock.mockReset() + getPRCommentsMock.mockImplementation(() => withNestedPermit([])) + getPRChecksMock.mockReset() + getPRChecksMock.mockImplementation(() => withNestedPermit([])) + + ghExecFileAsyncMock.mockReset() + ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { + const query = args.find((arg) => arg.startsWith('query=')) ?? '' + if (query.includes('viewerViewedState')) { + return { + stdout: JSON.stringify({ + data: { + repository: { + pullRequest: { + id: 'PR_id', + files: { pageInfo: { hasNextPage: false }, nodes: [] } + } + } + } + }) + } + } + if (query.includes('participants')) { + return { + stdout: JSON.stringify({ + data: { repository: { pullRequest: { participants: { nodes: [] } } } } + }) + } + } + const endpoint = args.find((arg) => arg.startsWith('repos/')) ?? '' + if (endpoint.includes('/files?')) { + return { stdout: '[]' } + } + if (/\/pulls\/\d+$/.test(endpoint)) { + return { + stdout: JSON.stringify({ body: 'body', head: { sha: 'head' }, base: { sha: 'base' } }) + } + } + return { stdout: JSON.stringify({ data: {} }) } + }) + }) + + it('does not deadlock four concurrent PR loads on nested client permits', async () => { + const details = await Promise.all( + [1, 2, 3, 4].map((number) => getWorkItemDetails('/repo', number, 'pr')) + ) + + expect(details.map((detail) => detail?.item.number)).toEqual([1, 2, 3, 4]) + expect(acquireMock.mock.calls.length).toBeGreaterThan(4) + expect(releaseMock).toHaveBeenCalledTimes(acquireMock.mock.calls.length) + }) +}) diff --git a/src/main/github/work-item-details-file-viewed.test.ts b/src/main/github/work-item-details-file-viewed.test.ts index 3ebe70aa1..7ea2f1498 100644 --- a/src/main/github/work-item-details-file-viewed.test.ts +++ b/src/main/github/work-item-details-file-viewed.test.ts @@ -26,8 +26,22 @@ const { getPRCommentsMock: vi.fn(), rateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })), noteRateLimitSpendMock: vi.fn(), - repositoryRateLimitGuardMock: vi.fn<() => RateLimitGuardResult>(() => ({ blocked: false })), - noteRepositoryRateLimitSpendMock: vi.fn(), + repositoryRateLimitGuardMock: vi.fn< + ( + repository: { host?: string } | null | undefined, + bucket: string, + options?: { cwd?: string; host?: string } + ) => RateLimitGuardResult + >(() => ({ blocked: false })), + noteRepositoryRateLimitSpendMock: + vi.fn< + ( + repository: { host?: string } | null | undefined, + bucket: string, + cost?: number, + options?: { cwd?: string; host?: string } + ) => void + >(), acquireMock: vi.fn(), releaseMock: vi.fn() })) @@ -184,6 +198,21 @@ describe('getWorkItemDetails PR file viewed state', () => { undefined, undefined ) + expect(repositoryRateLimitGuardMock.mock.calls.length).toBeGreaterThan(0) + expect( + repositoryRateLimitGuardMock.mock.calls.every(([, bucket, options]) => + bucket === 'graphql' + ? options?.cwd === '/repo-root' && options?.host === 'github.com' + : true + ) + ).toBe(true) + expect( + noteRepositoryRateLimitSpendMock.mock.calls.every(([, bucket, , options]) => + bucket === 'graphql' + ? options?.cwd === '/repo-root' && options?.host === 'github.com' + : true + ) + ).toBe(true) }) it('keeps PR details loadable when checks lookup fails', async () => { diff --git a/src/main/github/work-item-details-pr-files.test.ts b/src/main/github/work-item-details-pr-files.test.ts index 092b800a8..fc86f204c 100644 --- a/src/main/github/work-item-details-pr-files.test.ts +++ b/src/main/github/work-item-details-pr-files.test.ts @@ -5,13 +5,31 @@ const { getOwnerRepoMock, getWorkItemMock, getPRChecksMock, - getPRCommentsMock + getPRCommentsMock, + noteRepositoryRateLimitSpendMock, + repositoryRateLimitGuardMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn(), getOwnerRepoMock: vi.fn(), getWorkItemMock: vi.fn(), getPRChecksMock: vi.fn(), - getPRCommentsMock: vi.fn() + getPRCommentsMock: vi.fn(), + noteRepositoryRateLimitSpendMock: + vi.fn< + ( + repository: { host?: string } | null | undefined, + bucket: string, + cost?: number, + options?: { cwd?: string; host?: string } + ) => void + >(), + repositoryRateLimitGuardMock: vi.fn< + ( + repository: { host?: string } | null | undefined, + bucket: string, + options?: { cwd?: string; host?: string } + ) => { blocked: false } + >(() => ({ blocked: false })) })) vi.mock('./gh-utils', () => ({ @@ -36,14 +54,15 @@ vi.mock('./client', () => ({ })) vi.mock('./github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: vi.fn().mockResolvedValue(null) + getEnterpriseGitHubRepoSlug: vi.fn().mockResolvedValue(null), + isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) })) vi.mock('./rate-limit', () => ({ rateLimitGuard: vi.fn(() => ({ blocked: false })), noteRateLimitSpend: vi.fn(), - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: vi.fn() + repositoryRateLimitGuard: repositoryRateLimitGuardMock, + noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock })) import { getWorkItemDetails } from './work-item-details' @@ -106,6 +125,8 @@ describe('getWorkItemDetails PR file listing', () => { getPRChecksMock.mockResolvedValue([]) getPRCommentsMock.mockReset() getPRCommentsMock.mockResolvedValue([]) + noteRepositoryRateLimitSpendMock.mockReset() + repositoryRateLimitGuardMock.mockClear() }) it('loads files beyond the first 100-result REST page', async () => { @@ -145,6 +166,12 @@ describe('getWorkItemDetails PR file listing', () => { 'repos/acme/widgets/pulls/108/files?per_page=100', 'repos/acme/widgets/pulls/108/files?per_page=100&page=2' ]) + expect( + noteRepositoryRateLimitSpendMock.mock.calls.filter(([, bucket]) => bucket === 'core') + ).toHaveLength(3) + expect( + repositoryRateLimitGuardMock.mock.calls.filter(([, bucket]) => bucket === 'core') + ).toHaveLength(3) }) // Why: a rate-limited/auth-failed file fetch must not render as an empty PR; diff --git a/src/main/github/work-item-details.test.ts b/src/main/github/work-item-details.test.ts index 60b39d149..cf9f2b86f 100644 --- a/src/main/github/work-item-details.test.ts +++ b/src/main/github/work-item-details.test.ts @@ -65,7 +65,8 @@ vi.mock('./client', () => ({ vi.mock('./github-enterprise-repository', () => ({ getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, - getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugForRemoteMock + getEnterpriseGitHubRepoSlugForRemote: getEnterpriseGitHubRepoSlugForRemoteMock, + isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) })) vi.mock('./rate-limit', () => ({ @@ -243,19 +244,19 @@ describe('getWorkItemDetails', () => { expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith( { owner: 'acme', repo: 'widgets', host: 'github.com' }, 'graphql', - {} + { cwd: '/repo-root', host: 'github.com' } ) expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalledWith( { owner: 'acme', repo: 'widgets', host: 'github.com' }, 'graphql', 1, - {} + { cwd: '/repo-root', host: 'github.com' } ) }) - it('scopes collapsed issue GraphQL accounting to the selected WSL runtime', async () => { + it('scopes collapsed issue GraphQL accounting to an implicit WSL UNC runtime', async () => { const repository = { owner: 'acme', repo: 'widgets' } - const localGitOptions = { wslDistro: 'Ubuntu' } + const repoPath = String.raw`\\wsl.localhost\Ubuntu\home\me\widgets` getWorkItemMock.mockResolvedValueOnce({ id: 'issue:923', type: 'issue', @@ -285,24 +286,22 @@ describe('getWorkItemDetails', () => { }) .mockResolvedValueOnce({ stdout: '' }) - const details = await getWorkItemDetails('/repo-root', 923, 'issue', null, localGitOptions) + const details = await getWorkItemDetails(repoPath, 923, 'issue') expect(details?.body).toBe('WSL issue body') // Why: issue identities resolve hosted, pinned to github.com for dotcom. expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith( { ...repository, host: 'github.com' }, 'graphql', - localGitOptions + { cwd: repoPath, host: 'github.com' } ) expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalledWith( { ...repository, host: 'github.com' }, 'graphql', 1, - localGitOptions - ) - expect(ghExecFileAsyncMock.mock.calls.every((call) => call[1]?.wslDistro === 'Ubuntu')).toBe( - true + { cwd: repoPath, host: 'github.com' } ) + expect(ghExecFileAsyncMock.mock.calls.every((call) => call[1]?.cwd === repoPath)).toBe(true) }) it('enriches a non-participating assignee avatar from the GraphQL assignees connection', async () => { @@ -321,7 +320,7 @@ describe('getWorkItemDetails', () => { author: 'issue-author', assignees: [{ login: 'ghe-assignee', name: 'GHE Assignee', avatarUrl: '' }] }) - getIssueOwnerRepoMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) + getOwnerRepoForRemoteMock.mockResolvedValue({ owner: 'acme', repo: 'widgets' }) ghExecFileAsyncMock .mockResolvedValueOnce({ stdout: JSON.stringify({ @@ -612,7 +611,9 @@ describe('getWorkItemDetails', () => { expect(getWorkItemMock).toHaveBeenCalledWith('/remote/repo', 7, 'issue', 'ssh-1') expect(getWorkItemByOwnerRepoMock).not.toHaveBeenCalled() expect(getEnterpriseGitHubRepoSlugMock).toHaveBeenCalledTimes(1) - expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith(enterpriseRepository, 'graphql', {}) + expect(repositoryRateLimitGuardMock).toHaveBeenCalledWith(enterpriseRepository, 'graphql', { + host: 'github.acme-corp.com' + }) expect(noteRepositoryRateLimitSpendMock).toHaveBeenCalled() expect( ghExecFileAsyncMock.mock.calls.every( @@ -846,13 +847,13 @@ describe('getWorkItemDetails', () => { expect(ghExecFileAsyncMock).not.toHaveBeenCalled() }) - it('uses the GitHub Enterprise host when fetching PR file contents', async () => { - getOwnerRepoMock.mockResolvedValue(null) - getEnterpriseGitHubRepoSlugMock.mockResolvedValue({ + it('uses the selected upstream GitHub Enterprise repo for both PR file sides', async () => { + getOwnerRepoMock.mockResolvedValue({ owner: 'fork', repo: 'orca' }) + const prRepo = { owner: 'team', repo: 'orca', host: 'github.acme-corp.com' - }) + } ghExecFileAsyncMock.mockImplementation(async (args: string[]) => { const endpoint = args.find((arg) => arg.startsWith('repos/')) ?? '' if (endpoint === 'repos/team/orca/contents/src/path%23with%3Fchars.ts?ref=base-sha') { @@ -866,6 +867,7 @@ describe('getWorkItemDetails', () => { const contents = await getPRFileContents({ repoPath: '/repo-root', + prRepo, prNumber: 7, path: 'src/path#with?chars.ts', status: 'modified', diff --git a/src/main/github/work-item-details.ts b/src/main/github/work-item-details.ts index 1cb9e9d31..94df5d331 100644 --- a/src/main/github/work-item-details.ts +++ b/src/main/github/work-item-details.ts @@ -26,6 +26,7 @@ import { getIssueGitHubApiRepository, getOriginGitHubApiRepository, githubHostExecOptions, + resolveGitHubRepoExecution, type GitHubApiRepository } from './github-api-repository' import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-limit' @@ -359,11 +360,11 @@ async function getIssueDetailsViaGraphQL( if (!ownerRepo) { return null } - if (repositoryRateLimitGuard(ownerRepo, 'graphql', localGitOptions).blocked) { + if (repositoryRateLimitGuard(ownerRepo, 'graphql', ghOptions).blocked) { return null } try { - noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, localGitOptions) + noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions) const { stdout } = await ghExecFileAsync( [ 'api', @@ -515,7 +516,11 @@ async function getPRMetadata( ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), ...githubHostExecOptions(ownerRepo) } + if (repositoryRateLimitGuard(ownerRepo, 'core', ghOptions).blocked) { + return { body: '' } + } try { + noteRepositoryRateLimitSpend(ownerRepo, 'core', 1, ghOptions) if (ownerRepo) { const { stdout } = await ghExecFileAsync( ['api', '--cache', '60s', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${prNumber}`], @@ -571,7 +576,11 @@ async function getPRFiles( try { const data: RESTPRFile[] = [] for (let page = 1; data.length < MAX_PR_FILES; page += 1) { + if (repositoryRateLimitGuard(ownerRepo, 'core', ghOptions).blocked) { + return null + } const pageSuffix = page === 1 ? '' : `&page=${page}` + noteRepositoryRateLimitSpend(ownerRepo, 'core', 1, ghOptions) const { stdout } = await ghExecFileAsync( [ 'api', @@ -620,7 +629,7 @@ async function getPRFileViewedStates( ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), ...githubHostExecOptions(ownerRepo) } - if (repositoryRateLimitGuard(ownerRepo, 'graphql', localGitOptions).blocked) { + if (repositoryRateLimitGuard(ownerRepo, 'graphql', ghOptions).blocked) { return null } const viewedStates = new Map() @@ -644,7 +653,7 @@ async function getPRFileViewedStates( if (after) { args.push('-f', `after=${after}`) } - noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, localGitOptions) + noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions) const { stdout } = await ghExecFileAsync(args, ghOptions) const parsed = JSON.parse(stdout) as { data?: { @@ -815,11 +824,15 @@ async function getWorkItemParticipants( if (!ownerRepo) { return [] } - if (repositoryRateLimitGuard(ownerRepo, 'graphql', localGitOptions).blocked) { + const ghOptions = { + ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), + ...githubHostExecOptions(ownerRepo) + } + if (repositoryRateLimitGuard(ownerRepo, 'graphql', ghOptions).blocked) { return [] } try { - noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, localGitOptions) + noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions) const { stdout } = await ghExecFileAsync( [ 'api', @@ -835,10 +848,7 @@ async function getWorkItemParticipants( '-F', `isPr=${item.type === 'pr'}` ], - { - ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), - ...githubHostExecOptions(ownerRepo) - } + ghOptions ) const data = JSON.parse(stdout) as { data?: { @@ -881,7 +891,11 @@ async function getGitHubUsersByLogin( if (uniqueLogins.length === 0) { return [] } - const guard = repositoryRateLimitGuard(repository, 'graphql', localGitOptions) + const ghOptions = { + ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), + ...githubHostExecOptions(repository) + } + const guard = repositoryRateLimitGuard(repository, 'graphql', ghOptions) if (guard.blocked) { // Why: surface the skip. Callers degrade silently to login-based avatar URLs // (blank on GHE), so without this log "why are avatars missing" is untraceable. @@ -897,13 +911,10 @@ async function getGitHubUsersByLogin( ) .join('\n') try { - noteRepositoryRateLimitSpend(repository, 'graphql', 1, localGitOptions) + noteRepositoryRateLimitSpend(repository, 'graphql', 1, ghOptions) const { stdout } = await ghExecFileAsync( ['api', 'graphql', '-f', `query=query { ${fields} }`], - { - ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), - ...githubHostExecOptions(repository) - } + ghOptions ) const data = JSON.parse(stdout) as { data?: Record< @@ -1066,6 +1077,15 @@ async function getPRChecksForDetails( } } +async function withWorkItemDetailsPermit(operation: () => Promise): Promise { + await acquire() + try { + return await operation() + } finally { + release() + } +} + export async function getWorkItemDetails( repoPath: string, number: number, @@ -1090,9 +1110,8 @@ export async function getWorkItemDetails( : (item.prRepo ?? (await getOriginGitHubApiRepository(repoPath, connectionId, localGitOptions))) - await acquire() - try { - if (item.type === 'issue') { + if (item.type === 'issue') { + return withWorkItemDetailsPermit(async () => { // Why: try the collapsed single-GraphQL path first — body, assignees, // participants, and comments all return in one round-trip. On any // failure (permissions, partial errors, non-GitHub remote), strictly @@ -1152,33 +1171,45 @@ export async function getWorkItemDetails( participants: mentionParticipants, timelineItems } - } + }) + } - // PR: fetch metadata + comments + files + viewed states + participants in parallel. - const [metadata, comments, files, viewedStates, participants] = await Promise.all([ - getPRMetadata(repoPath, item.number, resolvedRepository, connectionId, localGitOptions), - getPRComments( - repoPath, - item.number, - { prRepo: resolvedRepository }, - connectionId, - ...localGitOptionArgs(localGitOptions) + // Why: getPRComments and getPRChecks own their semaphore permits. Keeping an + // outer permit while awaiting either can deadlock four concurrent detail loads. + const [[metadata, files, viewedStates, participants], comments] = await Promise.all([ + Promise.all([ + withWorkItemDetailsPermit(() => + getPRMetadata(repoPath, item.number, resolvedRepository, connectionId, localGitOptions) ), - getPRFiles(repoPath, item.number, resolvedRepository, connectionId, localGitOptions), - getPRFileViewedStates( - repoPath, - item.number, - resolvedRepository, - connectionId, - localGitOptions + withWorkItemDetailsPermit(() => + getPRFiles(repoPath, item.number, resolvedRepository, connectionId, localGitOptions) ), - getWorkItemParticipants(repoPath, item, resolvedRepository, connectionId, localGitOptions) - ]) + withWorkItemDetailsPermit(() => + getPRFileViewedStates( + repoPath, + item.number, + resolvedRepository, + connectionId, + localGitOptions + ) + ), + withWorkItemDetailsPermit(() => + getWorkItemParticipants(repoPath, item, resolvedRepository, connectionId, localGitOptions) + ) + ]), + getPRComments( + repoPath, + item.number, + { prRepo: resolvedRepository }, + connectionId, + ...localGitOptionArgs(localGitOptions) + ) + ]) - // Why: run the mention-author GraphQL lookup in parallel with the final - // checks fetch instead of serially — both depend only on data from the - // Promise.all above, so there's no ordering requirement between them. - const [mentionParticipants, checks] = await Promise.all([ + // Why: mention hydration directly spawns gh, while checks owns a permit. + // Bound the direct spawn separately so neither operation nests a permit. + const [mentionParticipants, checks] = await Promise.all([ + withWorkItemDetailsPermit(() => getMentionParticipants( repoPath, item, @@ -1187,33 +1218,31 @@ export async function getWorkItemDetails( resolvedRepository, connectionId, localGitOptions - ), - getPRChecksForDetails( - repoPath, - item.number, - metadata.headSha, - resolvedRepository, - connectionId, - localGitOptions ) - ]) + ), + getPRChecksForDetails( + repoPath, + item.number, + metadata.headSha, + resolvedRepository, + connectionId, + localGitOptions + ) + ]) - return { - item: enrichItemDisplayAvatars(item, mentionParticipants), - body: metadata.body, - comments, - headSha: metadata.headSha, - baseSha: metadata.baseSha, - pullRequestId: viewedStates?.pullRequestId, - checks, - // Why: distinguish a failed file fetch (null) from an empty PR so the - // Files tab surfaces a retry instead of "No files changed." - files: files === null ? undefined : mergePRFileViewedStates(files, viewedStates), - filesUnavailable: files === null, - participants: mentionParticipants - } - } finally { - release() + return { + item: enrichItemDisplayAvatars(item, mentionParticipants), + body: metadata.body, + comments, + headSha: metadata.headSha, + baseSha: metadata.baseSha, + pullRequestId: viewedStates?.pullRequestId, + checks, + // Why: distinguish a failed file fetch (null) from an empty PR so the + // Files tab surfaces a retry instead of "No files changed." + files: files === null ? undefined : mergePRFileViewedStates(files, viewedStates), + filesUnavailable: files === null, + participants: mentionParticipants } } @@ -1267,6 +1296,7 @@ export async function getPRFileContents(args: { repoPath: string connectionId?: string | null localGitOptions?: LocalGitExecOptions + prRepo?: GitHubApiRepository | null prNumber: number path: string oldPath?: string @@ -1274,8 +1304,9 @@ export async function getPRFileContents(args: { headSha: string baseSha: string }): Promise { - const ownerRepo = await getOriginGitHubApiRepository( + const { ownerRepo } = await resolveGitHubRepoExecution( args.repoPath, + args.prRepo, args.connectionId, args.localGitOptions ) diff --git a/src/main/ipc/github.test.ts b/src/main/ipc/github.test.ts index 71f5d2866..bb1dd0cc1 100644 --- a/src/main/ipc/github.test.ts +++ b/src/main/ipc/github.test.ts @@ -856,7 +856,7 @@ describe('registerGitHubHandlers', () => { updatedAt: 0 } ] - const prRepo = { owner: 'acme', repo: 'orca' } + const prRepo = { owner: 'acme', repo: 'orca', host: 'github.acme-corp.com' } const localGitOptions = { wslDistro: 'Ubuntu' } getWorkItemMock.mockResolvedValue(null) getWorkItemByOwnerRepoMock.mockResolvedValue(null) @@ -883,6 +883,7 @@ describe('registerGitHubHandlers', () => { repoPath: '/workspace/repo', owner: 'acme', repo: 'orca', + host: prRepo.host, number: 42, type: 'pr' }) @@ -894,6 +895,7 @@ describe('registerGitHubHandlers', () => { await handlers['gh:prFileContents'](null, { repoPath: '/workspace/repo', prNumber: 42, + prRepo, path: 'src/app.ts', status: 'modified', headSha: 'head-sha', @@ -923,13 +925,15 @@ describe('registerGitHubHandlers', () => { await handlers['gh:resolveReviewThread'](null, { repoPath: '/workspace/repo', threadId: 'thread-1', - resolve: true + resolve: true, + prRepo }) await handlers['gh:setPRFileViewed']( { sender: { id: 1 } }, { repoPath: '/workspace/repo', prNumber: 42, + prRepo, pullRequestId: 'PR_kw', path: 'src/app.ts', viewed: true @@ -940,12 +944,12 @@ describe('registerGitHubHandlers', () => { { repoPath: '/workspace/repo', prNumber: 42, + prRepo, commentId: 11, body: ' Reply ', threadId: 'thread-1', path: 'src/app.ts', - line: 10, - prRepo + line: 10 } ) await handlers['gh:addPRReviewComment']( @@ -953,6 +957,7 @@ describe('registerGitHubHandlers', () => { { repoPath: '/workspace/repo', prNumber: 42, + prRepo, commitId: ' head-sha ', path: 'src/app.ts', line: 10, @@ -992,21 +997,24 @@ describe('registerGitHubHandlers', () => { { repoPath: '/workspace/repo', prNumber: 42, - updates: { state: 'closed' } + updates: { state: 'closed' }, + prRepo } ) await handlers['gh:rerunPRChecks'](null, { repoPath: '/workspace/repo', prNumber: 42, headSha: 'head-sha', - failedOnly: true + failedOnly: true, + prRepo }) await handlers['gh:requestPRReviewers']( { sender: { id: 1 } }, { repoPath: '/workspace/repo', prNumber: 42, - reviewers: ['octo'] + reviewers: ['octo'], + prRepo } ) await handlers['gh:removePRReviewers']( @@ -1014,7 +1022,8 @@ describe('registerGitHubHandlers', () => { { repoPath: '/workspace/repo', prNumber: 42, - reviewers: ['octo'] + reviewers: ['octo'], + prRepo } ) @@ -1035,7 +1044,7 @@ describe('registerGitHubHandlers', () => { localGitOptions ) expect(getPRFileContentsMock).toHaveBeenCalledWith( - expect.objectContaining({ repoPath: '/workspace/repo', localGitOptions }) + expect.objectContaining({ repoPath: '/workspace/repo', localGitOptions, prRepo }) ) expect(getPRChecksMock).toHaveBeenCalledWith( '/workspace/repo', @@ -1070,10 +1079,11 @@ describe('registerGitHubHandlers', () => { 'thread-1', true, null, + prRepo, localGitOptions ) expect(setPRFileViewedMock).toHaveBeenCalledWith( - expect.objectContaining({ repoPath: '/workspace/repo', localGitOptions }) + expect.objectContaining({ repoPath: '/workspace/repo', localGitOptions, prRepo }) ) expect(addPRReviewCommentReplyMock).toHaveBeenCalledWith( '/workspace/repo', @@ -1092,6 +1102,7 @@ describe('registerGitHubHandlers', () => { repoPath: '/workspace/repo', commitId: 'head-sha', body: 'Inline', + prRepo, localGitOptions }) ) @@ -1125,12 +1136,13 @@ describe('registerGitHubHandlers', () => { 42, { state: 'closed' }, null, + prRepo, localGitOptions ) expect(rerunPRChecksMock).toHaveBeenCalledWith( '/workspace/repo', 42, - { headSha: 'head-sha', failedOnly: true }, + { headSha: 'head-sha', failedOnly: true, prRepo }, null, localGitOptions ) @@ -1139,6 +1151,7 @@ describe('registerGitHubHandlers', () => { 42, ['octo'], null, + prRepo, localGitOptions ) expect(removePRReviewersMock).toHaveBeenCalledWith( @@ -1146,6 +1159,7 @@ describe('registerGitHubHandlers', () => { 42, ['octo'], null, + prRepo, localGitOptions ) }) diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts index be0b9af0e..a01225bfc 100644 --- a/src/main/ipc/github.ts +++ b/src/main/ipc/github.ts @@ -543,6 +543,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi args: { repoPath: string prNumber: number + prRepo?: GitHubOwnerRepo | null path: string oldPath?: string status: GitHubPRFile['status'] @@ -555,6 +556,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi repoPath: repo.path, connectionId: repoConnectionId(repo), localGitOptions: localGitOptionArgs(store, repo)[0], + prRepo: args.prRepo ?? null, prNumber: args.prNumber, path: args.path, oldPath: args.oldPath, @@ -675,6 +677,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi sourceContext?: TaskSourceContext | null threadId: string resolve: boolean + prRepo?: GitHubOwnerRepo | null } ) => { const repo = assertRegisteredRepo(args, store) @@ -688,6 +691,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi args.threadId, args.resolve, repoConnectionId(repo), + args.prRepo ?? null, ...localGitOptionArgs(store, repo) ) } @@ -701,6 +705,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi repoPath: string repoId?: string prNumber: number + prRepo?: GitHubOwnerRepo | null pullRequestId: string path: string viewed: boolean @@ -721,6 +726,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi repoPath: repo.path, connectionId: repoConnectionId(repo), localGitOptions: localGitOptionArgs(store, repo)[0], + prRepo: args.prRepo ?? null, pullRequestId: args.pullRequestId.trim(), path: args.path, viewed: Boolean(args.viewed) @@ -799,6 +805,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi args: { repoPath: string prNumber: number + prRepo?: GitHubOwnerRepo | null commitId: string path: string line: number @@ -837,6 +844,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi } const result = await addPRReviewComment({ repoPath: repo.path, + prRepo: args.prRepo ?? null, prNumber: args.prNumber, commitId: args.commitId.trim(), path: args.path, @@ -951,7 +959,11 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi 'gh:updatePRState', async ( event, - args: RepoScopedArgs & { prNumber: number; updates: GitHubPullRequestStateUpdate } + args: RepoScopedArgs & { + prNumber: number + updates: GitHubPullRequestStateUpdate + prRepo?: GitHubOwnerRepo | null + } ) => { const repo = assertRegisteredRepo(args, store) if ( @@ -966,6 +978,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi args.prNumber, args.updates, repoConnectionId(repo), + args.prRepo ?? null, ...localGitOptionArgs(store, repo) ) if (result.ok) { @@ -982,7 +995,12 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi 'gh:rerunPRChecks', async ( _event, - args: RepoScopedArgs & { prNumber: number; headSha?: string; failedOnly?: boolean } + args: RepoScopedArgs & { + prNumber: number + headSha?: string + failedOnly?: boolean + prRepo?: GitHubOwnerRepo | null + } ) => { const repo = assertRegisteredRepo(args, store) if ( @@ -995,7 +1013,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi return rerunPRChecks( repo.path, args.prNumber, - { headSha: args.headSha, failedOnly: args.failedOnly }, + { headSha: args.headSha, failedOnly: args.failedOnly, prRepo: args.prRepo ?? null }, repoConnectionId(repo), ...localGitOptionArgs(store, repo) ) @@ -1004,13 +1022,21 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi ipcMain.handle( 'gh:requestPRReviewers', - async (event, args: RepoScopedArgs & { prNumber: number; reviewers: string[] }) => { + async ( + event, + args: RepoScopedArgs & { + prNumber: number + reviewers: string[] + prRepo?: GitHubOwnerRepo | null + } + ) => { const repo = assertRegisteredRepo(args, store) const result = await requestPRReviewers( repo.path, args.prNumber, args.reviewers, repoConnectionId(repo), + args.prRepo ?? null, ...localGitOptionArgs(store, repo) ) if (result.ok) { @@ -1025,13 +1051,21 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi ipcMain.handle( 'gh:removePRReviewers', - async (event, args: RepoScopedArgs & { prNumber: number; reviewers: string[] }) => { + async ( + event, + args: RepoScopedArgs & { + prNumber: number + reviewers: string[] + prRepo?: GitHubOwnerRepo | null + } + ) => { const repo = assertRegisteredRepo(args, store) const result = await removePRReviewers( repo.path, args.prNumber, args.reviewers, repoConnectionId(repo), + args.prRepo ?? null, ...localGitOptionArgs(store, repo) ) if (result.ok) { diff --git a/src/main/ipc/repos-remote.test.ts b/src/main/ipc/repos-remote.test.ts index eee64eff2..2fe6160f5 100644 --- a/src/main/ipc/repos-remote.test.ts +++ b/src/main/ipc/repos-remote.test.ts @@ -1890,6 +1890,61 @@ describe('repos:add + repos:clone', () => { expect(mockStore.addRepo).not.toHaveBeenCalled() }) + it('preserves the selected Enterprise host when aligning an existing folder', async () => { + const existing = { + id: 'repo-setup-enterprise', + path: '/tmp/from-setup-enterprise', + displayName: 'from-setup-enterprise', + kind: 'git', + badgeColor: '#22c55e' + } + const existingProject = { id: 'repo:repo-setup-enterprise', displayName: 'Existing' } + const selectedProject = { + id: 'github:github.acme-corp.com/acme/orca', + displayName: 'Enterprise project', + providerIdentity: { + provider: 'github', + owner: 'acme', + repo: 'orca', + host: 'github.acme-corp.com' + } + } + const setup = { + id: existing.id, + projectId: existingProject.id, + repoId: existing.id, + hostId: 'local', + path: existing.path, + displayName: existing.displayName, + setupState: 'ready', + setupMethod: 'legacy-repo' + } + let updatedRepo = existing + mockStore.getRepos.mockReturnValue([existing]) + mockStore.getProjects.mockReturnValue([existingProject, selectedProject]) + mockStore.getProjectHostSetups.mockReturnValue([setup]) + mockStore.updateRepo.mockImplementation((_repoId, updates) => { + updatedRepo = { ...updatedRepo, ...updates } + return updatedRepo + }) + + await handlers.get('projectHostSetups:setupExistingFolder')!(null, { + projectId: selectedProject.id, + hostId: 'local', + path: existing.path, + kind: 'git', + setupMethod: 'imported-existing-folder' + }) + + expect(mockStore.updateRepo).toHaveBeenNthCalledWith(1, existing.id, { + upstream: { + owner: 'acme', + repo: 'orca', + host: 'github.acme-corp.com' + } + }) + }) + it('prepares and invalidates roots when repos:update changes worktree base path', () => { const updated = { id: 'repo-update-root', diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index 007af79b5..cb9e027f7 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -163,7 +163,8 @@ function alignRepoWithRequestedProject( const updated = store.updateRepo(repo.id, { upstream: { owner: project.providerIdentity.owner, - repo: project.providerIdentity.repo + repo: project.providerIdentity.repo, + ...(project.providerIdentity.host ? { host: project.providerIdentity.host } : {}) } }) if (!updated) { diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 83f5cf356..db646b3bb 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -5314,6 +5314,7 @@ describe('OrcaRuntimeService', () => { }) it('allows host integration slug helpers for SSH repos through provider-aware GitHub clients', async () => { + const prRepo = { owner: 'acme', repo: 'orca', host: 'github.acme.test' } getIssueMock.mockResolvedValueOnce({ number: 12, title: 'Remote issue' }) listGitHubIssuesMock.mockResolvedValueOnce({ items: [{ number: 7, title: 'Remote issue list item' }] @@ -5341,16 +5342,30 @@ describe('OrcaRuntimeService', () => { await expect(runtime.listRepoIssues('id:repo-1', 10)).resolves.toEqual([ { number: 7, title: 'Remote issue list item' } ]) - await expect(runtime.requestRepoPRReviewers('id:repo-1', 7, ['alex'])).resolves.toEqual({ - ok: true - }) - await expect(runtime.removeRepoPRReviewers('id:repo-1', 7, ['alex'])).resolves.toEqual({ + await expect(runtime.requestRepoPRReviewers('id:repo-1', 7, ['alex'], prRepo)).resolves.toEqual( + { + ok: true + } + ) + await expect(runtime.removeRepoPRReviewers('id:repo-1', 7, ['alex'], prRepo)).resolves.toEqual({ ok: true }) expect(getIssueMock).toHaveBeenCalledWith('/remote/repo', 12, 'ssh-1') expect(listGitHubIssuesMock).toHaveBeenCalledWith('/remote/repo', 10, undefined, 'ssh-1') - expect(requestGitHubPRReviewersMock).toHaveBeenCalledWith('/remote/repo', 7, ['alex'], 'ssh-1') - expect(removeGitHubPRReviewersMock).toHaveBeenCalledWith('/remote/repo', 7, ['alex'], 'ssh-1') + expect(requestGitHubPRReviewersMock).toHaveBeenCalledWith( + '/remote/repo', + 7, + ['alex'], + 'ssh-1', + prRepo + ) + expect(removeGitHubPRReviewersMock).toHaveBeenCalledWith( + '/remote/repo', + 7, + ['alex'], + 'ssh-1', + prRepo + ) }) it('routes runtime GitHub repo identity helpers through the selected WSL project runtime', async () => { @@ -5524,14 +5539,18 @@ describe('OrcaRuntimeService', () => { } const runtime = new OrcaRuntimeService(runtimeStore as never) const localGitOptions = { wslDistro: 'Ubuntu' } - const prRepo = { owner: 'acme', repo: 'orca' } + const prRepo = { owner: 'acme', repo: 'orca', host: 'github.acme.test' } await runtime.getRepoPRForBranch('id:repo-1', 'feature/wsl', 42, 43) await runtime.getRepoWorkItem('id:repo-1', 42, 'pr') await runtime.getRepoWorkItemByOwnerRepo('id:repo-1', prRepo, 42, 'pr') await runtime.getRepoWorkItemDetails('id:repo-1', 42, 'pr') await runtime.getRepoPRChecks('id:repo-1', 42, 'head-sha', prRepo, { noCache: true }) - await runtime.rerunRepoPRChecks('id:repo-1', 42, { headSha: 'head-sha', failedOnly: true }) + await runtime.rerunRepoPRChecks('id:repo-1', 42, { + headSha: 'head-sha', + failedOnly: true, + prRepo + }) await runtime.getRepoPRCheckDetails('id:repo-1', { checkRunId: 9, workflowRunId: 8, @@ -5542,13 +5561,15 @@ describe('OrcaRuntimeService', () => { await runtime.getRepoPRComments('id:repo-1', 42, prRepo, { noCache: true }) await runtime.getRepoPRFileContents('id:repo-1', { prNumber: 42, + prRepo, path: 'src/app.ts', status: 'modified', headSha: 'head-sha', baseSha: 'base-sha' }) - await runtime.resolveRepoReviewThread('id:repo-1', 'thread-1', true) + await runtime.resolveRepoReviewThread('id:repo-1', 'thread-1', true, prRepo) await runtime.setRepoPRFileViewed('id:repo-1', { + prRepo, pullRequestId: 'PR_kw', path: 'src/app.ts', viewed: true @@ -5557,11 +5578,12 @@ describe('OrcaRuntimeService', () => { await runtime.updateRepoPRDetails('id:repo-1', 42, { body: 'New body' }, prRepo) await runtime.mergeRepoPR('id:repo-1', 42, 'squash', prRepo) await runtime.setRepoPRAutoMerge('id:repo-1', 42, true, 'squash', prRepo) - await runtime.updateRepoPRState('id:repo-1', 42, { state: 'closed' }) - await runtime.requestRepoPRReviewers('id:repo-1', 42, ['octo']) - await runtime.removeRepoPRReviewers('id:repo-1', 42, ['octo']) + await runtime.updateRepoPRState('id:repo-1', 42, { state: 'closed' }, prRepo) + await runtime.requestRepoPRReviewers('id:repo-1', 42, ['octo'], prRepo) + await runtime.removeRepoPRReviewers('id:repo-1', 42, ['octo'], prRepo) await runtime.addRepoPRReviewComment('id:repo-1', { prNumber: 42, + prRepo, body: 'Inline', commitId: 'head-sha', path: 'src/app.ts', @@ -5621,7 +5643,7 @@ describe('OrcaRuntimeService', () => { expect(rerunGitHubPRChecksMock).toHaveBeenCalledWith( TEST_REPO_PATH, 42, - { headSha: 'head-sha', failedOnly: true }, + { headSha: 'head-sha', failedOnly: true, prRepo }, null, localGitOptions ) @@ -5645,17 +5667,18 @@ describe('OrcaRuntimeService', () => { localGitOptions ) expect(getGitHubPRFileContentsMock).toHaveBeenCalledWith( - expect.objectContaining({ repoPath: TEST_REPO_PATH, localGitOptions }) + expect.objectContaining({ repoPath: TEST_REPO_PATH, localGitOptions, prRepo }) ) expect(resolveGitHubReviewThreadMock).toHaveBeenCalledWith( TEST_REPO_PATH, 'thread-1', true, null, + prRepo, localGitOptions ) expect(setGitHubPRFileViewedMock).toHaveBeenCalledWith( - expect.objectContaining({ repoPath: TEST_REPO_PATH, localGitOptions }) + expect.objectContaining({ repoPath: TEST_REPO_PATH, localGitOptions, prRepo }) ) expect(updateGitHubPRTitleMock).toHaveBeenCalledWith( TEST_REPO_PATH, @@ -5695,6 +5718,7 @@ describe('OrcaRuntimeService', () => { 42, { state: 'closed' }, null, + prRepo, localGitOptions ) expect(requestGitHubPRReviewersMock).toHaveBeenCalledWith( @@ -5702,6 +5726,7 @@ describe('OrcaRuntimeService', () => { 42, ['octo'], null, + prRepo, localGitOptions ) expect(removeGitHubPRReviewersMock).toHaveBeenCalledWith( @@ -5709,12 +5734,14 @@ describe('OrcaRuntimeService', () => { 42, ['octo'], null, + prRepo, localGitOptions ) expect(addGitHubPRReviewCommentMock).toHaveBeenCalledWith( expect.objectContaining({ repoPath: TEST_REPO_PATH, localGitOptions, + prRepo, body: 'Inline' }) ) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 133f668b7..92530eb91 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -12710,7 +12710,10 @@ export class OrcaRuntimeService { const updated = this.store.updateRepo(repo.id, { upstream: { owner: existingProject.providerIdentity.owner, - repo: existingProject.providerIdentity.repo + repo: existingProject.providerIdentity.repo, + ...(existingProject.providerIdentity.host + ? { host: existingProject.providerIdentity.host } + : {}) } }) if (!updated) { @@ -13811,7 +13814,7 @@ export class OrcaRuntimeService { return isWslUncPath(scope.path) ? 'linux' : process.platform } - async getRepoSlug(repoSelector: string): Promise<{ owner: string; repo: string } | null> { + async getRepoSlug(repoSelector: string): Promise { const repo = await this.resolveRepoSelector(repoSelector) const options = this.getHostedReviewExecutionOptions(repo) return options @@ -13819,7 +13822,7 @@ export class OrcaRuntimeService { : getRepoSlug(repo.path, repo.connectionId ?? null) } - async getRepoUpstream(repoSelector: string): Promise<{ owner: string; repo: string } | null> { + async getRepoUpstream(repoSelector: string): Promise { const repo = await this.resolveRepoSelector(repoSelector) const options = this.getHostedReviewExecutionOptions(repo) return options @@ -13840,7 +13843,7 @@ export class OrcaRuntimeService { if (repo.upstream !== undefined || repo.kind === 'folder' || repo.connectionId) { continue } - let upstream: { owner: string; repo: string } | null + let upstream: GitHubOwnerRepo | null try { upstream = await getRepoUpstream(repo.path, null) } catch { @@ -14528,7 +14531,11 @@ export class OrcaRuntimeService { async rerunRepoPRChecks( repoSelector: string, prNumber: number, - options?: { headSha?: string; failedOnly?: boolean } + options?: { + headSha?: string + failedOnly?: boolean + prRepo?: GitHubOwnerRepo | null + } ): Promise>> { const repo = await this.resolveRepoSelector(repoSelector) return rerunPRChecks( @@ -14579,6 +14586,7 @@ export class OrcaRuntimeService { repoSelector: string, args: { prNumber: number + prRepo?: GitHubOwnerRepo | null path: string oldPath?: string status: GitHubPRFile['status'] @@ -14598,7 +14606,8 @@ export class OrcaRuntimeService { async resolveRepoReviewThread( repoSelector: string, threadId: string, - resolve: boolean + resolve: boolean, + prRepo?: GitHubOwnerRepo | null ): Promise>> { const repo = await this.resolveRepoSelector(repoSelector) return resolveReviewThread( @@ -14606,6 +14615,7 @@ export class OrcaRuntimeService { threadId, resolve, repo.connectionId ?? null, + prRepo ?? null, ...this.getLocalGitExecutionOptionArgs(repo) ) } @@ -14613,6 +14623,7 @@ export class OrcaRuntimeService { async setRepoPRFileViewed( repoSelector: string, args: { + prRepo?: GitHubOwnerRepo | null pullRequestId: string path: string viewed: boolean @@ -14700,7 +14711,8 @@ export class OrcaRuntimeService { async updateRepoPRState( repoSelector: string, prNumber: number, - updates: GitHubPullRequestStateUpdate + updates: GitHubPullRequestStateUpdate, + prRepo?: GitHubOwnerRepo | null ): Promise>> { const repo = await this.resolveRepoSelector(repoSelector) return updatePRState( @@ -14708,6 +14720,7 @@ export class OrcaRuntimeService { prNumber, updates, repo.connectionId ?? null, + prRepo ?? null, ...this.getLocalGitExecutionOptionArgs(repo) ) } @@ -14715,7 +14728,8 @@ export class OrcaRuntimeService { async requestRepoPRReviewers( repoSelector: string, prNumber: number, - reviewers: string[] + reviewers: string[], + prRepo?: GitHubOwnerRepo | null ): Promise>> { const repo = await this.resolveRepoSelector(repoSelector) return requestPRReviewers( @@ -14723,6 +14737,7 @@ export class OrcaRuntimeService { prNumber, reviewers, repo.connectionId ?? null, + prRepo ?? null, ...this.getLocalGitExecutionOptionArgs(repo) ) } @@ -14730,7 +14745,8 @@ export class OrcaRuntimeService { async removeRepoPRReviewers( repoSelector: string, prNumber: number, - reviewers: string[] + reviewers: string[], + prRepo?: GitHubOwnerRepo | null ): Promise>> { const repo = await this.resolveRepoSelector(repoSelector) return removePRReviewers( @@ -14738,6 +14754,7 @@ export class OrcaRuntimeService { prNumber, reviewers, repo.connectionId ?? null, + prRepo ?? null, ...this.getLocalGitExecutionOptionArgs(repo) ) } diff --git a/src/main/runtime/rpc/methods/github.test.ts b/src/main/runtime/rpc/methods/github.test.ts index 7ea054aef..06cc04d91 100644 --- a/src/main/runtime/rpc/methods/github.test.ts +++ b/src/main/runtime/rpc/methods/github.test.ts @@ -235,6 +235,7 @@ describe('github RPC methods', () => { makeRequest('github.prFileContents', { repo: 'repo-1', prNumber: 7, + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' }, path: 'src/app.ts', status: 'modified', headSha: 'head', @@ -244,6 +245,7 @@ describe('github RPC methods', () => { expect(runtime.getRepoPRFileContents).toHaveBeenCalledWith('repo-1', { prNumber: 7, + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' }, path: 'src/app.ts', oldPath: undefined, status: 'modified', @@ -264,11 +266,16 @@ describe('github RPC methods', () => { makeRequest('github.resolveReviewThread', { repo: 'repo-1', threadId: 'PRRT_1', - resolve: true + resolve: true, + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' } }) ) - expect(runtime.resolveRepoReviewThread).toHaveBeenCalledWith('repo-1', 'PRRT_1', true) + expect(runtime.resolveRepoReviewThread).toHaveBeenCalledWith('repo-1', 'PRRT_1', true, { + owner: 'acme', + repo: 'widgets', + host: 'github.acme.test' + }) expect(response).toMatchObject({ ok: true, result: true }) }) @@ -282,6 +289,7 @@ describe('github RPC methods', () => { const response = await dispatcher.dispatch( makeRequest('github.setPRFileViewed', { repo: 'repo-1', + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' }, pullRequestId: 'PR_kwDO123', path: 'src/app.ts', viewed: true @@ -289,6 +297,7 @@ describe('github RPC methods', () => { ) expect(runtime.setRepoPRFileViewed).toHaveBeenCalledWith('repo-1', { + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' }, pullRequestId: 'PR_kwDO123', path: 'src/app.ts', viewed: true @@ -406,19 +415,29 @@ describe('github RPC methods', () => { makeRequest('github.requestPRReviewers', { repo: 'repo-1', prNumber: 7, - reviewers: ['octo'] + reviewers: ['octo'], + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' } }) ) const removeResponse = await dispatcher.dispatch( makeRequest('github.removePRReviewers', { repo: 'repo-1', prNumber: 7, - reviewers: ['octo'] + reviewers: ['octo'], + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' } }) ) - expect(runtime.requestRepoPRReviewers).toHaveBeenCalledWith('repo-1', 7, ['octo']) - expect(runtime.removeRepoPRReviewers).toHaveBeenCalledWith('repo-1', 7, ['octo']) + expect(runtime.requestRepoPRReviewers).toHaveBeenCalledWith('repo-1', 7, ['octo'], { + owner: 'acme', + repo: 'widgets', + host: 'github.acme.test' + }) + expect(runtime.removeRepoPRReviewers).toHaveBeenCalledWith('repo-1', 7, ['octo'], { + owner: 'acme', + repo: 'widgets', + host: 'github.acme.test' + }) expect(requestResponse).toMatchObject({ ok: true, result: { ok: true } }) expect(removeResponse).toMatchObject({ ok: true, result: { ok: true } }) }) @@ -434,11 +453,21 @@ describe('github RPC methods', () => { makeRequest('github.updatePRState', { repo: 'repo-1', prNumber: 7, + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' }, updates: { state: 'closed' } }) ) - expect(runtime.updateRepoPRState).toHaveBeenCalledWith('repo-1', 7, { state: 'closed' }) + expect(runtime.updateRepoPRState).toHaveBeenCalledWith( + 'repo-1', + 7, + { state: 'closed' }, + { + owner: 'acme', + repo: 'widgets', + host: 'github.acme.test' + } + ) expect(response).toMatchObject({ ok: true, result: { ok: true } }) }) @@ -542,6 +571,7 @@ describe('github RPC methods', () => { makeRequest('github.addPRReviewComment', { repo: 'repo-1', prNumber: 7, + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' }, commitId: 'head', path: 'src/app.ts', line: 12, @@ -552,6 +582,7 @@ describe('github RPC methods', () => { expect(runtime.addRepoPRReviewComment).toHaveBeenCalledWith('repo-1', { prNumber: 7, + prRepo: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' }, commitId: 'head', path: 'src/app.ts', line: 12, diff --git a/src/main/runtime/rpc/methods/github.ts b/src/main/runtime/rpc/methods/github.ts index d48096c5c..858d22b72 100644 --- a/src/main/runtime/rpc/methods/github.ts +++ b/src/main/runtime/rpc/methods/github.ts @@ -92,6 +92,7 @@ const RerunPullRequestChecks = PullRequest.extend({ const PullRequestFileContents = RepoSelector.extend({ prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), path: requiredString('Missing file path'), oldPath: OptionalString, status: z.enum(['added', 'removed', 'modified', 'renamed', 'copied', 'changed', 'unchanged']), @@ -100,12 +101,14 @@ const PullRequestFileContents = RepoSelector.extend({ }) const PullRequestFileViewed = RepoSelector.extend({ + prRepo: SlugRepo.nullable().optional(), pullRequestId: requiredString('Missing pull request ID'), path: requiredString('Missing file path'), viewed: z.boolean() }) const ReviewThread = RepoSelector.extend({ + prRepo: SlugRepo.nullable().optional(), threadId: requiredString('Missing thread ID'), resolve: z.boolean() }) @@ -140,6 +143,7 @@ const SetPrAutoMerge = RepoSelector.extend({ const UpdatePrState = RepoSelector.extend({ prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), updates: z.object({ state: z.enum(['open', 'closed']) }) @@ -147,11 +151,13 @@ const UpdatePrState = RepoSelector.extend({ const RequestPrReviewers = RepoSelector.extend({ prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), reviewers: z.array(z.string()).min(1) }) const RemovePrReviewers = RepoSelector.extend({ prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), reviewers: z.array(z.string()).min(1) }) @@ -186,6 +192,7 @@ const IssueComment = RepoSelector.extend({ const PRReviewComment = RepoSelector.extend({ prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), commitId: requiredString('Missing PR head SHA'), path: requiredString('File path required'), line: z.number().int().positive(), @@ -440,7 +447,8 @@ export const GITHUB_METHODS: RpcMethod[] = [ handler: async (params, { runtime }) => runtime.rerunRepoPRChecks(params.repo, params.prNumber, { headSha: params.headSha, - failedOnly: params.failedOnly + failedOnly: params.failedOnly, + prRepo: params.prRepo ?? null }) }), defineMethod({ @@ -457,6 +465,7 @@ export const GITHUB_METHODS: RpcMethod[] = [ handler: async (params, { runtime }) => runtime.getRepoPRFileContents(params.repo, { prNumber: params.prNumber, + prRepo: params.prRepo ?? null, path: params.path, oldPath: params.oldPath, status: params.status, @@ -468,13 +477,19 @@ export const GITHUB_METHODS: RpcMethod[] = [ name: 'github.resolveReviewThread', params: ReviewThread, handler: async (params, { runtime }) => - runtime.resolveRepoReviewThread(params.repo, params.threadId, params.resolve) + runtime.resolveRepoReviewThread( + params.repo, + params.threadId, + params.resolve, + params.prRepo ?? null + ) }), defineMethod({ name: 'github.setPRFileViewed', params: PullRequestFileViewed, handler: async (params, { runtime }) => runtime.setRepoPRFileViewed(params.repo, { + prRepo: params.prRepo ?? null, pullRequestId: params.pullRequestId, path: params.path, viewed: params.viewed @@ -519,19 +534,29 @@ export const GITHUB_METHODS: RpcMethod[] = [ name: 'github.updatePRState', params: UpdatePrState, handler: async (params, { runtime }) => - runtime.updateRepoPRState(params.repo, params.prNumber, params.updates) + runtime.updateRepoPRState(params.repo, params.prNumber, params.updates, params.prRepo ?? null) }), defineMethod({ name: 'github.requestPRReviewers', params: RequestPrReviewers, handler: async (params, { runtime }) => - runtime.requestRepoPRReviewers(params.repo, params.prNumber, params.reviewers) + runtime.requestRepoPRReviewers( + params.repo, + params.prNumber, + params.reviewers, + params.prRepo ?? null + ) }), defineMethod({ name: 'github.removePRReviewers', params: RemovePrReviewers, handler: async (params, { runtime }) => - runtime.removeRepoPRReviewers(params.repo, params.prNumber, params.reviewers) + runtime.removeRepoPRReviewers( + params.repo, + params.prNumber, + params.reviewers, + params.prRepo ?? null + ) }), defineMethod({ name: 'github.createIssue', @@ -564,6 +589,7 @@ export const GITHUB_METHODS: RpcMethod[] = [ handler: async (params, { runtime }) => runtime.addRepoPRReviewComment(params.repo, { prNumber: params.prNumber, + prRepo: params.prRepo ?? null, commitId: params.commitId, path: params.path, line: params.line, diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 2717f392b..82c5d2ce7 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1509,7 +1509,7 @@ export type PreloadApi = { repoUpstream: (args: { repoPath: string repoId?: string - }) => Promise<{ owner: string; repo: string } | null> + }) => Promise<{ owner: string; repo: string; host?: string } | null> prForBranch: (args: { repoPath: string repoId?: string @@ -1567,6 +1567,7 @@ export type PreloadApi = { prFileContents: ( args: GitHubRepoSelectorArgs & { prNumber: number + prRepo?: GitHubOwnerRepo | null path: string oldPath?: string status: GitHubPRFile['status'] @@ -1620,6 +1621,7 @@ export type PreloadApi = { prNumber: number headSha?: string failedOnly?: boolean + prRepo?: GitHubOwnerRepo | null } ) => Promise<{ ok: true; count: number } | { ok: false; error: string }> prComments: (args: { @@ -1636,10 +1638,12 @@ export type PreloadApi = { sourceContext?: TaskSourceContext | null threadId: string resolve: boolean + prRepo?: GitHubOwnerRepo | null }) => Promise setPRFileViewed: ( args: GitHubRepoSelectorArgs & { prNumber: number + prRepo?: GitHubOwnerRepo | null pullRequestId: string path: string viewed: boolean @@ -1671,18 +1675,21 @@ export type PreloadApi = { args: GitHubRepoSelectorArgs & { prNumber: number updates: { state: 'open' | 'closed' } + prRepo?: GitHubOwnerRepo | null } ) => Promise<{ ok: true } | { ok: false; error: string }> requestPRReviewers: ( args: GitHubRepoSelectorArgs & { prNumber: number reviewers: string[] + prRepo?: GitHubOwnerRepo | null } ) => Promise<{ ok: true } | { ok: false; error: string }> removePRReviewers: ( args: GitHubRepoSelectorArgs & { prNumber: number reviewers: string[] + prRepo?: GitHubOwnerRepo | null } ) => Promise<{ ok: true } | { ok: false; error: string }> updateIssue: ( diff --git a/src/preload/index.ts b/src/preload/index.ts index cf4a5d857..87ee2830c 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1305,6 +1305,7 @@ const api = { repoId?: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null path: string oldPath?: string status: string @@ -1369,6 +1370,7 @@ const api = { prNumber: number headSha?: string failedOnly?: boolean + prRepo?: GitHubOwnerRepo | null }): Promise<{ ok: true; count: number } | { ok: false; error: string }> => ipcRenderer.invoke('gh:rerunPRChecks', args), @@ -1387,6 +1389,7 @@ const api = { sourceContext?: TaskSourceContext | null threadId: string resolve: boolean + prRepo?: GitHubOwnerRepo | null }): Promise => ipcRenderer.invoke('gh:resolveReviewThread', args), setPRFileViewed: (args: { @@ -1394,6 +1397,7 @@ const api = { repoId?: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null pullRequestId: string path: string viewed: boolean @@ -1434,6 +1438,7 @@ const api = { sourceContext?: TaskSourceContext | null prNumber: number updates: { state: 'open' | 'closed' } + prRepo?: GitHubOwnerRepo | null }): Promise<{ ok: true } | { ok: false; error: string }> => ipcRenderer.invoke('gh:updatePRState', args), @@ -1443,6 +1448,7 @@ const api = { sourceContext?: TaskSourceContext | null prNumber: number reviewers: string[] + prRepo?: GitHubOwnerRepo | null }): Promise<{ ok: true } | { ok: false; error: string }> => ipcRenderer.invoke('gh:requestPRReviewers', args), @@ -1452,6 +1458,7 @@ const api = { sourceContext?: TaskSourceContext | null prNumber: number reviewers: string[] + prRepo?: GitHubOwnerRepo | null }): Promise<{ ok: true } | { ok: false; error: string }> => ipcRenderer.invoke('gh:removePRReviewers', args), @@ -1492,6 +1499,7 @@ const api = { repoId?: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null commitId: string path: string line: number diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index d924c3d40..9a17070e5 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -187,6 +187,7 @@ import { GITHUB_PR_MERGE_METHOD_LABELS, resolveGitHubPRMergeMethods } from '../../../shared/github-pr-merge-methods' +import { githubRepoIdentityKey } from '../../../shared/github-repository-identity-key' import { findGithubIssueWorkspaceAttachment, getGithubWorkItemWorkspaceAttachmentLabel @@ -952,7 +953,12 @@ function PRReviewersPanel({ ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.requestPRReviewers', - { repo: runtimeRepo, prNumber: item.number, reviewers: logins }, + { + repo: runtimeRepo, + prNumber: item.number, + reviewers: logins, + prRepo: item.prRepo ?? reviewSlug + }, { timeoutMs: 30_000 } ) : await window.api.gh.requestPRReviewers({ @@ -960,7 +966,8 @@ function PRReviewersPanel({ repoId: item.repoId, sourceContext, prNumber: item.number, - reviewers: logins + reviewers: logins, + prRepo: item.prRepo ?? reviewSlug }) if (!reviewerPanelMountedRef.current) { return @@ -1043,7 +1050,12 @@ function PRReviewersPanel({ ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.removePRReviewers', - { repo: runtimeRepo, prNumber: item.number, reviewers: logins }, + { + repo: runtimeRepo, + prNumber: item.number, + reviewers: logins, + prRepo: item.prRepo ?? reviewSlug + }, { timeoutMs: 30_000 } ) : await window.api.gh.removePRReviewers({ @@ -1051,7 +1063,8 @@ function PRReviewersPanel({ repoId: item.repoId, sourceContext, prNumber: item.number, - reviewers: logins + reviewers: logins, + prRepo: item.prRepo ?? reviewSlug }) if (!reviewerPanelMountedRef.current) { return @@ -1695,6 +1708,7 @@ function getPRFileContentCacheKey(args: { repoId: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null file: GitHubPRFile headSha: string baseSha: string @@ -1708,6 +1722,7 @@ function getPRFileContentCacheKey(args: { repositoryKey, sourceKey, args.prNumber, + args.prRepo ? githubRepoIdentityKey(args.prRepo) : '', args.file.path, args.file.oldPath ?? '', args.file.status, @@ -1721,6 +1736,7 @@ function loadPRFileContents(args: { repoId: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null file: GitHubPRFile headSha: string baseSha: string @@ -1741,6 +1757,7 @@ function loadPRFileContents(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), prNumber: args.prNumber, + prRepo: args.prRepo ?? null, path: args.file.path, oldPath: args.file.oldPath, status: args.file.status, @@ -1754,6 +1771,7 @@ function loadPRFileContents(args: { repoId: args.repoId, sourceContext: args.sourceContext, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, path: args.file.path, oldPath: args.file.oldPath, status: args.file.status, @@ -1786,6 +1804,7 @@ function addIssueCommentForRepo(args: { number: number body: string type?: 'issue' | 'pr' + prRepo?: GitHubOwnerRepo | null }): Promise>> { const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) if (runtimeHost) { @@ -1795,7 +1814,8 @@ function addIssueCommentForRepo(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), number: args.number, - body: args.body + body: args.body, + prRepo: args.prRepo ?? null }, { timeoutMs: 30_000 } ).then((result) => { @@ -1820,7 +1840,8 @@ function addIssueCommentForRepo(args: { sourceContext: args.sourceContext, number: args.number, body: args.body, - type: args.type + type: args.type, + prRepo: args.prRepo ?? null }) } @@ -1829,6 +1850,7 @@ function addPRReviewCommentForRepo(args: { repoPath: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null commitId: string path: string line: number @@ -1843,6 +1865,7 @@ function addPRReviewCommentForRepo(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), prNumber: args.prNumber, + prRepo: args.prRepo ?? null, commitId: args.commitId, path: args.path, line: args.line, @@ -1871,6 +1894,7 @@ function addPRReviewCommentForRepo(args: { repoId: args.repoId, sourceContext: args.sourceContext, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, commitId: args.commitId, path: args.path, line: args.line, @@ -1884,6 +1908,7 @@ function addPRReviewCommentReplyForRepo(args: { repoPath: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null commentId: number body: string threadId?: string @@ -1898,6 +1923,7 @@ function addPRReviewCommentReplyForRepo(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), prNumber: args.prNumber, + prRepo: args.prRepo ?? null, commentId: args.commentId, body: args.body, threadId: args.threadId, @@ -1926,6 +1952,7 @@ function addPRReviewCommentReplyForRepo(args: { repoId: args.repoId, sourceContext: args.sourceContext, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, commentId: args.commentId, body: args.body, threadId: args.threadId, @@ -1962,6 +1989,7 @@ function setPRFileViewedForRepo(args: { repoPath: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null pullRequestId: string path: string viewed: boolean @@ -1973,6 +2001,7 @@ function setPRFileViewedForRepo(args: { 'github.setPRFileViewed', { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + prRepo: args.prRepo ?? null, pullRequestId: args.pullRequestId, path: args.path, viewed: args.viewed @@ -1999,6 +2028,7 @@ function setPRFileViewedForRepo(args: { repoId: args.repoId, sourceContext: args.sourceContext, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, pullRequestId: args.pullRequestId, path: args.path, viewed: args.viewed @@ -2158,6 +2188,7 @@ type PRFilesCombinedDiffViewerProps = { repoId: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null prUrl: string headSha: string | undefined baseSha: string | undefined @@ -2173,6 +2204,7 @@ function PRFilesCombinedDiffViewer({ repoId, sourceContext, prNumber, + prRepo, prUrl, headSha, baseSha, @@ -2250,11 +2282,12 @@ function PRFilesCombinedDiffViewer({ JSON.stringify({ repoId, prNumber, + prRepo: prRepo ? githubRepoIdentityKey(prRepo) : null, headSha: headSha ?? null, baseSha: baseSha ?? null, files: diffEntrySignature }), - [baseSha, diffEntrySignature, headSha, prNumber, repoId] + [baseSha, diffEntrySignature, headSha, prNumber, prRepo, repoId] ) const [sections, setSections] = useState([]) const [sideBySide, setSideBySide] = useState(false) @@ -2348,6 +2381,7 @@ function PRFilesCombinedDiffViewer({ repoId, sourceContext, prNumber, + prRepo, file, headSha, baseSha @@ -2396,7 +2430,7 @@ function PRFilesCombinedDiffViewer({ ) }) }, - [baseSha, fileByPath, headSha, prNumber, repoId, repoPath, sourceContext] + [baseSha, fileByPath, headSha, prNumber, prRepo, repoId, repoPath, sourceContext] ) const retrySection = useCallback( @@ -2541,6 +2575,7 @@ function PRFilesCombinedDiffViewer({ repoId, sourceContext, prNumber, + prRepo, commitId: headSha, path: section.path, line: lineNumber, @@ -2563,7 +2598,7 @@ function PRFilesCombinedDiffViewer({ ) return true }, - [headSha, onCommentAdded, prNumber, repoId, repoPath, sourceContext] + [headSha, onCommentAdded, prNumber, prRepo, repoId, repoPath, sourceContext] ) const renderViewedCheckbox = useCallback( @@ -2711,6 +2746,7 @@ function CommentCodeContext({ repoId, sourceContext, prNumber, + prRepo, files, headSha, baseSha @@ -2720,6 +2756,7 @@ function CommentCodeContext({ repoId: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null files: GitHubPRFile[] headSha: string | undefined baseSha: string | undefined @@ -2743,7 +2780,16 @@ function CommentCodeContext({ return } let cancelled = false - loadPRFileContents({ repoPath, repoId, sourceContext, prNumber, file, headSha, baseSha }) + loadPRFileContents({ + repoPath, + repoId, + sourceContext, + prNumber, + prRepo, + file, + headSha, + baseSha + }) .then((result) => { if (!cancelled) { setContents(result) @@ -2757,7 +2803,7 @@ function CommentCodeContext({ return () => { cancelled = true } - }, [baseSha, file, headSha, line, prNumber, repoId, repoPath, sourceContext]) + }, [baseSha, file, headSha, line, prNumber, prRepo, repoId, repoPath, sourceContext]) const resolvedContextExpansionState = resolveCommentCodeContextExpansionState( contextExpansionState, @@ -3224,6 +3270,7 @@ function ConversationTab({ repoId: item.repoId, sourceContext, prNumber: item.number, + prRepo: item.prRepo ?? parseOwnerRepoFromItemUrl(item.url), commentId: comment.id, body: replyBody, threadId: comment.threadId, @@ -3236,7 +3283,8 @@ function ConversationTab({ sourceContext, number: item.number, body: `@${comment.author} ${replyBody}`, - type: item.type + type: item.type, + prRepo: item.prRepo ?? parseOwnerRepoFromItemUrl(item.url) }) if (!result.ok) { @@ -3254,8 +3302,10 @@ function ConversationTab({ [ canUseRepoMutationContext, item.number, + item.prRepo, item.repoId, item.type, + item.url, onCommentAdded, repoPath, sourceContext @@ -3402,6 +3452,7 @@ function ConversationTab({ repoId={item.repoId} sourceContext={sourceContext} prNumber={item.number} + prRepo={item.prRepo ?? parseOwnerRepoFromItemUrl(item.url)} files={files} headSha={headSha} baseSha={baseSha} @@ -3811,6 +3862,7 @@ function ConversationTab({ sourceContext={sourceContext} issueNumber={item.number} itemType={item.type} + prRepo={item.prRepo ?? parseOwnerRepoFromItemUrl(item.url)} onCommentAdded={onCommentAdded} /> )} @@ -3918,6 +3970,7 @@ function PRActionsPanel({ sourceContext, projectOrigin, number: item.number, + prRepo: item.prRepo ?? parseOwnerRepoFromItemUrl(item.url), updates: { state: nextState } }) useAppStore.getState().recordFeatureInteraction('github-tasks') @@ -4438,7 +4491,10 @@ function ChecksTab({ } const { localChecks, expandedCheckKey, detailsByCheckKey } = resolvedChecksState const list = useMemo(() => localChecks ?? checks ?? [], [checks, localChecks]) - const prRepo = useMemo(() => parseOwnerRepoFromItemUrl(item.url), [item.url]) + const prRepo = useMemo( + () => item.prRepo ?? parseOwnerRepoFromItemUrl(item.url), + [item.prRepo, item.url] + ) const runtimeHost = getGitHubSourceRuntimeHost(sourceContext) const canUseChecksRepoContext = canUseGitHubRepoContext(repoPath, sourceContext) const sorted = [...list].sort( @@ -4502,6 +4558,7 @@ function ChecksTab({ sourceContext, prNumber: item.number, headSha, + prRepo, noCache: true }))) as PRCheckDetail[] setChecksState((current) => updateGitHubChecksTabLocalChecks(current, nextChecks)) @@ -4545,7 +4602,8 @@ function ChecksTab({ repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId), prNumber: item.number, headSha, - failedOnly + failedOnly, + prRepo }, { timeoutMs: 30_000 } ) @@ -4555,7 +4613,8 @@ function ChecksTab({ sourceContext, prNumber: item.number, headSha, - failedOnly + failedOnly, + prRepo }) if (!result.ok) { toast.error(result.error) @@ -4583,6 +4642,7 @@ function ChecksTab({ headSha, item.number, item.repoId, + prRepo, runtimeHost, rerunning, repoId, @@ -5419,6 +5479,7 @@ async function runPullRequestStateUpdate(args: { sourceContext?: TaskSourceContext | null projectOrigin: GitHubItemDialogProjectOrigin | undefined number: number + prRepo?: GitHubOwnerRepo | null updates: { state: 'open' | 'closed' } }): Promise { if (args.projectOrigin) { @@ -5477,6 +5538,7 @@ async function runPullRequestStateUpdate(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), prNumber: args.number, + prRepo: args.prRepo ?? null, updates: args.updates }, { timeoutMs: 30_000 } @@ -5486,6 +5548,7 @@ async function runPullRequestStateUpdate(args: { repoId: args.repoId ?? undefined, sourceContext: args.sourceContext, prNumber: args.number, + prRepo: args.prRepo ?? null, updates: args.updates }) if (!res.ok) { @@ -6579,6 +6642,7 @@ function GHCommentComposer({ sourceContext, issueNumber, itemType, + prRepo, onCommentAdded }: { className?: string @@ -6587,6 +6651,7 @@ function GHCommentComposer({ sourceContext?: TaskSourceContext | null issueNumber: number itemType: 'issue' | 'pr' + prRepo?: GitHubOwnerRepo | null onCommentAdded: (comment: PRComment) => void }): React.JSX.Element { const [body, setBody] = useState('') @@ -6615,7 +6680,8 @@ function GHCommentComposer({ sourceContext, number: issueNumber, body: bodyState.body, - type: itemType + type: itemType, + prRepo }) if (!mountedRef.current) { return @@ -6644,7 +6710,17 @@ function GHCommentComposer({ setSubmitting(false) } } - }, [body, mountedRef, repoPath, repoId, sourceContext, issueNumber, itemType, onCommentAdded]) + }, [ + body, + mountedRef, + repoPath, + repoId, + sourceContext, + issueNumber, + itemType, + prRepo, + onCommentAdded + ]) const canSubmitComment = hasBoundedCommentBodyText(body) return ( @@ -7242,6 +7318,7 @@ export default function GitHubItemDialog({ repoPath: repoPath ?? '', sourceContext, prNumber: workItem.number, + prRepo: workItem.prRepo ?? parseOwnerRepoFromItemUrl(workItem.url), pullRequestId: details.pullRequestId, path, viewed @@ -7833,6 +7910,7 @@ export default function GitHubItemDialog({ repoId={effectiveRepoId ?? ''} sourceContext={sourceContext} prNumber={workItem.number} + prRepo={workItem.prRepo ?? parseOwnerRepoFromItemUrl(workItem.url)} prUrl={workItem.url} headSha={details?.headSha} baseSha={details?.baseSha} diff --git a/src/renderer/src/components/PullRequestPage.tsx b/src/renderer/src/components/PullRequestPage.tsx index eedc4ae32..252f9127a 100644 --- a/src/renderer/src/components/PullRequestPage.tsx +++ b/src/renderer/src/components/PullRequestPage.tsx @@ -179,6 +179,7 @@ import { GITHUB_PR_MERGE_METHOD_LABELS, resolveGitHubPRMergeMethods } from '../../../shared/github-pr-merge-methods' +import { githubRepoIdentityKey } from '../../../shared/github-repository-identity-key' import { findGithubPrWorkspaceAttachment, getGithubPrWorkspaceAttachmentLabel @@ -995,7 +996,12 @@ function PRReviewersPanel({ ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.requestPRReviewers', - { repo: runtimeRepo, prNumber: item.number, reviewers: logins }, + { + repo: runtimeRepo, + prNumber: item.number, + reviewers: logins, + prRepo: item.prRepo ?? reviewSlug + }, { timeoutMs: 30_000 } ) : await window.api.gh.requestPRReviewers({ @@ -1003,7 +1009,8 @@ function PRReviewersPanel({ repoId: item.repoId, sourceContext, prNumber: item.number, - reviewers: logins + reviewers: logins, + prRepo: item.prRepo ?? reviewSlug }) if (!reviewerPanelMountedRef.current) { return @@ -1085,7 +1092,12 @@ function PRReviewersPanel({ ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.removePRReviewers', - { repo: runtimeRepo, prNumber: item.number, reviewers: logins }, + { + repo: runtimeRepo, + prNumber: item.number, + reviewers: logins, + prRepo: item.prRepo ?? reviewSlug + }, { timeoutMs: 30_000 } ) : await window.api.gh.removePRReviewers({ @@ -1093,7 +1105,8 @@ function PRReviewersPanel({ repoId: item.repoId, sourceContext, prNumber: item.number, - reviewers: logins + reviewers: logins, + prRepo: item.prRepo ?? reviewSlug }) if (!reviewerPanelMountedRef.current) { return @@ -1736,6 +1749,7 @@ function getPRFileContentCacheKey(args: { repoId: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null file: GitHubPRFile headSha: string baseSha: string @@ -1749,6 +1763,7 @@ function getPRFileContentCacheKey(args: { repositoryKey, sourceKey, args.prNumber, + args.prRepo ? githubRepoIdentityKey(args.prRepo) : '', args.file.path, args.file.oldPath ?? '', args.file.status, @@ -1762,6 +1777,7 @@ function loadPRFileContents(args: { repoId: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null file: GitHubPRFile headSha: string baseSha: string @@ -1782,6 +1798,7 @@ function loadPRFileContents(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), prNumber: args.prNumber, + prRepo: args.prRepo ?? null, path: args.file.path, oldPath: args.file.oldPath, status: args.file.status, @@ -1795,6 +1812,7 @@ function loadPRFileContents(args: { repoId: args.repoId, sourceContext: args.sourceContext, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, path: args.file.path, oldPath: args.file.oldPath, status: args.file.status, @@ -1827,6 +1845,7 @@ function addIssueCommentForRepo(args: { number: number body: string type?: 'issue' | 'pr' + prRepo?: GitHubOwnerRepo | null }): Promise>> { const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) if (runtimeHost) { @@ -1836,7 +1855,8 @@ function addIssueCommentForRepo(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), number: args.number, - body: args.body + body: args.body, + prRepo: args.prRepo ?? null }, { timeoutMs: 30_000 } ).then((result) => { @@ -1861,7 +1881,8 @@ function addIssueCommentForRepo(args: { sourceContext: args.sourceContext, number: args.number, body: args.body, - type: args.type + type: args.type, + prRepo: args.prRepo ?? null }) } @@ -1870,6 +1891,7 @@ function addPRReviewCommentForRepo(args: { repoPath: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null commitId: string path: string line: number @@ -1884,6 +1906,7 @@ function addPRReviewCommentForRepo(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), prNumber: args.prNumber, + prRepo: args.prRepo ?? null, commitId: args.commitId, path: args.path, line: args.line, @@ -1912,6 +1935,7 @@ function addPRReviewCommentForRepo(args: { repoId: args.repoId, sourceContext: args.sourceContext, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, commitId: args.commitId, path: args.path, line: args.line, @@ -1925,6 +1949,7 @@ function addPRReviewCommentReplyForRepo(args: { repoPath: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null commentId: number body: string threadId?: string @@ -1939,6 +1964,7 @@ function addPRReviewCommentReplyForRepo(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), prNumber: args.prNumber, + prRepo: args.prRepo ?? null, commentId: args.commentId, body: args.body, threadId: args.threadId, @@ -1967,6 +1993,7 @@ function addPRReviewCommentReplyForRepo(args: { repoId: args.repoId, sourceContext: args.sourceContext, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, commentId: args.commentId, body: args.body, threadId: args.threadId, @@ -2003,6 +2030,7 @@ function setPRFileViewedForRepo(args: { repoPath: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null pullRequestId: string path: string viewed: boolean @@ -2014,6 +2042,7 @@ function setPRFileViewedForRepo(args: { 'github.setPRFileViewed', { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + prRepo: args.prRepo ?? null, pullRequestId: args.pullRequestId, path: args.path, viewed: args.viewed @@ -2040,6 +2069,7 @@ function setPRFileViewedForRepo(args: { repoId: args.repoId, sourceContext: args.sourceContext, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, pullRequestId: args.pullRequestId, path: args.path, viewed: args.viewed @@ -2213,6 +2243,7 @@ type PRFilesCombinedDiffViewerProps = { repoId: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null prUrl: string headSha: string | undefined baseSha: string | undefined @@ -2228,6 +2259,7 @@ function PRFilesCombinedDiffViewer({ repoId, sourceContext, prNumber, + prRepo, prUrl, headSha, baseSha, @@ -2305,15 +2337,16 @@ function PRFilesCombinedDiffViewer({ JSON.stringify({ repoId, prNumber, + prRepo: prRepo ? githubRepoIdentityKey(prRepo) : null, headSha: headSha ?? null, baseSha: baseSha ?? null, files: diffEntrySignature }), - [baseSha, diffEntrySignature, headSha, prNumber, repoId] + [baseSha, diffEntrySignature, headSha, prNumber, prRepo, repoId] ) const viewStateKey = useMemo( - () => [repoId || repoPath, prNumber].join('\0'), - [prNumber, repoId, repoPath] + () => [repoId || repoPath, prNumber, prRepo ? githubRepoIdentityKey(prRepo) : ''].join('\0'), + [prNumber, prRepo, repoId, repoPath] ) const [sections, setSections] = useState([]) const [sideBySide, setSideBySide] = useState(false) @@ -2428,6 +2461,7 @@ function PRFilesCombinedDiffViewer({ repoId, sourceContext, prNumber, + prRepo, file, headSha, baseSha @@ -2476,7 +2510,7 @@ function PRFilesCombinedDiffViewer({ ) }) }, - [baseSha, fileByPath, headSha, prNumber, repoId, repoPath, sourceContext] + [baseSha, fileByPath, headSha, prNumber, prRepo, repoId, repoPath, sourceContext] ) const retrySection = useCallback( @@ -2711,6 +2745,7 @@ function PRFilesCombinedDiffViewer({ repoId, sourceContext, prNumber, + prRepo, commitId: headSha, path: section.path, line: lineNumber, @@ -2730,7 +2765,7 @@ function PRFilesCombinedDiffViewer({ ) return true }, - [headSha, onCommentAdded, prNumber, repoId, repoPath, sourceContext] + [headSha, onCommentAdded, prNumber, prRepo, repoId, repoPath, sourceContext] ) const renderViewedCheckbox = useCallback( @@ -2878,6 +2913,7 @@ function CommentCodeContext({ repoId, sourceContext, prNumber, + prRepo, files, headSha, baseSha @@ -2887,6 +2923,7 @@ function CommentCodeContext({ repoId: string sourceContext?: TaskSourceContext | null prNumber: number + prRepo?: GitHubOwnerRepo | null files: GitHubPRFile[] headSha: string | undefined baseSha: string | undefined @@ -2910,7 +2947,16 @@ function CommentCodeContext({ return } let cancelled = false - loadPRFileContents({ repoPath, repoId, sourceContext, prNumber, file, headSha, baseSha }) + loadPRFileContents({ + repoPath, + repoId, + sourceContext, + prNumber, + prRepo, + file, + headSha, + baseSha + }) .then((result) => { if (!cancelled) { setContents(result) @@ -2924,7 +2970,7 @@ function CommentCodeContext({ return () => { cancelled = true } - }, [baseSha, file, headSha, line, prNumber, repoId, repoPath, sourceContext]) + }, [baseSha, file, headSha, line, prNumber, prRepo, repoId, repoPath, sourceContext]) const resolvedContextExpansionState = resolveCommentCodeContextExpansionState( contextExpansionState, @@ -3367,6 +3413,7 @@ function ConversationTab({ repoId: item.repoId, sourceContext, prNumber: item.number, + prRepo: item.prRepo ?? parseOwnerRepoFromItemUrl(item.url), commentId: comment.id, body: replyBody, threadId: comment.threadId, @@ -3379,7 +3426,8 @@ function ConversationTab({ sourceContext, number: item.number, body: `@${comment.author} ${replyBody}`, - type: item.type + type: item.type, + prRepo: item.prRepo ?? parseOwnerRepoFromItemUrl(item.url) }) if (!result.ok) { @@ -3397,8 +3445,10 @@ function ConversationTab({ [ canUseRepoMutationContext, item.number, + item.prRepo, item.repoId, item.type, + item.url, onCommentAdded, repoPath, sourceContext @@ -3545,6 +3595,7 @@ function ConversationTab({ repoId={item.repoId} sourceContext={sourceContext} prNumber={item.number} + prRepo={item.prRepo ?? parseOwnerRepoFromItemUrl(item.url)} files={files} headSha={headSha} baseSha={baseSha} @@ -3805,6 +3856,7 @@ function ConversationTab({ sourceContext={sourceContext} issueNumber={item.number} itemType={item.type} + prRepo={item.prRepo ?? parseOwnerRepoFromItemUrl(item.url)} mentionOptions={mentionOptions} onCommentAdded={onCommentAdded} /> @@ -3912,6 +3964,7 @@ function PRActionsPanel({ sourceContext, projectOrigin, number: item.number, + prRepo: item.prRepo ?? parseOwnerRepoFromItemUrl(item.url), updates: { state: nextState } }) toast.success( @@ -4541,7 +4594,10 @@ function ChecksTab({ }, [item, targetRepoId] ) - const prRepo = useMemo(() => parseOwnerRepoFromItemUrl(item.url), [item.url]) + const prRepo = useMemo( + () => item.prRepo ?? parseOwnerRepoFromItemUrl(item.url), + [item.prRepo, item.url] + ) const runtimeHost = getGitHubSourceRuntimeHost(sourceContext) const canUseChecksRepoContext = canUseGitHubRepoContext(repoPath, sourceContext) const sorted = [...list].sort( @@ -4605,6 +4661,7 @@ function ChecksTab({ sourceContext, prNumber: item.number, headSha, + prRepo, noCache: true }))) as PRCheckDetail[] setChecksState((current) => updateGitHubChecksTabLocalChecks(current, nextChecks)) @@ -4648,7 +4705,8 @@ function ChecksTab({ repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId), prNumber: item.number, headSha, - failedOnly + failedOnly, + prRepo }, { timeoutMs: 30_000 } ) @@ -4658,7 +4716,8 @@ function ChecksTab({ sourceContext, prNumber: item.number, headSha, - failedOnly + failedOnly, + prRepo }) if (!result.ok) { toast.error(result.error) @@ -4686,6 +4745,7 @@ function ChecksTab({ headSha, item.number, item.repoId, + prRepo, runtimeHost, rerunning, repoId, @@ -5701,6 +5761,7 @@ async function runPullRequestStateUpdate(args: { sourceContext?: TaskSourceContext | null projectOrigin: PullRequestPageProjectOrigin | undefined number: number + prRepo?: GitHubOwnerRepo | null updates: { state: 'open' | 'closed' } }): Promise { if (args.projectOrigin) { @@ -5759,6 +5820,7 @@ async function runPullRequestStateUpdate(args: { { repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), prNumber: args.number, + prRepo: args.prRepo ?? null, updates: args.updates }, { timeoutMs: 30_000 } @@ -5768,6 +5830,7 @@ async function runPullRequestStateUpdate(args: { repoId: args.repoId ?? undefined, sourceContext: args.sourceContext, prNumber: args.number, + prRepo: args.prRepo ?? null, updates: args.updates }) if (!res.ok) { @@ -6299,6 +6362,7 @@ function GHCommentComposer({ sourceContext, issueNumber, itemType, + prRepo, mentionOptions, onCommentAdded }: { @@ -6308,6 +6372,7 @@ function GHCommentComposer({ sourceContext?: TaskSourceContext | null issueNumber: number itemType: 'issue' | 'pr' + prRepo?: GitHubOwnerRepo | null mentionOptions: MentionOption[] onCommentAdded: (comment: PRComment) => void }): React.JSX.Element { @@ -6347,7 +6412,8 @@ function GHCommentComposer({ sourceContext, number: issueNumber, body: bodyState.body, - type: itemType + type: itemType, + prRepo }) if (!mountedRef.current) { return @@ -6386,6 +6452,7 @@ function GHCommentComposer({ sourceContext, issueNumber, itemType, + prRepo, onCommentAdded ]) const canSubmitComment = hasBoundedCommentBodyText(body) @@ -6962,6 +7029,7 @@ export default function PullRequestPage({ repoPath: repoPath ?? '', sourceContext, prNumber: workItem.number, + prRepo: workItem.prRepo ?? parseOwnerRepoFromItemUrl(workItem.url), pullRequestId: details.pullRequestId, path, viewed @@ -7364,6 +7432,7 @@ export default function PullRequestPage({ repoId={effectiveRepoId ?? ''} sourceContext={sourceContext} prNumber={workItem.number} + prRepo={workItem.prRepo ?? parseOwnerRepoFromItemUrl(workItem.url)} prUrl={workItem.url} headSha={details?.headSha} baseSha={details?.baseSha} diff --git a/src/renderer/src/components/TaskPage.tsx b/src/renderer/src/components/TaskPage.tsx index a167b7b3f..a4cecdce4 100644 --- a/src/renderer/src/components/TaskPage.tsx +++ b/src/renderer/src/components/TaskPage.tsx @@ -1894,6 +1894,7 @@ function GHAssigneesCell({ item.type, owner, patchWorkItem, + parsed?.slug.host, pendingLogin, repo, repoName, @@ -2335,7 +2336,12 @@ function PRReviewCell({ ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.requestPRReviewers', - { repo: runtimeRepoId, prNumber: item.number, reviewers: logins }, + { + repo: runtimeRepoId, + prNumber: item.number, + reviewers: logins, + prRepo: item.prRepo ?? null + }, { timeoutMs: 30_000 } ) : await window.api.gh.requestPRReviewers({ @@ -2343,7 +2349,8 @@ function PRReviewCell({ repoId: repo.id, sourceContext, prNumber: item.number, - reviewers: logins + reviewers: logins, + prRepo: item.prRepo ?? null }) if (result.ok) { toast.success(translate('auto.components.TaskPage.8f06dbb9e5', 'Reviewer requested')) @@ -2389,7 +2396,12 @@ function PRReviewCell({ ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.removePRReviewers', - { repo: runtimeRepoId, prNumber: item.number, reviewers: logins }, + { + repo: runtimeRepoId, + prNumber: item.number, + reviewers: logins, + prRepo: item.prRepo ?? null + }, { timeoutMs: 30_000 } ) : await window.api.gh.removePRReviewers({ @@ -2397,7 +2409,8 @@ function PRReviewCell({ repoId: repo.id, sourceContext, prNumber: item.number, - reviewers: logins + reviewers: logins, + prRepo: item.prRepo ?? null }) if (result.ok) { toast.success( diff --git a/src/renderer/src/components/github-project/ProjectPicker.tsx b/src/renderer/src/components/github-project/ProjectPicker.tsx index a4d54b3a7..b1dd25f0f 100644 --- a/src/renderer/src/components/github-project/ProjectPicker.tsx +++ b/src/renderer/src/components/github-project/ProjectPicker.tsx @@ -829,40 +829,51 @@ function AuthErrorBanner({ error }: { error: GitHubProjectViewError }): React.JS export function parseProjectInput( input: string ): { owner: string; number: number; host?: string; viewNumber?: number } | null { - if (!input) { + const trimmed = input.trim() + if (!trimmed) { return null } - if (isGitHubProjectRefInputTooLarge(input)) { + if (isGitHubProjectRefInputTooLarge(trimmed)) { return null } // owner/number - const short = /^([A-Za-z0-9][A-Za-z0-9-]*)\/(\d+)$/.exec(input) + const short = /^([A-Za-z0-9][A-Za-z0-9-]*)\/(\d+)$/.exec(trimmed) if (short) { - return { owner: short[1], number: Number(short[2]) } + const number = Number(short[2]) + return Number.isSafeInteger(number) && number > 0 ? { owner: short[1], number } : null } try { - const url = new URL(input) - if ((url.protocol !== 'https:' && url.protocol !== 'http:') || !url.host) { + const url = new URL(trimmed) + if ( + (url.protocol !== 'https:' && url.protocol !== 'http:') || + url.username || + url.password || + !url.host + ) { return null } const parts = url.pathname.split('/').filter(Boolean) + const hasView = parts.length === 6 && parts[4] === 'views' // /orgs/{owner}/projects/{n} or /users/{owner}/projects/{n}[/views/{viewNumber}] - if ((parts[0] === 'orgs' || parts[0] === 'users') && parts[2] === 'projects' && parts[3]) { + if ( + (parts[0] === 'orgs' || parts[0] === 'users') && + /^[A-Za-z0-9][A-Za-z0-9-]*$/.test(parts[1] ?? '') && + parts[2] === 'projects' && + (parts.length === 4 || hasView) + ) { const owner = parts[1] const number = Number(parts[3]) - if (Number.isNaN(number)) { + const viewNumber = hasView ? Number(parts[5]) : undefined + if ( + !Number.isSafeInteger(number) || + number < 1 || + (hasView && (!Number.isSafeInteger(viewNumber) || (viewNumber ?? 0) < 1)) + ) { return null } - let viewNumber: number | undefined - if (parts[4] === 'views' && parts[5]) { - const v = Number(parts[5]) - if (!Number.isNaN(v)) { - viewNumber = v - } - } // Why: URL.host preserves non-default GHES ports; URL.hostname would // silently route a project on :8443 to the server's default port. - return { owner, number, host: url.host, viewNumber } + return { owner, number, host: url.host.toLowerCase(), viewNumber } } } catch { return null diff --git a/src/renderer/src/components/github-project/project-picker-input.test.ts b/src/renderer/src/components/github-project/project-picker-input.test.ts index 87be9c5ba..358f1947e 100644 --- a/src/renderer/src/components/github-project/project-picker-input.test.ts +++ b/src/renderer/src/components/github-project/project-picker-input.test.ts @@ -16,4 +16,16 @@ describe('ProjectPicker project input', () => { it('keeps owner/number shorthand on the default host', () => { expect(parseProjectInput('acme/7')).toEqual({ owner: 'acme', number: 7 }) }) + + it('rejects credentials and malformed Project routes', () => { + for (const input of [ + 'https://user:token@github.corp.example/orgs/acme/projects/7', + 'https://github.corp.example/orgs/acme/projects/7evil', + 'https://github.corp.example/orgs/acme/projects/7/views/2evil', + 'https://github.corp.example/orgs/acme/projects/7/files', + 'https://github.corp.example/orgs/co_op/projects/7' + ]) { + expect(parseProjectInput(input)).toBeNull() + } + }) }) diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts new file mode 100644 index 000000000..f2f6d4bd7 --- /dev/null +++ b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts @@ -0,0 +1,75 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' +import type * as RuntimeRpcClient from '@/runtime/runtime-rpc-client' +import type { TaskSourceContext } from '../../../../shared/task-source-context' +import { getRepoSlugCached } from './SmartWorkspaceNameField' + +vi.mock('@/runtime/runtime-rpc-client', async (importOriginal) => ({ + ...(await importOriginal()), + callRuntimeRpc: vi.fn() +})) + +const repoSlug = vi.fn() + +// @ts-expect-error focused preload mock +globalThis.window = { api: { gh: { repoSlug } } } + +function runtimeSource(environmentId: string): TaskSourceContext { + return { + kind: 'task-source', + provider: 'github', + projectId: 'project-1', + hostId: `runtime:${environmentId}`, + repoId: 'repo-1' + } +} + +describe('SmartWorkspaceNameField repository slug routing', () => { + beforeEach(() => { + vi.mocked(callRuntimeRpc).mockReset() + repoSlug.mockReset() + }) + + it('resolves runtime-owned repos on their runtime and scopes the cache by runtime', async () => { + vi.mocked(callRuntimeRpc) + .mockResolvedValueOnce({ owner: 'acme', repo: 'widgets', host: 'github.one.test' }) + .mockResolvedValueOnce({ owner: 'acme', repo: 'widgets', host: 'github.two.test' }) + const cache = new Map() + const repo = { id: 'repo-1', path: '/workspace/widgets' } + + await expect(getRepoSlugCached(repo, runtimeSource('one'), cache)).resolves.toMatchObject({ + host: 'github.one.test' + }) + await expect(getRepoSlugCached(repo, runtimeSource('one'), cache)).resolves.toMatchObject({ + host: 'github.one.test' + }) + await expect(getRepoSlugCached(repo, runtimeSource('two'), cache)).resolves.toMatchObject({ + host: 'github.two.test' + }) + + expect(callRuntimeRpc).toHaveBeenCalledTimes(2) + expect(callRuntimeRpc).toHaveBeenNthCalledWith( + 1, + { kind: 'environment', environmentId: 'one' }, + 'github.repoSlug', + { repo: 'repo-1' }, + { timeoutMs: 30_000 } + ) + expect(repoSlug).not.toHaveBeenCalled() + }) + + it('does not permanently cache a failed GHES resolution', async () => { + vi.mocked(callRuntimeRpc) + .mockResolvedValueOnce(null) + .mockResolvedValueOnce({ owner: 'acme', repo: 'widgets', host: 'github.acme.test' }) + const cache = new Map() + const repo = { id: 'repo-1', path: '/workspace/widgets' } + const source = runtimeSource('one') + + await expect(getRepoSlugCached(repo, source, cache)).resolves.toBeNull() + await expect(getRepoSlugCached(repo, source, cache)).resolves.toMatchObject({ + host: 'github.acme.test' + }) + expect(callRuntimeRpc).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx index 9640ae691..059a753da 100644 --- a/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx +++ b/src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx @@ -79,10 +79,16 @@ import { } from './smart-workspace-localized-options' import { buildTaskSourceContextFromRepo, + getTaskSourceCacheScope, type TaskSourceContext } from '../../../../shared/task-source-context' import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' import { githubRepoIdentityKey } from '../../../../shared/github-repository-identity-key' +import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' +import { + getGitHubRuntimeRepoId, + getGitHubSourceRuntimeTarget +} from '@/lib/github-source-runtime-context' type RepoOption = ReturnType['repos'][number] const EMPTY_REPO_SEARCH_REPOS: readonly RepoOption[] = [] @@ -308,7 +314,7 @@ export default function SmartWorkspaceNameField({ const localInputRef = useRef(null) const focusedSelectedSourceKeyRef = useRef(null) const tabsListRef = useRef(null) - const repoSlugCacheRef = useRef>(new Map()) + const repoSlugCacheRef = useRef>(new Map()) const handledCrossRepoUrlRef = useRef(null) const localInputFocusFrameRef = useRef(null) // Why: dialog autofocus and other programmatic .focus() calls can look @@ -549,15 +555,6 @@ export default function SmartWorkspaceNameField({ let stale = false const directNumber = normalizedGhQuery.directNumber const directLink = parsedGhLink - const searchTargetForRepo = (repo: RepoOption) => - repoBackedSearchTargets.find((target) => target.repo.id === repo.id) ?? { - repo, - githubSourceContext: buildTaskSourceContextFromRepo({ - provider: 'github' as const, - projectId: repo.id, - repo - }) - } if (directLink !== null && handledCrossRepoUrlRef.current !== debouncedQuery.trim()) { setGithubLoading(true) const directLookup = async (): Promise<{ @@ -568,20 +565,22 @@ export default function SmartWorkspaceNameField({ } | null }> => { if (crossRepoSwitchTarget === 'task-source') { - const matchingRepo = await findMatchingRepoForSlug( - repoBackedSearchTargets.map((target) => target.repo), + const matchingTarget = await findMatchingRepoForSlug( + repoBackedSearchTargets.map((target) => ({ + repo: target.repo, + sourceContext: target.githubSourceContext + })), directLink.slug, repoSlugCacheRef.current ) handledCrossRepoUrlRef.current = debouncedQuery.trim() - if (!matchingRepo) { + if (!matchingTarget) { return { items: [], prompt: null } } - const target = searchTargetForRepo(matchingRepo) const item = await lookupGitHubWorkItemByOwnerRepoForSource({ - repoPath: target.repo.path, - repoId: target.repo.id, - sourceContext: target.githubSourceContext, + repoPath: matchingTarget.repo.path, + repoId: matchingTarget.repo.id, + sourceContext: matchingTarget.sourceContext, owner: directLink.slug.owner, repo: directLink.slug.repo, ...(directLink.slug.host ? { host: directLink.slug.host } : {}), @@ -589,14 +588,18 @@ export default function SmartWorkspaceNameField({ type: directLink.type }) return { - items: item ? [{ ...item, repoId: target.repo.id } as GitHubWorkItem] : [], + items: item ? [{ ...item, repoId: matchingTarget.repo.id } as GitHubWorkItem] : [], prompt: null } } if (!selectedRepo?.path) { return { items: [], prompt: null } } - const selectedSlug = await getRepoSlugCached(selectedRepo, repoSlugCacheRef.current) + const selectedSlug = await getRepoSlugCached( + selectedRepo, + githubSourceContext, + repoSlugCacheRef.current + ) if (!selectedSlug || sameSlug(selectedSlug, directLink.slug)) { handledCrossRepoUrlRef.current = debouncedQuery.trim() const item = await lookupSmartGitHubSubmitItem({ @@ -616,12 +619,22 @@ export default function SmartWorkspaceNameField({ }) return { items: item ? [item] : [], prompt: null } } - const matchingRepo = await findMatchingRepoForSlug( - repos, + const matchingTarget = await findMatchingRepoForSlug( + repos.map((repo) => ({ + repo, + sourceContext: buildTaskSourceContextFromRepo({ + provider: 'github', + projectId: repo.id, + repo + }) + })), directLink.slug, repoSlugCacheRef.current ) - return { items: [], prompt: { link: directLink, matchingRepo } } + return { + items: [], + prompt: { link: directLink, matchingRepo: matchingTarget?.repo ?? null } + } } void directLookup() .then((result) => { @@ -1202,8 +1215,12 @@ export default function SmartWorkspaceNameField({ if (!added) { return } - repoSlugCacheRef.current.delete(added.id) - const slug = await getRepoSlugCached(added, repoSlugCacheRef.current) + const sourceContext = buildTaskSourceContextFromRepo({ + provider: 'github', + projectId: added.id, + repo: added + }) + const slug = await getRepoSlugCached(added, sourceContext, repoSlugCacheRef.current) if (slug && sameSlug(slug, crossRepoPrompt.link.slug)) { await acceptGitHubLink(added) } @@ -1811,33 +1828,51 @@ function sameSlug(left: RepoSlug, right: RepoSlug): boolean { return githubRepoIdentityKey(left) === githubRepoIdentityKey(right) } -async function getRepoSlugCached( - repo: RepoOption, - cache: Map +export async function getRepoSlugCached( + repo: Pick, + sourceContext: TaskSourceContext | null | undefined, + cache: Map ): Promise { - const cacheKey = repo.id + const cacheKey = sourceContext + ? `${getTaskSourceCacheScope(sourceContext)}\0${repo.path}` + : `local:${repo.id}\0${repo.path}` if (cache.has(cacheKey)) { return cache.get(cacheKey) ?? null } try { - const slug = await window.api.gh.repoSlug({ repoPath: repo.path, repoId: repo.id }) - cache.set(cacheKey, slug) + const target = getGitHubSourceRuntimeTarget(sourceContext) + const slug = + target.kind === 'environment' + ? await callRuntimeRpc( + target, + 'github.repoSlug', + { repo: getGitHubRuntimeRepoId(sourceContext, repo.id) }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.repoSlug({ repoPath: repo.path, repoId: repo.id }) + if (slug) { + cache.set(cacheKey, slug) + } return slug } catch { - cache.set(cacheKey, null) return null } } +type RepoSlugTarget = { + repo: RepoOption + sourceContext: TaskSourceContext | null | undefined +} + async function findMatchingRepoForSlug( - repos: RepoOption[], + targets: RepoSlugTarget[], slug: RepoSlug, - cache: Map -): Promise { - for (const repo of repos) { - const candidate = await getRepoSlugCached(repo, cache) + cache: Map +): Promise { + for (const target of targets) { + const candidate = await getRepoSlugCached(target.repo, target.sourceContext, cache) if (candidate && sameSlug(candidate, slug)) { - return repo + return target } } return null diff --git a/src/renderer/src/components/right-sidebar/hosted-review-github-actions.ts b/src/renderer/src/components/right-sidebar/hosted-review-github-actions.ts index 8f20bbc8d..a498da990 100644 --- a/src/renderer/src/components/right-sidebar/hosted-review-github-actions.ts +++ b/src/renderer/src/components/right-sidebar/hosted-review-github-actions.ts @@ -78,6 +78,7 @@ export async function updateGitHubHostedReviewState(args: { repo: Repo prNumber: number nextState: 'open' | 'closed' + prRepo?: GitHubPRRepo | null }): Promise>> { const target = getGitHubActionTarget(args.repo) if (target.kind === 'environment') { @@ -87,6 +88,7 @@ export async function updateGitHubHostedReviewState(args: { { repo: args.repo.id, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, updates: { state: args.nextState } }, { timeoutMs: 30_000 } @@ -96,6 +98,7 @@ export async function updateGitHubHostedReviewState(args: { repoPath: args.repo.path, repoId: args.repo.id, prNumber: args.prNumber, + prRepo: args.prRepo ?? null, updates: { state: args.nextState } }) } diff --git a/src/renderer/src/components/right-sidebar/use-hosted-review-actions.ts b/src/renderer/src/components/right-sidebar/use-hosted-review-actions.ts index 7f2274bfd..92a51afb3 100644 --- a/src/renderer/src/components/right-sidebar/use-hosted-review-actions.ts +++ b/src/renderer/src/components/right-sidebar/use-hosted-review-actions.ts @@ -198,6 +198,7 @@ export function useHostedReviewActions({ : await updateGitHubHostedReviewState({ repo, prNumber: review.number, + prRepo: githubPR?.prRepo ?? null, nextState }) if (!result.ok) { @@ -230,6 +231,7 @@ export function useHostedReviewActions({ }, [ confirm, + githubPR?.prRepo, isGitLab, onRefreshReview, repo, diff --git a/src/renderer/src/components/settings/repository-icon-github.test.ts b/src/renderer/src/components/settings/repository-icon-github.test.ts index d4ddecc22..e98eeb44a 100644 --- a/src/renderer/src/components/settings/repository-icon-github.test.ts +++ b/src/renderer/src/components/settings/repository-icon-github.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { Repo } from '../../../../shared/types' +import { githubAvatarIcon } from '../../../../shared/repo-icon' import { buildRepositoryGitHubAvatarUpdate, resolveRepositoryGitHubAvatar @@ -160,4 +161,18 @@ describe('repository GitHub avatar resolution', () => { // Nothing changed, so no repo write is produced (no sticky null clobber). expect(buildRepositoryGitHubAvatarUpdate(repo, resolution)).toBeNull() }) + + it('persists an upstream change when only the GitHub host differs', () => { + const repo = makeRepo({ + upstream: { owner: 'acme', repo: 'widgets', host: 'github.com' } + }) + const enterprise = { owner: 'acme', repo: 'widgets', host: 'github.acme.test' } + + expect( + buildRepositoryGitHubAvatarUpdate(repo, { + repoIcon: githubAvatarIcon(enterprise), + upstream: enterprise + }) + ).toMatchObject({ upstream: enterprise }) + }) }) diff --git a/src/renderer/src/components/settings/repository-icon-github.ts b/src/renderer/src/components/settings/repository-icon-github.ts index 02f962fb6..dfaac40c7 100644 --- a/src/renderer/src/components/settings/repository-icon-github.ts +++ b/src/renderer/src/components/settings/repository-icon-github.ts @@ -1,5 +1,6 @@ import type { GitHubRepositoryIdentity, Repo } from '../../../../shared/types' import { githubAvatarIcon, type RepoIcon } from '../../../../shared/repo-icon' +import { githubRepoIdentityKey } from '../../../../shared/github-repository-identity-key' import { callRuntimeRpc, type getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' type RuntimeTarget = ReturnType @@ -77,7 +78,7 @@ function sameRepositoryIdentity( if (!a || !b) { return a === b } - return a.owner === b.owner && a.repo === b.repo + return githubRepoIdentityKey(a) === githubRepoIdentityKey(b) } function sameRepoIcon(a: RepoIcon | null | undefined, b: RepoIcon | null | undefined): boolean { diff --git a/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts b/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts index c46bd3ea5..25a4fa6cb 100644 --- a/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts +++ b/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts @@ -70,6 +70,18 @@ describe('useComposerState host-context boundaries', () => { ).toEqual({ workspaceName: 'title-derived-name', displayName: 'Title derived name' }) }) + it('requires pasted PR recovery to match the selected GitHub host', () => { + const recoverySection = sourceBetween( + HOOK_SOURCE, + 'const effectiveLinkedPR = useMemo', + 'const setupConfig = useMemo' + ) + + expect(recoverySection).toContain('githubRepoIdentityKey(fromName.slug)') + expect(recoverySection).toContain('githubRepoIdentityKey(selectedRepoSlug)') + expect(recoverySection).not.toContain('fromName.slug.owner.toLowerCase()') + }) + it('auto-owns linked-item generated prefilled names', () => { expect( getInitialAutoManagedWorkspaceName({ diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index 958bc0125..290cc7be8 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -38,6 +38,7 @@ import { type TaskSourceContext } from '../../../shared/task-source-context' import type { + GitHubRepositoryIdentity, GitHubWorkItem, GitHubPrStartPoint, GitPushTarget, @@ -55,6 +56,7 @@ import type { WorkspaceCreateTelemetrySource, ProjectGroup } from '../../../shared/types' +import { githubRepoIdentityKey } from '../../../shared/github-repository-identity-key' import { isWorkspaceStatusId } from '../../../shared/workspace-statuses' import { CLIENT_PLATFORM, @@ -1265,9 +1267,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS // Pasting a PR URL from a different repo would otherwise recover only the // PR number, mislinking the worktree to an unrelated PR with the same // number in the selected repo. - const [selectedRepoSlug, setSelectedRepoSlug] = useState<{ owner: string; repo: string } | null>( - null - ) + const [selectedRepoSlug, setSelectedRepoSlug] = useState(null) const selectedRepoPath = selectedRepo?.path const selectedRepoPathRef = useRef(selectedRepoPath) selectedRepoPathRef.current = selectedRepoPath @@ -1414,7 +1414,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS const target = getActiveRuntimeTarget(selectedRepoSettings) const slugRequest = target.kind === 'environment' - ? callRuntimeRpc<{ owner: string; repo: string } | null>( + ? callRuntimeRpc( target, 'github.repoSlug', { repo: repoId }, @@ -1504,8 +1504,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS // risking a cross-repo mislink. if ( selectedRepoSlug && - fromName.slug.owner.toLowerCase() === selectedRepoSlug.owner.toLowerCase() && - fromName.slug.repo.toLowerCase() === selectedRepoSlug.repo.toLowerCase() + githubRepoIdentityKey(fromName.slug) === githubRepoIdentityKey(selectedRepoSlug) ) { return fromName.number } diff --git a/src/renderer/src/lib/project-host-clone-url.test.ts b/src/renderer/src/lib/project-host-clone-url.test.ts index 26a0c9f13..4850e41a3 100644 --- a/src/renderer/src/lib/project-host-clone-url.test.ts +++ b/src/renderer/src/lib/project-host-clone-url.test.ts @@ -29,6 +29,39 @@ describe('getProjectHostCloneUrl', () => { ).toBe('https://github.com/stablyai/orca.git') }) + it('preserves an authenticated Enterprise host and port', () => { + expect( + getProjectHostCloneUrl( + createProject({ + providerIdentity: { + provider: 'github', + owner: 'enterprise owner', + repo: 'orca repo', + host: 'github.acme-corp.com:8443' + } + }) + ) + ).toBe('https://github.acme-corp.com:8443/enterprise%20owner/orca%20repo.git') + }) + + it('rejects malformed or path-bearing Enterprise hosts', () => { + for (const host of [ + 'https://github.acme-corp.com', + 'github.acme-corp.com/org', + 'user@github.acme-corp.com', + 'github.acme-corp.com?token=secret', + 'github.acme-corp.com:not-a-port' + ]) { + expect( + getProjectHostCloneUrl( + createProject({ + providerIdentity: { provider: 'github', owner: 'acme', repo: 'orca', host } + }) + ) + ).toBeNull() + } + }) + it('returns null when provider identity is missing or incomplete', () => { expect(getProjectHostCloneUrl(createProject())).toBeNull() expect( diff --git a/src/renderer/src/lib/project-host-clone-url.ts b/src/renderer/src/lib/project-host-clone-url.ts index ae1937ca1..e32e9a699 100644 --- a/src/renderer/src/lib/project-host-clone-url.ts +++ b/src/renderer/src/lib/project-host-clone-url.ts @@ -10,5 +10,26 @@ export function getProjectHostCloneUrl(project: Project | null | undefined): str if (!owner || !repo) { return null } - return `https://github.com/${owner}/${repo}.git` + const requestedHost = identity.host?.trim() || 'github.com' + if (/[\\/@?#]/.test(requestedHost)) { + return null + } + let host: string + try { + const parsed = new URL(`https://${requestedHost}`) + if ( + parsed.protocol !== 'https:' || + parsed.username || + parsed.password || + parsed.pathname !== '/' || + parsed.search || + parsed.hash + ) { + return null + } + host = parsed.host + } catch { + return null + } + return `https://${host}/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}.git` } diff --git a/src/renderer/src/lib/repo-slug-cache.test.ts b/src/renderer/src/lib/repo-slug-cache.test.ts index c49a6cca1..dd0f9e4bd 100644 --- a/src/renderer/src/lib/repo-slug-cache.test.ts +++ b/src/renderer/src/lib/repo-slug-cache.test.ts @@ -2,6 +2,11 @@ import { beforeEach, describe, expect, it } from 'vitest' import type { Repo } from '../../../shared/types' import { githubRepoIdentityKey } from '../../../shared/github-repository-identity-key' import { + REPO_SLUG_FAILURE_TTL_MS, + clearRepoSlugCacheValues, + nextRepoSlugFailureRetryDelay, + readRepoSlugCache, + rememberRepoSlug, lookupReposBySlugFromCache, settingsForRepoOwner, slugByRepoId, @@ -20,7 +25,7 @@ function repo(id: string): Repo { } describe('repo slug cache host identity', () => { - beforeEach(() => slugByRepoId.clear()) + beforeEach(() => clearRepoSlugCacheValues()) it('does not route a GHES project row to a same-named github.com repo', () => { const dotCom = repo('dotcom') @@ -40,4 +45,13 @@ describe('repo slug cache host identity', () => { lookupReposBySlugFromCache([dotCom, enterprise], null, 'acme/widgets', 'ghe.example:8443') ).toEqual([enterprise]) }) + + it('expires negative slug resolutions so an external GHES login can recover', () => { + const key = slugCacheKey('enterprise', null) + rememberRepoSlug(key, null, 1_000) + + expect(readRepoSlugCache(key, 1_000)).toEqual({ hit: true, value: null }) + expect(nextRepoSlugFailureRetryDelay(new Set([key]), 1_000)).toBe(REPO_SLUG_FAILURE_TTL_MS) + expect(readRepoSlugCache(key, 1_000 + REPO_SLUG_FAILURE_TTL_MS)).toEqual({ hit: false }) + }) }) diff --git a/src/renderer/src/lib/repo-slug-cache.ts b/src/renderer/src/lib/repo-slug-cache.ts index a4407f8eb..38ea5d329 100644 --- a/src/renderer/src/lib/repo-slug-cache.ts +++ b/src/renderer/src/lib/repo-slug-cache.ts @@ -10,8 +10,64 @@ import { githubRepoIdentityKey } from '../../../shared/github-repository-identit export type SlugIndex = Map /** Module-scope cache keyed by runtime scope + repo.id. A Repo that has already - * failed resolution is recorded as `null` so it is not retried on re-mount. */ + * failed resolution is recorded as `null` briefly so it is not retried on every + * cell mount, while still recovering after an external GHES auth login. */ export const slugByRepoId = new Map() +const slugFailureExpiresAtByRepoId = new Map() +export const REPO_SLUG_FAILURE_TTL_MS = 60_000 + +export function readRepoSlugCache( + cacheKey: string, + now = Date.now() +): { hit: true; value: string | null } | { hit: false } { + if (!slugByRepoId.has(cacheKey)) { + return { hit: false } + } + const value = slugByRepoId.get(cacheKey) ?? null + const failureExpiry = slugFailureExpiresAtByRepoId.get(cacheKey) + if (value !== null || failureExpiry === undefined || failureExpiry > now) { + return { hit: true, value } + } + slugByRepoId.delete(cacheKey) + slugFailureExpiresAtByRepoId.delete(cacheKey) + return { hit: false } +} + +export function rememberRepoSlug(cacheKey: string, value: string | null, now = Date.now()): void { + slugByRepoId.set(cacheKey, value) + if (value === null) { + slugFailureExpiresAtByRepoId.set(cacheKey, now + REPO_SLUG_FAILURE_TTL_MS) + } else { + slugFailureExpiresAtByRepoId.delete(cacheKey) + } +} + +export function deleteRepoSlugCacheKey(cacheKey: string): void { + slugByRepoId.delete(cacheKey) + slugFailureExpiresAtByRepoId.delete(cacheKey) +} + +export function clearRepoSlugCacheValues(): void { + slugByRepoId.clear() + slugFailureExpiresAtByRepoId.clear() +} + +export function nextRepoSlugFailureRetryDelay( + cacheKeys: ReadonlySet, + now = Date.now() +): number | null { + let earliestExpiry = Number.POSITIVE_INFINITY + for (const cacheKey of cacheKeys) { + if (slugByRepoId.get(cacheKey) !== null) { + continue + } + const expiresAt = slugFailureExpiresAtByRepoId.get(cacheKey) + if (expiresAt !== undefined) { + earliestExpiry = Math.min(earliestExpiry, expiresAt) + } + } + return Number.isFinite(earliestExpiry) ? Math.max(0, earliestExpiry - now) : null +} export function slugCacheKey( repoId: string, diff --git a/src/renderer/src/lib/repo-slug-index.ts b/src/renderer/src/lib/repo-slug-index.ts index dcfed6bf9..262f8e0ec 100644 --- a/src/renderer/src/lib/repo-slug-index.ts +++ b/src/renderer/src/lib/repo-slug-index.ts @@ -18,25 +18,39 @@ import { useAppStore } from '@/store' import type { Repo } from '../../../shared/types' import type { GlobalSettings } from '../../../shared/types' import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' -import { settingsForRepoOwner, slugByRepoId, slugCacheKey, type SlugIndex } from './repo-slug-cache' +import { + clearRepoSlugCacheValues, + deleteRepoSlugCacheKey, + nextRepoSlugFailureRetryDelay, + readRepoSlugCache, + rememberRepoSlug, + settingsForRepoOwner, + slugByRepoId, + slugCacheKey, + type SlugIndex +} from './repo-slug-cache' import { githubRepoIdentityKey } from '../../../shared/github-repository-identity-key' export { lookupReposBySlugFromCache } from './repo-slug-cache' +const slugResolutionInFlight = new Map>() + /** Drop a repo's cached slug result. Call when a repo is removed or its * remote URL is known to have changed (e.g. after `git remote set-url`), * so the next index build re-resolves rather than serving a stale entry. */ export function clearRepoSlugCacheEntry(repoId: string): void { for (const key of slugByRepoId.keys()) { if (key.endsWith(`:${repoId}`)) { - slugByRepoId.delete(key) + deleteRepoSlugCacheKey(key) + slugResolutionInFlight.delete(key) } } } /** Clear the entire slug cache. Useful for tests or full repo-list resets. */ export function clearRepoSlugCache(): void { - slugByRepoId.clear() + clearRepoSlugCacheValues() + slugResolutionInFlight.clear() } async function resolveRepoSlug( @@ -44,39 +58,54 @@ async function resolveRepoSlug( settings: Pick | null | undefined ): Promise { const cacheKey = slugCacheKey(repo.id, settings) - if (slugByRepoId.has(cacheKey)) { - return slugByRepoId.get(cacheKey) ?? null + const cached = readRepoSlugCache(cacheKey) + if (cached.hit) { + return cached.value } - try { - const target = getActiveRuntimeTarget(settings) - const result = - target.kind === 'environment' - ? await callRuntimeRpc<{ owner: string; repo: string; host?: string } | null>( - target, - 'github.repoSlug', - { repo: repo.id }, - { timeoutMs: 30_000 } - ) - : await window.api.gh.repoSlug({ repoPath: repo.path, repoId: repo.id }) - if (!result) { - slugByRepoId.set(cacheKey, null) + const inFlight = slugResolutionInFlight.get(cacheKey) + if (inFlight) { + return inFlight + } + const resolution = (async () => { + try { + const target = getActiveRuntimeTarget(settings) + const result = + target.kind === 'environment' + ? await callRuntimeRpc<{ owner: string; repo: string; host?: string } | null>( + target, + 'github.repoSlug', + { repo: repo.id }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.repoSlug({ repoPath: repo.path, repoId: repo.id }) + if (!result) { + rememberRepoSlug(cacheKey, null) + return null + } + const slug = githubRepoIdentityKey(result) + rememberRepoSlug(cacheKey, slug) + return slug + } catch { + // Why: GHES classification depends on auth that may change outside Orca; + // retry negative results after a bounded quiet period instead of forever. + rememberRepoSlug(cacheKey, null) return null } - const slug = githubRepoIdentityKey(result) - slugByRepoId.set(cacheKey, slug) - return slug - } catch { - // Why: treat any IPC failure as "not resolvable" rather than propagating — - // design doc §Row actions: "If gh:repoSlug fails for a repo, exclude it". - slugByRepoId.set(cacheKey, null) - return null + })() + slugResolutionInFlight.set(cacheKey, resolution) + try { + return await resolution + } finally { + if (slugResolutionInFlight.get(cacheKey) === resolution) { + slugResolutionInFlight.delete(cacheKey) + } } } async function buildIndex( repos: Repo[], settings: Pick | null | undefined -): Promise { +): Promise<{ index: SlugIndex; retryDelayMs: number | null }> { // Why: evict cached entries for repos that no longer exist in state so // the cache cannot grow unbounded across long sessions where users add // and remove repos. Without this, every removed repo's id (and its @@ -84,7 +113,8 @@ async function buildIndex( const liveKeys = new Set(repos.map((r) => slugCacheKey(r.id, settingsForRepoOwner(r, settings)))) for (const key of slugByRepoId.keys()) { if (!liveKeys.has(key)) { - slugByRepoId.delete(key) + deleteRepoSlugCacheKey(key) + slugResolutionInFlight.delete(key) } } const next: SlugIndex = new Map() @@ -101,7 +131,7 @@ async function buildIndex( next.set(slug, [...(next.get(slug) ?? []), repo]) } } - return next + return { index: next, retryDelayMs: nextRepoSlugFailureRetryDelay(liveKeys) } } export type RepoSlugIndexState = { @@ -117,21 +147,32 @@ export function useRepoSlugIndex(): RepoSlugIndexState { const settings = useAppStore((s) => s.settings) const [index, setIndex] = useState(() => new Map()) const [ready, setReady] = useState(false) + const [retryGeneration, setRetryGeneration] = useState(0) // Why: track the current repos snapshot so the effect can ignore stale // resolutions when repos change mid-flight. const generationRef = useRef(0) useEffect(() => { const gen = ++generationRef.current + let retryTimer: ReturnType | undefined setReady(false) - void buildIndex(repos, settings).then((next) => { + void buildIndex(repos, settings).then(({ index: next, retryDelayMs }) => { if (gen !== generationRef.current) { return } setIndex(next) setReady(true) + if (retryDelayMs !== null) { + retryTimer = setTimeout(() => setRetryGeneration((value) => value + 1), retryDelayMs) + } }) - }, [repos, settings]) + return () => { + generationRef.current += 1 + if (retryTimer) { + clearTimeout(retryTimer) + } + } + }, [repos, retryGeneration, settings]) return useMemo( () => ({ diff --git a/src/renderer/src/lib/smart-github-submit.test.ts b/src/renderer/src/lib/smart-github-submit.test.ts index e80d0ec8d..3ab27ebb7 100644 --- a/src/renderer/src/lib/smart-github-submit.test.ts +++ b/src/renderer/src/lib/smart-github-submit.test.ts @@ -42,6 +42,21 @@ describe('getSmartGitHubSubmitIntent', () => { }) }) + it('finds an embedded GitHub Enterprise item URL', () => { + expect( + getSmartGitHubSubmitIntent( + 'please review https://github.acme.test/platform/widgets/pull/2049 before release' + ) + ).toEqual({ + kind: 'link', + host: 'github.acme.test', + owner: 'platform', + repo: 'widgets', + number: 2049, + type: 'pr' + }) + }) + it('finds an embedded GitHub item URL when prose punctuation touches the URL', () => { expect( getSmartGitHubSubmitIntent('review (https://github.com/stablyai/orca/pull/2049), please') diff --git a/src/renderer/src/lib/smart-github-submit.ts b/src/renderer/src/lib/smart-github-submit.ts index 748c84161..131e532f5 100644 --- a/src/renderer/src/lib/smart-github-submit.ts +++ b/src/renderer/src/lib/smart-github-submit.ts @@ -58,7 +58,7 @@ export type SmartGitHubSubmitLookup = { const SMART_GITHUB_SUBMIT_LOOKUP_TTL_MS = 60_000 const SMART_GITHUB_SUBMIT_LOOKUP_CACHE_MAX_ENTRIES = 128 -const GITHUB_ITEM_URL_RE = /https?:\/\/(?:www\.)?github\.com\/\S+/i +const GITHUB_ITEM_URL_RE = /https?:\/\/[^\s/]+\/\S+/i const TRAILING_GITHUB_ITEM_URL_PUNCTUATION_RE = /[),.;\]}]+$/ type SmartGitHubSubmitLookupCacheEntry = { diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index c301492ef..2b59ffaeb 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -4060,7 +4060,12 @@ export const createGitHubSlice: StateCreator = (s ? await callRuntimeRpc( { kind: 'environment', environmentId: requestContext.target.environmentId }, 'github.resolveReviewThread', - { repo: requestContext.target.runtimeRepoId, threadId, resolve }, + { + repo: requestContext.target.runtimeRepoId, + threadId, + resolve, + prRepo: options?.prRepo ?? null + }, { timeoutMs: 30_000 } ) : await window.api.gh.resolveReviewThread({ @@ -4068,6 +4073,7 @@ export const createGitHubSlice: StateCreator = (s repoId, threadId, resolve, + prRepo: options?.prRepo ?? null, sourceContext: options?.sourceContext }) } catch (err) { diff --git a/src/shared/project-host-setup-projection.test.ts b/src/shared/project-host-setup-projection.test.ts index 0d0a67765..09e5d6c20 100644 --- a/src/shared/project-host-setup-projection.test.ts +++ b/src/shared/project-host-setup-projection.test.ts @@ -113,6 +113,72 @@ describe('project host setup projection', () => { ) }) + it('keeps same-named github.com and GHES repositories in separate projects', () => { + const projection = projectHostSetupProjectionFromRepos([ + repo({ + id: 'dotcom-repo', + path: '/work/dotcom', + displayName: 'widgets', + upstream: { owner: 'acme', repo: 'widgets', host: 'github.com' } + }), + repo({ + id: 'enterprise-repo', + path: '/work/enterprise', + displayName: 'widgets', + upstream: { owner: 'acme', repo: 'widgets', host: 'github.acme.test' } + }) + ]) + + expect(projection.projects).toHaveLength(2) + expect(projection.projects.map((project) => project.id)).toEqual([ + 'github:acme/widgets', + 'github:github.acme.test/acme/widgets' + ]) + expect(projection.projects[1]?.providerIdentity).toEqual({ + provider: 'github', + owner: 'acme', + repo: 'widgets', + host: 'github.acme.test' + }) + }) + + it('groups GHES icon identities only when their hosts match', () => { + const enterpriseIcon = (host: string) => ({ + type: 'image' as const, + src: `https://${host}/acme.png?size=64`, + source: 'github' as const, + label: 'acme/widgets' + }) + const projection = projectHostSetupProjectionFromRepos([ + repo({ + id: 'enterprise-local', + path: '/work/local', + displayName: 'widgets', + repoIcon: enterpriseIcon('github.acme.test') + }), + repo({ + id: 'enterprise-ssh', + path: '/work/ssh', + displayName: 'widgets', + connectionId: 'builder', + repoIcon: enterpriseIcon('github.acme.test') + }), + repo({ + id: 'other-enterprise', + path: '/work/other', + displayName: 'widgets', + repoIcon: enterpriseIcon('github.other.test') + }) + ]) + + expect(projection.projects).toHaveLength(2) + expect(projection.projects[0]).toMatchObject({ + id: 'github:github.acme.test/acme/widgets', + sourceRepoIds: ['enterprise-local', 'enterprise-ssh'] + }) + expect(projection.projects[1]?.id).toBe('github:github.other.test/acme/widgets') + }) + it('uses GitHub repo icon metadata as a provider identity fallback', () => { const projection = projectHostSetupProjectionFromRepos([ repo({ diff --git a/src/shared/project-host-setup-projection.ts b/src/shared/project-host-setup-projection.ts index 1b5e5be41..2f2aa94ac 100644 --- a/src/shared/project-host-setup-projection.ts +++ b/src/shared/project-host-setup-projection.ts @@ -1,4 +1,5 @@ import { getRepoExecutionHostId } from './execution-host' +import { githubRepoIdentityKey, isDefaultGitHubHost } from './github-repository-identity-key' import type { Project, ProjectHostSetup, @@ -16,17 +17,18 @@ export type ProjectHostSetupProjection = { setups: ProjectHostSetup[] } -function normalizeIdentityPart(value: string): string { - return value.trim().toLowerCase() -} - function getProjectProviderIdentity( repo: Pick ): ProjectProviderIdentity | null { const owner = typeof repo.upstream?.owner === 'string' ? repo.upstream.owner.trim() : '' const name = typeof repo.upstream?.repo === 'string' ? repo.upstream.repo.trim() : '' if (owner && name) { - return { provider: 'github', owner, repo: name } + return { + provider: 'github', + owner, + repo: name, + ...(repo.upstream?.host ? { host: repo.upstream.host } : {}) + } } if (repo.repoIcon?.type === 'image' && repo.repoIcon.source === 'github') { const parts = (repo.repoIcon.label?.trim() ?? '').split('/') @@ -35,7 +37,19 @@ function getProjectProviderIdentity( // Why: repo auto-detect can know the GitHub slug through the generated // avatar icon even when legacy `upstream` has not been backfilled yet. if (iconOwner && iconRepo && parts.length === 2) { - return { provider: 'github', owner: iconOwner, repo: iconRepo } + let host: string | undefined + try { + const url = new URL(repo.repoIcon.src) + host = url.protocol === 'https:' ? url.host : undefined + } catch { + // Legacy persisted icons can be malformed; keep the host-less fallback. + } + return { + provider: 'github', + owner: iconOwner, + repo: iconRepo, + ...(host && !isDefaultGitHubHost(host) ? { host } : {}) + } } } const canonicalKey = repo.gitRemoteIdentity?.canonicalKey.trim() @@ -73,7 +87,7 @@ export function getProjectIdentityKey( ): string { const identity = getProjectProviderIdentity(repo) if (identity) { - return `github:${normalizeIdentityPart(identity.owner)}/${normalizeIdentityPart(identity.repo)}` + return `github:${githubRepoIdentityKey(identity)}` } const gitRemoteIdentity = getProjectGitRemoteIdentity(repo) if (gitRemoteIdentity) { diff --git a/src/shared/repo-icon.test.ts b/src/shared/repo-icon.test.ts index fe2311da5..ea03bc839 100644 --- a/src/shared/repo-icon.test.ts +++ b/src/shared/repo-icon.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { sanitizeRepoIcon } from './repo-icon' +import { githubAvatarIcon, sanitizeRepoIcon } from './repo-icon' describe('sanitizeRepoIcon', () => { it('accepts lucide, emoji, and supported image icons', () => { @@ -24,6 +24,19 @@ describe('sanitizeRepoIcon', () => { source: 'github', label: 'stablyai/orca' }) + expect( + sanitizeRepoIcon({ + type: 'image', + src: 'https://github.acme.test/stablyai.png?size=64', + source: 'github', + label: 'stablyai/orca' + }) + ).toEqual({ + type: 'image', + src: 'https://github.acme.test/stablyai.png?size=64', + source: 'github', + label: 'stablyai/orca' + }) expect( sanitizeRepoIcon({ type: 'image', @@ -88,9 +101,25 @@ describe('sanitizeRepoIcon', () => { expect( sanitizeRepoIcon({ type: 'image', - src: 'https://example.com/icon.png', + src: 'https://example.com/nested/icon.png', + source: 'github' + }) + ).toBeUndefined() + expect( + sanitizeRepoIcon({ + type: 'image', + src: 'https://user@example.com/icon.png', source: 'github' }) ).toBeUndefined() }) + + it('builds hosted avatar URLs only from a valid host value', () => { + expect( + githubAvatarIcon({ owner: 'acme', repo: 'widgets', host: 'GitHub.Acme.Test:8443' }) + ).toMatchObject({ src: 'https://github.acme.test:8443/acme.png?size=64' }) + expect( + githubAvatarIcon({ owner: 'acme', repo: 'widgets', host: 'github.com@evil.example' }) + ).toMatchObject({ src: 'https://github.com/acme.png?size=64' }) + }) }) diff --git a/src/shared/repo-icon.ts b/src/shared/repo-icon.ts index 7c8edb709..7d74a05d4 100644 --- a/src/shared/repo-icon.ts +++ b/src/shared/repo-icon.ts @@ -33,14 +33,32 @@ export function faviconUrlFromWebsite(rawUrl: string): string | null { // main (auto-detect) and renderer (picker); keep the URL and label in one place. export function githubAvatarIcon(slug: { owner: string; repo: string; host?: string }): RepoIcon { // Why: GHES serves the same /.png avatar convention as github.com. + const host = normalizeGitHubAvatarHost(slug.host) return { type: 'image', - src: `https://${slug.host ?? 'github.com'}/${encodeURIComponent(slug.owner)}.png?size=64`, + src: `https://${host}/${encodeURIComponent(slug.owner)}.png?size=64`, source: 'github', label: `${slug.owner}/${slug.repo}` } } +function normalizeGitHubAvatarHost(rawHost?: string): string { + const candidate = rawHost?.trim().toLowerCase() || 'github.com' + try { + const url = new URL(`https://${candidate}`) + return !url.username && + !url.password && + url.host === candidate && + url.pathname === '/' && + !url.search && + !url.hash + ? url.host + : 'github.com' + } catch { + return 'github.com' + } +} + function isSupportedImageSrc(src: string, source: RepoIconImageSource): boolean { if (source === 'upload' || source === 'file') { return /^data:image\/png;base64,[A-Za-z0-9+/=\s]+$/i.test(src) @@ -57,7 +75,9 @@ function isSupportedImageSrc(src: string, source: RepoIconImageSource): boolean } if (source === 'github') { - return url.hostname === 'github.com' && /^\/[^/?#]+\.png$/i.test(url.pathname) + // Why: GHES hosts are user-configured and may be internal; constrain their + // persisted image URL to GitHub's owner-avatar path and forbid credentials. + return !url.username && !url.password && /^\/[^/?#]+\.png$/i.test(url.pathname) } return url.hostname === 'www.google.com' && url.pathname === '/s2/favicons' diff --git a/src/shared/task-source-context.test.ts b/src/shared/task-source-context.test.ts index 5af28c763..31aba0a4d 100644 --- a/src/shared/task-source-context.test.ts +++ b/src/shared/task-source-context.test.ts @@ -95,9 +95,22 @@ describe('task source context', () => { repoId: 'repo-1', providerIdentity: { provider: 'github', owner: 'other', repo: 'orca' } }) + const enterpriseRepo = getTaskSourceCacheScope({ + provider: 'github', + projectId: 'project-1', + hostId: 'local', + repoId: 'repo-1', + providerIdentity: { + provider: 'github', + owner: 'stablyai', + repo: 'orca', + host: 'github.acme.test' + } + }) expect(local).not.toBe(ssh) expect(local).not.toBe(differentRepo) + expect(local).not.toBe(enterpriseRepo) }) it('serializes provider identities for GitLab, Linear, and Jira cache scopes', () => { diff --git a/src/shared/task-source-context.ts b/src/shared/task-source-context.ts index 890e51893..dd707cd44 100644 --- a/src/shared/task-source-context.ts +++ b/src/shared/task-source-context.ts @@ -7,6 +7,7 @@ import { toSshExecutionHostId } from './execution-host' import type { GlobalSettings, ProjectProviderIdentity, Repo } from './types' +import { githubRepoIdentityKey } from './github-repository-identity-key' export type TaskProvider = 'github' | 'gitlab' | 'linear' | 'jira' @@ -209,7 +210,7 @@ function providerIdentityCachePart(identity: TaskProviderIdentity | null | undef } switch (identity.provider) { case 'github': - return [identity.owner, identity.repo].join('/') + return githubRepoIdentityKey(identity) case 'gitlab': return identity.projectId ?? [identity.namespace, identity.project].filter(Boolean).join('/') case 'linear': diff --git a/src/shared/types.ts b/src/shared/types.ts index 0bb9d03a5..cefe1ced0 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -103,6 +103,7 @@ export type ProjectProviderIdentity = { provider: 'github' owner: string repo: string + host?: string } export type Project = { @@ -1573,6 +1574,7 @@ export type GitHubPRFileContents = { export type GitHubPRReviewCommentInput = { repoPath: string + prRepo?: GitHubRepositoryIdentity | null prNumber: number commitId: string path: string