diff --git a/src/main/ipc/github.test.ts b/src/main/ipc/github.test.ts index 5b1612e85c7d..768981cec191 100644 --- a/src/main/ipc/github.test.ts +++ b/src/main/ipc/github.test.ts @@ -282,6 +282,88 @@ describe('registerGitHubHandlers', () => { ) }) + it('broadcasts mutation notifications by repo id even when the payload path is remote', async () => { + const sendMock = vi.fn() + getAllWebContentsMock.mockReturnValue([ + { id: 1, isDestroyed: () => false, send: vi.fn() }, + { id: 2, isDestroyed: () => false, send: sendMock } + ]) + registerGitHubHandlers(store as never, stats as never) + + const result = await handlers['gh:notifyWorkItemMutated']( + { sender: { id: 1 } }, + { + repoPath: '/home/runtime/repo', + repoId: 'repo-1', + type: 'pr', + number: 42 + } + ) + + expect(result).toBe(true) + expect(sendMock).toHaveBeenCalledWith('gh:workItemMutated', { + repoPath: '/workspace/repo', + repoId: 'repo-1', + type: 'pr', + number: 42 + }) + }) + + it('broadcasts mutation notifications with resolved repo id when called by repo path', async () => { + const sendMock = vi.fn() + getAllWebContentsMock.mockReturnValue([ + { id: 1, isDestroyed: () => false, send: vi.fn() }, + { id: 2, isDestroyed: () => false, send: sendMock } + ]) + registerGitHubHandlers(store as never, stats as never) + + const result = await handlers['gh:notifyWorkItemMutated']( + { sender: { id: 1 } }, + { + repoPath: '/workspace/repo', + type: 'issue', + number: 7 + } + ) + + expect(result).toBe(true) + expect(sendMock).toHaveBeenCalledWith('gh:workItemMutated', { + repoPath: '/workspace/repo', + repoId: 'repo-1', + type: 'issue', + number: 7 + }) + }) + + it('broadcasts PR file viewed mutations with repo id for sibling cache invalidation', async () => { + const sendMock = vi.fn() + getAllWebContentsMock.mockReturnValue([ + { id: 1, isDestroyed: () => false, send: vi.fn() }, + { id: 2, isDestroyed: () => false, send: sendMock } + ]) + setPRFileViewedMock.mockResolvedValue(true) + registerGitHubHandlers(store as never, stats as never) + + const result = await handlers['gh:setPRFileViewed']( + { sender: { id: 1 } }, + { + repoPath: '/workspace/repo', + prNumber: 42, + pullRequestId: 'PR_kw', + path: 'src/app.ts', + viewed: true + } + ) + + expect(result).toBe(true) + expect(sendMock).toHaveBeenCalledWith('gh:workItemMutated', { + repoPath: '/workspace/repo', + repoId: 'repo-1', + type: 'pr', + number: 42 + }) + }) + it('rejects unknown repository paths', async () => { registerGitHubHandlers(store as never, stats as never) diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts index 2a808f60325b..8a585e718f2d 100644 --- a/src/main/ipc/github.ts +++ b/src/main/ipc/github.ts @@ -497,6 +497,44 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi return dispatchWorkItem(args, repo, getWorkItemDetails, localGitOptionArgs(store, repo)[0]) }) + ipcMain.handle( + 'gh:notifyWorkItemMutated', + ( + event, + args: { + repoPath: string + repoId?: string + type: 'issue' | 'pr' + number: number + } + ) => { + const repo = args.repoId + ? store.getRepos().find((candidate) => candidate.id === args.repoId) + : assertRegisteredRepo(args, store) + if (!repo) { + return false + } + if ( + (args.type !== 'issue' && args.type !== 'pr') || + typeof args.number !== 'number' || + !Number.isInteger(args.number) || + args.number < 1 + ) { + return false + } + broadcastWorkItemMutated( + { + repoPath: repo.path, + repoId: repo.id, + type: args.type, + number: args.number + }, + event.sender.id + ) + return true + } + ) + ipcMain.handle( 'gh:prFileContents', ( @@ -688,7 +726,7 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi }) if (ok) { broadcastWorkItemMutated( - { repoPath: repo.path, type: 'pr', number: args.prNumber }, + { repoPath: repo.path, repoId: repo.id, type: 'pr', number: args.prNumber }, event.sender.id ) } diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 7ae75a59aa31..4631dd33b6f9 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1190,6 +1190,12 @@ export type PreloadApi = { type?: 'issue' | 'pr' } ) => Promise + notifyWorkItemMutated: (args: { + repoPath: string + repoId?: string + type: 'issue' | 'pr' + number: number + }) => Promise prFileContents: ( args: GitHubRepoSelectorArgs & { prNumber: number diff --git a/src/preload/index.ts b/src/preload/index.ts index a3adca161baf..0ca663716692 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1005,6 +1005,13 @@ const api = { type?: 'issue' | 'pr' }): Promise => ipcRenderer.invoke('gh:workItemDetails', args), + notifyWorkItemMutated: (args: { + repoPath: string + repoId?: string + type: 'issue' | 'pr' + number: number + }): Promise => ipcRenderer.invoke('gh:notifyWorkItemMutated', args), + prFileContents: (args: { repoPath: string repoId?: string diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index 1ff788a6c957..b6a051a66f78 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -159,6 +159,16 @@ import { getCommentBodySubmitState, hasBoundedCommentBodyText } from '@/lib/comment-body-submit-state' +import { + emitGitHubWorkItemDetailsCacheMutation, + onGitHubWorkItemDetailsCacheMutation +} from '@/lib/github-work-item-details-cache-events' +import { lookupGitHubWorkItemDetailsForSource } from '@/lib/github-work-item-source-lookup' +import { + canUseGitHubRepoContext, + getGitHubRuntimeRepoId, + getGitHubSourceRuntimeHost +} from '@/lib/github-source-runtime-context' import IssueSourceIndicator, { sameGitHubOwnerRepo } from '@/components/github/IssueSourceIndicator' import { getGitHubPRReviewerRows, @@ -200,6 +210,7 @@ import type { PRComment } from '../../../shared/types' import { + getTaskSourceCacheScope, getTaskSourceRuntimeSettings, type TaskSourceContext } from '../../../shared/task-source-context' @@ -939,12 +950,13 @@ function PRReviewersPanel({ } setSubmitting(true) try { + const runtimeRepo = getGitHubRuntimeRepoId(sourceContext, item.repoId) const result = target.kind === 'environment' ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.requestPRReviewers', - { repo: item.repoId, prNumber: item.number, reviewers: logins }, + { repo: runtimeRepo, prNumber: item.number, reviewers: logins }, { timeoutMs: 30_000 } ) : await window.api.gh.requestPRReviewers({ @@ -974,6 +986,18 @@ function PRReviewersPanel({ sourceContext }) onReviewersRequested(nextReviewRequests) + if (target.kind === 'environment') { + notifyWorkItemDetailsMutation( + { + repoPath: repoPath ?? '', + repoId: item.repoId, + sourceContext, + type: 'pr', + number: item.number + }, + { local: false } + ) + } setReviewerInput('') useAppStore.getState().recordFeatureInteraction('github-tasks') toast.success( @@ -1017,12 +1041,13 @@ function PRReviewersPanel({ } setSubmitting(true) try { + const runtimeRepo = getGitHubRuntimeRepoId(sourceContext, item.repoId) const result = target.kind === 'environment' ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.removePRReviewers', - { repo: item.repoId, prNumber: item.number, reviewers: logins }, + { repo: runtimeRepo, prNumber: item.number, reviewers: logins }, { timeoutMs: 30_000 } ) : await window.api.gh.removePRReviewers({ @@ -1051,6 +1076,18 @@ function PRReviewersPanel({ sourceContext }) onReviewersRequested(nextReviewRequests) + if (target.kind === 'environment') { + notifyWorkItemDetailsMutation( + { + repoPath: repoPath ?? '', + repoId: item.repoId, + sourceContext, + type: 'pr', + number: item.number + }, + { local: false } + ) + } setReviewerInput('') useAppStore.getState().recordFeatureInteraction('github-tasks') toast.success( @@ -1365,6 +1402,7 @@ function isPRFileViewed(file: GitHubPRFile): boolean { // background refetch on open. See docs/gh-work-item-drawer-cache.md. const WORK_ITEM_DETAILS_CACHE_MAX = 50 const WORK_ITEM_DETAILS_FRESH_MS = 30_000 +const WORK_ITEM_DETAILS_UNAVAILABLE_MESSAGE = 'Unable to load details for this GitHub item.' type WorkItemDetailsCacheEntry = { details: GitHubWorkItemDetails | null fetchedAt: number @@ -1394,12 +1432,16 @@ function getWorkItemDetailsCacheKey(args: { repoPath: string repoId: string issueSourcePreference: string | undefined + sourceCacheScope?: string | null type: 'issue' | 'pr' number: number }): string { // Why: include all axes that change which (repo, item) the IPC resolves to. // `\0` separator avoids ambiguity between fields that may contain `:` or `/`. - return [args.repoId, args.issueSourcePreference ?? 'auto', args.type, args.number].join('\0') + const keyParts = args.sourceCacheScope + ? [args.repoId, args.sourceCacheScope, args.issueSourcePreference ?? 'auto', args.type] + : [args.repoId, args.issueSourcePreference ?? 'auto', args.type] + return [...keyParts, args.number].join('\0') } function touchWorkItemDetailsCache(key: string, entry: WorkItemDetailsCacheEntry): void { @@ -1446,7 +1488,6 @@ function invalidateWorkItemDetailsCacheByMatch(args: { type: 'issue' | 'pr' number: number }): void { - workItemDetailsCacheGeneration += 1 const suffix = `\0${args.type}\0${args.number}` const prefix = `${args.repoId ?? args.repoPath}\0` let removed = false @@ -1457,6 +1498,7 @@ function invalidateWorkItemDetailsCacheByMatch(args: { } } if (removed) { + workItemDetailsCacheGeneration += 1 notifyWorkItemDetailsCache() } } @@ -1541,6 +1583,7 @@ function patchCachedWorkItemBody(cacheKey: string, body: string): void { // own cache when any window's mutation lands. We track the unsubscribe so // Vite HMR doesn't accumulate listeners across module reloads in dev. let workItemMutatedUnsub: (() => void) | undefined +let workItemDetailsCacheEventUnsub: (() => void) | undefined if (typeof window !== 'undefined' && window.api?.gh?.onWorkItemMutated) { workItemMutatedUnsub = window.api.gh.onWorkItemMutated((payload) => { invalidateWorkItemDetailsCacheByMatch({ @@ -1550,10 +1593,14 @@ if (typeof window !== 'undefined' && window.api?.gh?.onWorkItemMutated) { number: payload.number }) }) + workItemDetailsCacheEventUnsub = onGitHubWorkItemDetailsCacheMutation((payload) => { + invalidateWorkItemDetailsCacheByMatch(payload) + }) } if (typeof import.meta !== 'undefined' && import.meta.hot) { import.meta.hot.dispose(() => { workItemMutatedUnsub?.() + workItemDetailsCacheEventUnsub?.() }) } @@ -1650,14 +1697,20 @@ function touchPRFileContentCache( function getPRFileContentCacheKey(args: { repoPath: string repoId: string + sourceContext?: TaskSourceContext | null prNumber: number file: GitHubPRFile headSha: string baseSha: string }): string { const repositoryKey = args.repoId ? `repo:${args.repoId}` : `path:${args.repoPath}` + const sourceKey = + args.sourceContext?.provider === 'github' + ? `source:${getTaskSourceCacheScope(args.sourceContext)}` + : 'source:local' return [ repositoryKey, + sourceKey, args.prNumber, args.file.path, args.file.oldPath ?? '', @@ -1683,18 +1736,35 @@ function loadPRFileContents(args: { return Promise.resolve(cached.value) } let request: Promise - request = window.api.gh - .prFileContents({ - repoPath: args.repoPath, - repoId: args.repoId, - sourceContext: args.sourceContext, - prNumber: args.prNumber, - path: args.file.path, - oldPath: args.file.oldPath, - status: args.file.status, - headSha: args.headSha, - baseSha: args.baseSha - }) + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + request = ( + runtimeHost + ? callRuntimeRpc( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.prFileContents', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + prNumber: args.prNumber, + path: args.file.path, + oldPath: args.file.oldPath, + status: args.file.status, + headSha: args.headSha, + baseSha: args.baseSha + }, + { timeoutMs: 30_000 } + ) + : window.api.gh.prFileContents({ + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + prNumber: args.prNumber, + path: args.file.path, + oldPath: args.file.oldPath, + status: args.file.status, + headSha: args.headSha, + baseSha: args.baseSha + }) + ) .then((contents) => { if (prFileContentCache.get(cacheKey)?.value === request) { touchPRFileContentCache(cacheKey, contents) @@ -1721,6 +1791,33 @@ function addIssueCommentForRepo(args: { body: string type?: 'issue' | 'pr' }): Promise>> { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (runtimeHost) { + return callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.addIssueComment', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + number: args.number, + body: args.body + }, + { timeoutMs: 30_000 } + ).then((result) => { + if (result.ok) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + type: args.type ?? 'issue', + number: args.number + }, + { local: false } + ) + } + return result + }) + } return window.api.gh.addIssueComment({ repoPath: args.repoPath, repoId: args.repoId, @@ -1742,6 +1839,37 @@ function addPRReviewCommentForRepo(args: { startLine?: number body: string }): Promise>> { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (runtimeHost) { + return callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.addPRReviewComment', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + prNumber: args.prNumber, + commitId: args.commitId, + path: args.path, + line: args.line, + startLine: args.startLine, + body: args.body + }, + { timeoutMs: 30_000 } + ).then((result) => { + if (result.ok) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + type: 'pr', + number: args.prNumber + }, + { local: false } + ) + } + return result + }) + } return window.api.gh.addPRReviewComment({ repoPath: args.repoPath, repoId: args.repoId, @@ -1766,6 +1894,37 @@ function addPRReviewCommentReplyForRepo(args: { path?: string line?: number }): Promise>> { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (runtimeHost) { + return callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.addPRReviewCommentReply', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + prNumber: args.prNumber, + commentId: args.commentId, + body: args.body, + threadId: args.threadId, + path: args.path, + line: args.line + }, + { timeoutMs: 30_000 } + ).then((result) => { + if (result.ok) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + type: 'pr', + number: args.prNumber + }, + { local: false } + ) + } + return result + }) + } return window.api.gh.addPRReviewCommentReply({ repoPath: args.repoPath, repoId: args.repoId, @@ -1779,8 +1938,31 @@ function addPRReviewCommentReplyForRepo(args: { }) } +function notifyWorkItemDetailsMutation( + args: { + repoPath: string + repoId?: string + sourceContext?: TaskSourceContext | null + type: 'issue' | 'pr' + number: number + }, + options: { local?: boolean } = {} +): void { + if (options.local !== false) { + emitGitHubWorkItemDetailsCacheMutation(args) + } + void window.api.gh + .notifyWorkItemMutated({ + repoPath: args.repoPath, + repoId: args.repoId, + type: args.type, + number: args.number + }) + .catch(() => undefined) +} + function setPRFileViewedForRepo(args: { - repoId?: string + repoId: string repoPath: string sourceContext?: TaskSourceContext | null prNumber: number @@ -1788,6 +1970,34 @@ function setPRFileViewedForRepo(args: { path: string viewed: boolean }): Promise { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (runtimeHost) { + return callRuntimeRpc( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.setPRFileViewed', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + pullRequestId: args.pullRequestId, + path: args.path, + viewed: args.viewed + }, + { timeoutMs: 30_000 } + ).then((ok) => { + if (ok) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + type: 'pr', + number: args.prNumber + }, + { local: false } + ) + } + return ok + }) + } return window.api.gh.setPRFileViewed({ repoPath: args.repoPath, repoId: args.repoId, @@ -1799,22 +2009,6 @@ function setPRFileViewedForRepo(args: { }) } -function getWorkItemDetailsForRepo(args: { - repoId?: string - repoPath: string - sourceContext?: TaskSourceContext | null - number: number - type: 'issue' | 'pr' -}): Promise { - return window.api.gh.workItemDetails({ - repoPath: args.repoPath, - repoId: args.repoId, - sourceContext: args.sourceContext, - number: args.number, - type: args.type - }) -} - function PRViewedCheckbox({ checked, pending, @@ -2928,6 +3122,7 @@ function ConversationTab({ const [bodyDraft, setBodyDraft] = useState(body) const [bodyEditing, setBodyEditing] = useState(false) const [bodySaving, setBodySaving] = useState(false) + const canUseRepoMutationContext = canUseGitHubRepoContext(repoPath, sourceContext) const commentCounts = useMemo(() => getPRCommentAudienceCounts(comments), [comments]) const visibleComments = useMemo( () => filterPRCommentsByAudience(comments, commentFilter), @@ -2961,7 +3156,9 @@ function ConversationTab({ [bodySlug, projectOrigin] ) const canEditBody = - item.type === 'pr' ? Boolean(projectOrigin || bodySlug) : Boolean(projectOrigin || repoPath) + item.type === 'pr' + ? Boolean(projectOrigin || bodySlug) + : Boolean(projectOrigin || canUseRepoMutationContext) const bodyChanged = resolvedBodyDraft !== body const handleSaveBody = useCallback(async (): Promise => { @@ -3011,7 +3208,7 @@ function ConversationTab({ const handleReply = useCallback( async (comment: PRComment, replyBody: string): Promise => { - if (!repoPath) { + if (!canUseRepoMutationContext) { toast.error( translate( 'auto.components.GitHubItemDialog.745c9089ec', @@ -3023,7 +3220,7 @@ function ConversationTab({ const result = comment.path && item.type === 'pr' ? await addPRReviewCommentReplyForRepo({ - repoPath, + repoPath: repoPath ?? '', repoId: item.repoId, sourceContext, prNumber: item.number, @@ -3034,7 +3231,7 @@ function ConversationTab({ line: comment.line }) : await addIssueCommentForRepo({ - repoPath, + repoPath: repoPath ?? '', repoId: item.repoId, sourceContext, number: item.number, @@ -3054,7 +3251,15 @@ function ConversationTab({ toast.success(translate('auto.components.GitHubItemDialog.10f4ff5be8', 'Reply posted.')) return true }, - [item.number, item.repoId, item.type, onCommentAdded, repoPath, sourceContext] + [ + canUseRepoMutationContext, + item.number, + item.repoId, + item.type, + onCommentAdded, + repoPath, + sourceContext + ] ) const rightPanel = @@ -3598,10 +3803,10 @@ function ConversationTab({ ) : null} - {detailsLoaded && repoPath && ( + {detailsLoaded && canUseRepoMutationContext && ( { @@ -3727,7 +3938,7 @@ function PRActionsPanel({ } const handleMerge = async (method: GitHubPRMergeMethod): Promise => { - if (!repoPath || mergeDisabled) { + if (mergeDisabled) { return } const label = GITHUB_PR_MERGE_METHOD_LABELS[method] @@ -3748,19 +3959,44 @@ function PRActionsPanel({ } setMergePending(true) try { - const result = await window.api.gh.mergePR({ - repoPath, - repoId: repoId ?? undefined, - sourceContext, - prNumber: item.number, - method, - prRepo: item.prRepo ?? null - }) + const result = + mergeTarget.kind === 'environment' + ? await callRuntimeRpc>>( + mergeTarget, + 'github.mergePR', + { + repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId), + prNumber: item.number, + method, + prRepo: item.prRepo ?? null + }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.mergePR({ + repoPath: repoPath ?? '', + repoId: repoId ?? undefined, + sourceContext, + prNumber: item.number, + method, + prRepo: item.prRepo ?? null + }) if (!result.ok) { toast.error(result.error) return } applyStatePatch('merged') + if (mergeTarget.kind === 'environment') { + notifyWorkItemDetailsMutation( + { + repoPath: repoPath ?? '', + repoId: item.repoId, + sourceContext, + type: 'pr', + number: item.number + }, + { local: false } + ) + } useAppStore.getState().recordFeatureInteraction('github-tasks') toast.success(translate('auto.components.GitHubItemDialog.dbe5e2448e', 'Pull request merged')) onMutated() @@ -3774,25 +4010,51 @@ function PRActionsPanel({ } const handleAutoMerge = async (): Promise => { - if (!repoPath || !mergePresentation.autoMergeAction) { + if (!canMergeWithRepoContext || !mergePresentation.autoMergeAction) { return } const enabled = mergePresentation.autoMergeAction.kind === 'enable' setMergePending(true) try { - const result = await window.api.gh.setPRAutoMerge({ - repoPath, - repoId: repoId ?? undefined, - sourceContext, - prNumber: item.number, - enabled, - method: enabled ? mergeMethods.defaultMethod : undefined, - prRepo: item.prRepo ?? null - }) + const result = + mergeTarget.kind === 'environment' + ? await callRuntimeRpc>>( + mergeTarget, + 'github.setPRAutoMerge', + { + repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId), + prNumber: item.number, + enabled, + method: enabled ? mergeMethods.defaultMethod : undefined, + prRepo: item.prRepo ?? null + }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.setPRAutoMerge({ + repoPath: repoPath ?? '', + repoId: repoId ?? undefined, + sourceContext, + prNumber: item.number, + enabled, + method: enabled ? mergeMethods.defaultMethod : undefined, + prRepo: item.prRepo ?? null + }) if (!result.ok) { toast.error(result.error) return } + if (mergeTarget.kind === 'environment') { + notifyWorkItemDetailsMutation( + { + repoPath: repoPath ?? '', + repoId: item.repoId, + sourceContext, + type: 'pr', + number: item.number + }, + { local: false } + ) + } useAppStore.getState().recordFeatureInteraction('github-tasks') toast.success( enabled @@ -3850,7 +4112,7 @@ function PRActionsPanel({ - {!repoPath + {!canMergeWithRepoContext ? translate( 'auto.components.GitHubItemDialog.5932578f51', 'Merge requires a registered local repo' @@ -3861,7 +4123,7 @@ function PRActionsPanel({ {mergePresentation.autoMergeAction && ( void handleAutoMerge()} > @@ -4161,6 +4423,8 @@ function ChecksTab({ const { localChecks, expandedCheckKey, detailsByCheckKey } = resolvedChecksState const list = useMemo(() => localChecks ?? checks ?? [], [checks, localChecks]) const prRepo = useMemo(() => parseOwnerRepoFromItemUrl(item.url), [item.url]) + const runtimeHost = getGitHubSourceRuntimeHost(sourceContext) + const canUseChecksRepoContext = canUseGitHubRepoContext(repoPath, sourceContext) const sorted = [...list].sort( (a, b) => (CHECK_SORT_ORDER[getCheckConclusion(a)] ?? 3) - @@ -4188,7 +4452,7 @@ function ChecksTab({ const canFixBrokenChecks = Boolean((repoId ?? item.repoId) && failedChecks.length > 0) const handleRefresh = useCallback(async (): Promise => { - if (!repoPath) { + if (!canUseChecksRepoContext) { toast.error( translate( 'auto.components.GitHubItemDialog.e7007aa1d8', @@ -4199,14 +4463,27 @@ function ChecksTab({ } setRefreshing(true) try { - const nextChecks = (await window.api.gh.prChecks({ - repoPath, - repoId: repoId ?? undefined, - sourceContext, - prNumber: item.number, - headSha, - noCache: true - })) as PRCheckDetail[] + const nextChecks = (await (runtimeHost + ? callRuntimeRpc( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.prChecks', + { + repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId), + prNumber: item.number, + headSha, + prRepo, + noCache: true + }, + { timeoutMs: 30_000 } + ) + : window.api.gh.prChecks({ + repoPath: repoPath ?? '', + repoId: repoId ?? undefined, + sourceContext, + prNumber: item.number, + headSha, + noCache: true + }))) as PRCheckDetail[] setChecksState((current) => updateGitHubChecksTabLocalChecks(current, nextChecks)) onChecksUpdated(nextChecks) return nextChecks @@ -4220,23 +4497,46 @@ function ChecksTab({ } finally { setRefreshing(false) } - }, [headSha, item.number, onChecksUpdated, repoId, repoPath, sourceContext]) + }, [ + canUseChecksRepoContext, + headSha, + item.number, + item.repoId, + onChecksUpdated, + runtimeHost, + prRepo, + repoId, + repoPath, + sourceContext + ]) const handleRerun = useCallback( async (failedOnly: boolean): Promise => { - if (!repoPath || rerunning) { + if (!canUseChecksRepoContext || rerunning) { return } setRerunning(true) try { - const result = await window.api.gh.rerunPRChecks({ - repoPath, - repoId: repoId ?? undefined, - sourceContext, - prNumber: item.number, - headSha, - failedOnly - }) + const result = runtimeHost + ? await callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.rerunPRChecks', + { + repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId), + prNumber: item.number, + headSha, + failedOnly + }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.rerunPRChecks({ + repoPath: repoPath ?? '', + repoId: repoId ?? undefined, + sourceContext, + prNumber: item.number, + headSha, + failedOnly + }) if (!result.ok) { toast.error(result.error) return @@ -4257,7 +4557,18 @@ function ChecksTab({ setRerunning(false) } }, - [handleRefresh, headSha, item.number, rerunning, repoId, repoPath, sourceContext] + [ + canUseChecksRepoContext, + handleRefresh, + headSha, + item.number, + item.repoId, + runtimeHost, + rerunning, + repoId, + repoPath, + sourceContext + ] ) const handleFixBrokenChecks = useCallback(async (): Promise => { @@ -4324,7 +4635,7 @@ function ChecksTab({ const key = getCheckDetailsKey(check) setChecksState((current) => toggleGitHubChecksTabExpandedKey(current, key)) if ( - !repoPath || + !canUseChecksRepoContext || detailsByCheckKey[key] || (!check.checkRunId && !check.workflowRunId && !check.url) ) { @@ -4337,16 +4648,31 @@ function ChecksTab({ error: null }) ) - void window.api.gh - .prCheckDetails({ - repoPath, - repoId: repoId ?? undefined, - checkRunId: check.checkRunId, - workflowRunId: check.workflowRunId, - checkName: check.name, - url: check.url, - prRepo - }) + const detailsRequest = runtimeHost + ? callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.prCheckDetails', + { + repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId), + checkRunId: check.checkRunId, + workflowRunId: check.workflowRunId, + checkName: check.name, + url: check.url, + prRepo + }, + { timeoutMs: 30_000 } + ) + : window.api.gh.prCheckDetails({ + repoPath: repoPath ?? '', + repoId: repoId ?? undefined, + sourceContext, + checkRunId: check.checkRunId, + workflowRunId: check.workflowRunId, + checkName: check.name, + url: check.url, + prRepo + }) + void detailsRequest .then((details) => { if (!mountedRef.current) { return @@ -4372,7 +4698,17 @@ function ChecksTab({ ) }) }, - [detailsByCheckKey, mountedRef, prRepo, repoId, repoPath] + [ + canUseChecksRepoContext, + detailsByCheckKey, + item.repoId, + mountedRef, + runtimeHost, + prRepo, + repoId, + repoPath, + sourceContext + ] ) const refreshAction = ( @@ -4383,7 +4719,7 @@ function ChecksTab({ variant="ghost" size="icon-xs" className="size-7 shrink-0" - disabled={!repoPath || refreshing} + disabled={!canUseChecksRepoContext || refreshing} onClick={() => void handleRefresh()} aria-label={translate('auto.components.GitHubItemDialog.9a1004fc76', 'Refresh checks')} > @@ -4434,7 +4770,7 @@ function ChecksTab({ variant="outline" size="xs" className="h-7 gap-1 px-2 text-[11px]" - disabled={!repoPath || rerunning || list.length === 0} + disabled={!canUseChecksRepoContext || rerunning || list.length === 0} > {rerunning ? ( @@ -4891,7 +5227,11 @@ async function runIssueUpdate(args: { updates: Parameters[0]['updates'] }): Promise { if (args.projectOrigin) { - const target = getActiveRuntimeTarget(getGitHubMutationSettings(args.repoId)) + const targetSettings = + args.sourceContext?.provider === 'github' + ? getTaskSourceRuntimeSettings(args.sourceContext) + : getGitHubMutationSettings(args.repoId) + const target = getActiveRuntimeTarget(targetSettings) const updateArgs = { owner: args.projectOrigin.owner, repo: args.projectOrigin.repo, @@ -4912,21 +5252,57 @@ async function runIssueUpdate(args: { if (!res.ok) { throw new Error(res.error.message) } + if (target.kind === 'environment') { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath ?? '', + repoId: args.repoId ?? undefined, + sourceContext: args.sourceContext, + type: 'issue', + number: args.number + }, + { local: false } + ) + } return } - if (!args.repoPath) { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (!args.repoPath && !runtimeHost) { throw new Error('No repo context available for this edit.') } - const res = await window.api.gh.updateIssue({ - repoPath: args.repoPath, - repoId: args.repoId ?? undefined, - sourceContext: args.sourceContext, - number: args.number, - updates: args.updates - }) + const res = runtimeHost + ? await callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.updateIssue', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), + number: args.number, + updates: args.updates + }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.updateIssue({ + repoPath: args.repoPath ?? '', + repoId: args.repoId ?? undefined, + sourceContext: args.sourceContext, + number: args.number, + updates: args.updates + }) if (!res.ok) { throw new Error(res.error) } + if (runtimeHost) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath ?? '', + repoId: args.repoId ?? undefined, + sourceContext: args.sourceContext, + type: 'issue', + number: args.number + }, + { local: false } + ) + } } async function runWorkItemBodyUpdate(args: { @@ -4944,7 +5320,11 @@ async function runWorkItemBodyUpdate(args: { if (!targetSlug) { throw new Error('No GitHub repository context available for this pull request.') } - const target = getActiveRuntimeTarget(getGitHubMutationSettings(args.item.repoId)) + const targetSettings = + args.sourceContext?.provider === 'github' + ? getTaskSourceRuntimeSettings(args.sourceContext) + : getGitHubMutationSettings(args.item.repoId) + const target = getActiveRuntimeTarget(targetSettings) const updateArgs = { owner: targetSlug.owner, repo: targetSlug.repo, @@ -4965,6 +5345,18 @@ async function runWorkItemBodyUpdate(args: { if (!res.ok) { throw new Error(res.error.message) } + if (target.kind === 'environment') { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath ?? '', + repoId: args.item.repoId, + sourceContext: args.sourceContext, + type: 'pr', + number: args.item.number + }, + { local: false } + ) + } return } @@ -4987,7 +5379,11 @@ async function runPullRequestStateUpdate(args: { updates: { state: 'open' | 'closed' } }): Promise { if (args.projectOrigin) { - const target = getActiveRuntimeTarget(getGitHubMutationSettings(args.repoId)) + const targetSettings = + args.sourceContext?.provider === 'github' + ? getTaskSourceRuntimeSettings(args.sourceContext) + : getGitHubMutationSettings(args.repoId) + const target = getActiveRuntimeTarget(targetSettings) const updateArgs = { owner: args.projectOrigin.owner, repo: args.projectOrigin.repo, @@ -5008,21 +5404,57 @@ async function runPullRequestStateUpdate(args: { if (!res.ok) { throw new Error(res.error.message) } + if (target.kind === 'environment') { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath ?? '', + repoId: args.repoId ?? undefined, + sourceContext: args.sourceContext, + type: 'pr', + number: args.number + }, + { local: false } + ) + } return } - if (!args.repoPath) { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (!args.repoPath && !runtimeHost) { throw new Error('No repo context available for this pull request.') } - const res = await window.api.gh.updatePRState({ - repoPath: args.repoPath, - repoId: args.repoId ?? undefined, - sourceContext: args.sourceContext, - prNumber: args.number, - updates: args.updates - }) + const res = runtimeHost + ? await callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.updatePRState', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? ''), + prNumber: args.number, + updates: args.updates + }, + { timeoutMs: 30_000 } + ) + : await window.api.gh.updatePRState({ + repoPath: args.repoPath ?? '', + repoId: args.repoId ?? undefined, + sourceContext: args.sourceContext, + prNumber: args.number, + updates: args.updates + }) if (!res.ok) { throw new Error(res.error) } + if (runtimeHost) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath ?? '', + repoId: args.repoId ?? undefined, + sourceContext: args.sourceContext, + type: 'pr', + number: args.number + }, + { local: false } + ) + } } function GitHubLabelsSettingsLink({ @@ -6378,18 +6810,28 @@ export default function GitHubItemDialog({ return s.repos.find((r) => (effectiveRepoId ? r.id === effectiveRepoId : r.path === repoPath)) ?.issueSourcePreference }) + const canUseDetailsRepoContext = canUseGitHubRepoContext(repoPath, sourceContext) const detailsCacheKey = useMemo(() => { - if (!workItem || !repoPath || !effectiveRepoId) { + if (!workItem || !effectiveRepoId || !canUseDetailsRepoContext) { return null } return getWorkItemDetailsCacheKey({ - repoPath, + repoPath: repoPath ?? '', repoId: effectiveRepoId, issueSourcePreference, + sourceCacheScope: + sourceContext?.provider === 'github' ? getTaskSourceCacheScope(sourceContext) : null, type: workItem.type, number: workItem.number }) - }, [repoPath, effectiveRepoId, workItem, issueSourcePreference]) + }, [ + canUseDetailsRepoContext, + repoPath, + effectiveRepoId, + sourceContext, + workItem, + issueSourcePreference + ]) // Why: track comments added optimistically before the detail fetch resolves // so they can be merged into the fetch result instead of being overwritten. @@ -6503,9 +6945,7 @@ export default function GitHubItemDialog({ const loading = !!cachedEntry?.pending && !cachedEntry?.details const error = cachedEntry?.error && !cachedEntry?.details ? cachedEntry.error : null - const detailsLoaded = - Boolean(cachedEntry?.details) || - Boolean(cachedEntry && !cachedEntry.pending && !cachedEntry.error && cachedEntry.fetchedAt > 0) + const detailsLoaded = Boolean(cachedEntry?.details) // Why: if a cross-window mutation invalidates the open drawer's entry // (cachedEntry becomes undefined while workItem is still set), the main @@ -6519,7 +6959,7 @@ export default function GitHubItemDialog({ }, [workItem, detailsCacheKey, cachedEntry]) useEffect(() => { - if (!workItem || !repoPath || !detailsCacheKey) { + if (!workItem || !effectiveRepoId || !detailsCacheKey || !canUseDetailsRepoContext) { return } // Why: only clear optimistic comments when switching to a genuinely @@ -6546,9 +6986,9 @@ export default function GitHubItemDialog({ // racing two `gh` subprocesses against each other. const inflight: Promise = cached?.pending ?? - getWorkItemDetailsForRepo({ - repoPath, - repoId: effectiveRepoId ?? undefined, + lookupGitHubWorkItemDetailsForSource({ + repoPath: repoPath ?? '', + repoId: effectiveRepoId, sourceContext, number: workItem.number, type: workItem.type @@ -6572,20 +7012,24 @@ export default function GitHubItemDialog({ .then((result) => { const invalidatedMidFlight = workItemDetailsCacheGeneration !== launchedAtGeneration const prev = workItemDetailsCache.get(detailsCacheKey) - if (invalidatedMidFlight) { + if (invalidatedMidFlight && prev?.pending !== inflight) { // Why: entry was deliberately dropped; do not recreate it. If the // entry still exists (later open repopulated it) leave it alone too. return } - // Why: 404/unauthorized must not overwrite valid cached data. When the - // IPC resolves to null and we already have cached details, keep the - // stale data — only blank entries get the null payload. + // Why: null means unavailable/not found, not loaded empty content. if (result === null && prev?.details) { touchWorkItemDetailsCache(detailsCacheKey, { details: prev.details, fetchedAt: prev.fetchedAt, error: undefined }) + } else if (result === null) { + touchWorkItemDetailsCache(detailsCacheKey, { + details: null, + fetchedAt: 0, + error: WORK_ITEM_DETAILS_UNAVAILABLE_MESSAGE + }) } else { touchWorkItemDetailsCache(detailsCacheKey, { details: result, @@ -6597,10 +7041,10 @@ export default function GitHubItemDialog({ .catch((err) => { const message = err instanceof Error ? err.message : 'Failed to load details' const invalidatedMidFlight = workItemDetailsCacheGeneration !== launchedAtGeneration - if (invalidatedMidFlight) { + const prev = workItemDetailsCache.get(detailsCacheKey) + if (invalidatedMidFlight && prev?.pending !== inflight) { return } - const prev = workItemDetailsCache.get(detailsCacheKey) // Why: stale-on-error — keep cached data if we have it, drop the // pending promise so the next open can retry. Only surface the // blocking error when nothing is cached. @@ -6610,7 +7054,16 @@ export default function GitHubItemDialog({ error: message }) }) - }, [repoPath, effectiveRepoId, sourceContext, workItem, detailsCacheKey, initialTab, refetchTick]) + }, [ + canUseDetailsRepoContext, + repoPath, + effectiveRepoId, + sourceContext, + workItem, + detailsCacheKey, + initialTab, + refetchTick + ]) const Icon = workItem?.type === 'pr' ? GitPullRequest : CircleDot const displayWorkItem = useMemo(() => { @@ -6728,9 +7181,34 @@ export default function GitHubItemDialog({ [detailsCacheKey] ) + const invalidateCurrentDetailsCache = useCallback((): void => { + if (!workItem) { + return + } + // Why: local repos can invalidate every source-preference variant; runtime-only + // entries need their exact source-scoped key because there is no local path. + if (repoPath) { + invalidateWorkItemDetailsCacheByMatch({ + repoPath, + repoId: effectiveRepoId ?? undefined, + type: workItem.type, + number: workItem.number + }) + return + } + if (detailsCacheKey) { + invalidateWorkItemDetailsCacheForKey(detailsCacheKey) + } + }, [detailsCacheKey, effectiveRepoId, repoPath, workItem]) + const handlePRFileViewedChange = useCallback( async (path: string, viewed: boolean): Promise => { - if (!repoPath || !details?.pullRequestId || !workItem || workItem.type !== 'pr') { + if ( + !canUseDetailsRepoContext || + !details?.pullRequestId || + !workItem || + workItem.type !== 'pr' + ) { toast.error( translate( 'auto.components.GitHubItemDialog.c0253318d6', @@ -6747,7 +7225,7 @@ export default function GitHubItemDialog({ try { const ok = await setPRFileViewedForRepo({ repoId: workItem.repoId, - repoPath, + repoPath: repoPath ?? '', sourceContext, prNumber: workItem.number, pullRequestId: details.pullRequestId, @@ -6775,7 +7253,14 @@ export default function GitHubItemDialog({ }) } }, - [details?.pullRequestId, detailsCacheKey, repoPath, sourceContext, workItem] + [ + canUseDetailsRepoContext, + details?.pullRequestId, + detailsCacheKey, + repoPath, + sourceContext, + workItem + ] ) const isIssuePage = workItem?.type === 'issue' @@ -7108,7 +7593,7 @@ export default function GitHubItemDialog({ )} - {!isIssuePage && (repoPath || projectOrigin) && ( + {!isIssuePage && (canUseDetailsRepoContext || projectOrigin) && ( { - // Why: drop the cached details for this item so the next - // open issues a fresh fetch instead of painting pre-edit - // state. We invalidate by (repoPath, type, number) match - // because a single mutation can affect entries across all - // issueSourcePreference values for the same number. - if (repoPath) { - invalidateWorkItemDetailsCacheByMatch({ - repoPath, - repoId: effectiveRepoId ?? undefined, - type: workItem.type, - number: workItem.number - }) - } - }} + onMutated={invalidateCurrentDetailsCache} assignees={details?.assignees ?? []} onUse={onUse} onOpenOrUse={handleOpenOrUseIssueWorkspace} @@ -7165,16 +7636,7 @@ export default function GitHubItemDialog({ localState={localState} onStateChange={setLocalState} projectOrigin={projectOrigin} - onMutated={() => { - if (repoPath) { - invalidateWorkItemDetailsCacheByMatch({ - repoPath, - repoId: effectiveRepoId ?? undefined, - type: workItem.type, - number: workItem.number - }) - } - }} + onMutated={invalidateCurrentDetailsCache} onChecksUpdated={(nextChecks) => { if (detailsCacheKey) { patchCachedPRChecks(detailsCacheKey, nextChecks) @@ -7197,7 +7659,7 @@ export default function GitHubItemDialog({ }} /> - {(repoPath || projectOrigin) && ( + {(canUseDetailsRepoContext || projectOrigin) && (
{ - if (repoPath) { - invalidateWorkItemDetailsCacheByMatch({ - repoPath, - repoId: effectiveRepoId ?? undefined, - type: workItem.type, - number: workItem.number - }) - } - }} + onMutated={invalidateCurrentDetailsCache} assignees={details?.assignees ?? []} onUse={onUse} onOpenOrUse={handleOpenOrUseIssueWorkspace} @@ -7286,16 +7739,7 @@ export default function GitHubItemDialog({ localState={localState} onStateChange={setLocalState} projectOrigin={projectOrigin} - onMutated={() => { - if (repoPath) { - invalidateWorkItemDetailsCacheByMatch({ - repoPath, - repoId: effectiveRepoId ?? undefined, - type: workItem.type, - number: workItem.number - }) - } - }} + onMutated={invalidateCurrentDetailsCache} onChecksUpdated={(nextChecks) => { if (detailsCacheKey) { patchCachedPRChecks(detailsCacheKey, nextChecks) diff --git a/src/renderer/src/components/PullRequestPage.tsx b/src/renderer/src/components/PullRequestPage.tsx index c42fdff91196..29fc73ebe0d7 100644 --- a/src/renderer/src/components/PullRequestPage.tsx +++ b/src/renderer/src/components/PullRequestPage.tsx @@ -160,6 +160,16 @@ import { getCommentBodySubmitState, hasBoundedCommentBodyText } from '@/lib/comment-body-submit-state' +import { + emitGitHubWorkItemDetailsCacheMutation, + onGitHubWorkItemDetailsCacheMutation +} from '@/lib/github-work-item-details-cache-events' +import { lookupGitHubWorkItemDetailsForSource } from '@/lib/github-work-item-source-lookup' +import { + canUseGitHubRepoContext, + getGitHubRuntimeRepoId, + getGitHubSourceRuntimeHost +} from '@/lib/github-source-runtime-context' import { presentGitHubPRMergeState } from '@/components/github-pr-merge-state' import { GITHUB_PR_MERGE_METHOD_LABELS, @@ -201,6 +211,11 @@ import type { PRCheckDetail, PRComment } from '../../../shared/types' +import { + getTaskSourceCacheScope, + getTaskSourceRuntimeSettings, + type TaskSourceContext +} from '../../../shared/task-source-context' import { translate } from '@/i18n/i18n' import { getSettingsForRepoRuntimeOwner } from '@/lib/repo-runtime-owner' @@ -288,6 +303,7 @@ type PullRequestPageProps = { workItem: GitHubWorkItem | null repoPath: string | null repoId?: string | null + sourceContext?: TaskSourceContext | null initialTab?: ItemDialogTab backLabel?: string /** Called when the user clicks the primary CTA to start work from this item. */ @@ -503,11 +519,13 @@ function PRAssigneesPanel({ item, repoPath, projectOrigin, + sourceContext, onMutated }: { item: GitHubWorkItem repoPath: string | null projectOrigin: PullRequestPageProjectOrigin | undefined + sourceContext?: TaskSourceContext | null onMutated: () => void }): React.JSX.Element { const [assigneePopoverOpen, setAssigneePopoverOpen] = useState(false) @@ -524,6 +542,16 @@ function PRAssigneesPanel({ const repoOwnerSettings = useAppStore( useShallow((s) => getSettingsForRepoRuntimeOwner(s, item.repoId ?? null)) ) + const sourceSettings = useMemo( + () => + sourceContext?.provider === 'github' + ? ({ + ...repoOwnerSettings, + ...getTaskSourceRuntimeSettings(sourceContext) + } as typeof repoOwnerSettings) + : repoOwnerSettings, + [repoOwnerSettings, sourceContext] + ) const { isPending, run } = useImmediateMutation() // Why: PR assignees can change through background refetches; sync them @@ -554,9 +582,9 @@ function PRAssigneesPanel({ slugOwner, slugRepo, assigneeLogins, - repoOwnerSettings + sourceSettings ) - const repoAssigneesByPath = useRepoAssignees(repoPath, item.repoId, repoOwnerSettings) + const repoAssigneesByPath = useRepoAssignees(repoPath, item.repoId, sourceSettings) const repoAssignees = slugOwner && slugRepo ? repoAssigneesBySlug : repoAssigneesByPath const canEditAssignees = Boolean(projectOrigin || repoPath) const assigneesByLogin = useMemo( @@ -581,18 +609,19 @@ function PRAssigneesPanel({ runIssueUpdate({ repoId: item.repoId, repoPath, + sourceContext, projectOrigin, number: item.number, updates: isAssigned ? { removeAssignees: [login] } : { addAssignees: [login] } }), onOptimistic: () => { setLocalAssignees(nextAssignees) - patchWorkItem(item.id, { assignees: nextAssignees }, item.repoId) + patchWorkItem(item.id, { assignees: nextAssignees }, item.repoId, { sourceContext }) patchProjectRowIfNeeded(nextLogins) }, onRevert: () => { setLocalAssignees(prevAssignees) - patchWorkItem(item.id, { assignees: prevAssignees }, item.repoId) + patchWorkItem(item.id, { assignees: prevAssignees }, item.repoId, { sourceContext }) patchProjectRowIfNeeded(prevLogins) }, onSuccess: () => { @@ -613,7 +642,8 @@ function PRAssigneesPanel({ patchWorkItem, projectOrigin, repoPath, - run + run, + sourceContext ] ) @@ -719,11 +749,13 @@ function PRReviewersPanel({ item, loading, repoPath, + sourceContext, onReviewersRequested }: { item: GitHubWorkItem loading: boolean repoPath: string | null + sourceContext?: TaskSourceContext | null onReviewersRequested: (reviewRequests: GitHubAssignableUser[]) => void }): React.JSX.Element { const [open, setOpen] = useState(false) @@ -745,6 +777,16 @@ function PRReviewersPanel({ const repoOwnerSettings = useAppStore( useShallow((s) => getSettingsForRepoRuntimeOwner(s, item.repoId ?? null)) ) + const sourceSettings = useMemo( + () => + sourceContext?.provider === 'github' + ? ({ + ...repoOwnerSettings, + ...getTaskSourceRuntimeSettings(sourceContext) + } as typeof repoOwnerSettings) + : repoOwnerSettings, + [repoOwnerSettings, sourceContext] + ) const reviewerInputRef = useRef(null) const reviewerInputFocusFrameRef = useRef(null) const reviewerPanelMountedRef = useRef(true) @@ -819,12 +861,12 @@ function PRReviewersPanel({ open && reviewSlug ? reviewSlug.owner : null, open && reviewSlug ? reviewSlug.repo : null, reviewerSeedUsers.map((user) => user.login), - repoOwnerSettings + sourceSettings ) const reviewerMetadataByPath = useRepoAssignees( open && !reviewSlug ? repoPath : null, open && !reviewSlug ? item.repoId : null, - repoOwnerSettings + sourceSettings ) const reviewerMetadata = reviewSlug ? reviewerMetadataBySlug : reviewerMetadataByPath const displayItem = { ...item, reviewRequests: localReviewRequests } @@ -915,7 +957,7 @@ function PRReviewersPanel({ item.reviewRequests !== undefined || item.latestReviews !== undefined const canRequestReview = - !!repoPath || getActiveRuntimeTarget(repoOwnerSettings).kind === 'environment' + !!repoPath || getActiveRuntimeTarget(sourceSettings).kind === 'environment' const handleRequestReview = async (requestedLogins?: string[]): Promise => { if (submitting) { @@ -938,7 +980,7 @@ function PRReviewersPanel({ ) return } - const target = getActiveRuntimeTarget(repoOwnerSettings) + const target = getActiveRuntimeTarget(sourceSettings) if (target.kind !== 'environment' && !repoPath) { toast.error( translate( @@ -950,17 +992,19 @@ function PRReviewersPanel({ } setSubmitting(true) try { + const runtimeRepo = getGitHubRuntimeRepoId(sourceContext, item.repoId) const result = target.kind === 'environment' ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.requestPRReviewers', - { repo: item.repoId, prNumber: item.number, reviewers: logins }, + { repo: runtimeRepo, prNumber: item.number, reviewers: logins }, { timeoutMs: 30_000 } ) : await window.api.gh.requestPRReviewers({ repoPath: repoPath ?? '', repoId: item.repoId, + sourceContext, prNumber: item.number, reviewers: logins }) @@ -980,8 +1024,22 @@ function PRReviewersPanel({ localReviewRequests ) setLocalReviewRequests(nextReviewRequests) - patchWorkItem(item.id, { reviewRequests: nextReviewRequests }, item.repoId) + patchWorkItem(item.id, { reviewRequests: nextReviewRequests }, item.repoId, { + sourceContext + }) onReviewersRequested(nextReviewRequests) + if (target.kind === 'environment') { + notifyWorkItemDetailsMutation( + { + repoPath: repoPath ?? '', + repoId: item.repoId, + sourceContext, + type: 'pr', + number: item.number + }, + { local: false } + ) + } setReviewerInput('') toast.success( logins.length === 1 @@ -1012,7 +1070,7 @@ function PRReviewersPanel({ if (logins.length === 0) { return } - const target = getActiveRuntimeTarget(repoOwnerSettings) + const target = getActiveRuntimeTarget(sourceSettings) if (target.kind !== 'environment' && !repoPath) { toast.error( translate( @@ -1024,17 +1082,19 @@ function PRReviewersPanel({ } setSubmitting(true) try { + const runtimeRepo = getGitHubRuntimeRepoId(sourceContext, item.repoId) const result = target.kind === 'environment' ? await callRuntimeRpc<{ ok: boolean; error?: string }>( target, 'github.removePRReviewers', - { repo: item.repoId, prNumber: item.number, reviewers: logins }, + { repo: runtimeRepo, prNumber: item.number, reviewers: logins }, { timeoutMs: 30_000 } ) : await window.api.gh.removePRReviewers({ repoPath: repoPath ?? '', repoId: item.repoId, + sourceContext, prNumber: item.number, reviewers: logins }) @@ -1053,8 +1113,22 @@ function PRReviewersPanel({ (reviewer) => !removed.has(reviewer.login.toLowerCase()) ) setLocalReviewRequests(nextReviewRequests) - patchWorkItem(item.id, { reviewRequests: nextReviewRequests }, item.repoId) + patchWorkItem(item.id, { reviewRequests: nextReviewRequests }, item.repoId, { + sourceContext + }) onReviewersRequested(nextReviewRequests) + if (target.kind === 'environment') { + notifyWorkItemDetailsMutation( + { + repoPath: repoPath ?? '', + repoId: item.repoId, + sourceContext, + type: 'pr', + number: item.number + }, + { local: false } + ) + } setReviewerInput('') toast.success( logins.length === 1 @@ -1368,6 +1442,7 @@ function isPRFileViewed(file: GitHubPRFile): boolean { // background refetch on open. See docs/gh-work-item-drawer-cache.md. const WORK_ITEM_DETAILS_CACHE_MAX = 50 const WORK_ITEM_DETAILS_FRESH_MS = 30_000 +const WORK_ITEM_DETAILS_UNAVAILABLE_MESSAGE = 'Unable to load details for this GitHub item.' type WorkItemDetailsCacheEntry = { details: GitHubWorkItemDetails | null fetchedAt: number @@ -1397,12 +1472,16 @@ function getWorkItemDetailsCacheKey(args: { repoPath: string repoId: string issueSourcePreference: string | undefined + sourceCacheScope?: string | null type: 'issue' | 'pr' number: number }): string { // Why: include all axes that change which (repo, item) the IPC resolves to. // `\0` separator avoids ambiguity between fields that may contain `:` or `/`. - return [args.repoId, args.issueSourcePreference ?? 'auto', args.type, args.number].join('\0') + const keyParts = args.sourceCacheScope + ? [args.repoId, args.sourceCacheScope, args.issueSourcePreference ?? 'auto', args.type] + : [args.repoId, args.issueSourcePreference ?? 'auto', args.type] + return [...keyParts, args.number].join('\0') } function touchWorkItemDetailsCache(key: string, entry: WorkItemDetailsCacheEntry): void { @@ -1449,7 +1528,6 @@ function invalidateWorkItemDetailsCacheByMatch(args: { type: 'issue' | 'pr' number: number }): void { - workItemDetailsCacheGeneration += 1 const suffix = `\0${args.type}\0${args.number}` const prefix = `${args.repoId ?? args.repoPath}\0` let removed = false @@ -1460,6 +1538,7 @@ function invalidateWorkItemDetailsCacheByMatch(args: { } } if (removed) { + workItemDetailsCacheGeneration += 1 notifyWorkItemDetailsCache() } } @@ -1544,6 +1623,7 @@ function patchCachedWorkItemBody(cacheKey: string, body: string): void { // own cache when any window's mutation lands. We track the unsubscribe so // Vite HMR doesn't accumulate listeners across module reloads in dev. let workItemMutatedUnsub: (() => void) | undefined +let workItemDetailsCacheEventUnsub: (() => void) | undefined if (typeof window !== 'undefined' && window.api?.gh?.onWorkItemMutated) { workItemMutatedUnsub = window.api.gh.onWorkItemMutated((payload) => { invalidateWorkItemDetailsCacheByMatch({ @@ -1553,10 +1633,14 @@ if (typeof window !== 'undefined' && window.api?.gh?.onWorkItemMutated) { number: payload.number }) }) + workItemDetailsCacheEventUnsub = onGitHubWorkItemDetailsCacheMutation((payload) => { + invalidateWorkItemDetailsCacheByMatch(payload) + }) } if (typeof import.meta !== 'undefined' && import.meta.hot) { import.meta.hot.dispose(() => { workItemMutatedUnsub?.() + workItemDetailsCacheEventUnsub?.() }) } @@ -1653,14 +1737,20 @@ function touchPRFileContentCache( function getPRFileContentCacheKey(args: { repoPath: string repoId: string + sourceContext?: TaskSourceContext | null prNumber: number file: GitHubPRFile headSha: string baseSha: string }): string { const repositoryKey = args.repoId ? `repo:${args.repoId}` : `path:${args.repoPath}` + const sourceKey = + args.sourceContext?.provider === 'github' + ? `source:${getTaskSourceCacheScope(args.sourceContext)}` + : 'source:local' return [ repositoryKey, + sourceKey, args.prNumber, args.file.path, args.file.oldPath ?? '', @@ -1673,6 +1763,7 @@ function getPRFileContentCacheKey(args: { function loadPRFileContents(args: { repoPath: string repoId: string + sourceContext?: TaskSourceContext | null prNumber: number file: GitHubPRFile headSha: string @@ -1685,17 +1776,35 @@ function loadPRFileContents(args: { return Promise.resolve(cached.value) } let request: Promise - request = window.api.gh - .prFileContents({ - repoPath: args.repoPath, - repoId: args.repoId, - prNumber: args.prNumber, - path: args.file.path, - oldPath: args.file.oldPath, - status: args.file.status, - headSha: args.headSha, - baseSha: args.baseSha - }) + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + request = ( + runtimeHost + ? callRuntimeRpc( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.prFileContents', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + prNumber: args.prNumber, + path: args.file.path, + oldPath: args.file.oldPath, + status: args.file.status, + headSha: args.headSha, + baseSha: args.baseSha + }, + { timeoutMs: 30_000 } + ) + : window.api.gh.prFileContents({ + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + prNumber: args.prNumber, + path: args.file.path, + oldPath: args.file.oldPath, + status: args.file.status, + headSha: args.headSha, + baseSha: args.baseSha + }) + ) .then((contents) => { if (prFileContentCache.get(cacheKey)?.value === request) { touchPRFileContentCache(cacheKey, contents) @@ -1717,13 +1826,42 @@ function loadPRFileContents(args: { function addIssueCommentForRepo(args: { repoId?: string repoPath: string + sourceContext?: TaskSourceContext | null number: number body: string type?: 'issue' | 'pr' }): Promise>> { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (runtimeHost) { + return callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.addIssueComment', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + number: args.number, + body: args.body + }, + { timeoutMs: 30_000 } + ).then((result) => { + if (result.ok) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + type: args.type ?? 'issue', + number: args.number + }, + { local: false } + ) + } + return result + }) + } return window.api.gh.addIssueComment({ repoPath: args.repoPath, repoId: args.repoId, + sourceContext: args.sourceContext, number: args.number, body: args.body, type: args.type @@ -1733,6 +1871,7 @@ function addIssueCommentForRepo(args: { function addPRReviewCommentForRepo(args: { repoId?: string repoPath: string + sourceContext?: TaskSourceContext | null prNumber: number commitId: string path: string @@ -1740,9 +1879,41 @@ function addPRReviewCommentForRepo(args: { startLine?: number body: string }): Promise>> { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (runtimeHost) { + return callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.addPRReviewComment', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + prNumber: args.prNumber, + commitId: args.commitId, + path: args.path, + line: args.line, + startLine: args.startLine, + body: args.body + }, + { timeoutMs: 30_000 } + ).then((result) => { + if (result.ok) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + type: 'pr', + number: args.prNumber + }, + { local: false } + ) + } + return result + }) + } return window.api.gh.addPRReviewComment({ repoPath: args.repoPath, repoId: args.repoId, + sourceContext: args.sourceContext, prNumber: args.prNumber, commitId: args.commitId, path: args.path, @@ -1755,6 +1926,7 @@ function addPRReviewCommentForRepo(args: { function addPRReviewCommentReplyForRepo(args: { repoId?: string repoPath: string + sourceContext?: TaskSourceContext | null prNumber: number commentId: number body: string @@ -1762,9 +1934,41 @@ function addPRReviewCommentReplyForRepo(args: { path?: string line?: number }): Promise>> { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (runtimeHost) { + return callRuntimeRpc>>( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.addPRReviewCommentReply', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + prNumber: args.prNumber, + commentId: args.commentId, + body: args.body, + threadId: args.threadId, + path: args.path, + line: args.line + }, + { timeoutMs: 30_000 } + ).then((result) => { + if (result.ok) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + type: 'pr', + number: args.prNumber + }, + { local: false } + ) + } + return result + }) + } return window.api.gh.addPRReviewCommentReply({ repoPath: args.repoPath, repoId: args.repoId, + sourceContext: args.sourceContext, prNumber: args.prNumber, commentId: args.commentId, body: args.body, @@ -1774,17 +1978,70 @@ function addPRReviewCommentReplyForRepo(args: { }) } +function notifyWorkItemDetailsMutation( + args: { + repoPath: string + repoId?: string + sourceContext?: TaskSourceContext | null + type: 'issue' | 'pr' + number: number + }, + options: { local?: boolean } = {} +): void { + if (options.local !== false) { + emitGitHubWorkItemDetailsCacheMutation(args) + } + void window.api.gh + .notifyWorkItemMutated({ + repoPath: args.repoPath, + repoId: args.repoId, + type: args.type, + number: args.number + }) + .catch(() => undefined) +} + function setPRFileViewedForRepo(args: { - repoId?: string + repoId: string repoPath: string + sourceContext?: TaskSourceContext | null prNumber: number pullRequestId: string path: string viewed: boolean }): Promise { + const runtimeHost = getGitHubSourceRuntimeHost(args.sourceContext) + if (runtimeHost) { + return callRuntimeRpc( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.setPRFileViewed', + { + repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId), + pullRequestId: args.pullRequestId, + path: args.path, + viewed: args.viewed + }, + { timeoutMs: 30_000 } + ).then((ok) => { + if (ok) { + notifyWorkItemDetailsMutation( + { + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext: args.sourceContext, + type: 'pr', + number: args.prNumber + }, + { local: false } + ) + } + return ok + }) + } return window.api.gh.setPRFileViewed({ repoPath: args.repoPath, repoId: args.repoId, + sourceContext: args.sourceContext, prNumber: args.prNumber, pullRequestId: args.pullRequestId, path: args.path, @@ -1792,20 +2049,6 @@ function setPRFileViewedForRepo(args: { }) } -function getWorkItemDetailsForRepo(args: { - repoId?: string - repoPath: string - number: number - type: 'issue' | 'pr' -}): Promise { - return window.api.gh.workItemDetails({ - repoPath: args.repoPath, - repoId: args.repoId, - number: args.number, - type: args.type - }) -} - function PRViewedCheckbox({ checked, pending, @@ -1971,6 +2214,7 @@ type PRFilesCombinedDiffViewerProps = { comments: PRComment[] repoPath: string repoId: string + sourceContext?: TaskSourceContext | null prNumber: number prUrl: string headSha: string | undefined @@ -1985,6 +2229,7 @@ function PRFilesCombinedDiffViewer({ comments, repoPath, repoId, + sourceContext, prNumber, prUrl, headSha, @@ -2184,6 +2429,7 @@ function PRFilesCombinedDiffViewer({ const contents = await loadPRFileContents({ repoPath, repoId, + sourceContext, prNumber, file, headSha, @@ -2233,7 +2479,7 @@ function PRFilesCombinedDiffViewer({ ) }) }, - [baseSha, fileByPath, headSha, prNumber, repoId, repoPath] + [baseSha, fileByPath, headSha, prNumber, repoId, repoPath, sourceContext] ) const retrySection = useCallback( @@ -2466,6 +2712,7 @@ function PRFilesCombinedDiffViewer({ const result = await addPRReviewCommentForRepo({ repoPath, repoId, + sourceContext, prNumber, commitId: headSha, path: section.path, @@ -2486,7 +2733,7 @@ function PRFilesCombinedDiffViewer({ ) return true }, - [headSha, onCommentAdded, prNumber, repoId, repoPath] + [headSha, onCommentAdded, prNumber, repoId, repoPath, sourceContext] ) const renderViewedCheckbox = useCallback( @@ -2632,6 +2879,7 @@ function CommentCodeContext({ comment, repoPath, repoId, + sourceContext, prNumber, files, headSha, @@ -2640,6 +2888,7 @@ function CommentCodeContext({ comment: PRComment repoPath: string | null repoId: string + sourceContext?: TaskSourceContext | null prNumber: number files: GitHubPRFile[] headSha: string | undefined @@ -2664,7 +2913,7 @@ function CommentCodeContext({ return } let cancelled = false - loadPRFileContents({ repoPath, repoId, prNumber, file, headSha, baseSha }) + loadPRFileContents({ repoPath, repoId, sourceContext, prNumber, file, headSha, baseSha }) .then((result) => { if (!cancelled) { setContents(result) @@ -2678,7 +2927,7 @@ function CommentCodeContext({ return () => { cancelled = true } - }, [baseSha, file, headSha, line, prNumber, repoId, repoPath]) + }, [baseSha, file, headSha, line, prNumber, repoId, repoPath, sourceContext]) const resolvedContextExpansionState = resolveCommentCodeContextExpansionState( contextExpansionState, @@ -2931,6 +3180,7 @@ function ConversationTab({ item, repoPath, repoId, + sourceContext, body, comments, files, @@ -2952,6 +3202,7 @@ function ConversationTab({ item: GitHubWorkItem repoPath: string | null repoId: string | null + sourceContext?: TaskSourceContext | null body: string comments: PRComment[] files: GitHubPRFile[] @@ -2978,10 +3229,21 @@ function ConversationTab({ const [bodySaving, setBodySaving] = useState(false) const bodyTextareaRef = useRef(null) const bodyTextareaFocusFrameRef = useRef(null) + const canUseRepoMutationContext = canUseGitHubRepoContext(repoPath, sourceContext) const repoOwnerSettings = useAppStore( useShallow((s) => getSettingsForRepoRuntimeOwner(s, item.repoId ?? repoId ?? null)) ) - const repoAssignees = useRepoAssignees(repoPath, item.repoId, repoOwnerSettings) + const sourceSettings = useMemo( + () => + sourceContext?.provider === 'github' + ? ({ + ...repoOwnerSettings, + ...getTaskSourceRuntimeSettings(sourceContext) + } as typeof repoOwnerSettings) + : repoOwnerSettings, + [repoOwnerSettings, sourceContext] + ) + const repoAssignees = useRepoAssignees(repoPath, item.repoId, sourceSettings) const commentCounts = useMemo(() => getPRCommentAudienceCounts(comments), [comments]) const visibleComments = useMemo( () => filterPRCommentsByAudience(comments, commentFilter), @@ -3039,7 +3301,9 @@ function ConversationTab({ [bodySlug, projectOrigin] ) const canEditBody = - item.type === 'pr' ? Boolean(projectOrigin || bodySlug) : Boolean(projectOrigin || repoPath) + item.type === 'pr' + ? Boolean(projectOrigin || bodySlug) + : Boolean(projectOrigin || canUseRepoMutationContext) const bodyChanged = resolvedBodyDraft !== body const handleSaveBody = useCallback(async (): Promise => { @@ -3052,6 +3316,7 @@ function ConversationTab({ await runWorkItemBodyUpdate({ item, repoPath, + sourceContext, projectOrigin, body: resolvedBodyDraft, parsedSlug: bodySlug @@ -3076,12 +3341,13 @@ function ConversationTab({ item, onBodyUpdated, projectOrigin, - repoPath + repoPath, + sourceContext ]) const handleReply = useCallback( async (comment: PRComment, replyBody: string): Promise => { - if (!repoPath) { + if (!canUseRepoMutationContext) { toast.error( translate( 'auto.components.PullRequestPage.6885c619e7', @@ -3093,8 +3359,9 @@ function ConversationTab({ const result = comment.path && item.type === 'pr' ? await addPRReviewCommentReplyForRepo({ - repoPath, + repoPath: repoPath ?? '', repoId: item.repoId, + sourceContext, prNumber: item.number, commentId: comment.id, body: replyBody, @@ -3103,8 +3370,9 @@ function ConversationTab({ line: comment.line }) : await addIssueCommentForRepo({ - repoPath, + repoPath: repoPath ?? '', repoId: item.repoId, + sourceContext, number: item.number, body: `@${comment.author} ${replyBody}`, type: item.type @@ -3122,7 +3390,15 @@ function ConversationTab({ toast.success(translate('auto.components.PullRequestPage.11505c7a71', 'Reply posted.')) return true }, - [item.number, item.repoId, item.type, onCommentAdded, repoPath] + [ + canUseRepoMutationContext, + item.number, + item.repoId, + item.type, + onCommentAdded, + repoPath, + sourceContext + ] ) const rightPanel = @@ -3132,6 +3408,7 @@ function ConversationTab({ item={item} repoPath={repoPath} repoId={item.repoId} + sourceContext={sourceContext} projectOrigin={projectOrigin} localState={localState} onStateChange={onStateChange} @@ -3141,12 +3418,14 @@ function ConversationTab({ item={item} repoPath={repoPath} projectOrigin={projectOrigin} + sourceContext={sourceContext} onMutated={onMutated} />
- {(repoPath || projectOrigin) && ( + {(canUseDetailsRepoContext || projectOrigin) && ( { - // Why: drop the cached details for this item so the next - // open issues a fresh fetch instead of painting pre-edit - // state. We invalidate by (repoPath, type, number) match - // because a single mutation can affect entries across all - // issueSourcePreference values for the same number. - if (repoPath) { - invalidateWorkItemDetailsCacheByMatch({ - repoPath, - repoId: effectiveRepoId ?? undefined, - type: workItem.type, - number: workItem.number - }) - } - }} + onMutated={invalidateCurrentDetailsCache} assignees={details?.assignees ?? []} onUse={onUse} /> @@ -6597,6 +7191,7 @@ export default function PullRequestPage({ item={displayWorkItem ?? workItem} repoPath={repoPath} repoId={effectiveRepoId} + sourceContext={sourceContext} body={body} comments={comments} files={files} @@ -6609,16 +7204,7 @@ export default function PullRequestPage({ localState={localState} onStateChange={setLocalState} projectOrigin={projectOrigin} - onMutated={() => { - if (repoPath) { - invalidateWorkItemDetailsCacheByMatch({ - repoPath, - repoId: effectiveRepoId ?? undefined, - type: workItem.type, - number: workItem.number - }) - } - }} + onMutated={invalidateCurrentDetailsCache} onChecksUpdated={(nextChecks) => { if (detailsCacheKey) { patchCachedPRChecks(detailsCacheKey, nextChecks) @@ -6647,6 +7233,7 @@ export default function PullRequestPage({ item={workItem} repoPath={repoPath} repoId={effectiveRepoId} + sourceContext={sourceContext} headSha={details?.headSha} checks={checks} loading={loading || !detailsLoaded} @@ -6674,6 +7261,7 @@ export default function PullRequestPage({ comments={comments} repoPath={repoPath ?? ''} repoId={effectiveRepoId ?? ''} + sourceContext={sourceContext} prNumber={workItem.number} prUrl={workItem.url} headSha={details?.headSha} diff --git a/src/renderer/src/components/TaskPage.tsx b/src/renderer/src/components/TaskPage.tsx index 8e0bc6e29fd1..df16663c4adf 100644 --- a/src/renderer/src/components/TaskPage.tsx +++ b/src/renderer/src/components/TaskPage.tsx @@ -8899,6 +8899,7 @@ export default function TaskPage(): React.JSX.Element { initialTab={dialogInitialTab} repoPath={dialogRepoPath} repoId={dialogWorkItem.repoId} + sourceContext={dialogSourceContext} backLabel="Pull requests" onUse={(item) => { setDialogWorkItem(null) diff --git a/src/renderer/src/components/github-item-dialog-source-boundary.test.ts b/src/renderer/src/components/github-item-dialog-source-boundary.test.ts index 83c8b3cac470..deb287ca2d39 100644 --- a/src/renderer/src/components/github-item-dialog-source-boundary.test.ts +++ b/src/renderer/src/components/github-item-dialog-source-boundary.test.ts @@ -36,11 +36,24 @@ describe('GitHubItemDialog source host boundaries', () => { expect(section).toContain('useRepoAssignees(') expect(section).toContain('sourceSettings') expect(section).toContain('getActiveRuntimeTarget(sourceSettings)') + expect(section).toContain( + 'const runtimeRepo = getGitHubRuntimeRepoId(sourceContext, item.repoId)' + ) + expect(section).toContain("'github.requestPRReviewers'") + expect(section).toContain("'github.removePRReviewers'") + expect(section).toContain('{ repo: runtimeRepo, prNumber: item.number, reviewers: logins }') + expect(section).toContain('notifyWorkItemDetailsMutation(') + expect(section).toContain('{ local: false }') }) it('routes edit metadata through the same task source as issue mutations', () => { const source = componentSource('GitHubItemDialog.tsx') const section = sourceBetween(source, 'function GHEditSection', 'const hasAttachedWorkspace') + const helperSection = sourceBetween( + source, + 'function getGitHubMutationSettings', + 'function GitHubLabelsSettingsLink' + ) expect(section).toContain('getTaskSourceRuntimeSettings(sourceContext)') expect(section).toContain('useRepoLabels(') @@ -48,5 +61,168 @@ describe('GitHubItemDialog source host boundaries', () => { expect(section).toContain('useRepoAssignees(') expect(section).toContain('useRepoAssigneesBySlug(') expect(section).toContain('sourceSettings') + expect(helperSection).toContain("'github.updateIssue'") + expect(helperSection).toContain("'github.updatePRState'") + expect(helperSection).toContain("'github.project.updateIssueBySlug'") + expect(helperSection).toContain("'github.project.updatePullRequestBySlug'") + expect(helperSection).toContain("args.sourceContext?.provider === 'github'") + expect(helperSection).toContain('getTaskSourceRuntimeSettings(args.sourceContext)') + expect(helperSection).toContain('notifyWorkItemDetailsMutation(') + expect(helperSection).toContain( + "repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? '')" + ) + expect(helperSection).toContain('{ local: false }') + }) + + it('uses source-aware details routing and cache identity', () => { + const source = componentSource('GitHubItemDialog.tsx') + const cacheKeySection = sourceBetween( + source, + 'function getWorkItemDetailsCacheKey', + 'function touchWorkItemDetailsCache' + ) + const matchInvalidationSection = sourceBetween( + source, + 'function invalidateWorkItemDetailsCacheByMatch', + 'function patchCachedPRFileViewedState' + ) + + expect(source).toContain('lookupGitHubWorkItemDetailsForSource({') + expect(source).toContain('sourceContext,') + expect(cacheKeySection).toContain('sourceCacheScope') + expect(source).toContain('getTaskSourceCacheScope(sourceContext)') + expect(matchInvalidationSection).toContain( + 'if (removed) {\n workItemDetailsCacheGeneration += 1' + ) + }) + + it('treats null details as unavailable while preserving empty detail payloads', () => { + const source = componentSource('GitHubItemDialog.tsx') + const loadedSection = sourceBetween( + source, + 'const loading = !!cachedEntry?.pending && !cachedEntry?.details', + '// Why: if a cross-window mutation invalidates' + ) + const resultSection = sourceBetween(source, 'inflight', '.catch((err) => {') + + expect(loadedSection).toContain('const detailsLoaded = Boolean(cachedEntry?.details)') + expect(loadedSection).not.toContain('fetchedAt > 0') + expect(resultSection).toContain('} else if (result === null) {') + expect(resultSection).toContain('error: WORK_ITEM_DETAILS_UNAVAILABLE_MESSAGE') + expect(resultSection).toContain('details: result') + }) + + it('routes PR file viewed mutations through the task source context', () => { + const source = componentSource('GitHubItemDialog.tsx') + const helperSection = sourceBetween( + source, + 'function setPRFileViewedForRepo', + 'function PRViewedCheckbox' + ) + const changeSection = sourceBetween( + source, + 'const handlePRFileViewedChange = useCallback', + 'const isIssuePage = workItem?.type ===' + ) + + expect(helperSection).toContain('getGitHubSourceRuntimeHost(args.sourceContext)') + expect(helperSection).toContain("'github.setPRFileViewed'") + expect(helperSection).toContain('repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId)') + expect(helperSection).toContain('sourceContext: args.sourceContext') + expect(helperSection).toContain('{ local: false }') + expect(changeSection).toContain('canUseDetailsRepoContext') + expect(changeSection).toContain('repoPath: repoPath ??') + expect(changeSection).toContain('sourceContext,') + }) + + it('routes comment mutations through runtime source context when needed', () => { + const source = componentSource('GitHubItemDialog.tsx') + const helperSection = sourceBetween( + source, + 'function addIssueCommentForRepo', + 'function setPRFileViewedForRepo' + ) + + expect(helperSection).toContain('getGitHubSourceRuntimeHost(args.sourceContext)') + expect(helperSection).toContain("'github.addIssueComment'") + expect(helperSection).toContain("'github.addPRReviewComment'") + expect(helperSection).toContain("'github.addPRReviewCommentReply'") + expect(helperSection).toContain('repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId)') + expect(helperSection).toContain('sourceContext: args.sourceContext') + expect(helperSection).toContain('notifyWorkItemDetailsMutation(') + expect(helperSection).toContain('{ local: false }') + }) + + it('routes PR file contents and runtime viewed invalidations through the task source context', () => { + const source = componentSource('GitHubItemDialog.tsx') + const fileContentsSection = sourceBetween( + source, + 'function loadPRFileContents', + 'function setPRFileViewedForRepo' + ) + const fileContentsCacheKeySection = sourceBetween( + source, + 'function getPRFileContentCacheKey', + 'function loadPRFileContents' + ) + const listenerSection = sourceBetween(source, 'let workItemMutatedUnsub', '// Why: bounded LRU') + + expect(fileContentsCacheKeySection).toContain( + 'source:${getTaskSourceCacheScope(args.sourceContext)}' + ) + expect(fileContentsSection).toContain("'github.prFileContents'") + expect(fileContentsSection).toContain( + 'repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId)' + ) + expect(fileContentsSection).toContain('sourceContext: args.sourceContext') + expect(fileContentsSection).toContain('sourceContext,') + expect(listenerSection).toContain('onGitHubWorkItemDetailsCacheMutation') + expect(source).toContain('emitGitHubWorkItemDetailsCacheMutation(args)') + expect(source).toContain('options.local !== false') + expect(source).toContain('notifyWorkItemMutated({') + }) + + it('routes merge actions through the task source context', () => { + const source = componentSource('GitHubItemDialog.tsx') + const actionsSection = sourceBetween( + source, + 'function PRActionsPanel', + 'function CommentReactions' + ) + + expect(actionsSection).toContain('getTaskSourceRuntimeSettings(sourceContext)') + expect(actionsSection).toContain('getActiveRuntimeTarget(sourceSettings)') + expect(actionsSection).toContain( + 'const canMergeWithRepoContext = !!repoPath || mergeTarget.kind ===' + ) + expect(actionsSection).toContain("'github.mergePR'") + expect(actionsSection).toContain("'github.setPRAutoMerge'") + expect(actionsSection).toContain( + 'repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId)' + ) + expect(actionsSection).toContain('sourceContext,') + expect(actionsSection).toContain('notifyWorkItemDetailsMutation(') + expect(actionsSection).toContain('{ local: false }') + }) + + it('routes check actions through the task source context', () => { + const source = componentSource('GitHubItemDialog.tsx') + const checksSection = sourceBetween( + source, + 'function ChecksTab', + 'function getGitHubMutationSettings' + ) + + expect(checksSection).toContain('sourceContext?: TaskSourceContext | null') + expect(checksSection).toContain('sourceContext,') + expect(checksSection).toContain("'github.prChecks'") + expect(checksSection).toContain("'github.rerunPRChecks'") + expect(checksSection).toContain("'github.prCheckDetails'") + expect(checksSection).toContain( + 'repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId)' + ) + expect(checksSection).toContain('window.api.gh.prChecks({') + expect(checksSection).toContain('window.api.gh.rerunPRChecks({') + expect(checksSection).toContain('prCheckDetails({') }) }) diff --git a/src/renderer/src/components/github-project/ProjectViewWrapper.tsx b/src/renderer/src/components/github-project/ProjectViewWrapper.tsx index f9c8a4ceee70..09578f05c2f1 100644 --- a/src/renderer/src/components/github-project/ProjectViewWrapper.tsx +++ b/src/renderer/src/components/github-project/ProjectViewWrapper.tsx @@ -62,6 +62,7 @@ import { type CachedVisibleProjectTable } from './project-visible-table-cache' import { translate } from '@/i18n/i18n' +import { buildTaskSourceContextFromRepo } from '../../../../shared/task-source-context' type Props = { selectedRepoIds: ReadonlySet @@ -426,6 +427,16 @@ export default function ProjectViewWrapper({ selectedRepoIds }: Props): React.JS // Orca; clear them before the modal tree receives stale repo ids. setDialogRepoItem(resolvedDialogRepoItem) } + const resolvedDialogRepo = resolvedDialogRepoItem + ? (repos.find((repo) => repo.id === resolvedDialogRepoItem.repoId) ?? null) + : null + const resolvedDialogSourceContext = resolvedDialogRepo + ? buildTaskSourceContextFromRepo({ + provider: 'github', + projectId: resolvedDialogRepo.id, + repo: resolvedDialogRepo + }) + : null const resolvedMissingRepoDialogs = resolveMissingRepoProjectDialogState({ slugIndexReady, @@ -923,6 +934,7 @@ export default function ProjectViewWrapper({ selectedRepoIds }: Props): React.JS workItem={resolvedDialogRepoItem.workItem} repoPath={resolvedDialogRepoItem.repoPath} repoId={resolvedDialogRepoItem.repoId} + sourceContext={resolvedDialogSourceContext} projectOrigin={resolvedDialogRepoItem.origin} backLabel={translate( 'auto.components.github.project.ProjectViewWrapper.1aa7c952b9', diff --git a/src/renderer/src/components/github-project/project-view-wrapper-source-context-boundary.test.ts b/src/renderer/src/components/github-project/project-view-wrapper-source-context-boundary.test.ts new file mode 100644 index 000000000000..558fe2232254 --- /dev/null +++ b/src/renderer/src/components/github-project/project-view-wrapper-source-context-boundary.test.ts @@ -0,0 +1,34 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' + +const COMPONENT_ROOT = __dirname + +function componentSource(relativePath: string): string { + return readFileSync(join(COMPONENT_ROOT, relativePath), 'utf8') +} + +function sourceBetween(source: string, startPattern: string, endPattern: string): string { + const start = source.indexOf(startPattern) + expect(start).toBeGreaterThanOrEqual(0) + const end = source.indexOf(endPattern, start + startPattern.length) + expect(end).toBeGreaterThan(start) + return source.slice(start, end) +} + +describe('ProjectViewWrapper GitHub source context boundary', () => { + it('passes the matched repo source context into the repo-backed GitHub dialog', () => { + const source = componentSource('ProjectViewWrapper.tsx') + const contextSection = sourceBetween( + source, + 'const resolvedDialogRepo = resolvedDialogRepoItem', + 'const resolvedMissingRepoDialogs' + ) + const dialogSection = sourceBetween(source, ' {') + + expect(source).toContain('buildTaskSourceContextFromRepo') + expect(contextSection).toContain("provider: 'github'") + expect(contextSection).toContain('repo: resolvedDialogRepo') + expect(dialogSection).toContain('sourceContext={resolvedDialogSourceContext}') + }) +}) diff --git a/src/renderer/src/components/pull-request-page-host-boundary.test.ts b/src/renderer/src/components/pull-request-page-host-boundary.test.ts index 9c1148a51d82..888225aa350d 100644 --- a/src/renderer/src/components/pull-request-page-host-boundary.test.ts +++ b/src/renderer/src/components/pull-request-page-host-boundary.test.ts @@ -21,12 +21,24 @@ describe('PullRequestPage host boundaries', () => { const source = componentSource('PullRequestPage.tsx') const section = sourceBetween(source, 'function PRReviewersPanel', 'function isPRFileViewed') - expect(section).toContain('getSettingsForRepoRuntimeOwner(s, item.repoId ?? null)') + expect(section).toContain('getTaskSourceRuntimeSettings(sourceContext)') expect(section).toContain('useRepoAssigneesBySlug(') - expect(section).toContain('repoOwnerSettings') + expect(section).toContain('sourceSettings') expect(section).toContain('useRepoAssignees(') - expect(section).toContain('repoOwnerSettings') - expect(section).toContain('getActiveRuntimeTarget(repoOwnerSettings)') + expect(section).toContain('sourceSettings') + expect(section).toContain('getActiveRuntimeTarget(sourceSettings)') + expect(section).toContain('sourceContext,') + expect(section).toContain( + 'patchWorkItem(item.id, { reviewRequests: nextReviewRequests }, item.repoId, {' + ) + expect(section).toContain( + 'const runtimeRepo = getGitHubRuntimeRepoId(sourceContext, item.repoId)' + ) + expect(section).toContain("'github.requestPRReviewers'") + expect(section).toContain("'github.removePRReviewers'") + expect(section).toContain('{ repo: runtimeRepo, prNumber: item.number, reviewers: logins }') + expect(section).toContain('notifyWorkItemDetailsMutation(') + expect(section).toContain('{ local: false }') }) it('routes PR edit metadata through the same repo owner host as mutations', () => { @@ -34,11 +46,44 @@ describe('PullRequestPage host boundaries', () => { const section = sourceBetween(source, 'function GHEditSection', 'function GHCommentComposer') expect(section).toContain('getSettingsForRepoRuntimeOwner(s, item.repoId ?? repoId ?? null)') + expect(section).toContain('getTaskSourceRuntimeSettings(sourceContext)') expect(section).toContain('useRepoLabels(') - expect(section).toContain('useRepoLabelsBySlug(slugOwner, slugRepo, repoOwnerSettings)') + expect(section).toContain('useRepoLabelsBySlug(slugOwner, slugRepo, sourceSettings)') expect(section).toContain('useRepoAssignees(') expect(section).toContain('useRepoAssigneesBySlug(') - expect(section).toContain('repoOwnerSettings') + expect(section).toContain('sourceSettings') + }) + + it('source-scopes full-page optimistic work item patches', () => { + const source = componentSource('PullRequestPage.tsx') + const prAssigneesSection = sourceBetween( + source, + 'function PRAssigneesPanel', + 'function PRReviewersPanel' + ) + const prActionsSection = sourceBetween( + source, + 'function PRActionsPanel', + 'function CommentReactions' + ) + const issueEditSection = sourceBetween( + source, + 'function GHEditSection', + 'function GHCommentComposer' + ) + + expect(prAssigneesSection).toContain( + 'patchWorkItem(item.id, { assignees: nextAssignees }, item.repoId, { sourceContext })' + ) + expect(prActionsSection).toContain( + 'patchWorkItem(item.id, { state }, item.repoId, { sourceContext })' + ) + expect(issueEditSection).toContain( + 'patchWorkItem(item.id, { state: newState }, item.repoId, { sourceContext })' + ) + expect(issueEditSection).toContain( + 'patchWorkItem(item.id, { labels: newLabels }, item.repoId, { sourceContext })' + ) }) it('routes PR mention metadata through the PR repo owner host', () => { @@ -46,6 +91,213 @@ describe('PullRequestPage host boundaries', () => { const section = sourceBetween(source, 'function ConversationTab', 'const mentionOptions') expect(section).toContain('getSettingsForRepoRuntimeOwner(s, item.repoId ?? repoId ?? null)') - expect(section).toContain('useRepoAssignees(repoPath, item.repoId, repoOwnerSettings)') + expect(section).toContain('useRepoAssignees(repoPath, item.repoId, sourceSettings)') + }) + + it('uses source-aware initial details routing and cache identity', () => { + const source = componentSource('PullRequestPage.tsx') + const propsSection = sourceBetween( + source, + 'type PullRequestPageProps', + 'function formatRelativeTime' + ) + const cacheKeySection = sourceBetween( + source, + 'function getWorkItemDetailsCacheKey', + 'function touchWorkItemDetailsCache' + ) + const matchInvalidationSection = sourceBetween( + source, + 'function invalidateWorkItemDetailsCacheByMatch', + 'function patchCachedPRFileViewedState' + ) + + expect(propsSection).toContain('sourceContext?: TaskSourceContext | null') + expect(source).toContain('lookupGitHubWorkItemDetailsForSource({') + expect(source).toContain('sourceContext,') + expect(cacheKeySection).toContain('sourceCacheScope') + expect(source).toContain('getTaskSourceCacheScope(sourceContext)') + expect(matchInvalidationSection).toContain( + 'if (removed) {\n workItemDetailsCacheGeneration += 1' + ) + }) + + it('treats null details as unavailable while preserving empty detail payloads', () => { + const source = componentSource('PullRequestPage.tsx') + const loadedSection = sourceBetween( + source, + 'const loading = !!cachedEntry?.pending && !cachedEntry?.details', + '// Why: if a cross-window mutation invalidates' + ) + const resultSection = sourceBetween(source, 'inflight', '.catch((err) => {') + + expect(loadedSection).toContain('const detailsLoaded = Boolean(cachedEntry?.details)') + expect(loadedSection).not.toContain('fetchedAt > 0') + expect(resultSection).toContain('} else if (result === null) {') + expect(resultSection).toContain('error: WORK_ITEM_DETAILS_UNAVAILABLE_MESSAGE') + expect(resultSection).toContain('details: result') + }) + + it('routes file viewed mutations through the PR source context', () => { + const source = componentSource('PullRequestPage.tsx') + const helperSection = sourceBetween( + source, + 'function setPRFileViewedForRepo', + 'function PRViewedCheckbox' + ) + const changeSection = sourceBetween( + source, + 'const handlePRFileViewedChange = useCallback', + 'const ownerRepo = parseOwnerRepoFromItemUrl' + ) + + expect(helperSection).toContain('getGitHubSourceRuntimeHost(args.sourceContext)') + expect(helperSection).toContain("'github.setPRFileViewed'") + expect(helperSection).toContain('repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId)') + expect(helperSection).toContain('sourceContext: args.sourceContext') + expect(helperSection).toContain('{ local: false }') + expect(changeSection).toContain('canUseDetailsRepoContext') + expect(changeSection).toContain('repoPath: repoPath ??') + expect(changeSection).toContain('sourceContext,') + }) + + it('routes comment mutations through runtime source context when needed', () => { + const source = componentSource('PullRequestPage.tsx') + const helperSection = sourceBetween( + source, + 'function addIssueCommentForRepo', + 'function setPRFileViewedForRepo' + ) + const fileCommentSection = sourceBetween( + source, + 'const handleAddLineComment = useCallback', + 'const renderViewedCheckbox = useCallback' + ) + const conversationSection = sourceBetween( + source, + 'const handleReply = useCallback', + 'const rightPanel =' + ) + const composerSection = sourceBetween( + source, + 'const handleSubmit = useCallback', + 'const canSubmitComment =' + ) + + expect(helperSection).toContain('getGitHubSourceRuntimeHost(args.sourceContext)') + expect(helperSection).toContain("'github.addIssueComment'") + expect(helperSection).toContain("'github.addPRReviewComment'") + expect(helperSection).toContain("'github.addPRReviewCommentReply'") + expect(helperSection).toContain('repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId)') + expect(helperSection).toContain('sourceContext: args.sourceContext') + expect(helperSection).toContain('notifyWorkItemDetailsMutation(') + expect(helperSection).toContain('{ local: false }') + expect(fileCommentSection).toContain('sourceContext,') + expect(conversationSection).toContain('sourceContext,') + expect(composerSection).toContain('sourceContext,') + }) + + it('routes PR file contents and runtime viewed invalidations through the PR source context', () => { + const source = componentSource('PullRequestPage.tsx') + const fileContentsSection = sourceBetween( + source, + 'function loadPRFileContents', + 'function setPRFileViewedForRepo' + ) + const fileContentsCacheKeySection = sourceBetween( + source, + 'function getPRFileContentCacheKey', + 'function loadPRFileContents' + ) + const listenerSection = sourceBetween(source, 'let workItemMutatedUnsub', '// Why: bounded LRU') + const commentContextSection = sourceBetween( + source, + 'function CommentCodeContext', + 'const resolvedContextExpansionState' + ) + + expect(fileContentsCacheKeySection).toContain( + 'source:${getTaskSourceCacheScope(args.sourceContext)}' + ) + expect(fileContentsSection).toContain("'github.prFileContents'") + expect(fileContentsSection).toContain( + 'repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId)' + ) + expect(fileContentsSection).toContain('sourceContext: args.sourceContext') + expect(fileContentsSection).toContain('sourceContext,') + expect(listenerSection).toContain('onGitHubWorkItemDetailsCacheMutation') + expect(source).toContain('emitGitHubWorkItemDetailsCacheMutation(args)') + expect(source).toContain('options.local !== false') + expect(source).toContain('notifyWorkItemMutated({') + expect(commentContextSection).toContain('sourceContext?: TaskSourceContext | null') + expect(commentContextSection).toContain('sourceContext, prNumber') + }) + + it('routes check actions through the PR source context', () => { + const source = componentSource('PullRequestPage.tsx') + const checksSection = sourceBetween(source, 'function ChecksTab', 'function MentionTextarea') + + expect(checksSection).toContain('sourceContext?: TaskSourceContext | null') + expect(checksSection).toContain('sourceContext,') + expect(checksSection).toContain("'github.prChecks'") + expect(checksSection).toContain("'github.rerunPRChecks'") + expect(checksSection).toContain("'github.prCheckDetails'") + expect(checksSection).toContain( + 'repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId)' + ) + expect(checksSection).toContain('window.api.gh.prChecks({') + expect(checksSection).toContain('window.api.gh.rerunPRChecks({') + expect(checksSection).toContain('prCheckDetails({') + }) + + it('routes edit metadata and mutations through the PR source context', () => { + const source = componentSource('PullRequestPage.tsx') + const editHelperSection = sourceBetween( + source, + 'function getGitHubMutationSettings', + 'function GHCommentComposer' + ) + const editSection = sourceBetween( + source, + 'function GHEditSection', + 'function GHCommentComposer' + ) + + expect(editHelperSection).toContain("'github.updateIssue'") + expect(editHelperSection).toContain("'github.updatePRState'") + expect(editHelperSection).toContain("'github.project.updateIssueBySlug'") + expect(editHelperSection).toContain("'github.project.updatePullRequestBySlug'") + expect(editHelperSection).toContain('sourceContext?: TaskSourceContext | null') + expect(editHelperSection).toContain("args.sourceContext?.provider === 'github'") + expect(editHelperSection).toContain('getTaskSourceRuntimeSettings(args.sourceContext)') + expect(editHelperSection).toContain( + "repo: getGitHubRuntimeRepoId(args.sourceContext, args.repoId ?? '')" + ) + expect(editHelperSection).toContain('{ local: false }') + expect(editSection).toContain('getTaskSourceRuntimeSettings(sourceContext)') + expect(editSection).toContain('sourceContext,') + }) + + it('routes merge actions through the PR source context', () => { + const source = componentSource('PullRequestPage.tsx') + const actionsSection = sourceBetween( + source, + 'function PRActionsPanel', + 'function CommentReactions' + ) + + expect(actionsSection).toContain('getTaskSourceRuntimeSettings(sourceContext)') + expect(actionsSection).toContain('getActiveRuntimeTarget(sourceSettings)') + expect(actionsSection).toContain( + 'const canMergeWithRepoContext = !!repoPath || mergeTarget.kind ===' + ) + expect(actionsSection).toContain("'github.mergePR'") + expect(actionsSection).toContain("'github.setPRAutoMerge'") + expect(actionsSection).toContain( + 'repo: getGitHubRuntimeRepoId(sourceContext, repoId ?? item.repoId)' + ) + expect(actionsSection).toContain('sourceContext,') + expect(actionsSection).toContain('notifyWorkItemDetailsMutation(') + expect(actionsSection).toContain('{ local: false }') }) }) diff --git a/src/renderer/src/components/task-page-source-switch-boundary.test.ts b/src/renderer/src/components/task-page-source-switch-boundary.test.ts index 1b1d98786a72..b54683a2f6fc 100644 --- a/src/renderer/src/components/task-page-source-switch-boundary.test.ts +++ b/src/renderer/src/components/task-page-source-switch-boundary.test.ts @@ -27,6 +27,8 @@ describe('TaskPage source switching host boundary', () => { expect(modalSection).toContain('selectedRepoIds={repoSelection}') expect(detailSection).toContain('workItem={dialogWorkItem}') + expect(detailSection).toContain(' { + it('detects runtime-owned GitHub sources', () => { + expect(getGitHubSourceRuntimeHost(runtimeSourceContext)).toEqual({ + kind: 'runtime', + id: 'runtime:env-1', + environmentId: 'env-1' + }) + expect(getGitHubSourceRuntimeTarget(runtimeSourceContext)).toEqual({ + kind: 'environment', + environmentId: 'env-1' + }) + }) + + it('does not treat non-runtime or non-GitHub sources as runtime GitHub sources', () => { + expect(getGitHubSourceRuntimeHost({ ...runtimeSourceContext, hostId: 'local' })).toBeNull() + expect(getGitHubSourceRuntimeHost({ ...runtimeSourceContext, provider: 'gitlab' })).toBeNull() + expect(getGitHubSourceRuntimeTarget({ ...runtimeSourceContext, provider: 'gitlab' })).toEqual({ + kind: 'local' + }) + }) + + it('allows a repo context from either a local path or runtime source', () => { + expect(canUseGitHubRepoContext('', runtimeSourceContext)).toBe(true) + expect(canUseGitHubRepoContext('C:\\workspace\\repo', null)).toBe(true) + expect(canUseGitHubRepoContext('', { ...runtimeSourceContext, hostId: 'local' })).toBe(false) + }) + + it('uses the source repo id for GitHub runtime calls when available', () => { + expect(getGitHubRuntimeRepoId(runtimeSourceContext, 'fallback-repo')).toBe('runtime-repo') + expect(getGitHubRuntimeRepoId({ ...runtimeSourceContext, repoId: null }, 'fallback-repo')).toBe( + 'fallback-repo' + ) + expect( + getGitHubRuntimeRepoId({ ...runtimeSourceContext, provider: 'gitlab' }, 'fallback') + ).toBe('fallback') + }) +}) diff --git a/src/renderer/src/lib/github-source-runtime-context.ts b/src/renderer/src/lib/github-source-runtime-context.ts new file mode 100644 index 000000000000..617970335556 --- /dev/null +++ b/src/renderer/src/lib/github-source-runtime-context.ts @@ -0,0 +1,49 @@ +import type { ParsedExecutionHost } from '../../../shared/execution-host' +import { parseExecutionHostId } from '../../../shared/execution-host' +import type { TaskSourceContext } from '../../../shared/task-source-context' +import { getTaskSourceRuntimeSettings } from '../../../shared/task-source-context' +import type { RuntimeClientTarget } from '@/runtime/runtime-rpc-client' +import { getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' + +export type GitHubRuntimeHost = Extract + +export function getGitHubSourceRuntimeHost( + sourceContext: TaskSourceContext | null | undefined +): GitHubRuntimeHost | null { + if (sourceContext?.provider !== 'github') { + return null + } + const parsedHost = parseExecutionHostId(sourceContext.hostId) + return parsedHost?.kind === 'runtime' ? parsedHost : null +} + +export function getGitHubSourceRuntimeTarget( + sourceContext: TaskSourceContext | null | undefined +): RuntimeClientTarget { + return getActiveRuntimeTarget( + getTaskSourceRuntimeSettings(sourceContext?.provider === 'github' ? sourceContext : null) + ) +} + +export function canUseGitHubRepoContext( + repoPath: string | null | undefined, + sourceContext: TaskSourceContext | null | undefined +): boolean { + return Boolean(repoPath) || getGitHubSourceRuntimeHost(sourceContext) !== null +} + +export function getGitHubRuntimeRepoId( + sourceContext: TaskSourceContext | null | undefined, + fallbackRepoId: string +): string +export function getGitHubRuntimeRepoId( + sourceContext: TaskSourceContext | null | undefined, + fallbackRepoId: string | null | undefined +): string | undefined +export function getGitHubRuntimeRepoId( + sourceContext: TaskSourceContext | null | undefined, + fallbackRepoId: string | null | undefined +): string | undefined { + const fallback = fallbackRepoId ?? undefined + return sourceContext?.provider === 'github' ? (sourceContext.repoId ?? fallback) : fallback +} diff --git a/src/renderer/src/lib/github-work-item-details-cache-events.ts b/src/renderer/src/lib/github-work-item-details-cache-events.ts new file mode 100644 index 000000000000..ffdda51893e2 --- /dev/null +++ b/src/renderer/src/lib/github-work-item-details-cache-events.ts @@ -0,0 +1,32 @@ +import type { TaskSourceContext } from '../../../shared/task-source-context' + +export type GitHubWorkItemDetailsCacheMutation = { + repoPath: string + repoId?: string + sourceContext?: TaskSourceContext | null + type: 'issue' | 'pr' + number: number +} + +const GITHUB_WORK_ITEM_DETAILS_CACHE_MUTATED_EVENT = 'orca:github-work-item-details-cache-mutated' + +export function emitGitHubWorkItemDetailsCacheMutation( + payload: GitHubWorkItemDetailsCacheMutation +): void { + window.dispatchEvent( + new CustomEvent( + GITHUB_WORK_ITEM_DETAILS_CACHE_MUTATED_EVENT, + { detail: payload } + ) + ) +} + +export function onGitHubWorkItemDetailsCacheMutation( + listener: (payload: GitHubWorkItemDetailsCacheMutation) => void +): () => void { + const handler = (event: Event): void => { + listener((event as CustomEvent).detail) + } + window.addEventListener(GITHUB_WORK_ITEM_DETAILS_CACHE_MUTATED_EVENT, handler) + return () => window.removeEventListener(GITHUB_WORK_ITEM_DETAILS_CACHE_MUTATED_EVENT, handler) +} diff --git a/src/renderer/src/lib/github-work-item-source-lookup.test.ts b/src/renderer/src/lib/github-work-item-source-lookup.test.ts new file mode 100644 index 000000000000..48e78ff96ddb --- /dev/null +++ b/src/renderer/src/lib/github-work-item-source-lookup.test.ts @@ -0,0 +1,126 @@ +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 { lookupGitHubWorkItemDetailsForSource } from './github-work-item-source-lookup' +import type { TaskSourceContext } from '../../../shared/task-source-context' + +vi.mock('@/runtime/runtime-rpc-client', async () => { + const actual = await vi.importActual('@/runtime/runtime-rpc-client') + return { + ...actual, + callRuntimeRpc: vi.fn() + } +}) + +const runtimeSourceContext: TaskSourceContext = { + kind: 'task-source', + provider: 'github', + projectId: 'project-1', + hostId: 'runtime:env-1', + repoId: 'runtime-repo' +} + +describe('GitHub source lookup routing', () => { + beforeEach(() => { + vi.mocked(callRuntimeRpc).mockReset() + vi.stubGlobal('window', { + api: { + gh: { + workItemDetails: vi.fn() + } + } + }) + }) + + it('routes runtime-owned GitHub details through runtime RPC', async () => { + vi.mocked(callRuntimeRpc).mockResolvedValue(null) + + await expect( + lookupGitHubWorkItemDetailsForSource({ + repoPath: '/home/runtime/app', + repoId: 'renderer-repo', + sourceContext: runtimeSourceContext, + number: 42, + type: 'issue' + }) + ).resolves.toBeNull() + + expect(callRuntimeRpc).toHaveBeenCalledWith( + { kind: 'environment', environmentId: 'env-1' }, + 'github.workItemDetails', + { repo: 'runtime-repo', number: 42, type: 'issue' }, + { timeoutMs: 30_000 } + ) + expect(window.api.gh.workItemDetails).not.toHaveBeenCalled() + }) + + // Regression for #6429: a runtime-sourced details lookup must never reach the + // local Electron IPC, which rejects unregistered remote repos with + // "Access denied: unknown repository path". On main this routed through + // window.api.gh.workItemDetails and surfaced that error. + it('does not invoke the local IPC (which throws access-denied) for runtime sources', async () => { + vi.mocked(callRuntimeRpc).mockResolvedValue(null) + vi.mocked(window.api.gh.workItemDetails).mockRejectedValue( + new Error('Access denied: unknown repository path') + ) + + await expect( + lookupGitHubWorkItemDetailsForSource({ + repoPath: '/home/runtime/app', + repoId: 'renderer-repo', + sourceContext: runtimeSourceContext, + number: 42, + type: 'issue' + }) + ).resolves.toBeNull() + + expect(window.api.gh.workItemDetails).not.toHaveBeenCalled() + }) + + it('uses the renderer repo id for runtime details when the source has no repo id', async () => { + vi.mocked(callRuntimeRpc).mockResolvedValue(null) + + await lookupGitHubWorkItemDetailsForSource({ + repoPath: '/home/runtime/app', + repoId: 'renderer-repo', + sourceContext: { ...runtimeSourceContext, repoId: null }, + number: 42, + type: 'pr' + }) + + expect(callRuntimeRpc).toHaveBeenCalledWith( + { kind: 'environment', environmentId: 'env-1' }, + 'github.workItemDetails', + { repo: 'renderer-repo', number: 42, type: 'pr' }, + { timeoutMs: 30_000 } + ) + }) + + it('keeps local GitHub details on Electron IPC with source context', async () => { + vi.mocked(window.api.gh.workItemDetails).mockResolvedValue(null) + const sourceContext: TaskSourceContext = { + ...runtimeSourceContext, + hostId: 'local', + repoId: 'local-repo' + } + + await expect( + lookupGitHubWorkItemDetailsForSource({ + repoPath: 'C:\\workspace\\app', + repoId: 'local-repo', + sourceContext, + number: 42, + type: 'issue' + }) + ).resolves.toBeNull() + + expect(window.api.gh.workItemDetails).toHaveBeenCalledWith({ + repoPath: 'C:\\workspace\\app', + repoId: 'local-repo', + sourceContext, + number: 42, + type: 'issue' + }) + expect(callRuntimeRpc).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/lib/github-work-item-source-lookup.ts b/src/renderer/src/lib/github-work-item-source-lookup.ts index cfba24b672c2..e12de08b3b0a 100644 --- a/src/renderer/src/lib/github-work-item-source-lookup.ts +++ b/src/renderer/src/lib/github-work-item-source-lookup.ts @@ -1,7 +1,11 @@ -import type { GitHubWorkItem } from '../../../shared/types' +import type { GitHubWorkItem, GitHubWorkItemDetails } from '../../../shared/types' import type { TaskSourceContext } from '../../../shared/task-source-context' -import { getTaskSourceRuntimeSettings } from '../../../shared/task-source-context' -import { callRuntimeRpc, getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client' +import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' +import { + getGitHubRuntimeRepoId, + getGitHubSourceRuntimeHost, + getGitHubSourceRuntimeTarget +} from './github-source-runtime-context' type GitHubWorkItemLookupArgs = { repoPath: string @@ -17,14 +21,22 @@ type GitHubWorkItemByOwnerRepoLookupArgs = GitHubWorkItemLookupArgs & { type: 'issue' | 'pr' } +type GitHubWorkItemDetailsLookupArgs = { + repoPath: string + repoId: string + sourceContext?: TaskSourceContext | null + number: number + type: 'issue' | 'pr' +} + function runtimeRepoId(args: Pick): string { - return args.sourceContext?.repoId ?? args.repoId + return getGitHubRuntimeRepoId(args.sourceContext, args.repoId) } export async function lookupGitHubWorkItemForSource( args: GitHubWorkItemLookupArgs ): Promise { - const target = getActiveRuntimeTarget(getTaskSourceRuntimeSettings(args.sourceContext)) + const target = getGitHubSourceRuntimeTarget(args.sourceContext) const item = target.kind === 'environment' ? await callRuntimeRpc | null>( @@ -49,7 +61,7 @@ export async function lookupGitHubWorkItemForSource( export async function lookupGitHubWorkItemByOwnerRepoForSource( args: GitHubWorkItemByOwnerRepoLookupArgs ): Promise { - const target = getActiveRuntimeTarget(getTaskSourceRuntimeSettings(args.sourceContext)) + const target = getGitHubSourceRuntimeTarget(args.sourceContext) const item = target.kind === 'environment' ? await callRuntimeRpc | null>( @@ -74,3 +86,29 @@ export async function lookupGitHubWorkItemByOwnerRepoForSource( }) return item ? ({ ...item, repoId: args.repoId } as GitHubWorkItem) : null } + +export function lookupGitHubWorkItemDetailsForSource( + args: GitHubWorkItemDetailsLookupArgs +): Promise { + const sourceContext = args.sourceContext + const runtimeHost = getGitHubSourceRuntimeHost(sourceContext) + if (runtimeHost) { + return callRuntimeRpc( + { kind: 'environment', environmentId: runtimeHost.environmentId }, + 'github.workItemDetails', + { + repo: getGitHubRuntimeRepoId(sourceContext, args.repoId), + number: args.number, + type: args.type + }, + { timeoutMs: 30_000 } + ) + } + return window.api.gh.workItemDetails({ + repoPath: args.repoPath, + repoId: args.repoId, + sourceContext, + number: args.number, + type: args.type + }) +} diff --git a/src/renderer/src/web/web-preload-api.test.ts b/src/renderer/src/web/web-preload-api.test.ts index 08b3d91f78ab..5e531e0e1743 100644 --- a/src/renderer/src/web/web-preload-api.test.ts +++ b/src/renderer/src/web/web-preload-api.test.ts @@ -1952,6 +1952,7 @@ describe('web GitHub preload API', () => { 'listProjectViews', 'listWorkItems', 'mergePR', + 'notifyWorkItemMutated', 'onPRRefreshEvent', 'onWorkItemMutated', 'prCheckDetails', diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index eee02f7627ca..1178ebe89658 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1736,6 +1736,7 @@ function createGitHubApi(): WebGitHubApi { }), workItemDetails: (args) => route>(GITHUB_WEB_RPC_METHODS.workItemDetails, args), + notifyWorkItemMutated: () => Promise.resolve(false), prFileContents: (args) => route>(GITHUB_WEB_RPC_METHODS.prFileContents, args), listIssues: (args) =>