diff --git a/DEPLOY.md b/DEPLOY.md index 7a8dd5d2..a721a68e 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -132,7 +132,7 @@ The login flow requests `scope=repo read:org`: | `repo` | Read issues, PRs, check runs, workflow runs (includes private repos) | | `read:org` | `GET /user/orgs` — list user's organizations for the org selector | -**Note:** The `repo` scope grants write access to repositories, but this app never performs write operations (POST/PUT/PATCH/DELETE on repo endpoints). It is read-only by design. +**Note:** The `repo` scope grants write access to repositories. An Octokit request guard blocks all REST write operations (POST/PUT/PATCH/DELETE) and all GraphQL mutations except explicit user-confirmed PR approvals (`addPullRequestReview` with `event: APPROVE`). ### Local development OAuth App diff --git a/README.md b/README.md index 32c8398a..b1c484ed 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Open issues where you're the creator, assignee, or mentioned. A scope filter let ### Pull Requests -Open PRs with CI status dots (green/yellow/red), review decision badges, size badges (XS–XL by lines changed), and draft indicators. A "blocked" filter catches PRs where checks are failing or a review requested changes. The scope filter works here too. Reviewer avatars stack for multiple reviewers. +Open PRs with CI status dots (green/yellow/red), review decision badges, a read-only `auto` badge when GitHub auto-merge is enabled (with merge method tooltip), size badges (XS–XL by lines changed), draft indicators, and a two-step inline `Approve` button on PR rows requiring approval. A "blocked" filter catches PRs where checks are failing or a review requested changes. The scope filter works here too. Reviewer avatars stack for multiple reviewers. ### Actions @@ -128,8 +128,8 @@ src/ layout/ # Header, TabBar, FilterBar onboarding/ # OnboardingWizard, OrgSelector, RepoSelector settings/ # SettingsPage, TrackedUsersSection, ThemePicker, Section, SettingRow - shared/ # 19 shared components: FilterInput, FilterChips, StatusDot, - # ReviewBadge, SizeBadge, RoleBadge, SortDropdown, PaginationControls, + shared/ # 28 shared components: FilterInput, FilterChips, StatusDot, + # ReviewBadge, AutoMergeBadge, SizeBadge, RoleBadge, SortDropdown, PaginationControls, # LoadingSpinner, SkeletonRows, ToastContainer, NotificationDrawer, # RepoLockControls, UserAvatarBadge, ExpandCollapseButtons, # RepoGitHubLink, ChevronIcon, ExternalLinkIcon, Tooltip/InfoTooltip @@ -170,7 +170,7 @@ pnpm run screenshot # Capture dashboard screenshot ## Security -OAuth tokens are stored in `localStorage` under an app-specific key — this is standard for single-user personal dashboards and matches the threat model here. CSP headers block script injection via Cloudflare (`script-src 'self'` with a SHA-256 exception for the dark-mode initialization script only). An Octokit hook blocks all non-GET requests except `POST /graphql` as a read-only guard — the `repo` scope is required for private repo access, but the app never performs writes. OAuth state is generated with `crypto.getRandomValues` and verified on callback. Token validation runs on every page load via `GET /user`; a 401 clears the stored token immediately. +OAuth tokens are stored in `localStorage` under an app-specific key — this is standard for single-user personal dashboards and matches the threat model here. CSP headers block script injection via Cloudflare (`script-src 'self'` with a SHA-256 exception for the dark-mode initialization script only). An Octokit hook blocks all non-GET REST requests and all GraphQL mutations except the single user-confirmed PR approval mutation (addPullRequestReview with event: APPROVE) — the repo scope is required for private repo access, and all other write operations are rejected client-side. OAuth state is generated with `crypto.getRandomValues` and verified on callback. Token validation runs on every page load via `GET /user`; a 401 clears the stored token immediately. ## Deployment diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index e969dc39..1523301b 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -81,7 +81,7 @@ If you prefer not to use OAuth, you can sign in with a GitHub Personal Access To Two token formats are accepted: - **Classic tokens** (starts with `ghp_`) — recommended. Works across all organizations you belong to. Required scopes: `repo`, `read:org` (under admin:org). -- **Fine-grained tokens** (starts with `github_pat_`) — also work, but only access one organization at a time. Required permissions: Actions (read), Contents (read), Issues (read), Pull requests (read). +- **Fine-grained tokens** (starts with `github_pat_`) — also work, but only access one organization at a time. Required permissions: Actions (read), Contents (read), Issues (read), Pull requests (read and write to approve PRs from the dashboard, or read-only for viewing only). The token is validated against the GitHub API before being stored. It is saved permanently in your browser's `localStorage` — you will not need to re-enter it on revisit. @@ -223,6 +223,18 @@ The dot links to the PR's checks page on GitHub. | Needs review | Review has been requested but not yet submitted | | Dismissed | Previously submitted review was dismissed | +#### Auto-Merge Badge + +When GitHub auto-merge is enabled on a pull request, a read-only `auto` badge appears next to the review badge (in both comfortable and compact density across the Pull Requests, Dependencies, and Tracked tabs). Hover or focus the badge to view the configured merge method (`merge`, `squash`, or `rebase`). + +#### Inline Approve Action + +Open, non-draft pull requests not authored by you show an **Approve** button next to the pull request title on hover when branch protection requires a review (`Review needed`) or when a review has been requested of you or your team (unless you have already approved the PR without a fresh re-request). + +Approval uses a two-step inline confirmation to prevent accidental clicks: +1. Click **Approve** once to arm confirmation (**Confirm?**, or **Confirm (auto)** when auto-merge is enabled on the PR). The confirmation state resets automatically after 4 seconds, on Escape, or when focus leaves the button. +2. Click **Confirm?** (or **Confirm (auto)**) to submit an `APPROVE` review bound to the PR's current head commit SHA (`commitOID`). If new commits were pushed since the last refresh, GitHub rejects the stale approval and the dashboard triggers a refresh. + #### Size Badges PR size is computed from total lines changed (additions + deletions): @@ -826,7 +838,11 @@ For detailed per-source API call counts, see Settings > API Usage. OAuth tokens (from "Sign in with GitHub") work across all your organizations and support all features. Classic PATs with the correct scopes (`repo`, `read:org`) behave identically to OAuth. -Fine-grained PATs are limited to one organization at a time. Required permissions: Actions (read), Contents (read), Issues (read), Pull requests (read). +Fine-grained PATs are limited to one organization at a time. Required permissions: Actions (read), Contents (read), Issues (read), Pull requests (read and write to approve PRs from the dashboard, or read-only for viewing only). + +**Approving a PR fails with a permission error (403 / FORBIDDEN).** + +Your token does not have write permission for pull requests. If you are using a fine-grained Personal Access Token, open GitHub Settings, edit or regenerate the token with **Pull requests** set to **Read and write** (`Pull requests: Read and write`), and replace your token in **Settings > Data > Authentication**. **Data looks stale after switching back to the tab.** diff --git a/mcp/src/octokit.ts b/mcp/src/octokit.ts index bd4d22f9..6059ae2a 100644 --- a/mcp/src/octokit.ts +++ b/mcp/src/octokit.ts @@ -2,6 +2,7 @@ import { Octokit } from "@octokit/core"; import { throttling } from "@octokit/plugin-throttling"; import { retry } from "@octokit/plugin-retry"; import { paginateRest } from "@octokit/plugin-paginate-rest"; +import { isReadOnlyGraphqlQuery } from "../../src/shared/validation.js"; // ── Plugin-extended Octokit class ──────────────────────────────────────────── @@ -46,12 +47,11 @@ export function createOctokitClient(token: string): GitHubOctokitInstance { }, }); - // Read-only guard: block any non-GET request except POST /graphql - // (GraphQL queries are read-only but always use POST). + // Read-only guard: block any non-GET request except read-only POST /graphql queries. client.hook.before("request", (options) => { const method = (options.method ?? "GET").toUpperCase(); if (method === "GET") return; - if (method === "POST" && options.url === "/graphql") return; + if (method === "POST" && options.url === "/graphql" && isReadOnlyGraphqlQuery(options.query)) return; throw new Error( `[mcp] Write operation blocked: ${method} ${options.url}. This server is read-only.` ); diff --git a/mcp/tests/octokit.test.ts b/mcp/tests/octokit.test.ts index 6f6a0fae..1bf6c1a0 100644 --- a/mcp/tests/octokit.test.ts +++ b/mcp/tests/octokit.test.ts @@ -55,6 +55,43 @@ describe("createOctokitClient — write guard hook", () => { }) ).rejects.toThrow("Write operation blocked"); }); + + it("blocks GraphQL mutations (including addPullRequestReview) on POST /graphql", async () => { + const { createOctokitClient } = await import("../src/octokit.js"); + const client = createOctokitClient("fake-token"); + + await expect( + client.request("POST /graphql", { + query: `mutation ApprovePullRequest($pullRequestId: ID!, $commitOID: GitObjectID!) { + addPullRequestReview(input: { pullRequestId: $pullRequestId, commitOID: $commitOID, event: APPROVE }) { + pullRequestReview { state } + } + }`, + variables: { + pullRequestId: "PR_kwDOtest42", + commitOID: "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2", + }, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `mutation { mergePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `# query { viewer { login } }\nmutation { closePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `subscription { viewer { login } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + }); }); // ── Singleton tests ─────────────────────────────────────────────────────────── diff --git a/src/app/components/dashboard/DashboardPage.tsx b/src/app/components/dashboard/DashboardPage.tsx index f86006de..93044619 100644 --- a/src/app/components/dashboard/DashboardPage.tsx +++ b/src/app/components/dashboard/DashboardPage.tsx @@ -14,9 +14,9 @@ import DependenciesTab from "./DependenciesTab"; import { isDependencyPr, expandBotLogins, needsBodyFallback, parseRenovateBody, type VersionInfo } from "../../lib/dependency-detection"; import { isRepoExcludedFromDependencies } from "../../lib/dependency-exclusion"; import { findDashboardIssues, parseAbandonedSection, resetAbandonedPatternCache, type AbandonedDependency } from "../../lib/dependency-dashboard"; -import { fetchDashboardIssueBodies, fetchDepPRBodies, fallbackToPreviousEnrichment, pickEnrichmentFields } from "../../services/api"; +import { fetchDashboardIssueBodies, fetchDepPRBodies, fallbackToPreviousEnrichment, pickEnrichmentFields, approvePullRequest } from "../../services/api"; import type { SortOption } from "../shared/SortDropdown"; -import type { Issue, PullRequest, WorkflowRun } from "../../services/api"; +import type { Issue, PullRequest, WorkflowRun, HotPRStatusUpdate } from "../../services/api"; import { fetchOrgs } from "../../services/api"; import { createPollCoordinator, @@ -36,10 +36,10 @@ import { JIRA_SETTINGS_ACTION, type JiraIssue } from "../../../shared/jira-types import { detectAndLookupJiraKeys } from "../../services/jira-keys"; import JiraAssignedTab from "./JiraAssignedTab"; import { updateRelaySnapshot } from "../../lib/mcp-relay"; -import { pushNotification, pushError } from "../../lib/errors"; +import { pushNotification, pushError, dismissNotificationBySource } from "../../lib/errors"; import { detectNewItems, dispatchNotifications } from "../../lib/notifications"; import { getClient, getGraphqlRateLimit, fetchRateLimitDetails } from "../../services/github"; -import { formatCount, prSizeCategory, rateLimitCssClass, stripParenthetical } from "../../lib/format"; +import { canApprovePR, formatCount, prSizeCategory, rateLimitCssClass, stripParenthetical } from "../../lib/format"; import { setsEqual } from "../../lib/collections"; import { withScrollLock } from "../../lib/scroll"; import { Tooltip } from "../shared/Tooltip"; @@ -179,6 +179,86 @@ const [depMeta, setDepMeta] = createSignal>(loa let _fetchingDashboardBodies = false; let _fetchingDepBodies = false; +const [approvingPRIds, setApprovingPRIds] = createSignal>(new Set()); +const RECENT_APPROVAL_TTL_MS = 60_000; +const recentlyApprovedPRs = new Map< + number, + { headSha: string; reviewDecision: PullRequest["reviewDecision"]; approvedAt: number } +>(); + +function applyRecentApprovalGuard(pr: PullRequest, currentLogin: string): void { + const now = Date.now(); + for (const [id, entry] of recentlyApprovedPRs) { + if (now - entry.approvedAt > RECENT_APPROVAL_TTL_MS) { + recentlyApprovedPRs.delete(id); + } + } + const entry = recentlyApprovedPRs.get(pr.id); + if (!entry) return; + if (pr.headSha && pr.headSha !== entry.headSha) { + recentlyApprovedPRs.delete(pr.id); + return; + } + // Keep the entry for the full 60s TTL even if Phase 2 `nodes()` already shows + // `viewerLatestReviewState === "APPROVED"`, because Phase 1's search index can lag + // behind `nodes()` on `reviewDecision` ("REVIEW_REQUIRED" / "CHANGES_REQUESTED" vs "APPROVED"). + pr.viewerLatestReviewState = "APPROVED"; + pr.viewerReviewRequested = false; + pr.reviewDecision = entry.reviewDecision; + const loginLower = currentLogin.toLowerCase(); + if (loginLower && !pr.reviewerLogins.some((r) => r.toLowerCase() === loginLower)) { + pr.reviewerLogins = [...pr.reviewerLogins, loginLower]; + } +} + +export function applyHotPollPRUpdates( + state: { pullRequests: PullRequest[] }, + prUpdates: ReadonlyMap, + currentLogin = "" +): Set { + const terminalPrIds = new Set(); + for (const [prId, update] of prUpdates) { + const s = update.state; + if (s === "CLOSED" || s === "MERGED") terminalPrIds.add(prId); + } + const loginLower = currentLogin.toLowerCase(); + for (const pr of state.pullRequests) { + const update = prUpdates.get(pr.id); + if (!update) continue; + pr.state = update.state; // detect closed/merged quickly + pr.checkStatus = update.checkStatus; + pr.reviewDecision = update.reviewDecision; + if (update.headSha) { + pr.headSha = update.headSha; + } + if (update.autoMergeMethod !== undefined) { + pr.autoMergeMethod = update.autoMergeMethod; + } + if (update.viewerLatestReviewState !== undefined) { + pr.viewerLatestReviewState = update.viewerLatestReviewState; + } + if (update.viewerReviewRequested !== undefined) { + if (update.viewerReviewRequested) { + pr.viewerReviewRequested = true; + } else if (update.viewerLatestReviewState === "APPROVED") { + pr.viewerReviewRequested = false; + } + } + if ( + loginLower && + (pr.viewerReviewRequested || pr.viewerLatestReviewState != null) && + !pr.reviewerLogins.some((r) => r.toLowerCase() === loginLower) + ) { + pr.reviewerLogins = [...pr.reviewerLogins, loginLower]; + } + applyRecentApprovalGuard(pr, currentLogin); + } + if (terminalPrIds.size > 0) { + state.pullRequests = state.pullRequests.filter((pr) => !terminalPrIds.has(pr.id)); + } + return terminalPrIds; +} + // Skip retrying a dep-PR body fetch that errored/timed out on its last attempt until // this cooldown elapses — prevents burning a full GRAPHQL_BODY_FETCH_TIMEOUT_MS timeout, // an undeduped Sentry event, and a repeated user notification every poll cycle for as @@ -201,6 +281,8 @@ onAuthCleared(() => { _fetchingDashboardBodies = false; _fetchingDepBodies = false; _depBodyFailureCooldown.clear(); + setApprovingPRIds(new Set()); + recentlyApprovedPRs.clear(); resetAbandonedPatternCache(); const coord = _coordinator(); if (coord) { @@ -260,6 +342,8 @@ async function pollFetch(): Promise { setHasFetchedFresh(true); const now = new Date(); + const currentLogin = user()?.login ?? ""; + for (const pr of data.pullRequests) applyRecentApprovalGuard(pr, currentLogin); if (phaseOneFired) { // Phase 1 fired — use fine-grained merge for the light→enriched @@ -291,14 +375,17 @@ async function pollFetch(): Promise { const regressing = e.enriched === false && pr.enriched !== false; if (!regressing) { Object.assign(pr, pickEnrichmentFields(e)); + pr.reviewDecision = e.reviewDecision; pr.enriched = e.enriched; } pr.nodeId = e.nodeId; pr.surfacedBy = e.surfacedBy; pr.starCount = e.starCount; + applyRecentApprovalGuard(pr, currentLogin); } } else { state.pullRequests = fallbackToPreviousEnrichment(state.pullRequests, data.pullRequests); + for (const pr of state.pullRequests) applyRecentApprovalGuard(pr, currentLogin); } })); } else { @@ -308,6 +395,7 @@ async function pollFetch(): Promise { // DOM updates are synchronous within the setter, so save/restore // around it to prevent scroll reset from DOM rebuild. const pullRequests = fallbackToPreviousEnrichment(dashboardData.pullRequests, data.pullRequests); + for (const pr of pullRequests) applyRecentApprovalGuard(pr, currentLogin); withScrollLock(() => { setDashboardData({ issues: data.issues, @@ -361,6 +449,25 @@ const [_coordinator, _setCoordinator] = createSignal void } | null>(null); const [_eventsCoordinator, _setEventsCoordinator] = createSignal<{ destroy: () => void } | null>(null); +function persistDashboardSnapshot(): void { + // Capture snapshot eagerly — a concurrent hot poll can mutate the store via produce + // between here and the deferred setTimeout write. + const snapshot = { + _v: CACHE_VERSION, + issues: [...dashboardData.issues], + pullRequests: [...dashboardData.pullRequests], + workflowRuns: [...dashboardData.workflowRuns], + lastRefreshedAt: dashboardData.lastRefreshedAt?.toISOString() ?? null, + }; + setTimeout(() => { + try { + localStorage.setItem(DASHBOARD_STORAGE_KEY, JSON.stringify(snapshot)); + } catch { + // Non-fatal + } + }, 0); +} + // Mutates data.issues[].surfacedBy and data.pullRequests[].surfacedBy in-place before merging. function handleTargetedData(data: DashboardData, affectedRepos: string[]): void { const affectedSet = new Set(affectedRepos.map(r => r.toLowerCase())); @@ -373,7 +480,9 @@ function handleTargetedData(data: DashboardData, affectedRepos: string[]): void } } const oldSurfacedByPRs = new Map(); + const existingPRById = new Map(); for (const pr of dashboardData.pullRequests) { + existingPRById.set(pr.id, pr); if (affectedSet.has(pr.repoFullName.toLowerCase()) && pr.surfacedBy?.length) { oldSurfacedByPRs.set(pr.id, pr.surfacedBy); } @@ -386,11 +495,18 @@ function handleTargetedData(data: DashboardData, affectedRepos: string[]): void item.surfacedBy = [...new Set([...(item.surfacedBy ?? []), ...oldSb])]; } } + const currentLogin = user()?.login ?? ""; for (const pr of data.pullRequests) { const oldSb = oldSurfacedByPRs.get(pr.id); if (oldSb) { pr.surfacedBy = [...new Set([...(pr.surfacedBy ?? []), ...oldSb])]; } + const existingPr = existingPRById.get(pr.id); + if (existingPr && pr.enriched === false && existingPr.enriched !== false) { + Object.assign(pr, pickEnrichmentFields(existingPr)); + pr.enriched = existingPr.enriched; + } + applyRecentApprovalGuard(pr, currentLogin); } withScrollLock(() => { @@ -432,24 +548,7 @@ function handleTargetedData(data: DashboardData, affectedRepos: string[]): void dispatchNotifications(newItems, config); seedHotSetsFromTargeted(data); - - // Capture snapshot eagerly — a concurrent hot poll can mutate the store via produce - // between here and the deferred setTimeout write. - const lastRefreshed = dashboardData.lastRefreshedAt; - const snapshot = { - _v: CACHE_VERSION, - issues: [...dashboardData.issues], - pullRequests: [...dashboardData.pullRequests], - workflowRuns: [...dashboardData.workflowRuns], - lastRefreshedAt: lastRefreshed?.toISOString() ?? null, - }; - setTimeout(() => { - try { - localStorage.setItem(DASHBOARD_STORAGE_KEY, JSON.stringify(snapshot)); - } catch { - // Non-fatal - } - }, 0); + persistDashboardSnapshot(); } export default function DashboardPage() { @@ -739,20 +838,10 @@ export default function DashboardPage() { // If a full refresh completed during the fetch, _hotPollGeneration will have // been incremented by rebuildHotSets(), and fetchGeneration will be stale. if (fetchGeneration !== getHotPollGeneration()) return; // stale, discard - const terminalPrIds = new Set(); - for (const [prId, update] of prUpdates) { - const s = update.state; - if (s === "CLOSED" || s === "MERGED") terminalPrIds.add(prId); - } + let terminalPrIds = new Set(); setDashboardData(produce((state) => { - // Apply PR status updates - for (const pr of state.pullRequests) { - const update = prUpdates.get(pr.id); - if (!update) continue; - pr.state = update.state; // detect closed/merged quickly - pr.checkStatus = update.checkStatus; - pr.reviewDecision = update.reviewDecision; - } + const currentLogin = user()?.login ?? ""; + terminalPrIds = applyHotPollPRUpdates(state, prUpdates, currentLogin); // Apply workflow run updates for (const run of state.workflowRuns) { const update = runUpdates.get(run.id); @@ -762,9 +851,6 @@ export default function DashboardPage() { run.updatedAt = update.updatedAt; run.completedAt = update.completedAt; } - if (terminalPrIds.size > 0) { - state.pullRequests = state.pullRequests.filter((pr) => !terminalPrIds.has(pr.id)); - } })); if (terminalPrIds.size > 0) { console.info(`[hot-poll] Spliced ${terminalPrIds.size} terminal PR(s) from store`); @@ -1335,6 +1421,130 @@ export default function DashboardPage() { [...new Set([...config.selectedRepos, ...config.upstreamRepos, ...config.monitoredRepos].map(r => r.fullName))] ); + function isPermissionDeniedError(err: unknown): boolean { + if (!err || typeof err !== "object") return false; + const errObj = err as Record; + if (Array.isArray(errObj.errors)) { + for (const item of errObj.errors) { + if (item && typeof item === "object") { + const type = (item as Record).type; + const msg = String((item as Record).message ?? ""); + if ( + type === "FORBIDDEN" || + type === "INSUFFICIENT_SCOPES" || + /resource not accessible by personal access token|insufficient_scopes|write access/i.test(msg) + ) { + return true; + } + } + } + } + if (errObj.status === 403) { + const headers = (errObj.response as { headers?: Record } | undefined)?.headers; + if (headers?.["x-ratelimit-remaining"] === "0" || headers?.["retry-after"]) return false; + return true; + } + return false; + } + + function isStaleCommitError(err: unknown): boolean { + if (!err || typeof err !== "object") return false; + const errObj = err as Record; + const msg = err instanceof Error ? err.message : String(errObj.message ?? ""); + return /commitOID|was not part of the pull request|pull request head|outdated|end of the branch/i.test(msg); + } + + async function handleApprovePR(pr: PullRequest): Promise { + const currentLogin = userLogin(); + if (!canApprovePR(pr, currentLogin)) return; + if (approvingPRIds().has(pr.id)) return; + const client = getClient(); + if (!client || !pr.nodeId || !pr.headSha) return; + const nodeId = pr.nodeId; + const approvedHeadSha = pr.headSha; + const priorReviewDecision = pr.reviewDecision; + + // Clear any prior notification for this PR so a retry with the same error message + // is not suppressed by pushNotification's same-message no-op guard. + dismissNotificationBySource(`approve-pr:${pr.id}`); + + setApprovingPRIds((prev) => { + const next = new Set(prev); + next.add(pr.id); + return next; + }); + + try { + const result = await approvePullRequest(client, nodeId, approvedHeadSha); + if (getClient() !== client) return; + + const nextDecision: PullRequest["reviewDecision"] = + result.reviewDecision ?? (priorReviewDecision === "REVIEW_REQUIRED" ? "APPROVED" : priorReviewDecision); + + recentlyApprovedPRs.set(pr.id, { + headSha: approvedHeadSha, + reviewDecision: nextDecision, + approvedAt: Date.now(), + }); + + setDashboardData( + produce((state) => { + const target = state.pullRequests.find((item) => item.id === pr.id); + if (target) applyRecentApprovalGuard(target, currentLogin); + }) + ); + + // Seed the approved PR into _hotPRs so the next hot-poll cycle detects if + // GitHub auto-merged it (splicing it from dashboardData.pullRequests via onHotData), + // even when checkStatus was already "success" prior to approval. + seedHotSetsFromTargeted({ + issues: [], + pullRequests: [{ ...pr, nodeId, headSha: approvedHeadSha, enriched: true, checkStatus: "pending" }], + workflowRuns: [], + errors: [], + }); + + persistDashboardSnapshot(); + } catch (err) { + if (getClient() !== client) return; + const status = + typeof err === "object" && err !== null && typeof (err as Record).status === "number" + ? ((err as Record).status as number) + : null; + if (status === 401) { + expireToken(); + window.location.replace("/login"); + return; + } + if (isPermissionDeniedError(err)) { + pushNotification( + `approve-pr:${pr.id}`, + "Unable to approve PR: your token lacks Pull Requests write permission. For fine-grained PATs, set 'Pull requests' to 'Read and write' in GitHub Settings, then replace your token in Settings.", + "error" + ); + return; + } + if (isStaleCommitError(err)) { + pushNotification( + `approve-pr:${pr.id}`, + `Could not approve ${pr.repoFullName}#${pr.number}: new commits were pushed — refreshing`, + "warning" + ); + _coordinator()?.manualRefresh(); + return; + } + const message = err instanceof Error ? err.message : "Unknown error"; + pushNotification(`approve-pr:${pr.id}`, `Failed to approve ${pr.repoFullName}#${pr.number}: ${message}`, "error"); + } finally { + setApprovingPRIds((prev) => { + if (!prev.has(pr.id)) return prev; + const next = new Set(prev); + next.delete(pr.id); + return next; + }); + } + } + return (
@@ -1405,6 +1615,8 @@ export default function DashboardPage() { refreshTick={refreshTick()} jiraKeyMap={jiraKeyMap} depPrIds={dependencyPrIds()} + onApprovePR={handleApprovePR} + approvingPRIds={approvingPRIds()} /> @@ -1420,20 +1632,8 @@ export default function DashboardPage() { userLogin={userLogin()} trackedBotLogins={trackedBotLogins()} onRefresh={() => _coordinator()?.manualRefresh()} - /> - - - _coordinator()?.manualRefresh()} + onApprovePR={handleApprovePR} + approvingPRIds={approvingPRIds()} /> @@ -1444,6 +1644,8 @@ export default function DashboardPage() { refreshTick={refreshTick()} userLogin={userLogin()} hotPollingPRIds={hotPollingPRIds()} + onApprovePR={handleApprovePR} + approvingPRIds={approvingPRIds()} /> @@ -1508,6 +1710,8 @@ export default function DashboardPage() { customTabId={tab().id} filterPreset={tab().filterPreset} jiraKeyMap={jiraKeyMap} + onApprovePR={handleApprovePR} + approvingPRIds={approvingPRIds()} /> diff --git a/src/app/components/dashboard/DependenciesTab.tsx b/src/app/components/dashboard/DependenciesTab.tsx index 00158b3a..b1ddd204 100644 --- a/src/app/components/dashboard/DependenciesTab.tsx +++ b/src/app/components/dashboard/DependenciesTab.tsx @@ -3,6 +3,7 @@ import { config, updateConfig } from "../../stores/config"; import { viewState, setTabFilter, resetAllTabFilters, ignoreItem, unignoreItem, trackItem, untrackItem, DependencyFiltersSchema, setDependencyExpandedGroups } from "../../stores/view"; import IgnoreBadge from "./IgnoreBadge"; import { isSafeGitHubUrl } from "../../lib/url"; +import { canApprovePR } from "../../lib/format"; import type { PullRequest } from "../../services/api"; import type { AbandonedDependency } from "../../lib/dependency-dashboard"; import { @@ -23,6 +24,7 @@ import RepoGroupHeader from "../shared/RepoGroupHeader"; import StatusDot from "../shared/StatusDot"; import SizeBadge from "../shared/SizeBadge"; import ReviewBadge from "../shared/ReviewBadge"; +import AutoMergeBadge from "../shared/AutoMergeBadge"; import ItemRow from "./ItemRow"; import SkeletonRows from "../shared/SkeletonRows"; @@ -110,6 +112,8 @@ interface DependenciesTabProps { userLogin: string; trackedBotLogins: ReadonlySet; onRefresh?: () => void; + onApprovePR?: (pr: PullRequest) => void; + approvingPRIds?: ReadonlySet; } export default function DependenciesTab(props: DependenciesTabProps) { @@ -363,6 +367,9 @@ export default function DependenciesTab(props: DependenciesTabProps) { enableTracking={config.enableTracking} onIgnore={handleIgnore} onTrack={handleTrack} + userLogin={props.userLogin} + onApprovePR={props.onApprovePR} + approvingPRIds={props.approvingPRIds} /> )} @@ -385,6 +392,9 @@ interface StatusGroupProps { enableTracking: boolean; onIgnore: (pr: PullRequest) => void; onTrack: (pr: PullRequest) => void; + userLogin: string; + onApprovePR?: (pr: PullRequest) => void; + approvingPRIds?: ReadonlySet; } function stripCommitPrefix(title: string): string { @@ -436,6 +446,9 @@ function StatusGroup(props: StatusGroupProps) { onIgnore={() => props.onIgnore(pr)} onTrack={props.enableTracking ? () => props.onTrack(pr) : undefined} isTracked={props.enableTracking ? props.trackedPrIds.has(pr.id) : undefined} + onApprove={props.onApprovePR && canApprovePR(pr, props.userLogin) ? () => props.onApprovePR!(pr) : undefined} + isApproving={props.approvingPRIds?.has(pr.id)} + approveAutoMerge={pr.autoMergeMethod != null} isPolling={props.hotPollingPRIds?.has(pr.id)} hideAuthor hideNumber @@ -451,10 +464,8 @@ function StatusGroup(props: StatusGroupProps) {
- - - + 0 || pr.deletions > 0)}> diff --git a/src/app/components/dashboard/ItemRow.tsx b/src/app/components/dashboard/ItemRow.tsx index 07f8ccbf..424b9340 100644 --- a/src/app/components/dashboard/ItemRow.tsx +++ b/src/app/components/dashboard/ItemRow.tsx @@ -1,4 +1,4 @@ -import { createMemo, For, JSX, Show } from "solid-js"; +import { createEffect, createMemo, createSignal, For, JSX, on, onCleanup, Show } from "solid-js"; import { config } from "../../stores/config"; import { isSafeGitHubUrl } from "../../lib/url"; import { relativeTime, shortRelativeTime, formatCount } from "../../lib/format"; @@ -20,6 +20,12 @@ export interface ItemRowProps { onIgnore?: () => void; onTrack?: () => void; isTracked?: boolean; + /** Callback invoked on the second (confirmation) click of the Approve button */ + onApprove?: () => void; + /** True while an approval mutation for this PR is in flight */ + isApproving?: boolean; + /** True when auto-merge is enabled on the PR, adding an auto-merge hint on the Confirm step */ + approveAutoMerge?: boolean; commentCount?: number; hideRepo?: boolean; hideAuthor?: boolean; @@ -35,6 +41,66 @@ export default function ItemRow(props: ItemRowProps) { const isCompact = createMemo(() => config.viewDensity === "compact"); const safeUrl = () => isSafeGitHubUrl(props.url) ? props.url : undefined; + const APPROVE_CONFIRM_TIMEOUT_MS = 4_000; + const [confirmingApprove, setConfirmingApprove] = createSignal(false); + let approveConfirmTimer: ReturnType | undefined; + + function clearApproveTimer() { + if (approveConfirmTimer !== undefined) { + clearTimeout(approveConfirmTimer); + approveConfirmTimer = undefined; + } + } + + function resetApproveConfirm() { + clearApproveTimer(); + setConfirmingApprove(false); + } + + const isApproving = createMemo(() => Boolean(props.isApproving)); + const approveAutoMerge = createMemo(() => Boolean(props.approveAutoMerge)); + + createEffect( + on( + [() => props.onApprove, approveAutoMerge, isApproving], + (curr, prev) => { + if (!prev || curr.some((v, i) => v !== prev[i])) { + resetApproveConfirm(); + } + }, + { defer: true }, + ), + ); + + onCleanup(() => { + clearApproveTimer(); + }); + + function handleApproveClick(e: MouseEvent) { + e.stopPropagation(); + e.preventDefault(); + if (props.isApproving || !props.onApprove) return; + if (!confirmingApprove()) { + setConfirmingApprove(true); + clearApproveTimer(); + approveConfirmTimer = setTimeout(() => { + approveConfirmTimer = undefined; + setConfirmingApprove(false); + }, APPROVE_CONFIRM_TIMEOUT_MS); + return; + } + resetApproveConfirm(); + props.onApprove(); + } + + function handleApproveKeyDown(e: KeyboardEvent) { + if (e.key === "Escape" && confirmingApprove()) { + e.stopPropagation(); + e.preventDefault(); + resetApproveConfirm(); + } + } + // Static date info — recomputed only when createdAt/updatedAt change (not on tick) const staticDateInfo = createMemo(() => { const createdTitle = `Created: ${new Date(props.createdAt).toLocaleString()}`; @@ -86,6 +152,75 @@ export default function ItemRow(props: ItemRowProps) { return slash >= 0 ? props.repo.slice(slash + 1) : props.repo; }); + const approveButtonMeta = createMemo(() => { + if (props.isApproving) { + return { + wrapperClass: "ml-2 max-w-40 opacity-100 pointer-events-auto", + tooltip: "Submitting approval...", + buttonClass: "btn-ghost", + ariaLabel: `Approving #${props.number} ${props.title}`, + }; + } + if (confirmingApprove()) { + return { + wrapperClass: "ml-2 max-w-40 opacity-100 pointer-events-auto", + tooltip: props.approveAutoMerge + ? "Click again to confirm approval (auto-merge enabled)" + : "Click again to confirm approval", + buttonClass: "btn-warning", + ariaLabel: props.approveAutoMerge + ? `Confirm approve #${props.number} ${props.title} (auto-merge enabled)` + : `Confirm approve #${props.number} ${props.title}`, + }; + } + return { + wrapperClass: + "max-w-0 opacity-0 pointer-events-none group-hover:ml-2 group-hover:max-w-40 group-hover:opacity-100 group-hover:pointer-events-auto focus-within:ml-2 focus-within:max-w-40 focus-within:opacity-100 focus-within:pointer-events-auto", + tooltip: "Approve this pull request", + buttonClass: "btn-ghost text-success hover:bg-success/15", + ariaLabel: `Approve #${props.number} ${props.title}`, + }; + }); + + const renderApproveButton = () => ( + + + + + + ); + return (
{props.titlePrefix}
- {/* Title — truncated, fills available space */} - - {props.title} - + {/* Title + inline hover Approve button — fills available space */} +
+ + {props.title} + + {renderApproveButton()} +
{/* Children (badges) inline */} @@ -221,9 +359,12 @@ export default function ItemRow(props: ItemRowProps) {
{props.titlePrefix}
- - {props.title} - +
+ + {props.title} + + {renderApproveButton()} +
{/* Labels row */} diff --git a/src/app/components/dashboard/PullRequestsTab.tsx b/src/app/components/dashboard/PullRequestsTab.tsx index 6b8298d6..8e44d9c2 100644 --- a/src/app/components/dashboard/PullRequestsTab.tsx +++ b/src/app/components/dashboard/PullRequestsTab.tsx @@ -4,7 +4,7 @@ import { viewState, ignoreItem, unignoreItem, toggleExpandedRepo, setAllExpanded import { createTabFilterHandlers, mergeActiveFilters } from "../../lib/tabFilters"; import { isPrVisible } from "../../lib/filters"; import type { PullRequest, RepoRef } from "../../services/api"; -import { deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; +import { canApprovePR, deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; import { isSafeGitHubUrl } from "../../lib/url"; import ExpandCollapseButtons from "../shared/ExpandCollapseButtons"; import ItemRow from "./ItemRow"; @@ -15,6 +15,7 @@ import PaginationControls from "../shared/PaginationControls"; import { scopeFilterGroup, prFilterGroups, type FilterChipGroupDef } from "../shared/filterTypes"; import FilterToolbar from "../shared/FilterToolbar"; import ReviewBadge from "../shared/ReviewBadge"; +import AutoMergeBadge from "../shared/AutoMergeBadge"; import SizeBadge from "../shared/SizeBadge"; import RoleBadge from "../shared/RoleBadge"; import SkeletonRows from "../shared/SkeletonRows"; @@ -43,6 +44,8 @@ export interface PullRequestsTabProps { filterPreset?: Record; jiraKeyMap?: () => ReadonlyMap; depPrIds?: ReadonlySet; + onApprovePR?: (pr: PullRequest) => void; + approvingPRIds?: ReadonlySet; } type SortField = "repo" | "title" | "author" | "createdAt" | "updatedAt" | "checkStatus" | "reviewDecision" | "size"; @@ -523,6 +526,9 @@ export default function PullRequestsTab(props: PullRequestsTabProps) { onIgnore={() => handleIgnore(pr)} onTrack={config.enableTracking ? () => handleTrack(pr) : undefined} isTracked={config.enableTracking ? trackedPrIds().has(pr.id) : undefined} + onApprove={props.onApprovePR && canApprovePR(pr, props.userLogin) ? () => props.onApprovePR!(pr) : undefined} + isApproving={props.approvingPRIds?.has(pr.id)} + approveAutoMerge={pr.autoMergeMethod != null} surfacedByBadge={ props.trackedUsers && props.trackedUsers.length > 0 ? + @@ -576,6 +583,7 @@ export default function PullRequestsTab(props: PullRequestsTabProps) { + diff --git a/src/app/components/dashboard/TrackedTab.tsx b/src/app/components/dashboard/TrackedTab.tsx index f48191c0..d1301896 100644 --- a/src/app/components/dashboard/TrackedTab.tsx +++ b/src/app/components/dashboard/TrackedTab.tsx @@ -3,11 +3,12 @@ import { config } from "../../stores/config"; import { viewState, untrackItem, moveTrackedItem, untrackJiraItem, moveJiraItem } from "../../stores/view"; import type { TrackedItem } from "../../stores/view"; import type { Issue, PullRequest } from "../../services/api"; -import { deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; +import { canApprovePR, deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; import { isSafeGitHubUrl } from "../../lib/url"; import ItemRow from "./ItemRow"; import StatusDot from "../shared/StatusDot"; import ReviewBadge from "../shared/ReviewBadge"; +import AutoMergeBadge from "../shared/AutoMergeBadge"; import SizeBadge from "../shared/SizeBadge"; import RoleBadge from "../shared/RoleBadge"; import { Tooltip } from "../shared/Tooltip"; @@ -76,6 +77,8 @@ export interface TrackedTabProps { refreshTick?: number; userLogin: string; hotPollingPRIds?: ReadonlySet; + onApprovePR?: (pr: PullRequest) => void; + approvingPRIds?: ReadonlySet; } export default function TrackedTab(props: TrackedTabProps) { @@ -248,6 +251,9 @@ export default function TrackedTab(props: TrackedTabProps) { commentCount={commentCount()} onTrack={() => untrackItem(item.id, item.type as "issue" | "pullRequest")} isTracked={true} + onApprove={pr() && props.onApprovePR && canApprovePR(pr()!, props.userLogin) ? () => props.onApprovePR!(pr()!) : undefined} + isApproving={item.type === "pullRequest" && props.approvingPRIds?.has(item.id)} + approveAutoMerge={pr()?.autoMergeMethod != null} isPolling={item.type === "pullRequest" && props.hotPollingPRIds?.has(item.id)} > + @@ -295,6 +302,7 @@ export default function TrackedTab(props: TrackedTabProps) { + diff --git a/src/app/components/shared/AutoMergeBadge.tsx b/src/app/components/shared/AutoMergeBadge.tsx new file mode 100644 index 00000000..0a1377e3 --- /dev/null +++ b/src/app/components/shared/AutoMergeBadge.tsx @@ -0,0 +1,26 @@ +import { Show } from "solid-js"; +import type { AutoMergeMethod } from "../../services/api"; +import { Tooltip } from "./Tooltip"; + +export interface AutoMergeBadgeProps { + method?: AutoMergeMethod | null; + compact?: boolean; +} + +export default function AutoMergeBadge(props: AutoMergeBadgeProps) { + return ( + + {(method) => ( + + + auto + + + )} + + ); +} diff --git a/src/app/lib/format.ts b/src/app/lib/format.ts index 04993943..a3a7dd2b 100644 --- a/src/app/lib/format.ts +++ b/src/app/lib/format.ts @@ -1,5 +1,5 @@ // Re-exports from shared/format for backward compat with existing importers. -export { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount } from "../../shared/format"; +export { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, canApprovePR } from "../../shared/format"; export function stripParenthetical(name: string): string { return name.replace(/\s*\(.*\)$/, ""); diff --git a/src/app/pages/LoginPage.tsx b/src/app/pages/LoginPage.tsx index 6563f139..6dce0326 100644 --- a/src/app/pages/LoginPage.tsx +++ b/src/app/pages/LoginPage.tsx @@ -287,7 +287,7 @@ export default function LoginPage() { > Fine-grained tokens - {" "}also work, but only access one org at a time. Add read-only permissions for Actions, Contents, Issues, and Pull requests. + {" "}also work, but only access one org at a time. Add read-only permissions for Actions, Contents, and Issues, plus Read and write for Pull requests (or read-only if you don't approve PRs from the dashboard).

diff --git a/src/app/pages/PrivacyPage.tsx b/src/app/pages/PrivacyPage.tsx index 8ae75ccd..8e26b40a 100644 --- a/src/app/pages/PrivacyPage.tsx +++ b/src/app/pages/PrivacyPage.tsx @@ -194,9 +194,11 @@ export default function PrivacyPage() { GitHub API access

- The app accesses the GitHub API on your behalf using an OAuth token. - It reads your issues, pull requests, and workflow runs — nothing is - written. You can revoke access at any time from{" "} + The app accesses the GitHub API on your behalf using an OAuth token or + Personal Access Token. It reads your issues, pull requests, and workflow + runs, and only writes to GitHub when you explicitly click and confirm + Approve on a pull request. All other write operations are blocked + client-side. You can revoke access at any time from{" "} = { fetchOrgs: "Fetch Orgs", fetchRepos: "Fetch Repos", rateLimitCheck: "Rate Limit Check", + approvePR: "Approve PR", graphql: "GraphQL (other)", rest: "REST (other)", }; diff --git a/src/app/services/api.ts b/src/app/services/api.ts index ea2f285c..d27ec4c6 100644 --- a/src/app/services/api.ts +++ b/src/app/services/api.ts @@ -3,13 +3,13 @@ import * as Sentry from "@sentry/solid"; import { pushNotification } from "../lib/errors"; import type { ApiCallSource } from "./api-usage"; import type { TrackedUser } from "../stores/config"; -import { VALID_REPO_NAME, VALID_TRACKED_LOGIN, SEARCH_RESULT_CAP } from "../../shared/validation"; +import { VALID_REPO_NAME, VALID_TRACKED_LOGIN, SEARCH_RESULT_CAP, APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE } from "../../shared/validation"; import { REPO_CAP } from "../../shared/types"; -import type { Issue, IssueState, PullRequest, PullRequestState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError } from "../../shared/types"; +import type { Issue, IssueState, PullRequest, PullRequestState, AutoMergeMethod, ViewerReviewState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError } from "../../shared/types"; // ── Re-exports from shared/types (backward compat for existing importers) ───── export { REPO_CAP }; -export type { Issue, IssueState, PullRequest, PullRequestState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError, RateLimitInfo, DashboardSummary } from "../../shared/types"; +export type { Issue, IssueState, PullRequest, PullRequestState, AutoMergeMethod, ViewerReviewState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError, RateLimitInfo, DashboardSummary } from "../../shared/types"; // ── Types ──────────────────────────────────────────────────────────────────── @@ -399,6 +399,9 @@ const HEAVY_PR_BACKFILL_QUERY = ` changedFiles comments { totalCount } reviewThreads { totalCount } + autoMergeRequest { mergeMethod } + viewerLatestReview { state } + viewerLatestReviewRequest { id } commits(last: 1) { nodes { commit { @@ -419,8 +422,12 @@ const HOT_PR_STATUS_QUERY = ` ... on PullRequest { databaseId state + headRefOid mergeStateStatus reviewDecision + autoMergeRequest { mergeMethod } + viewerLatestReview { state } + viewerLatestReviewRequest { id } commits(last: 1) { nodes { commit { @@ -437,8 +444,12 @@ const HOT_PR_STATUS_QUERY = ` interface HotPRStatusNode { databaseId: number; state: PullRequestState; + headRefOid?: string; mergeStateStatus: string; reviewDecision: string | null; + autoMergeRequest?: { mergeMethod: string } | null; + viewerLatestReview?: { state: string } | null; + viewerLatestReviewRequest?: { id: string } | null; commits: { nodes: { commit: { statusCheckRollup: { state: string } | null } }[] }; } @@ -481,6 +492,9 @@ interface GraphQLHeavyPRNode { changedFiles: number; comments: { totalCount: number }; reviewThreads: { totalCount: number }; + autoMergeRequest?: { mergeMethod: string } | null; + viewerLatestReview?: { state: string } | null; + viewerLatestReviewRequest?: { id: string } | null; commits: { nodes: { commit: { @@ -750,10 +764,16 @@ interface LightSearchResult { function processLightPRNode( node: GraphQLLightPRNode, prMap: Map, - nodeIdMap: Map + nodeIdMap: Map, + isViewerReviewRequested = false, ): boolean { if (node.databaseId == null || !node.repository) return false; - if (prMap.has(node.databaseId)) return false; + if (prMap.has(node.databaseId)) { + if (isViewerReviewRequested) { + prMap.get(node.databaseId)!.viewerReviewRequested = true; + } + return false; + } nodeIdMap.set(node.databaseId, node.id); prMap.set(node.databaseId, { @@ -782,6 +802,9 @@ function processLightPRNode( labels: node.labels.nodes.map((l) => ({ name: l.name, color: l.color })), reviewDecision: mapReviewDecision(node.reviewDecision), totalReviewCount: 0, + autoMergeMethod: null, + viewerReviewRequested: isViewerReviewRequested, + viewerLatestReviewState: null, starCount: node.repository.stargazerCount, enriched: false, nodeId: node.id, @@ -853,7 +876,7 @@ async function executeLightCombinedQuery( for (const node of response.prReviewReq.nodes) { if (prMap.size >= prCap) break; if (!node) continue; - processLightPRNode(node, prMap, nodeIdMap); + processLightPRNode(node, prMap, nodeIdMap, source === "lightSearch"); } if (isPartial) return; @@ -877,7 +900,7 @@ async function executeLightCombinedQuery( if (response.prReviewReq.pageInfo.hasNextPage && response.prReviewReq.pageInfo.endCursor && prMap.size < prCap) { prPaginationTasks.push(paginateGraphQLSearch( octokit, LIGHT_PR_SEARCH_QUERY, prRevQ, errorLabel, errors, - (node) => processLightPRNode(node, prMap, nodeIdMap), + (node) => processLightPRNode(node, prMap, nodeIdMap, source === "lightSearch"), () => prMap.size, prCap, source, response.prReviewReq.pageInfo.endCursor, )); } @@ -1081,6 +1104,9 @@ export interface PREnrichmentData { comments: number; reviewThreads: number; totalReviewCount: number; + autoMergeMethod: AutoMergeMethod | null; + viewerReviewRequested: boolean; + viewerLatestReviewState: ViewerReviewState | null; } /** @@ -1145,6 +1171,9 @@ export async function fetchPREnrichment( comments: node.comments.totalCount, reviewThreads: node.reviewThreads.totalCount, totalReviewCount: node.latestReviews.totalCount, + autoMergeMethod: mapAutoMergeMethod(node.autoMergeRequest?.mergeMethod), + viewerReviewRequested: Boolean(node.viewerLatestReviewRequest?.id), + viewerLatestReviewState: mapViewerReviewState(node.viewerLatestReview?.state), }); } } catch (err) { @@ -1351,6 +1380,9 @@ type EnrichmentFields = Pick< | "comments" | "reviewThreads" | "totalReviewCount" + | "autoMergeMethod" + | "viewerReviewRequested" + | "viewerLatestReviewState" >; /** Extracts just the heavy enrichment fields from any PR-shaped source. */ @@ -1366,6 +1398,9 @@ export function pickEnrichmentFields(source: EnrichmentFields): EnrichmentFields comments: source.comments, reviewThreads: source.reviewThreads, totalReviewCount: source.totalReviewCount, + autoMergeMethod: source.autoMergeMethod, + viewerReviewRequested: source.viewerReviewRequested, + viewerLatestReviewState: source.viewerLatestReviewState, }; } @@ -1376,7 +1411,8 @@ export function pickEnrichmentFields(source: EnrichmentFields): EnrichmentFields function mergeEnrichment( lightPRs: PullRequest[], enrichments: Map, - forkInfoMap: Map + forkInfoMap: Map, + viewerLogin = "", ): PullRequest[] { return lightPRs.map((pr) => { const e = enrichments.get(pr.id); @@ -1386,9 +1422,22 @@ function mergeEnrichment( forkInfoMap.set(pr.id, e.headRepository); } + const viewerReviewRequested = + e.viewerLatestReviewState === "APPROVED" && !e.viewerReviewRequested + ? false + : Boolean(pr.viewerReviewRequested || e.viewerReviewRequested); + const reviewerLogins = + viewerLogin && + (viewerReviewRequested || e.viewerLatestReviewState !== null) && + !e.reviewerLogins.includes(viewerLogin) + ? [...e.reviewerLogins, viewerLogin] + : e.reviewerLogins; + return { ...pr, ...pickEnrichmentFields(e), + reviewerLogins, + viewerReviewRequested, enriched: true, }; }); @@ -1605,7 +1654,7 @@ export async function fetchIssuesAndPullRequests( // Apply main backfill enrichments to all PRs (main user PRs get enriched, tracked-only PRs get nothing yet) let enrichedPRs = mainBackfill.enrichments.size > 0 - ? mergeEnrichment(mergedPRs, mainBackfill.enrichments, forkInfoMap) + ? mergeEnrichment(mergedPRs, mainBackfill.enrichments, forkInfoMap, normalizedLogin) : mergedPRs; // Delta backfill: enrich PRs not already covered by main backfill — @@ -1621,7 +1670,7 @@ export async function fetchIssuesAndPullRequests( if (deltaNodeIds.length > 0) { const delta = await fetchPREnrichment(octokit, deltaNodeIds); backfillErrors.push(...delta.errors); - enrichedPRs = mergeEnrichment(enrichedPRs, delta.enrichments, forkInfoMap); + enrichedPRs = mergeEnrichment(enrichedPRs, delta.enrichments, forkInfoMap, normalizedLogin); } // Fork PR fallback for enriched PRs @@ -1676,6 +1725,24 @@ function mapReviewDecision( return null; } +function mapAutoMergeMethod(raw: string | null | undefined): AutoMergeMethod | null { + if (raw === "MERGE" || raw === "SQUASH" || raw === "REBASE") return raw; + return null; +} + +function mapViewerReviewState(raw: string | null | undefined): ViewerReviewState | null { + if ( + raw === "APPROVED" || + raw === "CHANGES_REQUESTED" || + raw === "COMMENTED" || + raw === "DISMISSED" || + raw === "PENDING" + ) { + return raw; + } + return null; +} + // ── Step 1: fetchOrgs ──────────────────────────────────────────────────────── /** @@ -1915,6 +1982,10 @@ export interface HotPRStatusUpdate { checkStatus: CheckStatus["status"]; mergeStateStatus: string; reviewDecision: PullRequest["reviewDecision"]; + headSha?: string; + autoMergeMethod?: AutoMergeMethod | null; + viewerReviewRequested?: boolean; + viewerLatestReviewState?: ViewerReviewState | null; } /** @@ -1951,6 +2022,10 @@ export async function fetchHotPRStatus( checkStatus, mergeStateStatus: node.mergeStateStatus, reviewDecision: mapReviewDecision(node.reviewDecision), + ...(node.headRefOid ? { headSha: node.headRefOid } : {}), + autoMergeMethod: mapAutoMergeMethod(node.autoMergeRequest?.mergeMethod), + viewerReviewRequested: Boolean(node.viewerLatestReviewRequest?.id), + viewerLatestReviewState: mapViewerReviewState(node.viewerLatestReview?.state), }); } })); @@ -2151,3 +2226,50 @@ export async function discoverUpstreamRepos( if (repos.length > CAP) repos.splice(CAP); return repos; } + +// ── PR Approval Mutation ───────────────────────────────────────────────────── + +interface ApprovePullRequestResponse { + addPullRequestReview: { + pullRequestReview: { + state: string | null; + pullRequest: { + reviewDecision: string | null; + } | null; + } | null; + } | null; + rateLimit?: GraphQLRateLimit; +} + +export async function approvePullRequest( + octokit: GitHubOctokit, + pullRequestId: string, + commitOID: string, +): Promise<{ state: ViewerReviewState | null; reviewDecision: PullRequest["reviewDecision"] }> { + if (!GITHUB_NODE_ID_RE.test(pullRequestId)) { + throw new Error(`Invalid pullRequestId: "${pullRequestId}"`); + } + if (!GIT_SHA_RE.test(commitOID)) { + throw new Error(`Invalid commitOID: "${commitOID}"`); + } + + const response = await octokit.graphql(APPROVE_PR_MUTATION, { + pullRequestId, + commitOID, + request: { apiSource: "approvePR", retries: 0 }, + }); + + if (response.rateLimit) { + updateGraphqlRateLimit(response.rateLimit); + } + + const review = response.addPullRequestReview?.pullRequestReview; + const state = mapViewerReviewState(review?.state); + if (state !== "APPROVED") { + throw new Error("GitHub did not confirm pull request approval"); + } + return { + state, + reviewDecision: mapReviewDecision(review?.pullRequest?.reviewDecision ?? null), + }; +} diff --git a/src/app/services/github.ts b/src/app/services/github.ts index 0c6e4123..563d57bb 100644 --- a/src/app/services/github.ts +++ b/src/app/services/github.ts @@ -6,6 +6,41 @@ import { paginateRest } from "@octokit/plugin-paginate-rest"; import { cachedFetch, type ConditionalHeaders } from "../stores/cache"; import { token } from "../stores/auth"; import { pushNotification } from "../lib/errors"; +import { APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, isReadOnlyGraphqlQuery } from "../../shared/validation"; + +export { APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, isReadOnlyGraphqlQuery }; + +const NORMALIZED_APPROVE_MUTATION = APPROVE_PR_MUTATION.replace(/\s+/g, " "); + +function isAllowedGraphqlRequest(options: { query?: unknown; variables?: unknown }): boolean { + if (typeof options.query !== "string") return false; + + // 1. Allow read-only GraphQL queries (starts with `query` or `{` and has no top-level mutation/subscription) + if (isReadOnlyGraphqlQuery(options.query)) { + return true; + } + + // 2. Allow ONLY the exact canonical ApprovePullRequest mutation + const stripped = options.query.replace(/#[^\r\n]*/g, "").trim(); + const normalized = stripped.replace(/\s+/g, " "); + if (normalized !== NORMALIZED_APPROVE_MUTATION) { + return false; + } + + // 3. Validate mutation variables + const vars = options.variables as Record | undefined; + if (!vars || typeof vars !== "object") return false; + if (typeof vars.pullRequestId !== "string" || !GITHUB_NODE_ID_RE.test(vars.pullRequestId)) { + return false; + } + if (typeof vars.commitOID !== "string" || !GIT_SHA_RE.test(vars.commitOID)) { + return false; + } + if (vars.event !== undefined && vars.event !== "APPROVE") { + return false; + } + return true; +} // ── Plugin-extended Octokit class ──────────────────────────────────────────── @@ -56,6 +91,22 @@ export function updateRateLimitFromHeaders(headers: Record): voi } } +function updateGraphqlRateLimitFromHeaders(headers: Record): void { + const remaining = headers["x-ratelimit-remaining"]; + const reset = headers["x-ratelimit-reset"]; + const limit = headers["x-ratelimit-limit"]; + if (remaining !== undefined && reset !== undefined) { + const parsedRemaining = parseInt(remaining, 10); + const parsedReset = parseInt(reset, 10); + if (!Number.isFinite(parsedReset)) return; + _setGraphqlRateLimit({ + limit: safePositiveNumber(limit !== undefined ? parseInt(limit, 10) : NaN, _graphqlRateLimit()?.limit ?? 5000), + remaining: Number.isFinite(parsedRemaining) ? parsedRemaining : 0, + resetAt: new Date(parsedReset * 1000), + }); + } +} + // ── API request tracking callback ──────────────────────────────────────────── export interface ApiRequestInfo { @@ -117,14 +168,14 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { }, }); - // Read-only guard: the OAuth App `repo` scope grants write access, but this - // app is strictly read-only. Block any non-GET request except POST /graphql - // (GraphQL queries are read-only but always use POST). + // Least-privilege write guard: the OAuth App `repo` scope grants broad write access, + // but this app only permits GET requests, read-only GraphQL queries, and the single + // explicit user-confirmed PR approval mutation (APPROVE_PR_MUTATION). client.hook.before("request", (options) => { const method = (options.method ?? "GET").toUpperCase(); if (method === "GET") return; - if (method === "POST" && options.url === "/graphql") return; - throw new Error(`[github] Write operation blocked: ${method} ${options.url}. This app is read-only.`); + if (method === "POST" && options.url === "/graphql" && isAllowedGraphqlRequest(options)) return; + throw new Error(`[github] Write operation blocked: ${method} ${options.url}. Only read queries and PR approvals are permitted.`); }); // Track every API request for usage analytics + update rate limit display @@ -169,16 +220,7 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { if (errHeaders) { try { if (isGraphql) { - const remaining = errHeaders["x-ratelimit-remaining"]; - const reset = errHeaders["x-ratelimit-reset"]; - const limit = errHeaders["x-ratelimit-limit"]; - if (remaining !== undefined && reset !== undefined) { - _setGraphqlRateLimit({ - limit: safePositiveNumber(limit !== undefined ? parseInt(limit, 10) : NaN, _graphqlRateLimit()?.limit ?? 5000), - remaining: Number.isFinite(parseInt(remaining, 10)) ? parseInt(remaining, 10) : 0, - resetAt: new Date(parseInt(reset, 10) * 1000), - }); - } + updateGraphqlRateLimitFromHeaders(errHeaders); } else { updateRateLimitFromHeaders(errHeaders); } @@ -191,9 +233,10 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { const headers = (response.headers ?? {}) as Record; const resetHeader = headers["x-ratelimit-reset"]; const resetEpochMs = resetHeader ? parseInt(resetHeader, 10) * 1000 : null; - const graphqlCost = isGraphql - ? (response.data as { data?: { rateLimit?: { cost?: number } } })?.data?.rateLimit?.cost ?? undefined + const bodyRateLimit = isGraphql + ? (response.data as { data?: { rateLimit?: { cost?: number } } })?.data?.rateLimit : undefined; + const graphqlCost = bodyRateLimit?.cost ?? undefined; const info: ApiRequestInfo = { url: options.url, method, status, isGraphql, apiSource, resetEpochMs, graphqlCost, }; @@ -201,6 +244,8 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { if (response.headers && !isGraphql) { updateRateLimitFromHeaders(response.headers as Record); + } else if (isGraphql && !bodyRateLimit) { + updateGraphqlRateLimitFromHeaders(headers); } return response; diff --git a/src/shared/format.ts b/src/shared/format.ts index 1dd8a7f4..d23f4f99 100644 --- a/src/shared/format.ts +++ b/src/shared/format.ts @@ -1,6 +1,8 @@ // ── Shared format utilities ─────────────────────────────────────────────────── // Browser-agnostic formatting functions shared between the SPA and MCP server. +import type { PullRequest } from "./types.js"; + const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" }); /** @@ -135,3 +137,21 @@ export function formatStarCount(count: number): string { if (count >= 1000) return `${parseFloat((count / 1000).toFixed(1))}k`; return String(count); } + +/** + * Returns true when the authenticated user can approve the given PR from a row action: + * - PR is OPEN, enriched, not a draft, and has a valid GraphQL nodeId + headSha + * - Authenticated user is not the PR author (case-insensitive) + * - Viewer has not already approved the PR without a fresh review request + * (`!(viewerLatestReviewState === "APPROVED" && !viewerReviewRequested)`) + * - Either branch protection requires review (`reviewDecision === "REVIEW_REQUIRED"`) + * or a review has been requested of the viewer/their team (`viewerReviewRequested === true`) + */ +export function canApprovePR(pr: PullRequest, userLogin: string): boolean { + if (!userLogin || !pr.nodeId || !pr.headSha) return false; + if (pr.enriched === false) return false; + if (pr.state !== "OPEN" || pr.draft) return false; + if (pr.userLogin.toLowerCase() === userLogin.toLowerCase()) return false; + if (pr.viewerLatestReviewState === "APPROVED" && !pr.viewerReviewRequested) return false; + return pr.reviewDecision === "REVIEW_REQUIRED" || pr.viewerReviewRequested === true; +} diff --git a/src/shared/types.ts b/src/shared/types.ts index ff135deb..f97fe421 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -46,6 +46,9 @@ export interface CheckStatus { status: "success" | "failure" | "pending" | "conflict" | null; } +export type AutoMergeMethod = "MERGE" | "SQUASH" | "REBASE"; +export type ViewerReviewState = "APPROVED" | "CHANGES_REQUESTED" | "COMMENTED" | "DISMISSED" | "PENDING"; + export interface PullRequest { id: number; number: number; @@ -72,6 +75,12 @@ export interface PullRequest { labels: { name: string; color: string }[]; reviewDecision: "APPROVED" | "CHANGES_REQUESTED" | "REVIEW_REQUIRED" | null; totalReviewCount: number; + /** Non-null when GitHub auto-merge is enabled on the PR */ + autoMergeMethod?: AutoMergeMethod | null; + /** True when a review has been requested of the authenticated viewer (directly or via team) */ + viewerReviewRequested?: boolean; + /** State of the authenticated viewer's latest submitted review */ + viewerLatestReviewState?: ViewerReviewState | null; starCount?: number; /** False when only light fields are loaded (phase 1); true/undefined when fully enriched */ enriched?: boolean; diff --git a/src/shared/validation.ts b/src/shared/validation.ts index 5a8d62ec..eecae657 100644 --- a/src/shared/validation.ts +++ b/src/shared/validation.ts @@ -9,6 +9,33 @@ export const VALID_TRACKED_LOGIN = /^[A-Za-z0-9-]{1,39}(\[bot\])?$/; export const SEARCH_RESULT_CAP = 1000; +export const APPROVE_PR_MUTATION = ` + mutation ApprovePullRequest($pullRequestId: ID!, $commitOID: GitObjectID!) { + addPullRequestReview(input: { pullRequestId: $pullRequestId, commitOID: $commitOID, event: APPROVE }) { + pullRequestReview { + state + pullRequest { + reviewDecision + } + } + } + } +`.trim(); + +export const GITHUB_NODE_ID_RE = /^(?:PR_[A-Za-z0-9_-]{4,120}|[A-Za-z0-9+/=_-]{8,128})$/; +export const GIT_SHA_RE = /^[0-9a-f]{40}$/i; + +export function isReadOnlyGraphqlQuery(query: unknown): boolean { + if (typeof query !== "string") return false; + // Strip block strings, single-line strings, and # comments in a single left-to-right pass + const sanitized = query + .replace(/"""[\s\S]*?"""|"(?:\\.|[^"\\])*"|#[^\r\n]*/g, (m) => (m.startsWith("#") ? "" : '""')) + .trim(); + if (!sanitized) return false; + if (!/^(?:query\b|\{)/i.test(sanitized)) return false; + return !/\b(?:mutation|subscription)\b/i.test(sanitized); +} + // ── Jira key detection ──────────────────────────────────────────────────────── const JIRA_KEY_REGEX = /\b([A-Z]{2,10}-\d+)\b/g; diff --git a/tests/components/DashboardPage.test.tsx b/tests/components/DashboardPage.test.tsx index 691b5cff..969e9ec9 100644 --- a/tests/components/DashboardPage.test.tsx +++ b/tests/components/DashboardPage.test.tsx @@ -6,6 +6,7 @@ import { makeIssue, makePullRequest, makeWorkflowRun } from "../helpers/index"; import type { DashboardData } from "../../src/app/services/poll"; import type { HotPRStatusUpdate, HotWorkflowRunUpdate } from "../../src/app/services/api"; import { GRAPHQL_BODY_FETCH_TIMEOUT_MS } from "../../src/app/services/api"; +import { APPROVE_PR_MUTATION } from "../../src/shared/validation"; const mockLocationReplace = vi.fn(); @@ -59,11 +60,12 @@ vi.mock("../../src/app/services/jira-keys", () => ({ clearJiraKeyCache: vi.fn(), })); -// Mock github service (used by Header + DashboardPage org sync) +// Mock github service (used by Header + DashboardPage org sync + approvePullRequest) vi.mock("../../src/app/services/github", () => ({ getCoreRateLimit: () => null, getGraphqlRateLimit: () => null, getClient: vi.fn(() => null), + updateGraphqlRateLimit: vi.fn(), })); // Mock notifications lib @@ -111,6 +113,8 @@ let pollService: typeof import("../../src/app/services/poll"); let authStore: typeof import("../../src/app/stores/auth"); let viewStore: typeof import("../../src/app/stores/view"); let configStore: typeof import("../../src/app/stores/config"); +let githubService: typeof import("../../src/app/services/github"); +let errorsLib: typeof import("../../src/app/lib/errors"); beforeEach(async () => { // Clear localStorage so loadCachedDashboard doesn't pick up stale data from prior tests @@ -172,6 +176,8 @@ beforeEach(async () => { authStore = await import("../../src/app/stores/auth"); viewStore = await import("../../src/app/stores/view"); configStore = await import("../../src/app/stores/config"); + githubService = await import("../../src/app/services/github"); + errorsLib = await import("../../src/app/lib/errors"); mockLocationReplace.mockClear(); capturedFetchAll = null; @@ -179,6 +185,10 @@ beforeEach(async () => { capturedOnTargetedData = null; vi.mocked(authStore.clearAuth).mockClear(); vi.mocked(authStore.expireToken).mockClear(); + vi.mocked(githubService.getClient).mockReset(); + vi.mocked(githubService.getClient).mockReturnValue(null); + vi.mocked(errorsLib.pushNotification).mockClear(); + vi.mocked(errorsLib.dismissNotificationBySource).mockClear(); vi.mocked(pollService.fetchAllData).mockResolvedValue({ issues: [], pullRequests: [], @@ -730,6 +740,89 @@ describe("DashboardPage — onHotData integration", () => { }); }); + it("updates autoMergeMethod, headSha, viewerReviewRequested, viewerLatestReviewState, and reviewerLogins via real onHotData callback", async () => { + const initialSha = "1111111111111111111111111111111111111111"; + const updatedSha = "2222222222222222222222222222222222222222"; + const teamRequestedPR = makePullRequest({ + id: 49, + number: 49, + title: "Team review PR", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0049", + headSha: initialSha, + checkStatus: "pending", + reviewDecision: null, + autoMergeMethod: null, + viewerReviewRequested: true, + viewerLatestReviewState: null, + reviewerLogins: [], + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [teamRequestedPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await waitFor(() => { + expect(capturedOnHotData).not.toBeNull(); + }); + + const user = userEvent.setup(); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + // Hot poll 1: sets autoMergeMethod: "SQUASH", updates headSha, and preserves team viewerReviewRequested: true + capturedOnHotData!( + new Map([[49, { + state: "OPEN" as const, + checkStatus: "success" as const, + mergeStateStatus: "BLOCKED", + reviewDecision: "REVIEW_REQUIRED" as const, + headSha: updatedSha, + autoMergeMethod: "SQUASH" as const, + viewerReviewRequested: false, + viewerLatestReviewState: null, + }]]), + new Map(), + 0 + ); + + await waitFor(() => { + expect(screen.getByTestId("auto-merge-badge")).toBeTruthy(); + expect(screen.getByText("Review needed")).toBeTruthy(); + expect(screen.getByLabelText("Approve #49 Team review PR")).toBeTruthy(); + }); + + // Hot poll 2: viewer approves -> viewerLatestReviewState: "APPROVED" clears viewerReviewRequested and hides Approve button + capturedOnHotData!( + new Map([[49, { + state: "OPEN" as const, + checkStatus: "success" as const, + mergeStateStatus: "CLEAN", + reviewDecision: "APPROVED" as const, + headSha: updatedSha, + autoMergeMethod: "SQUASH" as const, + viewerReviewRequested: false, + viewerLatestReviewState: "APPROVED" as const, + }]]), + new Map(), + 0 + ); + + await waitFor(() => { + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByLabelText("Approve #49 Team review PR")).toBeNull(); + }); + }); + it("discards stale hot poll updates when generation mismatches", async () => { const testPR = makePullRequest({ id: 43, @@ -2028,6 +2121,53 @@ describe("DashboardPage — events poll targeted merge", () => { expect(vi.mocked(pollService.rebuildHotSets)).not.toHaveBeenCalled(); expect(vi.mocked(pollService.seedHotSetsFromTargeted)).toHaveBeenCalledWith(targetedData); }); + + it("preserves prior enrichment in handleTargetedData when targeted PR arrives with enriched: false", async () => { + const enrichedPR = makePullRequest({ + id: 61, + repoFullName: "org/repo", + enriched: true, + autoMergeMethod: "SQUASH", + viewerReviewRequested: true, + viewerLatestReviewState: "CHANGES_REQUESTED", + checkStatus: "success", + headSha: "1111111111111111111111111111111111111111", + }); + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [enrichedPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await waitFor(() => expect(capturedOnTargetedData).not.toBeNull()); + + const unenrichedTargetedPR = makePullRequest({ + id: 61, + repoFullName: "org/repo", + enriched: false, + autoMergeMethod: null, + viewerReviewRequested: false, + viewerLatestReviewState: null, + checkStatus: null, + headSha: "", + }); + const targetedData: DashboardData = { + issues: [], + pullRequests: [unenrichedTargetedPR], + workflowRuns: [], + errors: [], + }; + capturedOnTargetedData?.(targetedData, ["org/repo"]); + + expect(unenrichedTargetedPR.enriched).toBe(true); + expect(unenrichedTargetedPR.autoMergeMethod).toBe("SQUASH"); + expect(unenrichedTargetedPR.viewerReviewRequested).toBe(true); + expect(unenrichedTargetedPR.viewerLatestReviewState).toBe("CHANGES_REQUESTED"); + expect(unenrichedTargetedPR.checkStatus).toBe("success"); + expect(unenrichedTargetedPR.headSha).toBe("1111111111111111111111111111111111111111"); + }); }); describe("DashboardPage — dependency pre-exclusivity", () => { @@ -3452,3 +3592,787 @@ describe("DashboardPage — Jira expiration UX and reactive re-authentication", expect(screen.queryByText("Expired")).toBeNull(); }); }); + +// ── PR Approval Integration ────────────────────────────────────────────────── + +describe("DashboardPage — PR approval integration", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("completes two-step PR approval flow, updates badge to Approved, seeds hot sets, and does not push a persistent notification on success", async () => { + const user = userEvent.setup(); + const graphqlMock = vi.fn().mockResolvedValue({ + addPullRequestReview: { + pullRequestReview: { + state: "APPROVED", + pullRequest: { + reviewDecision: "APPROVED", + }, + }, + }, + rateLimit: { limit: 5000, remaining: 4999, resetAt: "2026-04-20T00:00:00Z" }, + }); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const openPR = makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + autoMergeMethod: null, + viewerReviewRequested: false, + viewerLatestReviewState: null, + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [openPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => { + screen.getByText("owner/repo"); + }); + await user.click(screen.getByText("owner/repo")); + + await waitFor(() => { + expect(screen.getByText("Review needed")).toBeTruthy(); + }); + + const approveBtn = screen.getByLabelText("Approve #42 Fix race condition"); + expect(approveBtn.textContent).toBe("Approve"); + + // Step 1: Enter confirmation mode + await user.click(approveBtn); + expect(graphqlMock).not.toHaveBeenCalled(); + expect(approveBtn.textContent).toBe("Confirm?"); + + // Step 2: Confirm approval + await user.click(approveBtn); + await waitFor(() => { + expect(graphqlMock).toHaveBeenCalledOnce(); + }); + + expect(graphqlMock).toHaveBeenCalledWith(APPROVE_PR_MUTATION, { + pullRequestId: "PR_kwDOtest0042", + commitOID: validSha, + request: { apiSource: "approvePR", retries: 0 }, + }); + + expect(errorsLib.dismissNotificationBySource).toHaveBeenCalledWith("approve-pr:42"); + expect(pollService.seedHotSetsFromTargeted).toHaveBeenCalledWith({ + issues: [], + pullRequests: [expect.objectContaining({ id: 42, enriched: true, checkStatus: "pending" })], + workflowRuns: [], + errors: [], + }); + + await waitFor(() => { + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByText("Review needed")).toBeNull(); + }); + expect(screen.queryByLabelText("Approve #42 Fix race condition")).toBeNull(); + expect(errorsLib.pushNotification).not.toHaveBeenCalled(); + }); + + it("handles 403 / FORBIDDEN error without calling expireToken, leaves PR unapproved, re-enables Approve button, and pushes PAT write permission error", async () => { + const user = userEvent.setup(); + const forbiddenErr = Object.assign(new Error("Resource not accessible by personal access token"), { + status: 403, + errors: [{ type: "FORBIDDEN", message: "Resource not accessible by personal access token" }], + }); + const graphqlMock = vi.fn().mockRejectedValue(forbiddenErr); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const openPR = makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [openPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => { + screen.getByText("owner/repo"); + }); + await user.click(screen.getByText("owner/repo")); + + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition") as HTMLButtonElement); + await user.click(approveBtn); + await user.click(approveBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "approve-pr:42", + "Unable to approve PR: your token lacks Pull Requests write permission. For fine-grained PATs, set 'Pull requests' to 'Read and write' in GitHub Settings, then replace your token in Settings.", + "error" + ); + }); + + expect(authStore.expireToken).not.toHaveBeenCalled(); + expect(screen.getByText("Review needed")).toBeTruthy(); + + const btnAfter = screen.getByLabelText("Approve #42 Fix race condition") as HTMLButtonElement; + expect(btnAfter.disabled).toBe(false); + expect(btnAfter.textContent).toBe("Approve"); + }); + + it("handles stale commitOID error by pushing a warning notification and triggering manualRefresh", async () => { + const user = userEvent.setup(); + const manualRefreshSpy = vi.fn(); + vi.mocked(pollService.createPollCoordinator).mockImplementation( + (_getInterval: unknown, fetchAll: () => Promise) => { + capturedFetchAll = fetchAll; + void fetchAll().catch(() => {}); + return { + isRefreshing: () => false, + lastRefreshAt: () => null, + manualRefresh: manualRefreshSpy, + destroy: vi.fn(), + }; + } + ); + + const staleErr = new Error("Pull request review thread commitOID was not part of the pull request"); + const graphqlMock = vi.fn().mockRejectedValue(staleErr); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const openPR = makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [openPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => { + screen.getByText("owner/repo"); + }); + await user.click(screen.getByText("owner/repo")); + + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition")); + await user.click(approveBtn); + await user.click(approveBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "approve-pr:42", + "Could not approve owner/repo#42: new commits were pushed — refreshing", + "warning" + ); + }); + expect(manualRefreshSpy).toHaveBeenCalledOnce(); + }); + + it("preserves approved state across subsequent hot, targeted, and full polls within 60s, and evicts when headSha changes", async () => { + const user = userEvent.setup(); + const newSha = "b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3"; + const graphqlMock = vi.fn().mockResolvedValue({ + addPullRequestReview: { + pullRequestReview: { + state: "APPROVED", + pullRequest: { reviewDecision: "APPROVED" }, + }, + }, + }); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const makeStalePR = (sha = validSha) => + makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: sha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + viewerReviewRequested: true, + viewerLatestReviewState: null, + reviewerLogins: [], + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [makeStalePR()], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition")); + await user.click(approveBtn); + await user.click(approveBtn); + + await waitFor(() => { + expect(screen.getByText("Approved")).toBeTruthy(); + }); + + // 1. Subsequent hot poll with stale review state on the same headSha + capturedOnHotData!( + new Map([[42, { + state: "OPEN", + checkStatus: "success", + mergeStateStatus: "BLOCKED", + reviewDecision: "REVIEW_REQUIRED", + headSha: validSha, + viewerLatestReviewState: null, + viewerReviewRequested: true, + }]]), + new Map(), + 0 + ); + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByLabelText("Approve #42 Fix race condition")).toBeNull(); + + // 2. Subsequent targeted poll with stale review state on the same headSha + capturedOnTargetedData!( + { issues: [], pullRequests: [makeStalePR()], workflowRuns: [], errors: [] }, + ["owner/repo"] + ); + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByLabelText("Approve #42 Fix race condition")).toBeNull(); + + // 3. Subsequent full poll with stale review state on the same headSha + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [makeStalePR()], + workflowRuns: [], + errors: [], + }); + await capturedFetchAll!(); + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByLabelText("Approve #42 Fix race condition")).toBeNull(); + + // 4. Subsequent full poll with a new headSha evicts the guard entry + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [makeStalePR(newSha)], + workflowRuns: [], + errors: [], + }); + await capturedFetchAll!(); + + await waitFor(() => { + expect(screen.getByText("Review needed")).toBeTruthy(); + expect(screen.getByLabelText("Approve #42 Fix race condition")).toBeTruthy(); + }); + }); + + it("evicts recent approval guard entry after 60-second TTL expires", async () => { + const user = userEvent.setup(); + const graphqlMock = vi.fn().mockResolvedValue({ + addPullRequestReview: { + pullRequestReview: { + state: "APPROVED", + pullRequest: { reviewDecision: "APPROVED" }, + }, + }, + }); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const makeStalePR = () => + makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + viewerReviewRequested: true, + viewerLatestReviewState: null, + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [makeStalePR()], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition")); + await user.click(approveBtn); + await user.click(approveBtn); + + await waitFor(() => { + expect(screen.getByText("Approved")).toBeTruthy(); + }); + + // Advance Date.now past the 60_000ms TTL and run a full poll + const expiredNow = Date.now() + 60_001; + const nowSpy = vi.spyOn(Date, "now").mockReturnValue(expiredNow); + try { + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [makeStalePR()], + workflowRuns: [], + errors: [], + }); + await capturedFetchAll!(); + } finally { + nowSpy.mockRestore(); + } + + await waitFor(() => { + expect(screen.getByText("Review needed")).toBeTruthy(); + expect(screen.getByLabelText("Approve #42 Fix race condition")).toBeTruthy(); + }); + }); + + it("does not mark a newly pushed commit Approved if onHotData mutates pr.headSha in place while approvePullRequest is in flight", async () => { + const user = userEvent.setup(); + const newSha = "c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4"; + let resolveMutation!: (val: unknown) => void; + const graphqlMock = vi.fn().mockImplementation( + () => new Promise((resolve) => { resolveMutation = resolve; }) + ); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const openPR = makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "pending", + viewerReviewRequested: true, + viewerLatestReviewState: null, + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [openPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition")); + await user.click(approveBtn); + await user.click(approveBtn); + + await waitFor(() => expect(graphqlMock).toHaveBeenCalledOnce()); + + // Simulate hot poll mutating pr.headSha in place while mutation for validSha is in flight + capturedOnHotData!( + new Map([[42, { + state: "OPEN", + checkStatus: "pending", + mergeStateStatus: "BLOCKED", + reviewDecision: "REVIEW_REQUIRED", + headSha: newSha, + viewerLatestReviewState: null, + viewerReviewRequested: true, + }]]), + new Map(), + 0 + ); + + resolveMutation({ + addPullRequestReview: { + pullRequestReview: { + state: "APPROVED", + pullRequest: { reviewDecision: "APPROVED" }, + }, + }, + }); + + await waitFor(() => { + expect(pollService.seedHotSetsFromTargeted).toHaveBeenCalledOnce(); + }); + + // Because headSha changed to newSha while validSha was being approved, the guard evicts the entry + // and leaves the new commit in Review needed state with the Approve button active. + expect(screen.getByText("Review needed")).toBeTruthy(); + expect(screen.queryByText("Approved")).toBeNull(); + expect(screen.getByLabelText("Approve #42 Fix race condition")).toBeTruthy(); + }); + + it("merges Phase 2 enrichment fields, reviewDecision, and recent approval guard when Phase 1 onLightData fires", async () => { + const user = userEvent.setup(); + const graphqlMock = vi.fn().mockResolvedValue({ + addPullRequestReview: { + pullRequestReview: { + state: "APPROVED", + pullRequest: { reviewDecision: "APPROVED" }, + }, + }, + }); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const lightPR1 = makePullRequest({ + id: 101, + number: 101, + title: "Phase 1 light PR", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + enriched: false, + nodeId: "PR_kwDOtest0101", + headSha: "", + reviewDecision: "REVIEW_REQUIRED", + checkStatus: null, + autoMergeMethod: null, + viewerReviewRequested: false, + viewerLatestReviewState: null, + }); + const lightPR2 = makePullRequest({ + id: 102, + number: 102, + title: "Approve during Phase 1", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + enriched: true, + nodeId: "PR_kwDOtest0102", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "pending", + autoMergeMethod: null, + viewerReviewRequested: true, + viewerLatestReviewState: null, + }); + + let resolvePhase2!: (data: DashboardData) => void; + vi.mocked(pollService.fetchAllData).mockImplementation(async (onLightData) => { + onLightData?.({ issues: [], pullRequests: [lightPR1, lightPR2], workflowRuns: [], errors: [] }); + return new Promise((resolve) => { + resolvePhase2 = resolve; + }); + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + // Phase 1 is rendered; approve PR #102 before Phase 2 resolves + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #102 Approve during Phase 1")); + await user.click(approveBtn); + await user.click(approveBtn); + await waitFor(() => expect(graphqlMock).toHaveBeenCalledOnce()); + + // Now resolve Phase 2: PR #101 gets enriched fields + reviewDecision: "CHANGES_REQUESTED", + // while PR #102 returns stale reviewDecision: "REVIEW_REQUIRED" that applyRecentApprovalGuard must override + const enrichedPR1 = makePullRequest({ + id: 101, + number: 101, + title: "Phase 1 light PR", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + enriched: true, + nodeId: "PR_kwDOtest0101", + headSha: validSha, + reviewDecision: "CHANGES_REQUESTED", + checkStatus: "success", + autoMergeMethod: "SQUASH", + viewerReviewRequested: false, + viewerLatestReviewState: null, + }); + const staleEnrichedPR2 = makePullRequest({ + id: 102, + number: 102, + title: "Approve during Phase 1", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + enriched: true, + nodeId: "PR_kwDOtest0102", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + autoMergeMethod: null, + viewerReviewRequested: true, + viewerLatestReviewState: null, + }); + + resolvePhase2({ + issues: [], + pullRequests: [enrichedPR1, staleEnrichedPR2], + workflowRuns: [], + errors: [], + }); + + await waitFor(() => { + expect(screen.getByTestId("auto-merge-badge")).toBeTruthy(); + expect(screen.getByText("Changes")).toBeTruthy(); + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByText("Review needed")).toBeNull(); + }); + }); + + it("treats 403 with rate-limit headers (x-ratelimit-remaining: 0 or retry-after) as a generic error instead of permission denied", async () => { + const user = userEvent.setup(); + const rateLimit403 = Object.assign(new Error("API rate limit exceeded"), { + status: 403, + response: { headers: { "x-ratelimit-remaining": "0" } }, + }); + const retryAfter403 = Object.assign(new Error("Secondary rate limit"), { + status: 403, + response: { headers: { "retry-after": "60" } }, + }); + const graphqlMock = vi.fn() + .mockRejectedValueOnce(rateLimit403) + .mockRejectedValueOnce(retryAfter403); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [ + makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + }), + ], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition")); + await user.click(approveBtn); + await user.click(approveBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "approve-pr:42", + "Failed to approve owner/repo#42: API rate limit exceeded", + "error" + ); + }); + + // Second attempt: 403 with retry-after header + const retryBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition")); + await user.click(retryBtn); + await user.click(retryBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "approve-pr:42", + "Failed to approve owner/repo#42: Secondary rate limit", + "error" + ); + }); + }); + + it("handles 401 error during PR approval by calling expireToken and redirecting to /login", async () => { + const user = userEvent.setup(); + const unauthorizedErr = Object.assign(new Error("Bad credentials"), { status: 401 }); + const graphqlMock = vi.fn().mockRejectedValue(unauthorizedErr); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [ + makePullRequest({ + id: 42, + number: 42, + title: "Fix race condition", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + }), + ], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const approveBtn = await waitFor(() => screen.getByLabelText("Approve #42 Fix race condition")); + await user.click(approveBtn); + await user.click(approveBtn); + + await waitFor(() => { + expect(authStore.expireToken).toHaveBeenCalledOnce(); + expect(mockLocationReplace).toHaveBeenCalledWith("/login"); + }); + expect(errorsLib.pushNotification).not.toHaveBeenCalled(); + }); + + it("falls back to priorReviewDecision when mutation returns null reviewDecision (REVIEW_REQUIRED -> APPROVED, CHANGES_REQUESTED preserved)", async () => { + const user = userEvent.setup(); + const graphqlMock = vi.fn().mockResolvedValue({ + addPullRequestReview: { + pullRequestReview: { + state: "APPROVED", + pullRequest: { reviewDecision: null }, + }, + }, + }); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [ + makePullRequest({ + id: 42, + number: 42, + title: "PR needing review", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0042", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + }), + makePullRequest({ + id: 43, + number: 43, + title: "PR with changes requested", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0043", + headSha: validSha, + reviewDecision: "CHANGES_REQUESTED", + viewerReviewRequested: true, + }), + ], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + // Approve PR #42 (REVIEW_REQUIRED -> falls back to APPROVED when result.reviewDecision is null) + const approveBtn42 = await waitFor(() => screen.getByLabelText("Approve #42 PR needing review")); + await user.click(approveBtn42); + await user.click(approveBtn42); + + await waitFor(() => { + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByLabelText("Approve #42 PR needing review")).toBeNull(); + }); + + // Approve PR #43 (CHANGES_REQUESTED -> preserves CHANGES_REQUESTED when result.reviewDecision is null, while hiding Approve button) + const approveBtn43 = await waitFor(() => screen.getByLabelText("Approve #43 PR with changes requested")); + await user.click(approveBtn43); + await user.click(approveBtn43); + + await waitFor(() => { + expect(screen.queryByLabelText("Approve #43 PR with changes requested")).toBeNull(); + }); + expect(screen.getByText("Changes")).toBeTruthy(); + }); +}); diff --git a/tests/components/ItemRow.test.tsx b/tests/components/ItemRow.test.tsx index d9c43b4c..92a823ea 100644 --- a/tests/components/ItemRow.test.tsx +++ b/tests/components/ItemRow.test.tsx @@ -475,4 +475,157 @@ describe("ItemRow", () => { // updatedAt was 30m before MOCK_NOW; after +3h it is 3h30m ago → Math.floor(210/60) = 3 → "3h" expect(updated!.textContent).toBe("3h"); }); + + describe("Approve button (two-step inline confirmation)", () => { + it("is omitted when onApprove is undefined and rendered when onApprove is provided", () => { + const { unmount } = render(() => ); + expect(screen.queryByLabelText(/Approve #42/i)).toBeNull(); + unmount(); + + render(() => ); + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + expect(btn.textContent).toContain("Approve"); + }); + + it("Click 1 transitions from 'Approve' to 'Confirm?' without calling onApprove", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + + expect(onApprove).not.toHaveBeenCalled(); + expect(btn.textContent).toBe("Confirm?"); + expect(btn.getAttribute("aria-label")).toBe("Confirm approve #42 Fix a bug"); + }); + + it("shows 'Confirm (auto)' and auto-merge aria-label when approveAutoMerge={true}", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + + expect(onApprove).not.toHaveBeenCalled(); + expect(btn.textContent).toBe("Confirm (auto)"); + expect(btn.getAttribute("aria-label")).toBe("Confirm approve #42 Fix a bug (auto-merge enabled)"); + }); + + it("auto-resets from 'Confirm?' back to 'Approve' after 4000ms without calling onApprove", () => { + vi.useFakeTimers(); + const onApprove = vi.fn(); + const { unmount } = render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + + vi.advanceTimersByTime(4000); + expect(btn.textContent).toContain("Approve"); + expect(btn.getAttribute("aria-label")).toBe("Approve #42 Fix a bug"); + expect(onApprove).not.toHaveBeenCalled(); + + unmount(); + vi.useRealTimers(); + }); + + it("resets immediately on Escape keyDown or blur while in 'Confirm?' state", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + + fireEvent.keyDown(btn, { key: "Escape" }); + expect(btn.textContent).toContain("Approve"); + + // Re-arm and test blur reset + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + fireEvent.blur(btn); + expect(btn.textContent).toContain("Approve"); + expect(onApprove).not.toHaveBeenCalled(); + }); + + it("Click 2 while in 'Confirm?' state invokes onApprove once and resets confirmation state", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + + fireEvent.click(btn); + expect(onApprove).toHaveBeenCalledOnce(); + expect(btn.textContent).toContain("Approve"); + }); + + it("disables button, shows .loading-spinner, and ignores clicks when isApproving={true}", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approving #42 Fix a bug") as HTMLButtonElement; + expect(btn.disabled).toBe(true); + expect(btn.querySelector(".loading-spinner")).not.toBeNull(); + + fireEvent.click(btn); + expect(onApprove).not.toHaveBeenCalled(); + }); + + it("resets 'Confirm?' back to 'Approve' when onApprove prop reference changes (e.g. headSha updated on poll)", () => { + const onApproveA = vi.fn(); + const onApproveB = vi.fn(); + const [approveFn, setApproveFn] = createSignal<() => void>(onApproveA); + + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + + setApproveFn(() => onApproveB); + expect(btn.textContent).toContain("Approve"); + expect(onApproveA).not.toHaveBeenCalled(); + expect(onApproveB).not.toHaveBeenCalled(); + }); + + it("keeps 'Confirm?' armed when a shared approvingPRIds signal updates for a different PR", () => { + const onApprove = vi.fn(); + const [approvingSet, setApprovingSet] = createSignal>(new Set()); + + render(() => ( + + )); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + fireEvent.click(btn); + expect(btn.textContent).toBe("Confirm?"); + + // Another PR (#99) starts and finishes approving — #42's isApproving remains false + setApprovingSet(new Set([99])); + expect(btn.textContent).toBe("Confirm?"); + setApprovingSet(new Set()); + expect(btn.textContent).toBe("Confirm?"); + }); + + it("renders right after the title and collapses width (max-w-0) when idle so non-hovered rows have no blank space", () => { + const onApprove = vi.fn(); + render(() => ); + + const btn = screen.getByLabelText("Approve #42 Fix a bug"); + const wrapper = btn.parentElement!; + expect(wrapper.previousElementSibling?.textContent).toBe("Fix a bug"); + expect(wrapper.className).toContain("max-w-0"); + expect(wrapper.className).toContain("group-hover:max-w-40"); + + fireEvent.click(btn); + expect(wrapper.className).toContain("max-w-40"); + expect(wrapper.className).not.toContain("max-w-0"); + }); + }); }); diff --git a/tests/components/LoginPage.test.tsx b/tests/components/LoginPage.test.tsx index cc88648a..6d9b3d5b 100644 --- a/tests/components/LoginPage.test.tsx +++ b/tests/components/LoginPage.test.tsx @@ -209,6 +209,13 @@ describe("LoginPage — PAT form navigation", () => { screen.getByText(/only access one org at a time/i); }); + it("displays 'Read and write for Pull requests' in fine-grained token guidance", async () => { + const user = userEvent.setup(); + render(() => ); + await user.click(screen.getByText("Use a Personal Access Token")); + expect(screen.getByText(/Read and write for Pull requests/)).toBeTruthy(); + }); + it("clicking 'Use OAuth instead' returns to OAuth view and clears state", async () => { const user = userEvent.setup(); render(() => ); diff --git a/tests/components/PullRequestsTab.test.tsx b/tests/components/PullRequestsTab.test.tsx index 67b2017d..22a7de99 100644 --- a/tests/components/PullRequestsTab.test.tsx +++ b/tests/components/PullRequestsTab.test.tsx @@ -1,5 +1,5 @@ -import { describe, it, expect, beforeEach } from "vitest"; -import { render, screen } from "@solidjs/testing-library"; +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { render, screen, fireEvent } from "@solidjs/testing-library"; import userEvent from "@testing-library/user-event"; import { createSignal } from "solid-js"; import PullRequestsTab from "../../src/app/components/dashboard/PullRequestsTab"; @@ -7,7 +7,7 @@ import type { PullRequest } from "../../src/app/services/api"; import * as viewStore from "../../src/app/stores/view"; import { setAllExpanded } from "../../src/app/stores/view"; import { makePullRequest, resetViewStore } from "../helpers/index"; -import { updateConfig, resetConfig } from "../../src/app/stores/config"; +import { setConfig, updateConfig, resetConfig } from "../../src/app/stores/config"; beforeEach(() => { resetViewStore(); @@ -663,4 +663,126 @@ describe("PullRequestsTab", () => { const rows = container.querySelectorAll("[role='listitem']"); expect(rows[0]?.querySelector(".animate-shimmer")).toBeFalsy(); }); + + describe("auto-merge badge and inline Approve button", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("renders auto-merge badge in comfortable and compact density when autoMergeMethod is set, and hides when null or unenriched", () => { + setAllExpanded("pullRequests", true); + const prAuto = makePullRequest({ + id: 1, + number: 1, + title: "Auto PR", + repoFullName: "org/repo", + autoMergeMethod: "SQUASH", + enriched: true, + }); + const prUnenriched = makePullRequest({ + id: 2, + number: 2, + title: "Unenriched PR", + repoFullName: "org/repo", + autoMergeMethod: "SQUASH", + enriched: false, + }); + const prNoAuto = makePullRequest({ + id: 3, + number: 3, + title: "Manual PR", + repoFullName: "org/repo", + autoMergeMethod: null, + enriched: true, + }); + + const { unmount } = render(() => ( + + )); + const badges = screen.getAllByTestId("auto-merge-badge"); + expect(badges).toHaveLength(1); + expect(badges[0].className).toContain("badge-sm"); + unmount(); + + setConfig("viewDensity", "compact"); + render(() => ( + + )); + const compactBadges = screen.getAllByTestId("auto-merge-badge"); + expect(compactBadges).toHaveLength(1); + expect(compactBadges[0].className).toContain("badge-xs"); + }); + + it("shows Approve button only for eligible PRs and invokes onApprovePR(pr) on two-step confirmation", () => { + setAllExpanded("pullRequests", true); + const onApprovePR = vi.fn(); + + const eligiblePR = makePullRequest({ + id: 10, + number: 10, + title: "Needs Review PR", + repoFullName: "org/repo", + userLogin: "bob", + nodeId: "PR_kwDOtest0010", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + const selfPR = makePullRequest({ + id: 11, + number: 11, + title: "Self PR", + repoFullName: "org/repo", + userLogin: "alice", + nodeId: "PR_kwDOtest0011", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + const alreadyApprovedPR = makePullRequest({ + id: 12, + number: 12, + title: "Already Approved PR", + repoFullName: "org/repo", + userLogin: "bob", + nodeId: "PR_kwDOtest0012", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: false, + enriched: true, + }); + const draftPR = makePullRequest({ + id: 13, + number: 13, + title: "Draft PR", + repoFullName: "org/repo", + userLogin: "bob", + nodeId: "PR_kwDOtest0013", + headSha: validSha, + draft: true, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + + render(() => ( + + )); + + const approveBtn = screen.getByLabelText("Approve #10 Needs Review PR"); + expect(screen.queryByLabelText(/Approve #11/)).toBeNull(); + expect(screen.queryByLabelText(/Approve #12/)).toBeNull(); + expect(screen.queryByLabelText(/Approve #13/)).toBeNull(); + + fireEvent.click(approveBtn); + expect(onApprovePR).not.toHaveBeenCalled(); + expect(approveBtn.textContent).toBe("Confirm?"); + + fireEvent.click(approveBtn); + expect(onApprovePR).toHaveBeenCalledOnce(); + expect(onApprovePR).toHaveBeenCalledWith(eligiblePR); + }); + }); }); diff --git a/tests/components/dashboard/DashboardPage.test.tsx b/tests/components/dashboard/DashboardPage.test.tsx index 4bd8363d..6a501239 100644 --- a/tests/components/dashboard/DashboardPage.test.tsx +++ b/tests/components/dashboard/DashboardPage.test.tsx @@ -1,5 +1,7 @@ import { describe, it, expect } from "vitest"; import { rateLimitCssClass } from "../../../src/app/lib/format"; +import { applyHotPollPRUpdates } from "../../../src/app/components/dashboard/DashboardPage"; +import { makePullRequest } from "../../helpers/index"; import type { PullRequest } from "../../../src/shared/types"; import type { HotPRStatusUpdate } from "../../../src/app/services/api"; @@ -28,106 +30,112 @@ describe("rateLimitCssClass", () => { // ── PA-008: Hot poll terminal PR splice ─────────────────────────────────────── describe("hot poll terminal PR splice logic", () => { - function makeOpenPR(id: number): PullRequest { - return { - id, - number: id, - title: `PR ${id}`, - state: "OPEN", - draft: false, - htmlUrl: `https://github.com/owner/repo/pull/${id}`, - createdAt: "2024-01-10T08:00:00Z", - updatedAt: "2024-01-12T14:30:00Z", - userLogin: "octocat", - userAvatarUrl: "https://github.com/images/error/octocat_happy.gif", - headSha: "abc123", - headRef: "feature", - baseRef: "main", - assigneeLogins: [], - reviewerLogins: [], - repoFullName: "owner/repo", - checkStatus: null, - additions: 0, - deletions: 0, - changedFiles: 0, - comments: 0, - reviewThreads: 0, - labels: [], - reviewDecision: null, - totalReviewCount: 0, - enriched: true, - }; - } - - function simulateHotPollCallback( - state: { pullRequests: PullRequest[] }, - prUpdates: Map - ): void { - // Mirrors the onHotData callback logic in DashboardPage.tsx (without SolidJS store produce) - const terminalPrIds = new Set(); - for (const [prId, update] of prUpdates) { - if (update.state === "CLOSED" || update.state === "MERGED") { - terminalPrIds.add(prId); - } - } - for (const pr of state.pullRequests) { - const update = prUpdates.get(pr.id); - if (!update) continue; - pr.state = update.state; - pr.checkStatus = update.checkStatus; - pr.reviewDecision = update.reviewDecision; - } - if (terminalPrIds.size > 0) { - state.pullRequests = state.pullRequests.filter((pr) => !terminalPrIds.has(pr.id)); - } - } - it("removes a MERGED PR from pullRequests when hot poll returns state:MERGED", () => { - const state = { pullRequests: [makeOpenPR(1), makeOpenPR(2)] }; + const state = { pullRequests: [makePullRequest({ id: 1 }), makePullRequest({ id: 2 })] }; const prUpdates = new Map([ [1, { state: "MERGED", checkStatus: null, mergeStateStatus: "MERGED", reviewDecision: null }], ]); - simulateHotPollCallback(state, prUpdates); + applyHotPollPRUpdates(state, prUpdates); expect(state.pullRequests.map((p) => p.id)).toEqual([2]); }); it("removes a CLOSED PR from pullRequests when hot poll returns state:CLOSED", () => { - const state = { pullRequests: [makeOpenPR(10), makeOpenPR(20)] }; + const state = { pullRequests: [makePullRequest({ id: 10 }), makePullRequest({ id: 20 })] }; const prUpdates = new Map([ [10, { state: "CLOSED", checkStatus: null, mergeStateStatus: "", reviewDecision: null }], ]); - simulateHotPollCallback(state, prUpdates); + applyHotPollPRUpdates(state, prUpdates); expect(state.pullRequests.map((p) => p.id)).toEqual([20]); }); it("keeps OPEN PRs in pullRequests after hot poll update", () => { - const state = { pullRequests: [makeOpenPR(5)] }; + const state = { pullRequests: [makePullRequest({ id: 5 })] }; const prUpdates = new Map([ [5, { state: "OPEN", checkStatus: "success", mergeStateStatus: "CLEAN", reviewDecision: "APPROVED" }], ]); - simulateHotPollCallback(state, prUpdates); + applyHotPollPRUpdates(state, prUpdates); expect(state.pullRequests).toHaveLength(1); expect(state.pullRequests[0].id).toBe(5); }); it("removes only the MERGED PR and leaves remaining PRs intact", () => { - const state = { pullRequests: [makeOpenPR(100), makeOpenPR(101), makeOpenPR(102)] }; + const state = { + pullRequests: [makePullRequest({ id: 100 }), makePullRequest({ id: 101 }), makePullRequest({ id: 102 })], + }; const prUpdates = new Map([ [101, { state: "MERGED", checkStatus: null, mergeStateStatus: "MERGED", reviewDecision: null }], ]); - simulateHotPollCallback(state, prUpdates); + applyHotPollPRUpdates(state, prUpdates); expect(state.pullRequests.map((p) => p.id)).toEqual([100, 102]); }); + + it("updates headSha and autoMergeMethod while preserving Phase 1 team viewerReviewRequested and reviewerLogins until approved", () => { + const teamRequestedPR: PullRequest = makePullRequest({ + id: 7, + viewerReviewRequested: true, + reviewerLogins: [], + }); + const state = { pullRequests: [teamRequestedPR] }; + const newSha = "f0e1d2c3b4a5f0e1d2c3b4a5f0e1d2c3b4a5f0e1"; + + // Hot poll returns direct viewerReviewRequested: false (because review was requested via a team), + // updated headSha, and autoMergeMethod: "SQUASH", while viewer has not yet approved. + const prUpdates1 = new Map([ + [ + 7, + { + state: "OPEN", + checkStatus: "success", + mergeStateStatus: "BLOCKED", + reviewDecision: "REVIEW_REQUIRED", + headSha: newSha, + autoMergeMethod: "SQUASH", + viewerReviewRequested: false, + viewerLatestReviewState: null, + }, + ], + ]); + + applyHotPollPRUpdates(state, prUpdates1, "TestUser"); + + expect(state.pullRequests[0].headSha).toBe(newSha); + expect(state.pullRequests[0].autoMergeMethod).toBe("SQUASH"); + expect(state.pullRequests[0].viewerReviewRequested).toBe(true); + expect(state.pullRequests[0].reviewerLogins).toEqual(["testuser"]); + + // Subsequent hot poll after viewer approves: viewerReviewRequested is cleared and viewer remains in reviewerLogins + const prUpdates2 = new Map([ + [ + 7, + { + state: "OPEN", + checkStatus: "success", + mergeStateStatus: "CLEAN", + reviewDecision: "APPROVED", + headSha: newSha, + autoMergeMethod: "SQUASH", + viewerReviewRequested: false, + viewerLatestReviewState: "APPROVED", + }, + ], + ]); + + applyHotPollPRUpdates(state, prUpdates2, "TestUser"); + + expect(state.pullRequests[0].viewerLatestReviewState).toBe("APPROVED"); + expect(state.pullRequests[0].viewerReviewRequested).toBe(false); + expect(state.pullRequests[0].reviewerLogins).toEqual(["testuser"]); + }); }); diff --git a/tests/components/dashboard/DependenciesTab.test.tsx b/tests/components/dashboard/DependenciesTab.test.tsx index 9fef0397..2d3dfc89 100644 --- a/tests/components/dashboard/DependenciesTab.test.tsx +++ b/tests/components/dashboard/DependenciesTab.test.tsx @@ -782,6 +782,87 @@ describe("DependenciesTab — unknown bot banner", () => { }); }); +// ── Auto-merge badge and inline Approve action ─────────────────────────────── + +describe("DependenciesTab — auto-merge badge and Approve action", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("renders auto-merge badge in comfortable and compact density and preserves category badge first in DOM order", () => { + const prAuto = makeMergeablePR({ + id: 8001, + number: 801, + title: "Bump axios from 0.27.1 to 0.27.2", + autoMergeMethod: "SQUASH", + enriched: true, + }); + const prNoAuto = makeMergeablePR({ + id: 8002, + number: 802, + title: "Bump lodash from 4.16.0 to 4.17.0", + autoMergeMethod: null, + enriched: true, + }); + + const { unmount } = renderTab({ pullRequests: [prAuto, prNoAuto] }); + const badges = screen.getAllByTestId("auto-merge-badge"); + expect(badges).toHaveLength(1); + expect(badges[0].className).toContain("badge-sm"); + + // Verify category badge ("patch") still comes before auto-merge badge in DOM order + const items = screen.getAllByRole("listitem"); + expect(items[0].querySelector(".badge")?.textContent?.trim()).toBe("patch"); + unmount(); + + updateConfig({ viewDensity: "compact" }); + renderTab({ pullRequests: [prAuto, prNoAuto] }); + const compactBadges = screen.getAllByTestId("auto-merge-badge"); + expect(compactBadges).toHaveLength(1); + expect(compactBadges[0].className).toContain("badge-xs"); + }); + + it("shows Approve button for eligible dependency PRs and invokes onApprovePR(pr) on confirmation", () => { + const onApprovePR = vi.fn(); + const eligibleDepPR = makeNeedsActionPR({ + id: 8010, + number: 810, + title: "Bump axios from 0.27.2 to 1.0.0", + nodeId: "PR_kwDOdep8010", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + checkStatus: "success", + enriched: true, + }); + const alreadyApprovedDepPR = makeMergeablePR({ + id: 8011, + number: 811, + title: "Bump lodash from 4.16.0 to 4.17.0", + nodeId: "PR_kwDOdep8011", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: false, + enriched: true, + }); + + renderTab({ + pullRequests: [eligibleDepPR, alreadyApprovedDepPR], + userLogin: "testuser", + onApprovePR, + }); + + const approveBtn = screen.getByLabelText(/^Approve #810 /); + expect(screen.queryByLabelText(/^Approve #811 /)).toBeNull(); + + fireEvent.click(approveBtn); + expect(onApprovePR).not.toHaveBeenCalled(); + expect(approveBtn.textContent).toBe("Confirm?"); + + fireEvent.click(approveBtn); + expect(onApprovePR).toHaveBeenCalledOnce(); + expect(onApprovePR).toHaveBeenCalledWith(eligibleDepPR); + }); +}); + // ── Ignore button ───────────────────────────────────────────────────────────── describe("DependenciesTab — ignore button", () => { diff --git a/tests/components/dashboard/TrackedTab.test.tsx b/tests/components/dashboard/TrackedTab.test.tsx index a2f649a8..d0f417d9 100644 --- a/tests/components/dashboard/TrackedTab.test.tsx +++ b/tests/components/dashboard/TrackedTab.test.tsx @@ -30,6 +30,7 @@ vi.mock("../../../src/app/lib/url", () => ({ import TrackedTab from "../../../src/app/components/dashboard/TrackedTab"; import { viewState, resetViewState, updateViewState, untrackJiraItem } from "../../../src/app/stores/view"; +import { setConfig, resetConfig } from "../../../src/app/stores/config"; // ── Setup ───────────────────────────────────────────────────────────────────── @@ -37,6 +38,7 @@ beforeEach(() => { vi.clearAllMocks(); localStorageMock.clear(); resetViewState(); + resetConfig(); }); // ── Tests ───────────────────────────────────────────────────────────────────── @@ -350,3 +352,103 @@ describe("TrackedTab — Jira items", () => { expect(screen.queryByText(/#-42/)).toBeNull(); }); }); + +describe("TrackedTab — auto-merge badge and Approve action", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("renders auto-merge badge on live PR rows in comfortable and compact density, and omits when null or unenriched", () => { + const prAuto = makePullRequest({ + id: 901, + number: 901, + title: "Auto Tracked PR", + autoMergeMethod: "MERGE", + enriched: true, + }); + const prUnenriched = makePullRequest({ + id: 902, + number: 902, + title: "Unenriched Tracked PR", + autoMergeMethod: "MERGE", + enriched: false, + }); + + updateViewState({ + trackedItems: [ + makeTrackedItem({ id: 901, number: 901, type: "pullRequest", title: "Auto Tracked PR" }), + makeTrackedItem({ id: 902, number: 902, type: "pullRequest", title: "Unenriched Tracked PR" }), + ], + }); + + const { unmount } = render(() => ( + + )); + const badges = screen.getAllByTestId("auto-merge-badge"); + expect(badges).toHaveLength(1); + expect(badges[0].className).toContain("badge-sm"); + unmount(); + + setConfig("viewDensity", "compact"); + render(() => ( + + )); + const compactBadges = screen.getAllByTestId("auto-merge-badge"); + expect(compactBadges).toHaveLength(1); + expect(compactBadges[0].className).toContain("badge-xs"); + }); + + it("renders Approve button on eligible live PR rows, suppresses on issue/fallback/self-authored rows, and calls onApprovePR(pr) on confirmation", () => { + const onApprovePR = vi.fn(); + const eligiblePR = makePullRequest({ + id: 910, + number: 910, + title: "Eligible Tracked PR", + userLogin: "otheruser", + nodeId: "PR_kwDOtrack910", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + const selfPR = makePullRequest({ + id: 911, + number: 911, + title: "Self Tracked PR", + userLogin: "testuser", + nodeId: "PR_kwDOtrack911", + headSha: validSha, + reviewDecision: "REVIEW_REQUIRED", + enriched: true, + }); + const liveIssue = makeIssue({ id: 912, number: 912, title: "Tracked Issue" }); + + updateViewState({ + trackedItems: [ + makeTrackedItem({ id: 910, number: 910, type: "pullRequest", title: "Eligible Tracked PR" }), + makeTrackedItem({ id: 911, number: 911, type: "pullRequest", title: "Self Tracked PR" }), + makeTrackedItem({ id: 912, number: 912, type: "issue", title: "Tracked Issue" }), + makeTrackedItem({ id: 913, number: 913, type: "pullRequest", title: "Fallback Missing PR" }), + ], + }); + + render(() => ( + + )); + + const approveBtn = screen.getByLabelText("Approve #910 Eligible Tracked PR"); + expect(screen.queryByLabelText(/Approve #911/)).toBeNull(); + expect(screen.queryByLabelText(/Approve #912/)).toBeNull(); + expect(screen.queryByLabelText(/Approve #913/)).toBeNull(); + + fireEvent.click(approveBtn); + expect(onApprovePR).not.toHaveBeenCalled(); + expect(approveBtn.textContent).toBe("Confirm?"); + + fireEvent.click(approveBtn); + expect(onApprovePR).toHaveBeenCalledOnce(); + expect(onApprovePR).toHaveBeenCalledWith(eligiblePR); + }); +}); diff --git a/tests/components/shared-badges.test.tsx b/tests/components/shared-badges.test.tsx index fcc0a286..a65bc9e2 100644 --- a/tests/components/shared-badges.test.tsx +++ b/tests/components/shared-badges.test.tsx @@ -3,6 +3,7 @@ import { render, screen, fireEvent } from "@solidjs/testing-library"; import RoleBadge from "../../src/app/components/shared/RoleBadge"; import ReviewBadge from "../../src/app/components/shared/ReviewBadge"; import SizeBadge from "../../src/app/components/shared/SizeBadge"; +import AutoMergeBadge from "../../src/app/components/shared/AutoMergeBadge"; describe("RoleBadge", () => { it("renders nothing for empty roles", () => { @@ -149,3 +150,52 @@ describe("SizeBadge", () => { }); }); }); + +describe("AutoMergeBadge", () => { + it("renders nothing when method is null or undefined", () => { + const { container: c1 } = render(() => ); + expect(c1.textContent).toBe(""); + const { container: c2 } = render(() => ); + expect(c2.textContent).toBe(""); + }); + + it("renders 'auto' with badge-sm by default for MERGE, SQUASH, and REBASE", () => { + const { unmount: u1 } = render(() => ); + const b1 = screen.getByTestId("auto-merge-badge"); + expect(b1.textContent).toBe("auto"); + expect(b1.className).toContain("badge-sm"); + expect(b1.getAttribute("aria-label")).toBe("Auto-merge enabled (merge)"); + u1(); + + const { unmount: u2 } = render(() => ); + const b2 = screen.getByTestId("auto-merge-badge"); + expect(b2.getAttribute("aria-label")).toBe("Auto-merge enabled (squash)"); + u2(); + + const { unmount: u3 } = render(() => ); + const b3 = screen.getByTestId("auto-merge-badge"); + expect(b3.getAttribute("aria-label")).toBe("Auto-merge enabled (rebase)"); + u3(); + }); + + it("renders badge-xs when compact={true}", () => { + render(() => ); + const badge = screen.getByTestId("auto-merge-badge"); + expect(badge.className).toContain("badge-xs"); + expect(badge.className).not.toContain("badge-sm"); + }); + + it("shows tooltip with merge method on hover", () => { + vi.useFakeTimers(); + const { container, unmount } = render(() => ); + const trigger = container.querySelector("span.inline-flex"); + expect(trigger).not.toBeNull(); + fireEvent.pointerEnter(trigger!); + vi.advanceTimersByTime(300); + expect(document.body.textContent).toContain("Auto-merge enabled (squash)"); + fireEvent.pointerLeave(trigger!); + vi.advanceTimersByTime(500); + unmount(); + vi.useRealTimers(); + }); +}); diff --git a/tests/helpers/factories.ts b/tests/helpers/factories.ts index 3dd43590..f017026c 100644 --- a/tests/helpers/factories.ts +++ b/tests/helpers/factories.ts @@ -50,6 +50,9 @@ export function makePullRequest(overrides: Partial = {}): PullReque labels: [], reviewDecision: null, totalReviewCount: 0, + autoMergeMethod: null, + viewerReviewRequested: false, + viewerLatestReviewState: null, enriched: true, ...overrides, }; diff --git a/tests/lib/format.test.ts b/tests/lib/format.test.ts index 42c251e4..e24b6a91 100644 --- a/tests/lib/format.test.ts +++ b/tests/lib/format.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, formatScopeSummary } from "../../src/app/lib/format"; +import { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, formatScopeSummary, canApprovePR } from "../../src/app/lib/format"; +import { makePullRequest } from "../helpers/factories"; describe("relativeTime", () => { beforeEach(() => { @@ -444,3 +445,136 @@ describe("formatStarCount", () => { expect(formatStarCount(1234567)).toBe("1.2M"); }); }); + +describe("canApprovePR", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("returns true when reviewDecision is REVIEW_REQUIRED on an open enriched non-draft PR by another author", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(pr, "reviewer")).toBe(true); + }); + + it("returns true when viewerReviewRequested is true even if reviewDecision is null or CHANGES_REQUESTED", () => { + const prNullDecision = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: null, + viewerReviewRequested: true, + }); + const prChangesRequested = makePullRequest({ + nodeId: "PR_kwDOtest0002", + headSha: validSha, + userLogin: "author", + reviewDecision: "CHANGES_REQUESTED", + viewerReviewRequested: true, + }); + expect(canApprovePR(prNullDecision, "reviewer")).toBe(true); + expect(canApprovePR(prChangesRequested, "reviewer")).toBe(true); + }); + + it("returns false for self-authored PR (case-insensitive)", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "OctoCat", + reviewDecision: "REVIEW_REQUIRED", + viewerReviewRequested: true, + }); + expect(canApprovePR(pr, "octocat")).toBe(false); + }); + + it("returns false when viewerLatestReviewState is APPROVED and viewerReviewRequested is false", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: false, + }); + expect(canApprovePR(pr, "reviewer")).toBe(false); + }); + + it("returns true when viewerLatestReviewState is APPROVED but viewerReviewRequested is true (re-requested review)", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: true, + }); + expect(canApprovePR(pr, "reviewer")).toBe(true); + }); + + it("returns false when PR is a draft", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + draft: true, + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(pr, "reviewer")).toBe(false); + }); + + it("returns false when PR state is CLOSED or MERGED", () => { + const closedPr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + state: "CLOSED", + reviewDecision: "REVIEW_REQUIRED", + }); + const mergedPr = makePullRequest({ + nodeId: "PR_kwDOtest0002", + headSha: validSha, + userLogin: "author", + state: "MERGED", + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(closedPr, "reviewer")).toBe(false); + expect(canApprovePR(mergedPr, "reviewer")).toBe(false); + }); + + it("returns false when PR is not yet enriched (enriched === false)", () => { + const pr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + enriched: false, + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(pr, "reviewer")).toBe(false); + }); + + it("returns false when nodeId, headSha, or userLogin is missing", () => { + const noNodeId = makePullRequest({ + nodeId: undefined, + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + }); + const noHeadSha = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: "", + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + }); + const validPr = makePullRequest({ + nodeId: "PR_kwDOtest0001", + headSha: validSha, + userLogin: "author", + reviewDecision: "REVIEW_REQUIRED", + }); + expect(canApprovePR(noNodeId, "reviewer")).toBe(false); + expect(canApprovePR(noHeadSha, "reviewer")).toBe(false); + expect(canApprovePR(validPr, "")).toBe(false); + }); +}); diff --git a/tests/services/api-optimization.test.ts b/tests/services/api-optimization.test.ts index 674c39b2..09a14838 100644 --- a/tests/services/api-optimization.test.ts +++ b/tests/services/api-optimization.test.ts @@ -57,7 +57,7 @@ const graphqlLightPRNodeDefaults = { repository: { nameWithOwner: "octocat/Hello-World" }, headRefName: "feature-branch", baseRefName: "main", - reviewDecision: "APPROVED", + reviewDecision: "APPROVED" as string | null, labels: { nodes: [{ name: "feature", color: "a2eeef" }] }, }; @@ -69,7 +69,7 @@ function makeHeavyPRNode(databaseId: number, _nodeId?: string) { headRepository: { owner: { login: "octocat" }, nameWithOwner: "octocat/Hello-World" }, mergeStateStatus: "CLEAN", assignees: { nodes: [{ login: "octocat" }] }, - reviewRequests: { nodes: [{ requestedReviewer: { login: "reviewer2" } }] }, + reviewRequests: { nodes: [{ requestedReviewer: { login: "reviewer2" } as { login?: string } | null }] }, latestReviews: { totalCount: 1, nodes: [{ author: { login: "reviewer1" } }] }, additions: 100, deletions: 20, @@ -77,6 +77,9 @@ function makeHeavyPRNode(databaseId: number, _nodeId?: string) { comments: { totalCount: 3 }, reviewThreads: { totalCount: 2 }, commits: { nodes: [{ commit: { statusCheckRollup: { state: "SUCCESS" } } }] }, + autoMergeRequest: null as { mergeMethod: string } | null, + viewerLatestReview: null as { state: string } | null, + viewerLatestReviewRequest: null as { id: string } | null, }; } @@ -708,6 +711,9 @@ describe("pickEnrichmentFields", () => { checkStatus: "success", additions: 10, reviewerLogins: ["r1"], + autoMergeMethod: "SQUASH", + viewerReviewRequested: true, + viewerLatestReviewState: "COMMENTED", }); const fields = pickEnrichmentFields(pr); expect(fields).toEqual({ @@ -721,9 +727,126 @@ describe("pickEnrichmentFields", () => { comments: pr.comments, reviewThreads: pr.reviewThreads, totalReviewCount: pr.totalReviewCount, + autoMergeMethod: pr.autoMergeMethod, + viewerReviewRequested: pr.viewerReviewRequested, + viewerLatestReviewState: pr.viewerLatestReviewState, }); expect(fields).not.toHaveProperty("title"); expect(fields).not.toHaveProperty("state"); expect(fields).not.toHaveProperty("enriched"); }); }); + +describe("Phase 1 prReviewReq -> Phase 2 mergeEnrichment team review request preservation", () => { + const repos = makeRepos(2); + + it("retains viewerReviewRequested: true and adds normalized userLogin to reviewerLogins for a team review request (even when also returned in prInvolves)", async () => { + const lightPR = makeLightPRNode({ + id: "PR_kwDOteam42", + databaseId: 42, + reviewDecision: null, + }); + const heavyNode = { + ...makeHeavyPRNode(42, "PR_kwDOteam42"), + // Team review request: no direct User node in reviewRequests and viewerLatestReviewRequest is null + reviewRequests: { nodes: [{ requestedReviewer: {} }] }, + latestReviews: { totalCount: 0, nodes: [] }, + autoMergeRequest: { mergeMethod: "SQUASH" }, + viewerLatestReview: null, + viewerLatestReviewRequest: null, + }; + + const octokit = makeTwoPhaseOctokit( + async () => ({ + issues: makeSearchResponse([]), + prInvolves: makeSearchResponse([lightPR]), + prReviewReq: makeSearchResponse([lightPR]), + rateLimit, + }), + [heavyNode], + ); + + const result = await fetchIssuesAndPullRequests(octokit as unknown as OctokitLike, repos, "TestUser"); + expect(result.pullRequests).toHaveLength(1); + const pr = result.pullRequests[0]; + expect(pr.viewerReviewRequested).toBe(true); + expect(pr.autoMergeMethod).toBe("SQUASH"); + expect(pr.reviewerLogins).toContain("testuser"); + }); + + it("clears viewerReviewRequested to false when viewerLatestReview.state is APPROVED and viewerLatestReviewRequest is null, while retaining userLogin in reviewerLogins", async () => { + const lightPR = makeLightPRNode({ + id: "PR_kwDOteam43", + databaseId: 43, + reviewDecision: "APPROVED", + }); + const heavyNode = { + ...makeHeavyPRNode(43, "PR_kwDOteam43"), + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 0, nodes: [] }, + autoMergeRequest: null, + viewerLatestReview: { state: "APPROVED" }, + viewerLatestReviewRequest: null, + }; + + const octokit = makeTwoPhaseOctokit( + async () => ({ + issues: makeSearchResponse([]), + prInvolves: makeSearchResponse([]), + prReviewReq: makeSearchResponse([lightPR]), + rateLimit, + }), + [heavyNode], + ); + + const result = await fetchIssuesAndPullRequests(octokit as unknown as OctokitLike, repos, "TestUser"); + expect(result.pullRequests).toHaveLength(1); + const pr = result.pullRequests[0]; + expect(pr.viewerLatestReviewState).toBe("APPROVED"); + expect(pr.viewerReviewRequested).toBe(false); + expect(pr.reviewerLogins).toContain("testuser"); + }); + + it("does not set viewerReviewRequested or inject viewerLogin into reviewerLogins when prReviewReq matches a tracked user (globalUserSearch)", async () => { + const lightPR = makeLightPRNode({ + id: "PR_kwDOteam44", + databaseId: 44, + reviewDecision: null, + }); + const heavyNode = { + ...makeHeavyPRNode(44, "PR_kwDOteam44"), + reviewRequests: { nodes: [{ requestedReviewer: { login: "teammate" } }] }, + latestReviews: { totalCount: 0, nodes: [] }, + autoMergeRequest: null, + viewerLatestReview: null, + viewerLatestReviewRequest: null, + }; + + const octokit = makeTwoPhaseOctokit( + async (_query, variables) => { + const prRevQ = String((variables as Record | undefined)?.prRevQ ?? ""); + const isTrackedUserQuery = prRevQ.includes("review-requested:teammate"); + return { + issues: makeSearchResponse([]), + prInvolves: makeSearchResponse([]), + prReviewReq: makeSearchResponse(isTrackedUserQuery ? [lightPR] : []), + rateLimit, + }; + }, + [heavyNode], + ); + + const result = await fetchIssuesAndPullRequests( + octokit as unknown as OctokitLike, + repos, + "TestUser", + undefined, + [{ login: "teammate", avatarUrl: "https://github.com/teammate.png", name: "Teammate", type: "user" }], + ); + expect(result.pullRequests).toHaveLength(1); + const pr = result.pullRequests[0]; + expect(pr.viewerReviewRequested).toBe(false); + expect(pr.reviewerLogins).toEqual(["teammate"]); + expect(pr.reviewerLogins).not.toContain("testuser"); + }); +}); diff --git a/tests/services/api.test.ts b/tests/services/api.test.ts index 96a36eb7..69b849e8 100644 --- a/tests/services/api.test.ts +++ b/tests/services/api.test.ts @@ -7,9 +7,11 @@ import { validateGitHubUser, fetchPREnrichment, fetchHotPRStatus, + approvePullRequest, discoverUpstreamRepos, type RepoRef, } from "../../src/app/services/api"; +import { APPROVE_PR_MUTATION } from "../../src/app/services/github"; import { clearCache } from "../../src/app/stores/cache"; import { pushNotification } from "../../src/app/lib/errors"; @@ -1392,3 +1394,186 @@ describe("error-path rateLimit extraction — updateGraphqlRateLimit called", () ); }); }); + +// ── fetchPREnrichment — autoMergeMethod, viewerLatestReviewState, viewerReviewRequested ── + +describe("fetchPREnrichment — autoMergeMethod and viewer review fields", () => { + it("maps MERGE, SQUASH, REBASE, unknown autoMergeMethod, viewerLatestReviewState, and viewerReviewRequested", async () => { + const octokit = makeOctokit( + async () => ({ data: {} }), + async () => ({ + nodes: [ + { + databaseId: 101, + headRefOid: "1111111111111111111111111111111111111111", + headRepository: null, + mergeStateStatus: "CLEAN", + assignees: { nodes: [] }, + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 1, nodes: [] }, + additions: 10, + deletions: 2, + changedFiles: 1, + comments: { totalCount: 0 }, + reviewThreads: { totalCount: 0 }, + commits: { nodes: [{ commit: { statusCheckRollup: { state: "SUCCESS" } } }] }, + autoMergeRequest: { mergeMethod: "SQUASH" }, + viewerLatestReview: { state: "CHANGES_REQUESTED" }, + viewerLatestReviewRequest: { id: "RR_kwDOtest101" }, + }, + { + databaseId: 102, + headRefOid: "2222222222222222222222222222222222222222", + headRepository: null, + mergeStateStatus: "CLEAN", + assignees: { nodes: [] }, + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 0, nodes: [] }, + additions: 1, + deletions: 1, + changedFiles: 1, + comments: { totalCount: 0 }, + reviewThreads: { totalCount: 0 }, + commits: { nodes: [] }, + autoMergeRequest: { mergeMethod: "MERGE" }, + viewerLatestReview: { state: "APPROVED" }, + viewerLatestReviewRequest: null, + }, + { + databaseId: 103, + headRefOid: "3333333333333333333333333333333333333333", + headRepository: null, + mergeStateStatus: "CLEAN", + assignees: { nodes: [] }, + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 0, nodes: [] }, + additions: 1, + deletions: 1, + changedFiles: 1, + comments: { totalCount: 0 }, + reviewThreads: { totalCount: 0 }, + commits: { nodes: [] }, + autoMergeRequest: { mergeMethod: "REBASE" }, + viewerLatestReview: { state: "UNKNOWN_STATE" }, + viewerLatestReviewRequest: null, + }, + { + databaseId: 104, + headRefOid: "4444444444444444444444444444444444444444", + headRepository: null, + mergeStateStatus: "CLEAN", + assignees: { nodes: [] }, + reviewRequests: { nodes: [] }, + latestReviews: { totalCount: 0, nodes: [] }, + additions: 1, + deletions: 1, + changedFiles: 1, + comments: { totalCount: 0 }, + reviewThreads: { totalCount: 0 }, + commits: { nodes: [] }, + autoMergeRequest: { mergeMethod: "INVALID" }, + viewerLatestReview: null, + viewerLatestReviewRequest: null, + }, + ], + rateLimit: { limit: 5000, remaining: 4990, resetAt: "2026-04-23T12:00:00Z" }, + }) + ); + + const { enrichments } = await fetchPREnrichment(octokit as never, ["PR_1", "PR_2", "PR_3", "PR_4"]); + + expect(enrichments.get(101)).toMatchObject({ + autoMergeMethod: "SQUASH", + viewerLatestReviewState: "CHANGES_REQUESTED", + viewerReviewRequested: true, + }); + expect(enrichments.get(102)).toMatchObject({ + autoMergeMethod: "MERGE", + viewerLatestReviewState: "APPROVED", + viewerReviewRequested: false, + }); + expect(enrichments.get(103)).toMatchObject({ + autoMergeMethod: "REBASE", + viewerLatestReviewState: null, + viewerReviewRequested: false, + }); + expect(enrichments.get(104)).toMatchObject({ + autoMergeMethod: null, + viewerLatestReviewState: null, + viewerReviewRequested: false, + }); + }); +}); + +// ── approvePullRequest ──────────────────────────────────────────────────────── + +describe("approvePullRequest", () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + it("executes APPROVE_PR_MUTATION with commitOID, retries: 0, updates rateLimit, and returns normalized state + reviewDecision", async () => { + const githubModule = await import("../../src/app/services/github"); + const updateSpy = vi.spyOn(githubModule, "updateGraphqlRateLimit"); + + const octokit = makeOctokit( + async () => ({ data: {} }), + async () => ({ + addPullRequestReview: { + pullRequestReview: { + state: "APPROVED", + pullRequest: { + reviewDecision: "APPROVED", + }, + }, + }, + rateLimit: { cost: 1, limit: 5000, remaining: 4988, resetAt: "2026-04-23T12:00:00Z" }, + }) + ); + + const result = await approvePullRequest(octokit as never, "PR_kwDOtest0042", validSha); + + expect(octokit.graphql).toHaveBeenCalledWith(APPROVE_PR_MUTATION, { + pullRequestId: "PR_kwDOtest0042", + commitOID: validSha, + request: { apiSource: "approvePR", retries: 0 }, + }); + expect(updateSpy).toHaveBeenCalledWith( + expect.objectContaining({ limit: 5000, remaining: 4988, resetAt: "2026-04-23T12:00:00Z" }) + ); + expect(result).toEqual({ + state: "APPROVED", + reviewDecision: "APPROVED", + }); + }); + + it("rejects invalid pullRequestId or commitOID before calling octokit.graphql", async () => { + const octokit = makeOctokit(async () => ({ data: {} })); + + await expect( + approvePullRequest(octokit as never, "bad!id", validSha) + ).rejects.toThrow(/Invalid pullRequestId/); + + await expect( + approvePullRequest(octokit as never, "PR_kwDOtest0042", "not-a-40-char-sha") + ).rejects.toThrow(/Invalid commitOID/); + + expect(octokit.graphql).not.toHaveBeenCalled(); + }); + + it("throws when GitHub response does not confirm APPROVED review state", async () => { + const octokit = makeOctokit( + async () => ({ data: {} }), + async () => ({ + addPullRequestReview: { + pullRequestReview: { + state: "PENDING", + pullRequest: { reviewDecision: "REVIEW_REQUIRED" }, + }, + }, + }) + ); + + await expect( + approvePullRequest(octokit as never, "PR_kwDOtest0042", validSha) + ).rejects.toThrow("GitHub did not confirm pull request approval"); + }); +}); diff --git a/tests/services/github.test.ts b/tests/services/github.test.ts index c74d508a..d8a76f3c 100644 --- a/tests/services/github.test.ts +++ b/tests/services/github.test.ts @@ -1,7 +1,7 @@ import "fake-indexeddb/auto"; import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { createRoot } from "solid-js"; -import { createGitHubClient, cachedRequest, getClient, initClientWatcher, getGraphqlRateLimit, updateGraphqlRateLimit, updateRateLimitFromHeaders, getCoreRateLimit, fetchRateLimitDetails, onApiRequest, type ApiRequestInfo } from "../../src/app/services/github"; +import { createGitHubClient, cachedRequest, getClient, initClientWatcher, getGraphqlRateLimit, updateGraphqlRateLimit, updateRateLimitFromHeaders, getCoreRateLimit, fetchRateLimitDetails, onApiRequest, APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, type ApiRequestInfo } from "../../src/app/services/github"; import { clearCache } from "../../src/app/stores/cache"; // ── createGitHubClient ─────────────────────────────────────────────────────── @@ -91,6 +91,127 @@ describe("createGitHubClient", () => { }) ).rejects.toThrow(/Write operation blocked/); }); + + it("allows APPROVE_PR_MUTATION with valid PR_ nodeId and 40-hex commitOID", async () => { + const client = createGitHubClient("test-token"); + const mockFetch = vi.fn().mockImplementation(async () => + new Response( + JSON.stringify({ + data: { + addPullRequestReview: { + pullRequestReview: { state: "APPROVED", pullRequest: { reviewDecision: "APPROVED" } }, + }, + }, + }), + { status: 200, headers: { "content-type": "application/json" } } + ) + ); + vi.stubGlobal("fetch", mockFetch); + + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha }, + }) + ).resolves.toBeDefined(); + + // Also verify legacy Base64 node ID format via client.graphql() + await expect( + client.graphql(APPROVE_PR_MUTATION, { + pullRequestId: "MDExOlB1bGxSZXF1ZXN0NDI=", + commitOID: validSha, + }) + ).resolves.toBeDefined(); + + expect(GITHUB_NODE_ID_RE.test("PR_kwDOtest42")).toBe(true); + expect(GITHUB_NODE_ID_RE.test("MDExOlB1bGxSZXF1ZXN0NDI=")).toBe(true); + expect(GIT_SHA_RE.test(validSha)).toBe(true); + expect(APPROVE_PR_MUTATION).not.toContain("rateLimit"); + vi.unstubAllGlobals(); + }); + + it("blocks arbitrary, comment-prefixed, and aliased/combined GraphQL mutations", async () => { + const client = createGitHubClient("test-token"); + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + await expect( + client.request("POST /graphql", { + query: `mutation { mergePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `mutation { closePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + await expect( + client.request("POST /graphql", { + query: `mutation { deleteIssue(input: { issueId: "I_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Comment-prefixed mutation + await expect( + client.request("POST /graphql", { + query: `# addPullRequestReview\nmutation { closePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha }, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Combined / aliased mutation smuggling + await expect( + client.request("POST /graphql", { + query: `mutation ApprovePullRequest($pullRequestId: ID!, $commitOID: GitObjectID!) { + a: addPullRequestReview(input: { pullRequestId: $pullRequestId, commitOID: $commitOID, event: APPROVE }) { + pullRequestReview { state } + } + b: mergePullRequest(input: { pullRequestId: $pullRequestId }) { + clientMutationId + } + }`, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha }, + }) + ).rejects.toThrow(/Write operation blocked/); + }); + + it("blocks APPROVE_PR_MUTATION with missing or malformed pullRequestId or commitOID", async () => { + const client = createGitHubClient("test-token"); + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + + // Missing variables object + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Malformed pullRequestId + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: { pullRequestId: "bad!id", commitOID: validSha }, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Missing/non-SHA commitOID + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: "not-a-sha" }, + }) + ).rejects.toThrow(/Write operation blocked/); + + // Disallowed event override in variables + await expect( + client.request("POST /graphql", { + query: APPROVE_PR_MUTATION, + variables: { pullRequestId: "PR_kwDOtest42", commitOID: validSha, event: "REQUEST_CHANGES" }, + }) + ).rejects.toThrow(/Write operation blocked/); + }); }); // ── cachedRequest ──────────────────────────────────────────────────────────── @@ -531,6 +652,21 @@ describe("hook.wrap — request tracking callbacks", () => { expect(cbSpy).not.toHaveBeenCalled(); }); + it("does not fire callback when GraphQL mutation guard blocks a mutation", async () => { + ensureRegistered(); + vi.stubGlobal("fetch", vi.fn().mockResolvedValue( + new Response(JSON.stringify({}), { status: 200, headers: { "content-type": "application/json" } }) + )); + + const client = createGitHubClient("test-token"); + await expect( + client.request("POST /graphql", { + query: `mutation { mergePullRequest(input: { pullRequestId: "PR_kwDOtest42" }) { clientMutationId } }`, + }) + ).rejects.toThrow(/Write operation blocked/); + expect(cbSpy).not.toHaveBeenCalled(); + }); + it("fires callback exactly once per request even with multiple clients", async () => { ensureRegistered(); vi.stubGlobal("fetch", vi.fn().mockResolvedValue( @@ -668,6 +804,11 @@ describe("hook.wrap — rate limit signal routing", () => { // _coreRateLimit must remain at seeded value — GraphQL success must not contaminate it const rl = getCoreRateLimit(); expect(rl!.remaining).toBe(1234); + + // Because the response had no body rateLimit (as on GraphQL mutations), _graphqlRateLimit updates from headers + const graphqlRl = getGraphqlRateLimit(); + expect(graphqlRl).not.toBeNull(); + expect(graphqlRl!.remaining).toBe(9999); }); it("successful REST request updates _coreRateLimit but NOT _graphqlRateLimit", async () => { diff --git a/tests/services/hot-poll.test.ts b/tests/services/hot-poll.test.ts index c82b25d0..a5d351e4 100644 --- a/tests/services/hot-poll.test.ts +++ b/tests/services/hot-poll.test.ts @@ -204,6 +204,49 @@ describe("fetchHotPRStatus", () => { const { results } = await fetchHotPRStatus(octokit as never, ["PR_node4"]); expect(results.get(45)!.checkStatus).toBe("pending"); }); + + it("maps headRefOid (headSha), autoMergeMethod, viewerLatestReviewState, and viewerReviewRequested", async () => { + const validSha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"; + const octokit = makeOctokit(undefined, () => Promise.resolve({ + nodes: [ + { + databaseId: 46, + state: "OPEN", + mergeStateStatus: "CLEAN", + reviewDecision: "REVIEW_REQUIRED", + headRefOid: validSha, + autoMergeRequest: { mergeMethod: "REBASE" }, + viewerLatestReview: { state: "APPROVED" }, + viewerLatestReviewRequest: { id: "RR_kwDOtest46" }, + commits: { nodes: [{ commit: { statusCheckRollup: { state: "SUCCESS" } } }] }, + }, + { + databaseId: 47, + state: "OPEN", + mergeStateStatus: "CLEAN", + reviewDecision: null, + autoMergeRequest: null, + viewerLatestReview: null, + viewerLatestReviewRequest: null, + commits: { nodes: [] }, + }, + ], + rateLimit: { limit: 5000, remaining: 4999, resetAt: "2026-01-01T00:00:00Z" }, + })); + + const { results } = await fetchHotPRStatus(octokit as never, ["PR_node5", "PR_node6"]); + const u46 = results.get(46)!; + expect(u46.headSha).toBe(validSha); + expect(u46.autoMergeMethod).toBe("REBASE"); + expect(u46.viewerLatestReviewState).toBe("APPROVED"); + expect(u46.viewerReviewRequested).toBe(true); + + const u47 = results.get(47)!; + expect(u47.headSha).toBeUndefined(); + expect(u47.autoMergeMethod).toBeNull(); + expect(u47.viewerLatestReviewState).toBeNull(); + expect(u47.viewerReviewRequested).toBe(false); + }); }); describe("fetchWorkflowRunById", () => { diff --git a/tests/shared/validation.test.ts b/tests/shared/validation.test.ts index aa0fab3a..49c12a0e 100644 --- a/tests/shared/validation.test.ts +++ b/tests/shared/validation.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { extractJiraKeys } from "../../src/shared/validation"; +import { extractJiraKeys, isReadOnlyGraphqlQuery } from "../../src/shared/validation"; // ── Jira key pattern (via extractJiraKeys) ─────────────────────────────────── @@ -106,3 +106,41 @@ describe("extractJiraKeys", () => { expect(result[1]).toBe("PROJ-1"); }); }); + +// ── isReadOnlyGraphqlQuery ──────────────────────────────────────────────────── + +describe("isReadOnlyGraphqlQuery", () => { + it("allows shorthand and named query operations", () => { + expect(isReadOnlyGraphqlQuery("{ viewer { login } }")).toBe(true); + expect(isReadOnlyGraphqlQuery("query GetViewer { viewer { login } }")).toBe(true); + }); + + it("ignores mutation/subscription keywords inside comments and string literals", () => { + expect( + isReadOnlyGraphqlQuery( + '# mutation fake\nquery { search(query: "mutation subscription", type: ISSUE, first: 1) { issueCount } }' + ) + ).toBe(true); + expect( + isReadOnlyGraphqlQuery( + 'query { search(query: """mutation { closePullRequest }""", type: ISSUE, first: 1) { issueCount } }' + ) + ).toBe(true); + }); + + it("rejects mutations, comment-prefixed mutations, subscriptions, empty queries, and non-strings", () => { + expect( + isReadOnlyGraphqlQuery('mutation { closePullRequest(input: { pullRequestId: "PR_1" }) { clientMutationId } }') + ).toBe(false); + expect( + isReadOnlyGraphqlQuery( + '# query { viewer { login } }\nmutation { closePullRequest(input: { pullRequestId: "PR_1" }) { clientMutationId } }' + ) + ).toBe(false); + expect(isReadOnlyGraphqlQuery("subscription { viewer { login } }")).toBe(false); + expect(isReadOnlyGraphqlQuery("# only a comment")).toBe(false); + expect(isReadOnlyGraphqlQuery(" ")).toBe(false); + expect(isReadOnlyGraphqlQuery(undefined)).toBe(false); + expect(isReadOnlyGraphqlQuery(null)).toBe(false); + }); +});