From 7686eaba2d03383c89f72086af0745a8b020abac Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sat, 30 May 2026 18:33:31 -0700 Subject: [PATCH] fix: address review findings (#3968) --- src/main/github/client.ts | 11 +- src/main/github/issues.ts | 11 +- src/main/ipc/github.ts | 17 +- src/main/runtime/orca-runtime.ts | 16 +- src/main/runtime/rpc/methods/github.test.ts | 14 +- src/main/runtime/rpc/methods/github.ts | 11 +- src/main/runtime/runtime-rpc.test.ts | 5 +- src/preload/api-types.ts | 2 + src/preload/index.ts | 2 + .../components/right-sidebar/ChecksPanel.tsx | 290 ++++- .../checks-panel-content.test.tsx | 79 +- .../right-sidebar/checks-panel-content.tsx | 1123 ++++++++++++++--- .../right-panel-comment-composer.tsx | 237 ++++ src/renderer/src/store/slices/github.test.ts | 245 +++- src/renderer/src/store/slices/github.ts | 256 +++- 15 files changed, 2100 insertions(+), 219 deletions(-) create mode 100644 src/renderer/src/components/right-sidebar/right-panel-comment-composer.tsx diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 0bb6fcd25..883e6cab6 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -3008,10 +3008,11 @@ export async function addPRReviewCommentReply( threadId?: string, path?: string, line?: number, - connectionId?: string | null + connectionId?: string | null, + prRepo?: OwnerRepo | null ): Promise { const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId)) - const ownerRepo = await getOwnerRepo(repoPath, connectionId) + const ownerRepo = prRepo ?? (await getOwnerRepo(repoPath, connectionId)) if (!ownerRepo) { return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' } } @@ -3028,9 +3029,13 @@ export async function addPRReviewCommentReply( ], ghOptions ) + const data = JSON.parse(stdout) as Parameters[0] + if (typeof data.id !== 'number' || !Number.isSafeInteger(data.id) || data.id < 1) { + return { ok: false, error: 'Unexpected response from GitHub' } + } return { ok: true, - comment: mapReviewCommentResponse(JSON.parse(stdout), body, path, line, undefined, threadId) + comment: mapReviewCommentResponse(data, body, path, line, undefined, threadId) } } catch (err) { const stderr = err instanceof Error ? err.message : String(err) diff --git a/src/main/github/issues.ts b/src/main/github/issues.ts index de9ed513a..6322e60dd 100644 --- a/src/main/github/issues.ts +++ b/src/main/github/issues.ts @@ -13,6 +13,7 @@ import type { PRComment } from '../../shared/types' import { mapIssueInfo } from './mappers' +import type { OwnerRepo } from './gh-utils' // prettier-ignore import { ghExecFileAsync, acquire, release, getIssueOwnerRepo, resolveIssueSource, classifyGhError, classifyListIssuesError, ghRepoExecOptions, githubRepoContext } from './gh-utils' @@ -330,11 +331,12 @@ export async function addIssueComment( repoPath: string, issueNumber: number, body: string, - connectionId?: string | null + connectionId?: string | null, + ownerRepoOverride?: OwnerRepo | null ): Promise { const context = githubRepoContext(repoPath, connectionId) const ghOptions = ghRepoExecOptions(context) - const ownerRepo = await getIssueOwnerRepo(repoPath, connectionId) + const ownerRepo = ownerRepoOverride ?? (await getIssueOwnerRepo(repoPath, connectionId)) if (!ownerRepo) { return { ok: false, error: 'Could not resolve GitHub owner/repo for this repository' } } @@ -358,8 +360,11 @@ export async function addIssueComment( created_at?: string html_url?: string } + if (typeof data.id !== 'number' || !Number.isSafeInteger(data.id) || data.id < 1) { + return { ok: false, error: 'Unexpected response from GitHub' } + } const comment: PRComment = { - id: data.id ?? Date.now(), + id: data.id, author: data.user?.login ?? 'You', authorAvatarUrl: data.user?.avatar_url ?? '', body: data.body ?? body, diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts index e4cd93469..5156d19c7 100644 --- a/src/main/ipc/github.ts +++ b/src/main/ipc/github.ts @@ -528,12 +528,14 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi event, args: { repoPath: string + repoId?: string prNumber: number commentId: number body: string threadId?: string path?: string line?: number + prRepo?: GitHubOwnerRepo | null } ) => { const repo = assertRegisteredRepo(args, store) @@ -562,7 +564,8 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi args.threadId, args.path, args.line, - repoConnectionId(repo) + repoConnectionId(repo), + args.prRepo ?? null ) if (result.ok) { broadcastWorkItemMutated( @@ -840,7 +843,14 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi 'gh:addIssueComment', async ( event, - args: { repoPath: string; number: number; body: string; type?: 'issue' | 'pr' } + args: { + repoPath: string + repoId?: string + number: number + body: string + type?: 'issue' | 'pr' + prRepo?: GitHubOwnerRepo | null + } ) => { const repo = assertRegisteredRepo(args, store) if (typeof args.number !== 'number' || !Number.isInteger(args.number) || args.number < 1) { @@ -853,7 +863,8 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi repo.path, args.number, args.body.trim(), - repoConnectionId(repo) + repoConnectionId(repo), + args.prRepo ?? null ) if (result.ok) { // Why: PR conversation comments hit `/issues/N/comments` too, but the diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 57e2c3757..15db685ad 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -6374,8 +6374,11 @@ export class OrcaRuntimeService { } ): Promise>> { const repo = await this.resolveRepoSelector(repoSelector) - this.assertHostIntegrationRepoIsLocal(repo, 'repo_pr_check_details') - return getPRCheckDetails(repo.path, { ...args, prRepo: args.prRepo ?? null }) + return getPRCheckDetails( + repo.path, + { ...args, prRepo: args.prRepo ?? null }, + repo.connectionId ?? null + ) } async getRepoPRComments( @@ -6534,10 +6537,11 @@ export class OrcaRuntimeService { async addRepoIssueComment( repoSelector: string, number: number, - body: string + body: string, + prRepo?: GitHubOwnerRepo | null ): Promise>> { const repo = await this.resolveRepoSelector(repoSelector) - return addIssueComment(repo.path, number, body, repo.connectionId ?? null) + return addIssueComment(repo.path, number, body, repo.connectionId ?? null, prRepo ?? null) } async addRepoPRReviewComment( @@ -6561,6 +6565,7 @@ export class OrcaRuntimeService { threadId?: string path?: string line?: number + prRepo?: GitHubOwnerRepo | null } ): Promise>> { const repo = await this.resolveRepoSelector(repoSelector) @@ -6572,7 +6577,8 @@ export class OrcaRuntimeService { args.threadId, args.path, args.line, - repo.connectionId ?? null + repo.connectionId ?? null, + args.prRepo ?? null ) } diff --git a/src/main/runtime/rpc/methods/github.test.ts b/src/main/runtime/rpc/methods/github.test.ts index c8b5a37a5..1311b52a4 100644 --- a/src/main/runtime/rpc/methods/github.test.ts +++ b/src/main/runtime/rpc/methods/github.test.ts @@ -519,11 +519,15 @@ describe('github RPC methods', () => { repo: 'repo-1', number: 3, body: 'Looks good', - type: 'pr' + type: 'pr', + prRepo: { owner: 'acme', repo: 'widgets' } }) ) - expect(runtime.addRepoIssueComment).toHaveBeenCalledWith('repo-1', 3, 'Looks good') + expect(runtime.addRepoIssueComment).toHaveBeenCalledWith('repo-1', 3, 'Looks good', { + owner: 'acme', + repo: 'widgets' + }) expect(response).toMatchObject({ ok: true, result: { ok: true, comment: { id: 1 } } }) }) @@ -572,7 +576,8 @@ describe('github RPC methods', () => { body: 'Done', threadId: 'PRRT_1', path: 'src/app.ts', - line: 12 + line: 12, + prRepo: { owner: 'acme', repo: 'widgets' } }) ) @@ -582,7 +587,8 @@ describe('github RPC methods', () => { body: 'Done', threadId: 'PRRT_1', path: 'src/app.ts', - line: 12 + line: 12, + prRepo: { owner: 'acme', repo: 'widgets' } }) expect(response).toMatchObject({ ok: true, result: { ok: true, comment: { id: 4 } } }) }) diff --git a/src/main/runtime/rpc/methods/github.ts b/src/main/runtime/rpc/methods/github.ts index 599956f40..4c6db9b58 100644 --- a/src/main/runtime/rpc/methods/github.ts +++ b/src/main/runtime/rpc/methods/github.ts @@ -171,7 +171,8 @@ const UpdateIssue = RepoSelector.extend({ const IssueComment = RepoSelector.extend({ number: z.number().int().positive(), body: requiredString('Comment body required'), - type: z.enum(['issue', 'pr']).optional() + type: z.enum(['issue', 'pr']).optional(), + prRepo: SlugRepo.nullable().optional() }) const PRReviewComment = RepoSelector.extend({ @@ -189,7 +190,8 @@ const PRReviewCommentReply = RepoSelector.extend({ body: requiredString('Comment body required'), threadId: OptionalString, path: OptionalString, - line: z.number().int().positive().optional() + line: z.number().int().positive().optional(), + prRepo: SlugRepo.nullable().optional() }) const ProjectOwnerType = z.enum(['organization', 'user']) @@ -500,7 +502,7 @@ export const GITHUB_METHODS: RpcMethod[] = [ name: 'github.addIssueComment', params: IssueComment, handler: async (params, { runtime }) => - runtime.addRepoIssueComment(params.repo, params.number, params.body) + runtime.addRepoIssueComment(params.repo, params.number, params.body, params.prRepo ?? null) }), defineMethod({ name: 'github.addPRReviewComment', @@ -525,7 +527,8 @@ export const GITHUB_METHODS: RpcMethod[] = [ body: params.body, threadId: params.threadId, path: params.path, - line: params.line + line: params.line, + prRepo: params.prRepo ?? null }) }), defineMethod({ diff --git a/src/main/runtime/runtime-rpc.test.ts b/src/main/runtime/runtime-rpc.test.ts index cea3a6e55..1472ca073 100644 --- a/src/main/runtime/runtime-rpc.test.ts +++ b/src/main/runtime/runtime-rpc.test.ts @@ -1749,7 +1749,7 @@ describe('OrcaRuntimeRpcServer', () => { }) expect(listRepoLabels).toHaveBeenCalledWith('id:repo-1') expect(listRepoAssignableUsers).toHaveBeenCalledWith('id:repo-1') - expect(addRepoIssueComment).toHaveBeenCalledWith('id:repo-1', 123, 'done') + expect(addRepoIssueComment).toHaveBeenCalledWith('id:repo-1', 123, 'done', null) expect(addRepoPRReviewComment).toHaveBeenCalledWith('id:repo-1', { prNumber: 456, commitId: 'abc123', @@ -1764,7 +1764,8 @@ describe('OrcaRuntimeRpcServer', () => { body: 'fixed', threadId: 'thread-1', path: 'src/app.ts', - line: 10 + line: 10, + prRepo: null }) expect(getRepoPRFileContents).toHaveBeenCalledWith('id:repo-1', { prNumber: 456, diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 2f8792668..03b02e0fb 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1072,6 +1072,7 @@ export type PreloadApi = { * scope the cross-window invalidation broadcast correctly and avoid * evicting an unrelated PR/issue that happens to share the number. */ type?: 'issue' | 'pr' + prRepo?: GitHubOwnerRepo | null }) => Promise addPRReviewCommentReply: (args: { repoPath: string @@ -1082,6 +1083,7 @@ export type PreloadApi = { threadId?: string path?: string line?: number + prRepo?: GitHubOwnerRepo | null }) => Promise addPRReviewComment: ( args: GitHubPRReviewCommentInput & { repoId?: string } diff --git a/src/preload/index.ts b/src/preload/index.ts index c48133e05..6cbcdfdd9 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1027,6 +1027,7 @@ const api = { number: number body: string type?: 'issue' | 'pr' + prRepo?: { owner: string; repo: string } | null }): Promise => ipcRenderer.invoke('gh:addIssueComment', args), addPRReviewCommentReply: (args: { @@ -1038,6 +1039,7 @@ const api = { threadId?: string path?: string line?: number + prRepo?: { owner: string; repo: string } | null }): Promise => ipcRenderer.invoke('gh:addPRReviewCommentReply', args), addPRReviewComment: (args: { diff --git a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx index f43d86173..a941305ea 100644 --- a/src/renderer/src/components/right-sidebar/ChecksPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ChecksPanel.tsx @@ -3,7 +3,11 @@ merge actions, and conflict state in one component to keep the data flow straigh import React, { useCallback, useEffect, useRef, useState } from 'react' import { LoaderCircle, ExternalLink, RefreshCw, Check, X, Pencil, GitMerge } from 'lucide-react' import { useAppStore } from '@/store' -import { prChecksCacheSuffix, prCommentsCacheSuffix } from '@/store/slices/github' +import { + mergePRCommentIntoList, + prChecksCacheSuffix, + prCommentsCacheSuffix +} from '@/store/slices/github' import { getGitHubPRCacheKey, getGitHubRepoCacheKey } from '@/store/slices/github-cache-key' import { useActiveWorktree, useRepoById } from '@/store/selectors' import { cn } from '@/lib/utils' @@ -16,7 +20,8 @@ import { ConflictingFilesSection, MergeConflictNotice, ChecksList, - PRCommentsList + PRCommentsList, + PRTriageStrip } from './checks-panel-content' import { ENTRY_REFRESH_GRACE_MS, shouldEntryRefresh } from './checks-entry-refresh' import type { @@ -177,8 +182,18 @@ export default function ChecksPanel(): React.JSX.Element { const isPanelVisible = rightSidebarOpen && rightSidebarTab === 'checks' const fetchPRChecks = useAppStore((s) => s.fetchPRChecks) + const fetchPRCheckDetails = useAppStore((s) => s.fetchPRCheckDetails) const fetchPRComments = useAppStore((s) => s.fetchPRComments) + const addPRConversationComment = useAppStore((s) => s.addPRConversationComment) + const addPRReviewCommentReply = useAppStore((s) => s.addPRReviewCommentReply) const resolveReviewThread = useAppStore((s) => s.resolveReviewThread) + const detectedAgentIds = useAppStore((s) => s.detectedAgentIds) + const remoteDetectedAgentIds = useAppStore((s) => { + const connectionId = activeWorktreeId ? getConnectionId(activeWorktreeId) : undefined + return typeof connectionId === 'string' + ? (s.remoteDetectedAgentIds[connectionId] ?? null) + : null + }) const [checks, setChecks] = useState([]) const [checksLoading, setChecksLoading] = useState(false) @@ -981,6 +996,26 @@ export default function ChecksPanel(): React.JSX.Element { ] ) + const handleLoadCheckDetails = useCallback( + (check: PRCheckDetail) => { + if (!repo) { + return Promise.resolve(null) + } + return fetchPRCheckDetails( + repo.path, + { + checkRunId: check.checkRunId, + workflowRunId: check.workflowRunId, + checkName: check.name, + url: check.url, + prRepo: pr?.prRepo ?? null + }, + { repoId: repo.id } + ) + }, + [fetchPRCheckDetails, pr?.prRepo, repo] + ) + useEffect(() => { if (activeGitLabReview) { return @@ -989,19 +1024,24 @@ export default function ChecksPanel(): React.JSX.Element { setComments([]) return } - // Why: without this guard a slow response from a previous PR can overwrite - // state after the user switches worktrees, showing the wrong PR's comments. let cancelled = false + const requestKey = checksPanelAsyncResultKey( + prCacheKey, + branch, + prNumber, + pr?.prRepo, + pr?.headSha + ) setCommentsLoading(true) void fetchPRComments(repo.path, prNumber, { repoId: repo.id, prRepo: pr?.prRepo }).then( (result) => { - if (!cancelled) { + if (!cancelled && isCurrentAsyncResult(requestKey)) { setComments(result) setCommentsLoading(false) } }, () => { - if (!cancelled) { + if (!cancelled && isCurrentAsyncResult(requestKey)) { setComments([]) setCommentsLoading(false) } @@ -1010,7 +1050,32 @@ export default function ChecksPanel(): React.JSX.Element { return () => { cancelled = true } - }, [activeGitLabReview, repo, prNumber, pr?.prRepo, prCacheKey, isPanelVisible, fetchPRComments]) + }, [ + activeGitLabReview, + repo, + prNumber, + pr?.headSha, + pr?.prRepo, + prCacheKey, + branch, + isPanelVisible, + fetchPRComments, + isCurrentAsyncResult + ]) + + useEffect(() => { + if (activeGitLabReview || !repo || !prNumber || !isPanelVisible) { + return undefined + } + return window.api.gh.onWorkItemMutated((payload) => { + const sameRepo = + payload.repoId != null ? payload.repoId === repo.id : payload.repoPath === repo.path + if (!sameRepo || payload.type !== 'pr' || payload.number !== prNumber) { + return + } + void fetchComments({ force: true }) + }) + }, [activeGitLabReview, fetchComments, isPanelVisible, prNumber, repo]) const handleRefresh = useCallback(async () => { if (!repo || !branch) { @@ -1355,25 +1420,156 @@ export default function ChecksPanel(): React.JSX.Element { ) const handleResolve = useCallback( - (threadId: string, resolve: boolean) => { + async (threadId: string, resolve: boolean): Promise => { if (!repo || !prNumber) { - return + return false } - void resolveReviewThread(repo.path, prNumber, threadId, resolve, { + const requestKey = checksPanelAsyncResultKey( + prCacheKey, + branch, + prNumber, + pr?.prRepo, + pr?.headSha + ) + const previousComments = comments + setComments((prev) => + prev.map((comment) => + comment.threadId === threadId ? { ...comment, isResolved: resolve } : comment + ) + ) + const ok = await resolveReviewThread(repo.path, prNumber, threadId, resolve, { repoId: repo.id, prRepo: pr?.prRepo - }).then((ok) => { - if (ok) { - // Update local state to match the optimistic store update - setComments((prev) => - prev.map((c) => (c.threadId === threadId ? { ...c, isResolved: resolve } : c)) - ) - } else { - toast.error('Could not update review thread. Check the GitHub API budget.') - } }) + if (!isCurrentAsyncResult(requestKey)) { + return ok + } + if (!ok) { + setComments(previousComments) + toast.error('Could not update review thread. Check the GitHub API budget.') + } + return ok }, - [repo, prNumber, pr?.prRepo, resolveReviewThread] + [ + branch, + comments, + isCurrentAsyncResult, + pr?.headSha, + pr?.prRepo, + prCacheKey, + prNumber, + repo, + resolveReviewThread + ] + ) + + const canTargetPRComments = Boolean(repo && prNumber && pr?.prRepo) + const commentsDisabledReason = canTargetPRComments + ? undefined + : 'Commenting requires a GitHub PR repository target.' + const activeConnectionId = activeWorktreeId ? getConnectionId(activeWorktreeId) : undefined + const detectedAgentsForAI = + typeof activeConnectionId === 'string' ? remoteDetectedAgentIds : detectedAgentIds + const noEnabledAgentKnown = + detectedAgentsForAI != null && + pickDefaultSourceControlAgent( + settings?.defaultTuiAgent, + detectedAgentsForAI, + settings?.disabledTuiAgents + ) == null + const aiActionDisabledReason = !activeWorktreeId + ? 'Select a workspace before launching an AI action.' + : activeConnectionId === undefined + ? 'Unable to resolve the workspace connection.' + : noEnabledAgentKnown + ? 'No enabled AI agents. Configure agents in Settings.' + : undefined + + const handleAddPRComment = useCallback( + async (body: string) => { + if (!repo || !prNumber || !pr?.prRepo) { + return { ok: false as const, error: commentsDisabledReason ?? 'Commenting unavailable.' } + } + const requestKey = checksPanelAsyncResultKey( + prCacheKey, + branch, + prNumber, + pr.prRepo, + pr.headSha + ) + const result = await addPRConversationComment(repo.path, prNumber, body, { + repoId: repo.id, + prRepo: pr.prRepo + }) + if (!isCurrentAsyncResult(requestKey)) { + return result.ok ? { ok: true as const } : result + } + if (!result.ok) { + toast.error(result.error) + return result + } + setComments((prev) => mergePRCommentIntoList(prev, result.comment)) + return { ok: true as const } + }, + [ + addPRConversationComment, + branch, + commentsDisabledReason, + isCurrentAsyncResult, + pr, + prCacheKey, + prNumber, + repo + ] + ) + + const handleReplyToComment = useCallback( + async (comment: PRComment, body: string) => { + if (!repo || !prNumber || !pr?.prRepo) { + return { ok: false as const, error: commentsDisabledReason ?? 'Commenting unavailable.' } + } + const requestKey = checksPanelAsyncResultKey( + prCacheKey, + branch, + prNumber, + pr.prRepo, + pr.headSha + ) + const canReplyToReviewThread = + Boolean(comment.threadId) && Number.isSafeInteger(comment.id) && comment.id > 0 + const result = canReplyToReviewThread + ? await addPRReviewCommentReply(repo.path, prNumber, comment.id, body, { + repoId: repo.id, + prRepo: pr.prRepo, + threadId: comment.threadId, + path: comment.path, + line: comment.line + }) + : await addPRConversationComment(repo.path, prNumber, `@${comment.author} ${body}`, { + repoId: repo.id, + prRepo: pr.prRepo + }) + if (!isCurrentAsyncResult(requestKey)) { + return result.ok ? { ok: true as const } : result + } + if (!result.ok) { + toast.error(result.error) + return result + } + setComments((prev) => mergePRCommentIntoList(prev, result.comment)) + return { ok: true as const } + }, + [ + addPRConversationComment, + addPRReviewCommentReply, + branch, + commentsDisabledReason, + isCurrentAsyncResult, + pr, + prCacheKey, + prNumber, + repo + ] ) // Why: PR conflict files come from the host mergeability check, not a local @@ -1384,6 +1580,7 @@ export default function ChecksPanel(): React.JSX.Element { return } const conflictFiles = pr.conflictSummary?.files ?? [] + const requestKey = stateRequestKey setIsResolvingConflictsWithAI(true) try { const connectionId = getConnectionId(activeWorktreeId) @@ -1405,6 +1602,9 @@ export default function ChecksPanel(): React.JSX.Element { toast.error('No enabled AI agents. Configure agents in Settings.') return } + if (!isCurrentAsyncResult(requestKey)) { + return + } const prompt = buildResolvePullRequestConflictsPrompt({ baseRef: pr.conflictSummary?.baseRef, entries: conflictFiles.map((path) => ({ path })), @@ -1426,7 +1626,14 @@ export default function ChecksPanel(): React.JSX.Element { } finally { setIsResolvingConflictsWithAI(false) } - }, [activeWorktreeId, activeWorktreePath, isResolvingConflictsWithAI, pr]) + }, [ + activeWorktreeId, + activeWorktreePath, + isCurrentAsyncResult, + isResolvingConflictsWithAI, + pr, + stateRequestKey + ]) const handleFixChecksWithAI = useCallback(async (): Promise => { if (isFixingChecksWithAI || !activeWorktreeId || !activeReview) { @@ -1437,6 +1644,7 @@ export default function ChecksPanel(): React.JSX.Element { toast.message('No broken checks to fix.') return } + const requestKey = stateRequestKey setIsFixingChecksWithAI(true) try { const connectionId = getConnectionId(activeWorktreeId) @@ -1458,6 +1666,9 @@ export default function ChecksPanel(): React.JSX.Element { toast.error('No enabled AI agents. Configure agents in Settings.') return } + if (!isCurrentAsyncResult(requestKey)) { + return + } const prompt = buildFixBrokenChecksPrompt({ reviewKind: activeReview.provider === 'gitlab' ? 'MR' : 'PR', reviewNumber: activeReview.number, @@ -1483,7 +1694,14 @@ export default function ChecksPanel(): React.JSX.Element { } finally { setIsFixingChecksWithAI(false) } - }, [activeReview, activeWorktreeId, checks, isFixingChecksWithAI]) + }, [ + activeReview, + activeWorktreeId, + checks, + isCurrentAsyncResult, + isFixingChecksWithAI, + stateRequestKey + ]) // Refresh PR (passed to PRActions) const handleRefreshPR = useCallback(async () => { @@ -1913,16 +2131,22 @@ export default function ChecksPanel(): React.JSX.Element { {pr && ( <> - void handleResolveConflictsWithAI()} - /> + void handleResolveConflictsWithAI()} + /> + void handleResolveConflictsWithAI()} + resolveConflictsDisabled={Boolean(aiActionDisabledReason)} + resolveConflictsDisabledReason={aiActionDisabledReason} + isFixingChecksWithAI={isFixingChecksWithAI} + onFixChecksWithAI={() => void handleFixChecksWithAI()} + fixChecksDisabled={Boolean(aiActionDisabledReason)} + fixChecksDisabledReason={aiActionDisabledReason} /> )} @@ -1933,13 +2157,17 @@ export default function ChecksPanel(): React.JSX.Element { void handleFixChecksWithAI()} + checkDetailsContextKey={stateRequestKey} + onLoadCheckDetails={handleLoadCheckDetails} /> )} diff --git a/src/renderer/src/components/right-sidebar/checks-panel-content.test.tsx b/src/renderer/src/components/right-sidebar/checks-panel-content.test.tsx index 234a6b79e..1fa66bcea 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-content.test.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel-content.test.tsx @@ -1,8 +1,13 @@ import React from 'react' import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it } from 'vitest' -import type { PRInfo } from '../../../../shared/types' -import { MergeConflictNotice } from './checks-panel-content' +import type { PRCheckDetail, PRComment, PRInfo } from '../../../../shared/types' +import { + getFailedChecksForDetails, + MergeConflictNotice, + PRCommentsList, + PRTriageStrip +} from './checks-panel-content' function makePR(overrides: Partial = {}): PRInfo { return { @@ -21,9 +26,7 @@ function renderNotice(pr: PRInfo, isRefreshingConflictDetails = false): string { return renderToStaticMarkup( React.createElement(MergeConflictNotice, { pr, - isRefreshingConflictDetails, - isResolvingWithAI: false, - onResolveWithAI: () => {} + isRefreshingConflictDetails }) ) } @@ -57,11 +60,71 @@ describe('MergeConflictNotice', () => { expect(markup).toBe('') }) - it('renders the Sparkles icon on the idle Resolve with AI button', () => { + it('keeps the conflict details informational without a duplicate AI action', () => { const markup = renderNotice(makePR()) - expect(markup).toContain('Resolve with AI') + expect(markup).not.toContain('Resolve with AI') + expect(markup).not.toContain('lucide-sparkles') + }) + + it('renders the single conflict AI action in the triage strip', () => { + const markup = renderToStaticMarkup( + React.createElement(PRTriageStrip, { + pr: makePR(), + checks: [], + isResolvingConflictsWithAI: false, + onResolveConflictsWithAI: () => {}, + isFixingChecksWithAI: false, + onFixChecksWithAI: () => {} + }) + ) + + expect(markup).toContain('Resolve') expect(markup).toContain('lucide-sparkles') - expect(markup).not.toMatch(/\blucide-sparkle(?!s)\b/) + expect(markup).not.toContain('Resolve with AI') + }) +}) + +describe('PRCommentsList', () => { + it('places the collapsed add-comment action after existing comments', () => { + const comments: PRComment[] = [ + { + id: 1, + author: 'AmethystLiang', + authorAvatarUrl: '', + body: 'Existing review context', + createdAt: '2026-05-14T00:00:00Z', + url: 'https://github.com/acme/widgets/pull/42#issuecomment-1' + } + ] + + const markup = renderToStaticMarkup( + React.createElement(PRCommentsList, { + comments, + commentsLoading: false, + onAddComment: () => Promise.resolve({ ok: true as const }) + }) + ) + + expect(markup.indexOf('Existing review context')).toBeLessThan(markup.indexOf('Add Comment')) + expect(markup).not.toContain('Add a PR comment') + }) +}) + +describe('getFailedChecksForDetails', () => { + it('selects failed, cancelled, and timed out checks for inline details', () => { + const checks: PRCheckDetail[] = [ + { name: 'unit', status: 'completed', conclusion: 'success', url: null }, + { name: 'verify', status: 'completed', conclusion: 'failure', url: null }, + { name: 'lint', status: 'completed', conclusion: 'cancelled', url: null }, + { name: 'e2e', status: 'completed', conclusion: 'timed_out', url: null }, + { name: 'deploy', status: 'in_progress', conclusion: 'pending', url: null } + ] + + expect(getFailedChecksForDetails(checks).map((check) => check.name)).toEqual([ + 'verify', + 'lint', + 'e2e' + ]) }) }) diff --git a/src/renderer/src/components/right-sidebar/checks-panel-content.tsx b/src/renderer/src/components/right-sidebar/checks-panel-content.tsx index 04ec39eaa..2b687d2f3 100644 --- a/src/renderer/src/components/right-sidebar/checks-panel-content.tsx +++ b/src/renderer/src/components/right-sidebar/checks-panel-content.tsx @@ -1,6 +1,6 @@ /* eslint-disable max-lines -- Why: co-locating all checks-panel sub-components (checks list, conflict sections, threaded PR comments) keeps the shared icon/color maps in one place. */ -import React, { useCallback, useRef, useState } from 'react' +import React, { useCallback, useEffect, useRef, useState } from 'react' import { CircleCheck, CircleX, @@ -13,9 +13,13 @@ import { Check, MessageSquare, ChevronDown, + ChevronRight, Sparkles, RefreshCw, - Wrench + Wrench, + AlertTriangle, + Maximize2, + Plus } from 'lucide-react' import { ExternalLink } from 'lucide-react' import { Button } from '@/components/ui/button' @@ -25,6 +29,14 @@ import { AccordionItem, AccordionTrigger } from '@/components/ui/accordion' +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger +} from '@/components/ui/dialog' import { cn } from '@/lib/utils' import CommentMarkdown from '@/components/sidebar/CommentMarkdown' import { @@ -46,8 +58,12 @@ import { PR_COMMENT_RESOLVED_CONTAINER_CLASS, type PRCommentGroup } from '@/lib/pr-comment-groups' -import type { PRInfo, PRCheckDetail, PRComment } from '../../../../shared/types' +import type { PRInfo, PRCheckDetail, PRCheckRunDetails, PRComment } from '../../../../shared/types' import { useCheckDetailsResize } from './check-details-resize' +import { + RightPanelCommentComposer, + type RightPanelCommentSubmitResult +} from './right-panel-comment-composer' export const PullRequestIcon = GitPullRequest @@ -71,50 +87,7 @@ export const CHECK_COLOR: Record = { timed_out: 'text-rose-500' } -function ResolveConflictsWithAIButton({ - isResolvingWithAI, - onResolveWithAI, - disabled, - disabledReason -}: { - isResolvingWithAI: boolean - onResolveWithAI: () => void - disabled?: boolean - disabledReason?: string -}): React.JSX.Element { - return ( - - ) -} - -export function ConflictingFilesSection({ - pr, - isResolvingWithAI, - onResolveWithAI, - resolveDisabled, - resolveDisabledReason -}: { - pr: PRInfo - isResolvingWithAI: boolean - onResolveWithAI: () => void - resolveDisabled?: boolean - resolveDisabledReason?: string -}): React.JSX.Element | null { +export function ConflictingFilesSection({ pr }: { pr: PRInfo }): React.JSX.Element | null { const files = pr.conflictSummary?.files ?? [] if (pr.mergeable !== 'CONFLICTING' || files.length === 0) { return null @@ -143,12 +116,6 @@ export function ConflictingFilesSection({ ))} - ) } @@ -156,18 +123,10 @@ export function ConflictingFilesSection({ /** Fallback shown when GitHub reports merge conflicts but no file list is available yet. */ export function MergeConflictNotice({ pr, - isRefreshingConflictDetails, - isResolvingWithAI, - onResolveWithAI, - resolveDisabled, - resolveDisabledReason + isRefreshingConflictDetails }: { pr: PRInfo isRefreshingConflictDetails: boolean - isResolvingWithAI: boolean - onResolveWithAI: () => void - resolveDisabled?: boolean - resolveDisabledReason?: string }): React.JSX.Element | null { if (pr.mergeable !== 'CONFLICTING' || (pr.conflictSummary?.files.length ?? 0) > 0) { return null @@ -183,12 +142,135 @@ export function MergeConflictNotice({ ? 'Refreshing conflict details…' : 'Conflict file details are unavailable'} - + + ) +} + +export function PRTriageStrip({ + pr, + checks, + isResolvingConflictsWithAI, + onResolveConflictsWithAI, + resolveConflictsDisabled, + resolveConflictsDisabledReason, + isFixingChecksWithAI, + onFixChecksWithAI, + fixChecksDisabled, + fixChecksDisabledReason +}: { + pr: PRInfo + checks: PRCheckDetail[] + isResolvingConflictsWithAI: boolean + onResolveConflictsWithAI: () => void + resolveConflictsDisabled?: boolean + resolveConflictsDisabledReason?: string + isFixingChecksWithAI: boolean + onFixChecksWithAI: () => void + fixChecksDisabled?: boolean + fixChecksDisabledReason?: string +}): React.JSX.Element { + const failingCount = checks.filter((check) => isFailedCheck(check)).length + const pendingCount = checks.filter( + (check) => check.conclusion === 'pending' || check.conclusion === null + ).length + + if (pr.mergeable === 'CONFLICTING') { + return ( +
+
+ +
+
+ Conflicts block this PR +
+
+ Resolve conflicts before checks and merge can complete. +
+
+ +
+
+ ) + } + + if (failingCount > 0) { + return ( +
+
+ +
+
+ {failingCount} failing check{failingCount === 1 ? '' : 's'} +
+
+ Inspect details or start an AI fix pass. +
+
+ +
+
+ ) + } + + if (pendingCount > 0) { + return ( +
+
+ +
+
+ {pendingCount} check{pendingCount === 1 ? '' : 's'} pending +
+
+ Orca will refresh checks while this panel stays open. +
+
+
+
+ ) + } + + return ( +
+
+ +
+
+ No blocking PR action +
+
+ Checks and comments below show the current fetched context. +
+
+
) } @@ -203,26 +285,516 @@ const CHECK_SORT_ORDER: Record = { success: 5 } +type CheckDetailsLoadState = { + loading: boolean + details: PRCheckRunDetails | null + error: string | null +} + +function getCheckIdentityKey(check: PRCheckDetail, index: number): string { + if (check.checkRunId) { + return `check-run:${check.checkRunId}` + } + if (check.workflowRunId) { + return `workflow-run:${check.workflowRunId}` + } + if (check.url) { + return `url:${check.url}` + } + return `fallback:${check.name}:${index}` +} + +function getCheckDetailsKey(contextKey: string, check: PRCheckDetail, index: number): string { + return `${contextKey}::${getCheckIdentityKey(check, index)}` +} + +function getCheckConclusion(check: PRCheckDetail): NonNullable { + return check.conclusion ?? 'pending' +} + +function isFailedCheck(check: PRCheckDetail): boolean { + return ['failure', 'cancelled', 'timed_out'].includes(getCheckConclusion(check)) +} + +function isFailureState(state: string | null | undefined): boolean { + return state === 'failure' || state === 'failed' || state === 'cancelled' || state === 'timed_out' +} + +function getCheckStatusLabel(check: PRCheckDetail): string { + const conclusion = getCheckConclusion(check) + if (conclusion === 'success') { + return 'Successful' + } + if (conclusion === 'failure') { + return 'Failed' + } + if (conclusion === 'cancelled') { + return 'Cancelled' + } + if (conclusion === 'timed_out') { + return 'Timed out' + } + if (conclusion === 'neutral') { + return 'Neutral' + } + if (conclusion === 'skipped') { + return 'Skipped' + } + if (check.status === 'queued') { + return 'Queued' + } + if (check.status === 'in_progress') { + return 'In progress' + } + return 'Pending' +} + +function formatCheckTimestamp(input: string | null | undefined): string | null { + if (!input) { + return null + } + const date = new Date(input) + if (Number.isNaN(date.getTime())) { + return null + } + return date.toLocaleString(undefined, { + month: 'short', + day: 'numeric', + hour: 'numeric', + minute: '2-digit' + }) +} + +export function getFailedChecksForDetails(checks: PRCheckDetail[]): PRCheckDetail[] { + return checks.filter(isFailedCheck) +} + +function CheckRunDetails({ + check, + state +}: { + check: PRCheckDetail + state: CheckDetailsLoadState | undefined +}): React.JSX.Element { + const details = state?.details + const openUrl = details?.detailsUrl ?? details?.url ?? check.url + const startedAt = formatCheckTimestamp(details?.startedAt) + const completedAt = formatCheckTimestamp(details?.completedAt) + const detailsStatusCheck: PRCheckDetail = { + ...check, + status: (details?.status as PRCheckDetail['status'] | undefined) ?? check.status, + conclusion: (details?.conclusion as PRCheckDetail['conclusion'] | undefined) ?? check.conclusion + } + const failedJobs = + details?.jobs.filter((job) => { + const state = job.conclusion ?? job.status + return isFailureState(state) + }) ?? [] + const jobs = failedJobs.length > 0 ? failedJobs : (details?.jobs ?? []) + const hasOutput = Boolean(details?.title || details?.summary || details?.text) + const hasAnnotations = (details?.annotations.length ?? 0) > 0 + const hasJobs = jobs.length > 0 + + return ( +
+ {state?.loading ? ( +
+ + Loading check details… +
+ ) : ( +
+
+ + Status:{' '} + {details ? getCheckStatusLabel(detailsStatusCheck) : getCheckStatusLabel(check)} + + {startedAt && Started {startedAt}} + {completedAt && Completed {completedAt}} + {check.checkRunId && check #{check.checkRunId}} + {check.workflowRunId && ( + workflow #{check.workflowRunId} + )} +
+ + {state?.error &&
{state.error}
} + + {hasOutput && ( +
+ {details?.title && ( +
{details.title}
+ )} + {details?.summary && ( + + )} + {details?.text && ( + + )} +
+ )} + + {hasAnnotations && ( +
+
+ Annotations +
+
+ {details!.annotations.map((annotation, index) => ( +
0 && 'border-t border-border/30' + )} + > +
+ + {annotation.path ?? 'Annotation'} + {annotation.startLine ? `:${annotation.startLine}` : ''} + + {annotation.annotationLevel && ( + + {annotation.annotationLevel} + + )} +
+ {annotation.title && ( +
+ {annotation.title} +
+ )} +
+ {annotation.message} +
+ {annotation.rawDetails && ( +
+                        {annotation.rawDetails}
+                      
+ )} +
+ ))} +
+ {details!.annotations.length >= 20 && ( +
+ Showing first 20 annotations +
+ )} +
+ )} + + {hasJobs && ( +
+
+ {failedJobs.length > 0 ? 'Failed jobs' : 'Jobs'} +
+
+ {jobs.map((job, index) => ( +
0 && 'border-t border-border/30')} + > +
+ + {job.name} + + + {job.conclusion ?? job.status ?? 'unknown'} + +
+ {job.steps.length > 0 && ( +
+ {job.steps + .filter((step) => { + const state = step.conclusion ?? step.status + return isFailureState(state) + }) + .map((step) => ( +
+ {step.name} + {step.conclusion ?? step.status} +
+ ))} +
+ )} +
+ ))} +
+ {(details?.jobs.length ?? 0) >= 100 && ( +
+ Showing first 100 jobs +
+ )} +
+ )} + + {!state?.error && !hasOutput && !hasAnnotations && !hasJobs && ( +
+ No inline details are available for this check. +
+ )} + +
+ {!state?.loading && ( + + + + + + + )} + {openUrl && ( + + )} +
+
+ )} +
+ ) +} + +function CheckRunDetailsDialog({ + check, + state, + detailsStatusCheck, + jobs, + openUrl +}: { + check: PRCheckDetail + state: CheckDetailsLoadState | undefined + detailsStatusCheck: PRCheckDetail + jobs: NonNullable + openUrl: string | null | undefined +}): React.JSX.Element { + const details = state?.details + const startedAt = formatCheckTimestamp(details?.startedAt) + const completedAt = formatCheckTimestamp(details?.completedAt) + const hasOutput = Boolean(details?.title || details?.summary || details?.text) + const hasAnnotations = (details?.annotations.length ?? 0) > 0 + const hasJobs = jobs.length > 0 + + return ( + event.stopPropagation()} + > + + {check.name} + + + Status: {details ? getCheckStatusLabel(detailsStatusCheck) : getCheckStatusLabel(check)} + + {startedAt && Started {startedAt}} + {completedAt && Completed {completedAt}} + {check.checkRunId && check #{check.checkRunId}} + {check.workflowRunId && ( + workflow #{check.workflowRunId} + )} + + +
+
+ {state?.error &&
{state.error}
} + + {hasOutput && ( +
+
Output
+
+ {details?.title && ( +
{details.title}
+ )} + {details?.summary && ( + + )} + {details?.text && ( + + )} +
+
+ )} + + {hasAnnotations && ( +
+
+ Annotations +
+
+ {details!.annotations.map((annotation, index) => ( +
+
+ + {annotation.path ?? 'Annotation'} + {annotation.startLine ? `:${annotation.startLine}` : ''} + + {annotation.annotationLevel && ( + + {annotation.annotationLevel} + + )} +
+ {annotation.title && ( +
+ {annotation.title} +
+ )} +
+ {annotation.message} +
+ {annotation.rawDetails && ( +
+                        {annotation.rawDetails}
+                      
+ )} +
+ ))} +
+
+ )} + + {hasJobs && ( +
+
Jobs
+
+ {jobs.map((job, index) => ( +
+
+ + {job.name} + + + {job.conclusion ?? job.status ?? 'unknown'} + +
+ {job.steps.length > 0 && ( +
+ {job.steps.map((step) => ( +
+ {step.name} + {step.conclusion ?? step.status} +
+ ))} +
+ )} +
+ ))} +
+
+ )} + + {!state?.error && !hasOutput && !hasAnnotations && !hasJobs && ( +
+ No details are available for this check. +
+ )} +
+
+ {openUrl && ( +
+ +
+ )} +
+ ) +} + /** Renders the checks summary bar + scrollable check list. */ export function ChecksList({ checks, checksLoading, - isFixingWithAI, - onFixWithAI + checkDetailsContextKey, + onLoadCheckDetails }: { checks: PRCheckDetail[] checksLoading: boolean - isFixingWithAI?: boolean - onFixWithAI?: () => void + checkDetailsContextKey: string + onLoadCheckDetails?: (check: PRCheckDetail) => Promise }): React.JSX.Element { const [checksExpanded, setChecksExpanded] = useState(true) + const [expandedCheckKeys, setExpandedCheckKeys] = useState>(new Set()) + const [detailsByCheckKey, setDetailsByCheckKey] = useState>( + {} + ) + const detailsContextRef = useRef(checkDetailsContextKey) + const autoExpandedContextRef = useRef(null) const { detailsHeight, handleResizeStart } = useCheckDetailsResize( checksExpanded && checks.length > 0 ) - const sorted = [...checks].sort( - (a, b) => - (CHECK_SORT_ORDER[a.conclusion ?? 'pending'] ?? 3) - - (CHECK_SORT_ORDER[b.conclusion ?? 'pending'] ?? 3) + detailsContextRef.current = checkDetailsContextKey + const sorted = React.useMemo( + () => + [...checks].sort( + (a, b) => + (CHECK_SORT_ORDER[a.conclusion ?? 'pending'] ?? 3) - + (CHECK_SORT_ORDER[b.conclusion ?? 'pending'] ?? 3) + ), + [checks] + ) + const rows = React.useMemo( + () => + sorted.map((check, index) => ({ + check, + key: getCheckDetailsKey(checkDetailsContextKey, check, index) + })), + [checkDetailsContextKey, sorted] ) const passingCount = checks.filter((c) => c.conclusion === 'success').length const failingCount = checks.filter( @@ -233,6 +805,123 @@ export function ChecksList({ (c) => c.conclusion === 'pending' || c.conclusion === null ).length + useEffect(() => { + const validKeys = new Set(rows.map((row) => row.key)) + setDetailsByCheckKey((current) => { + const next: Record = {} + for (const [key, state] of Object.entries(current)) { + if (validKeys.has(key)) { + next[key] = state + } + } + return next + }) + setExpandedCheckKeys((current) => { + const next = new Set([...current].filter((key) => validKeys.has(key))) + if (autoExpandedContextRef.current !== checkDetailsContextKey) { + const firstFailed = rows.find((row) => isFailedCheck(row.check)) + if (firstFailed) { + next.add(firstFailed.key) + } + autoExpandedContextRef.current = checkDetailsContextKey + } + return next + }) + }, [checkDetailsContextKey, rows]) + + const requestCheckDetails = useCallback( + (row: { check: PRCheckDetail; key: string }) => { + if (detailsByCheckKey[row.key]?.loading || detailsByCheckKey[row.key]?.details) { + return + } + if (!row.check.checkRunId && !row.check.workflowRunId && !row.check.url) { + setDetailsByCheckKey((current) => ({ + ...current, + [row.key]: { + loading: false, + details: null, + error: 'No inline details are available for this check.' + } + })) + return + } + if (!onLoadCheckDetails) { + setDetailsByCheckKey((current) => ({ + ...current, + [row.key]: { + loading: false, + details: null, + error: 'No inline details are available for this check.' + } + })) + return + } + const requestContextKey = checkDetailsContextKey + setDetailsByCheckKey((current) => ({ + ...current, + [row.key]: { loading: true, details: null, error: null } + })) + void onLoadCheckDetails(row.check) + .then((details) => { + if (detailsContextRef.current !== requestContextKey) { + return + } + setDetailsByCheckKey((current) => ({ + ...current, + [row.key]: { + loading: false, + details, + error: details ? null : 'No inline details are available for this check.' + } + })) + }) + .catch((err) => { + if (detailsContextRef.current !== requestContextKey) { + return + } + setDetailsByCheckKey((current) => ({ + ...current, + [row.key]: { + loading: false, + details: null, + error: err instanceof Error ? err.message : 'Failed to load check details.' + } + })) + }) + }, + [checkDetailsContextKey, detailsByCheckKey, onLoadCheckDetails] + ) + + useEffect(() => { + if (!checksExpanded) { + return + } + for (const row of rows) { + if (expandedCheckKeys.has(row.key) && !detailsByCheckKey[row.key]) { + requestCheckDetails(row) + } + } + }, [checksExpanded, detailsByCheckKey, expandedCheckKeys, requestCheckDetails, rows]) + + const toggleCheckExpanded = useCallback( + (row: { check: PRCheckDetail; key: string }) => { + const willExpand = !expandedCheckKeys.has(row.key) + setExpandedCheckKeys((current) => { + const next = new Set(current) + if (next.has(row.key)) { + next.delete(row.key) + } else { + next.add(row.key) + } + return next + }) + if (willExpand) { + requestCheckDetails(row) + } + }, + [expandedCheckKeys, requestCheckDetails] + ) + return ( <> {/* Checks Summary */} @@ -269,29 +958,6 @@ export function ChecksList({ )} - {/* Why: surface a one-click "Fix with AI" path right at the top of the - checks list so users can hand failing CI off to the default agent - without leaving the right sidebar — mirrors the Tasks page action. */} - {failingCount > 0 && onFixWithAI && ( -
- -
- )} - {/* Checks List */} {checksLoading && checks.length === 0 ? (
@@ -307,34 +973,42 @@ export function ChecksList({ className="overflow-y-auto py-1 scrollbar-sleek" style={{ maxHeight: detailsHeight }} > - {sorted.map((check) => { + {rows.map((row) => { + const check = row.check const conclusion = check.conclusion ?? 'pending' const Icon = CHECK_ICON[conclusion] ?? CircleDashed const color = CHECK_COLOR[conclusion] ?? 'text-muted-foreground' + const expanded = expandedCheckKeys.has(row.key) return ( -
{ - if (check.url) { - window.api.shell.openUrl(check.url) - } - }} - > - +
- {check.name} - {check.url && ( - - )} + onClick={() => toggleCheckExpanded(row)} + > + + + + {check.name} + + + {getCheckStatusLabel(check)} + +
+ {expanded && }
) })} @@ -348,6 +1022,11 @@ export function ChecksList({ >
+ {checks.length >= 100 && ( +
+ Showing first 100 checks +
+ )} )} @@ -415,7 +1094,7 @@ function ResolveButton({ }: { threadId: string isResolved: boolean - onResolve: (threadId: string, resolve: boolean) => void + onResolve: (threadId: string, resolve: boolean) => boolean | Promise }): React.JSX.Element { const [loading, setLoading] = useState(false) const loadingResetTimerRef = useRef(null) @@ -441,11 +1120,7 @@ function ResolveButton({ e.stopPropagation() clearLoadingResetTimer() setLoading(true) - loadingResetTimerRef.current = window.setTimeout(() => { - loadingResetTimerRef.current = null - setLoading(false) - }, 300) - onResolve(threadId, !isResolved) + void Promise.resolve(onResolve(threadId, !isResolved)).finally(() => setLoading(false)) }, [clearLoadingResetTimer, threadId, isResolved, onResolve] ) @@ -492,12 +1167,20 @@ function CommentRow({ comment, isReply, showResolve, - onResolve + showReply, + replyDisabled, + replyDisabledReason, + onResolve, + onReply }: { comment: PRComment isReply: boolean showResolve: boolean - onResolve?: (threadId: string, resolve: boolean) => void + showReply?: boolean + replyDisabled?: boolean + replyDisabledReason?: string + onResolve?: (threadId: string, resolve: boolean) => boolean | Promise + onReply?: (comment: PRComment) => void }): React.JSX.Element { const automated = isBotPRComment(comment) return ( @@ -555,6 +1238,19 @@ function CommentRow({ onResolve={onResolve} /> )} + {showReply && onReply && ( + + )}
@@ -562,7 +1258,7 @@ function CommentRow({ content={comment.body} className={cn( 'mt-1 text-[11px] leading-snug text-muted-foreground', - 'break-words [&_p]:my-1 [&_pre]:max-h-none [&_table]:min-w-max', + 'break-words [&_p]:my-1 [&_pre]:max-h-none [&_pre]:max-w-full [&_pre]:whitespace-pre-wrap [&_table]:w-full [&_table]:max-w-full', isReply ? 'pl-5' : 'pl-[22px]' )} /> @@ -571,24 +1267,72 @@ function CommentRow({ ) } -function renderCommentGroup( - group: PRCommentGroup, - onResolve?: (threadId: string, resolve: boolean) => void -): React.JSX.Element { +function PRCommentGroupView({ + group, + replyingGroupId, + replyDisabled, + replyDisabledReason, + onResolve, + onStartReply, + onCancelReply, + onReply +}: { + group: PRCommentGroup + replyingGroupId: string | null + replyDisabled?: boolean + replyDisabledReason?: string + onResolve?: (threadId: string, resolve: boolean) => boolean | Promise + onStartReply?: (groupId: string) => void + onCancelReply?: () => void + onReply?: (comment: PRComment, body: string) => Promise +}): React.JSX.Element { + const groupId = getPRCommentGroupId(group) + const root = getPRCommentGroupRoot(group) + const replyComposer = + replyingGroupId === groupId && onReply ? ( +
+ onReply(root, body)} + /> +
+ ) : null + const startReply = onStartReply ? () => onStartReply(groupId) : undefined + if (group.kind === 'standalone') { return ( - +
+ startReply() : undefined} + /> + {replyComposer} +
) } return (
- + startReply() : undefined} + /> {group.replies.length > 0 && (
{group.replies.map((reply) => ( @@ -597,21 +1341,35 @@ function renderCommentGroup( comment={reply} isReply={true} showResolve={false} + showReply={false} onResolve={onResolve} /> ))}
)} + {replyComposer}
) } function ResolvedCommentGroupAccordion({ group, - onResolve + replyingGroupId, + replyDisabled, + replyDisabledReason, + onResolve, + onStartReply, + onCancelReply, + onReply }: { group: PRCommentGroup - onResolve?: (threadId: string, resolve: boolean) => void + replyingGroupId: string | null + replyDisabled?: boolean + replyDisabledReason?: string + onResolve?: (threadId: string, resolve: boolean) => boolean | Promise + onStartReply?: (groupId: string) => void + onCancelReply?: () => void + onReply?: (comment: PRComment, body: string) => Promise }): React.JSX.Element { const root = getPRCommentGroupRoot(group) const count = getPRCommentGroupCount(group) @@ -625,7 +1383,16 @@ function ResolvedCommentGroupAccordion({ - {renderCommentGroup(group, onResolve)} + @@ -636,13 +1403,23 @@ function ResolvedCommentGroupAccordion({ export function PRCommentsList({ comments, commentsLoading, + commentsDisabled, + commentsDisabledReason, + onAddComment, + onReply, onResolve }: { comments: PRComment[] commentsLoading: boolean - onResolve?: (threadId: string, resolve: boolean) => void + commentsDisabled?: boolean + commentsDisabledReason?: string + onAddComment?: (body: string) => Promise + onReply?: (comment: PRComment, body: string) => Promise + onResolve?: (threadId: string, resolve: boolean) => boolean | Promise }): React.JSX.Element { const [commentFilter, setCommentFilter] = useState('all') + const [replyingGroupId, setReplyingGroupId] = useState(null) + const [isAddingComment, setIsAddingComment] = useState(false) const commentCounts = React.useMemo(() => getPRCommentAudienceCounts(comments), [comments]) const visibleComments = React.useMemo( () => filterPRCommentsByAudience(comments, commentFilter), @@ -683,6 +1460,11 @@ export function PRCommentsList({ })} )} + {comments.length >= 100 && ( +
+ Showing first 100 comments per source +
+ )} {/* List */} @@ -706,14 +1488,61 @@ export function PRCommentsList({ setReplyingGroupId(null)} + onReply={onReply} /> ) } - return renderCommentGroup(group, onResolve) + return ( + setReplyingGroupId(null)} + onReply={onReply} + /> + ) })} )} + {onAddComment && ( +
+ {isAddingComment ? ( + setIsAddingComment(false)} + onSubmit={onAddComment} + /> + ) : ( +
+ +
+ )} +
+ )} ) } diff --git a/src/renderer/src/components/right-sidebar/right-panel-comment-composer.tsx b/src/renderer/src/components/right-sidebar/right-panel-comment-composer.tsx new file mode 100644 index 000000000..2ca69c089 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/right-panel-comment-composer.tsx @@ -0,0 +1,237 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react' +import { Bold, Code2, Italic, List, LoaderCircle, Quote, Send } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' +import { cn } from '@/lib/utils' + +export type RightPanelCommentSubmitResult = { ok: true } | { ok: false; error: string } + +type MarkdownAction = 'bold' | 'italic' | 'code' | 'quote' | 'list' + +type RightPanelCommentComposerProps = { + placeholder: string + submitLabel: string + onSubmit: (body: string) => Promise + disabled?: boolean + disabledReason?: string + autoFocus?: boolean + className?: string + onCancel?: () => void +} + +function applyMarkdownAction(value: string, start: number, end: number, action: MarkdownAction) { + const selected = value.slice(start, end) + switch (action) { + case 'bold': + return { + value: `${value.slice(0, start)}**${selected || 'strong text'}**${value.slice(end)}`, + selectionStart: start + 2, + selectionEnd: start + 2 + (selected || 'strong text').length + } + case 'italic': + return { + value: `${value.slice(0, start)}_${selected || 'emphasis'}_${value.slice(end)}`, + selectionStart: start + 1, + selectionEnd: start + 1 + (selected || 'emphasis').length + } + case 'code': + return { + value: `${value.slice(0, start)}\`${selected || 'code'}\`${value.slice(end)}`, + selectionStart: start + 1, + selectionEnd: start + 1 + (selected || 'code').length + } + case 'quote': { + const prefix = start === 0 || value[start - 1] === '\n' ? '> ' : '\n> ' + return { + value: `${value.slice(0, start)}${prefix}${selected || 'quote'}${value.slice(end)}`, + selectionStart: start + prefix.length, + selectionEnd: start + prefix.length + (selected || 'quote').length + } + } + case 'list': { + const prefix = start === 0 || value[start - 1] === '\n' ? '- ' : '\n- ' + return { + value: `${value.slice(0, start)}${prefix}${selected || 'item'}${value.slice(end)}`, + selectionStart: start + prefix.length, + selectionEnd: start + prefix.length + (selected || 'item').length + } + } + } +} + +export function RightPanelCommentComposer({ + placeholder, + submitLabel, + onSubmit, + disabled, + disabledReason, + autoFocus, + className, + onCancel +}: RightPanelCommentComposerProps): React.JSX.Element { + const [body, setBody] = useState('') + const [submitting, setSubmitting] = useState(false) + const [error, setError] = useState(null) + const textareaRef = useRef(null) + const isMac = navigator.userAgent.includes('Mac') + const modLabel = isMac ? '⌘' : 'Ctrl' + + useEffect(() => { + const textarea = textareaRef.current + if (!textarea) { + return + } + textarea.style.height = '0px' + textarea.style.height = `${Math.min(textarea.scrollHeight, 180)}px` + }, [body]) + + useEffect(() => { + if (autoFocus) { + setTimeout(() => textareaRef.current?.focus(), 0) + } + }, [autoFocus]) + + const stopPropagation = useCallback((event: React.SyntheticEvent) => { + event.stopPropagation() + }, []) + + const applyAction = useCallback( + (action: MarkdownAction) => { + const textarea = textareaRef.current + if (!textarea) { + return + } + const next = applyMarkdownAction(body, textarea.selectionStart, textarea.selectionEnd, action) + setBody(next.value) + setTimeout(() => { + textarea.focus() + textarea.setSelectionRange(next.selectionStart, next.selectionEnd) + }, 0) + }, + [body] + ) + + const submit = useCallback(async () => { + const trimmed = body.trim() + if (!trimmed || submitting || disabled) { + return + } + setSubmitting(true) + setError(null) + try { + const result = await onSubmit(trimmed) + if (result.ok) { + setBody('') + onCancel?.() + } else { + setError(result.error) + } + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to post comment.') + } finally { + setSubmitting(false) + } + }, [body, disabled, onCancel, onSubmit, submitting]) + + const handleKeyDown = useCallback( + (event: React.KeyboardEvent) => { + const modifierPressed = isMac ? event.metaKey : event.ctrlKey + if (event.key === 'Enter' && modifierPressed) { + event.preventDefault() + void submit() + } + }, + [isMac, submit] + ) + + const toolbar = [ + { action: 'bold' as const, label: 'Bold', icon: Bold }, + { action: 'italic' as const, label: 'Italic', icon: Italic }, + { action: 'code' as const, label: 'Code', icon: Code2 }, + { action: 'quote' as const, label: 'Quote', icon: Quote }, + { action: 'list' as const, label: 'List', icon: List } + ] + + return ( +
+