diff --git a/DEPLOY.md b/DEPLOY.md index a721a68e..302da456 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. 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`). +**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`) and marking draft PRs ready (`markPullRequestReadyForReview`). ### Local development OAuth App diff --git a/README.md b/README.md index b1c484ed..365395e0 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, 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. +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), clickable two-step `Draft` → `Ready?` badges on your own draft PRs (read-only draft indicators on others'), and a two-step inline `Approve` button on PR rows requiring approval (hidden when CI checks are failing). 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 @@ -81,7 +81,7 @@ Star counts appear in repo group headers, fetched as part of the standard data r ### Dependencies Tab -An auto-detected built-in tab that appears when dependency bot PRs are found in your tracked repos. Dependency PRs are identified via a multi-layer bot detection pipeline (PR author login, branch name prefix, configurable label). Items are grouped by status — **Needs Review** (CI passing, not yet approved), **Waiting** (CI pending or draft), and **Stale** (open more than 14 days) — rather than by repo. Abandoned dependency pills link directly to the Renovate Dashboard issue for bulk resolution. Configurable via **Settings > Dependencies**. +An auto-detected built-in tab that appears when dependency bot PRs are found in your tracked repos. Dependency PRs are identified via a multi-layer bot detection pipeline (PR author login, branch name prefix, configurable label). Items are grouped by status — **Mergeable** (CI passing or no CI configured, not a draft, and no changes requested), **Pending Rebase**, **Needs Action** (with explicit reason badges for failing/running checks, merge conflicts, drafts, or requested changes), and **Stale** (not updated in over 14 days) — rather than by repo. Abandoned dependency pills link directly to the Renovate Dashboard issue for bulk resolution. Configurable via **Settings > Dependencies**. ### Custom Tabs @@ -128,8 +128,8 @@ src/ layout/ # Header, TabBar, FilterBar onboarding/ # OnboardingWizard, OrgSelector, RepoSelector settings/ # SettingsPage, TrackedUsersSection, ThemePicker, Section, SettingRow - shared/ # 28 shared components: FilterInput, FilterChips, StatusDot, - # ReviewBadge, AutoMergeBadge, SizeBadge, RoleBadge, SortDropdown, PaginationControls, + shared/ # 29 shared components: FilterInput, FilterChips, StatusDot, + # ReviewBadge, AutoMergeBadge, DraftBadge, 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 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. +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 explicit user-confirmed PR approval (`addPullRequestReview` with `event: APPROVE`) and marking draft PRs ready (`markPullRequestReadyForReview`) — 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 1523301b..d1f3a1fa 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 and write to approve PRs from the dashboard, or read-only for viewing only). +- **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 or mark draft PRs ready 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. @@ -227,9 +227,17 @@ The dot links to the PR's checks page on GitHub. 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`). +#### Draft Badge & Mark Ready Action + +Draft pull requests display a `Draft` badge (`D` in compact mode) across the Pull Requests, Dependencies, and Tracked tabs. When you are the author of an open draft PR, the badge is interactive and uses a two-step confirmation to mark the PR ready for review on GitHub: +1. Click **Draft** (or **D**) once to arm confirmation (**Ready?**). The confirmation state resets automatically after 4 seconds, on Escape, or when focus leaves the badge. +2. Click **Ready?** to execute `markPullRequestReadyForReview` on GitHub and transition the PR out of draft status. + +Draft PRs authored by other users render as a read-only indicator. + #### 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). +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). The **Approve** button is hidden when CI checks are failing (`checkStatus === "failure"`). 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. @@ -318,10 +326,10 @@ Unlike the Pull Requests tab (which groups by repo), the Dependencies tab groups | Group | Criteria | |-------|----------| -| **Mergeable** | CI passing (all checks green), not yet approved — awaiting review | +| **Mergeable** | CI passing (or no CI configured), not a draft, and no changes requested — ready to review or merge | | **Pending Rebase** | PR has the configured rebase label — waiting for the bot to rebase | -| **Needs Action** | CI pending, checks still running, or PR is a draft — not yet actionable | -| **Stale** | PR has been open more than 14 days without merging — may need a rebase or manual review | +| **Needs Action** | Failing or running CI checks, merge conflicts, draft PR, or changes requested — rows display explicit reason badges (`Failing checks`, `Merge conflict`, `Checks running`, `Draft`, `Changes`) | +| **Stale** | PR has not been updated in over 14 days — may need a rebase or manual review | Within each group, PRs are sorted by repository name, then update category (maintenance, pin, digest, patch, minor, major), then update date. @@ -838,9 +846,9 @@ 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 and write to approve PRs from the dashboard, or read-only for viewing only). +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 or mark draft PRs ready from the dashboard, or read-only for viewing only). -**Approving a PR fails with a permission error (403 / FORBIDDEN).** +**Approving a PR or marking a draft PR ready 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**. diff --git a/mcp/tests/octokit.test.ts b/mcp/tests/octokit.test.ts index 1bf6c1a0..a0a6c356 100644 --- a/mcp/tests/octokit.test.ts +++ b/mcp/tests/octokit.test.ts @@ -92,6 +92,21 @@ describe("createOctokitClient — write guard hook", () => { }) ).rejects.toThrow(/Write operation blocked/); }); + + it("blocks MARK_PR_READY_MUTATION (markPullRequestReadyForReview) on POST /graphql", async () => { + const { createOctokitClient } = await import("../src/octokit.js"); + const { MARK_PR_READY_MUTATION } = await import("../../src/shared/validation.js"); + const client = createOctokitClient("fake-token"); + + await expect( + client.request("POST /graphql", { + query: MARK_PR_READY_MUTATION, + variables: { + pullRequestId: "PR_kwDOtest42", + }, + }) + ).rejects.toThrow(/Write operation blocked/); + }); }); // ── Singleton tests ─────────────────────────────────────────────────────────── diff --git a/src/app/components/dashboard/DashboardPage.tsx b/src/app/components/dashboard/DashboardPage.tsx index 93044619..8dd4192d 100644 --- a/src/app/components/dashboard/DashboardPage.tsx +++ b/src/app/components/dashboard/DashboardPage.tsx @@ -14,7 +14,7 @@ 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, approvePullRequest } from "../../services/api"; +import { fetchDashboardIssueBodies, fetchDepPRBodies, fallbackToPreviousEnrichment, pickEnrichmentFields, approvePullRequest, markPullRequestReady } from "../../services/api"; import type { SortOption } from "../shared/SortDropdown"; import type { Issue, PullRequest, WorkflowRun, HotPRStatusUpdate } from "../../services/api"; import { fetchOrgs } from "../../services/api"; @@ -39,7 +39,7 @@ import { updateRelaySnapshot } from "../../lib/mcp-relay"; import { pushNotification, pushError, dismissNotificationBySource } from "../../lib/errors"; import { detectNewItems, dispatchNotifications } from "../../lib/notifications"; import { getClient, getGraphqlRateLimit, fetchRateLimitDetails } from "../../services/github"; -import { canApprovePR, formatCount, prSizeCategory, rateLimitCssClass, stripParenthetical } from "../../lib/format"; +import { canApprovePR, canMarkPRReady, formatCount, prSizeCategory, rateLimitCssClass, stripParenthetical } from "../../lib/format"; import { setsEqual } from "../../lib/collections"; import { withScrollLock } from "../../lib/scroll"; import { Tooltip } from "../shared/Tooltip"; @@ -211,6 +211,28 @@ function applyRecentApprovalGuard(pr: PullRequest, currentLogin: string): void { } } +const [markingReadyPRIds, setMarkingReadyPRIds] = createSignal>(new Set()); +const RECENT_READY_TTL_MS = 60_000; +const recentlyMarkedReadyPRs = new Map< + number, + { reviewDecision: PullRequest["reviewDecision"]; markedAt: number } +>(); + +function applyRecentReadyGuard(pr: PullRequest): void { + const now = Date.now(); + for (const [id, entry] of recentlyMarkedReadyPRs) { + if (now - entry.markedAt > RECENT_READY_TTL_MS) { + recentlyMarkedReadyPRs.delete(id); + } + } + const entry = recentlyMarkedReadyPRs.get(pr.id); + if (!entry) return; + pr.draft = false; + if (pr.reviewDecision === null && entry.reviewDecision !== null) { + pr.reviewDecision = entry.reviewDecision; + } +} + export function applyHotPollPRUpdates( state: { pullRequests: PullRequest[] }, prUpdates: ReadonlyMap, @@ -226,6 +248,7 @@ export function applyHotPollPRUpdates( const update = prUpdates.get(pr.id); if (!update) continue; pr.state = update.state; // detect closed/merged quickly + if (typeof update.draft === "boolean") pr.draft = update.draft; pr.checkStatus = update.checkStatus; pr.reviewDecision = update.reviewDecision; if (update.headSha) { @@ -251,6 +274,7 @@ export function applyHotPollPRUpdates( ) { pr.reviewerLogins = [...pr.reviewerLogins, loginLower]; } + applyRecentReadyGuard(pr); applyRecentApprovalGuard(pr, currentLogin); } if (terminalPrIds.size > 0) { @@ -283,6 +307,8 @@ onAuthCleared(() => { _depBodyFailureCooldown.clear(); setApprovingPRIds(new Set()); recentlyApprovedPRs.clear(); + setMarkingReadyPRIds(new Set()); + recentlyMarkedReadyPRs.clear(); resetAbandonedPatternCache(); const coord = _coordinator(); if (coord) { @@ -343,7 +369,10 @@ async function pollFetch(): Promise { setHasFetchedFresh(true); const now = new Date(); const currentLogin = user()?.login ?? ""; - for (const pr of data.pullRequests) applyRecentApprovalGuard(pr, currentLogin); + for (const pr of data.pullRequests) { + applyRecentReadyGuard(pr); + applyRecentApprovalGuard(pr, currentLogin); + } if (phaseOneFired) { // Phase 1 fired — use fine-grained merge for the light→enriched @@ -376,16 +405,21 @@ async function pollFetch(): Promise { if (!regressing) { Object.assign(pr, pickEnrichmentFields(e)); pr.reviewDecision = e.reviewDecision; + pr.draft = e.draft; pr.enriched = e.enriched; } pr.nodeId = e.nodeId; pr.surfacedBy = e.surfacedBy; pr.starCount = e.starCount; + applyRecentReadyGuard(pr); applyRecentApprovalGuard(pr, currentLogin); } } else { state.pullRequests = fallbackToPreviousEnrichment(state.pullRequests, data.pullRequests); - for (const pr of state.pullRequests) applyRecentApprovalGuard(pr, currentLogin); + for (const pr of state.pullRequests) { + applyRecentReadyGuard(pr); + applyRecentApprovalGuard(pr, currentLogin); + } } })); } else { @@ -395,7 +429,10 @@ 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); + for (const pr of pullRequests) { + applyRecentReadyGuard(pr); + applyRecentApprovalGuard(pr, currentLogin); + } withScrollLock(() => { setDashboardData({ issues: data.issues, @@ -407,7 +444,15 @@ async function pollFetch(): Promise { }); } const filteredRuns = config.enableActions ? data.workflowRuns : []; - rebuildHotSets({ ...data, workflowRuns: filteredRuns }); + const hotPullRequests = + recentlyMarkedReadyPRs.size > 0 || recentlyApprovedPRs.size > 0 + ? data.pullRequests.map((pr) => + (recentlyMarkedReadyPRs.has(pr.id) || recentlyApprovedPRs.has(pr.id)) && pr.nodeId + ? { ...pr, enriched: true, checkStatus: "pending" as const } + : pr + ) + : data.pullRequests; + rebuildHotSets({ ...data, pullRequests: hotPullRequests, workflowRuns: filteredRuns }); // Persist for stale-while-revalidate on full page reload. // Errors are transient and not persisted. Deferred to avoid blocking paint. const cachePayload = { @@ -506,6 +551,7 @@ function handleTargetedData(data: DashboardData, affectedRepos: string[]): void Object.assign(pr, pickEnrichmentFields(existingPr)); pr.enriched = existingPr.enriched; } + applyRecentReadyGuard(pr); applyRecentApprovalGuard(pr, currentLogin); } @@ -1454,6 +1500,40 @@ export default function DashboardPage() { return /commitOID|was not part of the pull request|pull request head|outdated|end of the branch/i.test(msg); } + function addIdToSet(prev: ReadonlySet, id: number): ReadonlySet { + const next = new Set(prev); + next.add(id); + return next; + } + + function removeIdFromSet(prev: ReadonlySet, id: number): ReadonlySet { + if (!prev.has(id)) return prev; + const next = new Set(prev); + next.delete(id); + return next; + } + + function handlePRMutationCommonError( + err: unknown, + source: string, + permissionDeniedMsg: string + ): boolean { + 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 true; + } + if (isPermissionDeniedError(err)) { + pushNotification(source, permissionDeniedMsg, "error"); + return true; + } + return false; + } + async function handleApprovePR(pr: PullRequest): Promise { const currentLogin = userLogin(); if (!canApprovePR(pr, currentLogin)) return; @@ -1468,11 +1548,7 @@ export default function DashboardPage() { // 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; - }); + setApprovingPRIds((prev) => addIdToSet(prev, pr.id)); try { const result = await approvePullRequest(client, nodeId, approvedHeadSha); @@ -1507,21 +1583,13 @@ export default function DashboardPage() { 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( + if ( + handlePRMutationCommonError( + err, `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" - ); + "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." + ) + ) { return; } if (isStaleCommitError(err)) { @@ -1536,12 +1604,66 @@ export default function DashboardPage() { 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; + setApprovingPRIds((prev) => removeIdFromSet(prev, pr.id)); + } + } + + async function handleMarkPRReady(pr: PullRequest): Promise { + const currentLogin = userLogin(); + if (!canMarkPRReady(pr, currentLogin)) return; + if (markingReadyPRIds().has(pr.id)) return; + const client = getClient(); + if (!client || !pr.nodeId) return; + const nodeId = pr.nodeId; + + dismissNotificationBySource(`mark-ready-pr:${pr.id}`); + + setMarkingReadyPRIds((prev) => addIdToSet(prev, pr.id)); + + try { + const result = await markPullRequestReady(client, nodeId); + if (getClient() !== client) return; + + recentlyMarkedReadyPRs.set(pr.id, { + reviewDecision: result.reviewDecision, + markedAt: Date.now(), + }); + + setDashboardData( + produce((state) => { + const target = state.pullRequests.find((item) => item.id === pr.id); + if (target) { + target.draft = false; + if (result.reviewDecision !== null) { + target.reviewDecision = result.reviewDecision; + } + } + }) + ); + + seedHotSetsFromTargeted({ + issues: [], + pullRequests: [{ ...pr, nodeId, draft: false, enriched: true, checkStatus: "pending" }], + workflowRuns: [], + errors: [], }); + + persistDashboardSnapshot(); + } catch (err) { + if (getClient() !== client) return; + if ( + handlePRMutationCommonError( + err, + `mark-ready-pr:${pr.id}`, + "Unable to mark PR ready: 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." + ) + ) { + return; + } + const message = err instanceof Error ? err.message : "Unknown error"; + pushNotification(`mark-ready-pr:${pr.id}`, `Failed to mark ${pr.repoFullName}#${pr.number} ready for review: ${message}`, "error"); + } finally { + setMarkingReadyPRIds((prev) => removeIdFromSet(prev, pr.id)); } } @@ -1617,6 +1739,8 @@ export default function DashboardPage() { depPrIds={dependencyPrIds()} onApprovePR={handleApprovePR} approvingPRIds={approvingPRIds()} + onMarkPRReady={handleMarkPRReady} + markingReadyPRIds={markingReadyPRIds()} /> @@ -1634,6 +1758,8 @@ export default function DashboardPage() { onRefresh={() => _coordinator()?.manualRefresh()} onApprovePR={handleApprovePR} approvingPRIds={approvingPRIds()} + onMarkPRReady={handleMarkPRReady} + markingReadyPRIds={markingReadyPRIds()} /> @@ -1646,6 +1772,8 @@ export default function DashboardPage() { hotPollingPRIds={hotPollingPRIds()} onApprovePR={handleApprovePR} approvingPRIds={approvingPRIds()} + onMarkPRReady={handleMarkPRReady} + markingReadyPRIds={markingReadyPRIds()} /> @@ -1712,6 +1840,8 @@ export default function DashboardPage() { jiraKeyMap={jiraKeyMap} onApprovePR={handleApprovePR} approvingPRIds={approvingPRIds()} + onMarkPRReady={handleMarkPRReady} + markingReadyPRIds={markingReadyPRIds()} /> diff --git a/src/app/components/dashboard/DependenciesTab.tsx b/src/app/components/dashboard/DependenciesTab.tsx index b1ddd204..6ff6227a 100644 --- a/src/app/components/dashboard/DependenciesTab.tsx +++ b/src/app/components/dashboard/DependenciesTab.tsx @@ -3,7 +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 { canApprovePR, canMarkPRReady } from "../../lib/format"; import type { PullRequest } from "../../services/api"; import type { AbandonedDependency } from "../../lib/dependency-dashboard"; import { @@ -25,6 +25,7 @@ import StatusDot from "../shared/StatusDot"; import SizeBadge from "../shared/SizeBadge"; import ReviewBadge from "../shared/ReviewBadge"; import AutoMergeBadge from "../shared/AutoMergeBadge"; +import DraftBadge from "../shared/DraftBadge"; import ItemRow from "./ItemRow"; import SkeletonRows from "../shared/SkeletonRows"; @@ -114,6 +115,8 @@ interface DependenciesTabProps { onRefresh?: () => void; onApprovePR?: (pr: PullRequest) => void; approvingPRIds?: ReadonlySet; + onMarkPRReady?: (pr: PullRequest) => void; + markingReadyPRIds?: ReadonlySet; } export default function DependenciesTab(props: DependenciesTabProps) { @@ -370,6 +373,8 @@ export default function DependenciesTab(props: DependenciesTabProps) { userLogin={props.userLogin} onApprovePR={props.onApprovePR} approvingPRIds={props.approvingPRIds} + onMarkPRReady={props.onMarkPRReady} + markingReadyPRIds={props.markingReadyPRIds} /> )} @@ -395,6 +400,8 @@ interface StatusGroupProps { userLogin: string; onApprovePR?: (pr: PullRequest) => void; approvingPRIds?: ReadonlySet; + onMarkPRReady?: (pr: PullRequest) => void; + markingReadyPRIds?: ReadonlySet; } function stripCommitPrefix(title: string): string { @@ -463,9 +470,23 @@ function StatusGroup(props: StatusGroupProps) { >
- + + + + + Merge conflict + + + + Failing checks + + + Checks running + 0 || pr.deletions > 0)}> @@ -476,9 +497,14 @@ function StatusGroup(props: StatusGroupProps) { /> - - Draft - + props.onMarkPRReady!(pr) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(pr.id)} + /> ; onApprovePR?: (pr: PullRequest) => void; approvingPRIds?: ReadonlySet; + onMarkPRReady?: (pr: PullRequest) => void; + markingReadyPRIds?: ReadonlySet; } type SortField = "repo" | "title" | "author" | "createdAt" | "updatedAt" | "checkStatus" | "reviewDecision" | "size"; @@ -561,11 +564,13 @@ export default function PullRequestsTab(props: PullRequestsTabProps) { - - - Draft - - + props.onMarkPRReady!(pr) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(pr.id)} + /> 0}> @@ -593,9 +598,14 @@ export default function PullRequestsTab(props: PullRequestsTabProps) { - - D - + props.onMarkPRReady!(pr) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(pr.id)} + /> 0 || (prMeta().get(pr.id)?.roles ?? []).length > 0)}> 0 ? `Role: ${(prMeta().get(pr.id)?.roles ?? []).join(", ")}` : false, diff --git a/src/app/components/dashboard/TrackedTab.tsx b/src/app/components/dashboard/TrackedTab.tsx index d1301896..eb3063ee 100644 --- a/src/app/components/dashboard/TrackedTab.tsx +++ b/src/app/components/dashboard/TrackedTab.tsx @@ -3,12 +3,13 @@ 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 { canApprovePR, deriveInvolvementRoles, prSizeCategory } from "../../lib/format"; +import { canApprovePR, canMarkPRReady, 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 DraftBadge from "../shared/DraftBadge"; import SizeBadge from "../shared/SizeBadge"; import RoleBadge from "../shared/RoleBadge"; import { Tooltip } from "../shared/Tooltip"; @@ -79,6 +80,8 @@ export interface TrackedTabProps { hotPollingPRIds?: ReadonlySet; onApprovePR?: (pr: PullRequest) => void; approvingPRIds?: ReadonlySet; + onMarkPRReady?: (pr: PullRequest) => void; + markingReadyPRIds?: ReadonlySet; } export default function TrackedTab(props: TrackedTabProps) { @@ -291,9 +294,13 @@ export default function TrackedTab(props: TrackedTabProps) { - - Draft - + props.onMarkPRReady!(prData()) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(prData().id)} + />
} > @@ -312,9 +319,14 @@ export default function TrackedTab(props: TrackedTabProps) { - - D - + props.onMarkPRReady!(prData()) : undefined} + isMarkingReady={props.markingReadyPRIds?.has(prData().id)} + /> ); diff --git a/src/app/components/shared/DraftBadge.tsx b/src/app/components/shared/DraftBadge.tsx new file mode 100644 index 00000000..2bdfdf0a --- /dev/null +++ b/src/app/components/shared/DraftBadge.tsx @@ -0,0 +1,152 @@ +import { createEffect, createMemo, createSignal, on, onCleanup, Show } from "solid-js"; +import { Tooltip } from "./Tooltip"; + +export interface DraftBadgeProps { + draft: boolean; + compact?: boolean; + prNumber?: number; + prTitle?: string; + /** Defined only when canMarkPRReady(pr, userLogin) is true */ + onMarkReady?: () => void; + /** True while markPullRequestReady mutation is in flight for this PR */ + isMarkingReady?: boolean; +} + +const READY_CONFIRM_TIMEOUT_MS = 4_000; + +function InteractiveDraftBadge(props: DraftBadgeProps) { + const [confirming, setConfirming] = createSignal(false); + let confirmTimer: ReturnType | undefined; + + function clearTimer() { + if (confirmTimer !== undefined) { + clearTimeout(confirmTimer); + confirmTimer = undefined; + } + } + + function resetConfirm() { + clearTimer(); + setConfirming(false); + } + + const isMarkingReady = createMemo(() => Boolean(props.isMarkingReady)); + + createEffect( + on( + [() => props.draft, () => props.onMarkReady, isMarkingReady], + (curr, prev) => { + if (!prev || curr.some((v, i) => v !== prev[i])) { + resetConfirm(); + } + }, + { defer: true }, + ), + ); + + onCleanup(clearTimer); + + function handleClick(e: MouseEvent) { + e.stopPropagation(); + e.preventDefault(); + if (isMarkingReady() || !props.onMarkReady) return; + if (!confirming()) { + setConfirming(true); + clearTimer(); + confirmTimer = setTimeout(() => { + confirmTimer = undefined; + setConfirming(false); + }, READY_CONFIRM_TIMEOUT_MS); + return; + } + resetConfirm(); + props.onMarkReady(); + } + + function handleKeyDown(e: KeyboardEvent) { + if (e.key === "Escape" && confirming()) { + e.stopPropagation(); + e.preventDefault(); + resetConfirm(); + } + } + + const meta = createMemo(() => { + const target = [props.prNumber != null ? `#${props.prNumber}` : "", props.prTitle ?? ""] + .filter(Boolean) + .join(" "); + const labelTarget = target ? ` ${target}` : ""; + const sizeClass = props.compact ? "badge-xs" : "badge-sm"; + + if (isMarkingReady()) { + return { + tooltip: "Marking ready for review...", + ariaLabel: `Marking${labelTarget} ready for review`, + buttonClass: `badge badge-ghost ${sizeClass}`, + }; + } + + if (confirming()) { + return { + tooltip: "Click again to mark ready for review", + ariaLabel: `Confirm mark${labelTarget} ready for review`, + buttonClass: `badge badge-warning cursor-pointer font-medium ${sizeClass}`, + }; + } + + return { + tooltip: "Click to mark ready for review", + ariaLabel: `Mark${labelTarget} ready for review`, + buttonClass: `badge badge-ghost italic text-base-content/70 hover:badge-info hover:not-italic hover:text-info-content cursor-pointer transition-colors ${sizeClass}`, + }; + }); + + return ( + + + + ); +} + +export default function DraftBadge(props: DraftBadgeProps) { + return ( + + + {props.compact ? "D" : "Draft"} + + } + > + + + + ); +} diff --git a/src/app/lib/dependency-detection.ts b/src/app/lib/dependency-detection.ts index 8182ca7e..0dd1827e 100644 --- a/src/app/lib/dependency-detection.ts +++ b/src/app/lib/dependency-detection.ts @@ -282,12 +282,12 @@ export function classifyDepStatus( return "pending-rebase"; } - // 2. Enriched + CI green + not draft + not approved → mergeable + // 2. Enriched + CI green (or no CI configured) + not draft + not changes-requested → mergeable if ( pr.enriched !== false && !pr.draft && - pr.checkStatus === "success" && - pr.reviewDecision !== "APPROVED" + (pr.checkStatus === "success" || pr.checkStatus === null) && + pr.reviewDecision !== "CHANGES_REQUESTED" ) { return "mergeable"; } diff --git a/src/app/lib/format.ts b/src/app/lib/format.ts index a3a7dd2b..40216f1b 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, canApprovePR } from "../../shared/format"; +export { relativeTime, shortRelativeTime, labelTextColor, formatDuration, prSizeCategory, deriveInvolvementRoles, formatCount, formatStarCount, canApprovePR, canMarkPRReady } 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 6dce0326..52a9ab58 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, and Issues, plus Read and write for Pull requests (or read-only if you don't approve PRs from the dashboard). + {" "}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 or mark drafts ready from the dashboard).

diff --git a/src/app/pages/PrivacyPage.tsx b/src/app/pages/PrivacyPage.tsx index 8e26b40a..e1d48a7e 100644 --- a/src/app/pages/PrivacyPage.tsx +++ b/src/app/pages/PrivacyPage.tsx @@ -197,8 +197,8 @@ export default function PrivacyPage() { 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{" "} + Approve or mark a draft pull request as ready for review. All other write + operations are blocked client-side. You can revoke access at any time from{" "} = { fetchRepos: "Fetch Repos", rateLimitCheck: "Rate Limit Check", approvePR: "Approve PR", + markPRReady: "Mark PR Ready", graphql: "GraphQL (other)", rest: "REST (other)", }; diff --git a/src/app/services/api.ts b/src/app/services/api.ts index d27ec4c6..e0e32fcf 100644 --- a/src/app/services/api.ts +++ b/src/app/services/api.ts @@ -3,7 +3,7 @@ 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, APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE } from "../../shared/validation"; +import { VALID_REPO_NAME, VALID_TRACKED_LOGIN, SEARCH_RESULT_CAP, APPROVE_PR_MUTATION, MARK_PR_READY_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE } from "../../shared/validation"; import { REPO_CAP } from "../../shared/types"; import type { Issue, IssueState, PullRequest, PullRequestState, AutoMergeMethod, ViewerReviewState, WorkflowRun, RepoRef, RepoEntry, OrgEntry, CheckStatus, ApiError } from "../../shared/types"; @@ -422,6 +422,7 @@ const HOT_PR_STATUS_QUERY = ` ... on PullRequest { databaseId state + isDraft headRefOid mergeStateStatus reviewDecision @@ -444,6 +445,7 @@ const HOT_PR_STATUS_QUERY = ` interface HotPRStatusNode { databaseId: number; state: PullRequestState; + isDraft?: boolean; headRefOid?: string; mergeStateStatus: string; reviewDecision: string | null; @@ -1979,6 +1981,7 @@ export async function fetchWorkflowRuns( export interface HotPRStatusUpdate { state: PullRequestState; + draft?: boolean; checkStatus: CheckStatus["status"]; mergeStateStatus: string; reviewDecision: PullRequest["reviewDecision"]; @@ -2019,6 +2022,7 @@ export async function fetchHotPRStatus( results.set(node.databaseId, { state: node.state, + ...(typeof node.isDraft === "boolean" ? { draft: node.isDraft } : {}), checkStatus, mergeStateStatus: node.mergeStateStatus, reviewDecision: mapReviewDecision(node.reviewDecision), @@ -2273,3 +2277,40 @@ export async function approvePullRequest( reviewDecision: mapReviewDecision(review?.pullRequest?.reviewDecision ?? null), }; } + +interface MarkPullRequestReadyResponse { + markPullRequestReadyForReview: { + pullRequest: { + isDraft: boolean | null; + reviewDecision: string | null; + } | null; + } | null; + rateLimit?: GraphQLRateLimit; +} + +export async function markPullRequestReady( + octokit: GitHubOctokit, + pullRequestId: string, +): Promise<{ draft: false; reviewDecision: PullRequest["reviewDecision"] }> { + if (!GITHUB_NODE_ID_RE.test(pullRequestId)) { + throw new Error(`Invalid pullRequestId: "${pullRequestId}"`); + } + + const response = await octokit.graphql(MARK_PR_READY_MUTATION, { + pullRequestId, + request: { apiSource: "markPRReady", retries: 0 }, + }); + + if (response.rateLimit) { + updateGraphqlRateLimit(response.rateLimit); + } + + const pr = response.markPullRequestReadyForReview?.pullRequest; + if (!pr || pr.isDraft !== false) { + throw new Error("GitHub did not confirm pull request is ready for review"); + } + return { + draft: false, + reviewDecision: mapReviewDecision(pr.reviewDecision ?? null), + }; +} diff --git a/src/app/services/github.ts b/src/app/services/github.ts index 563d57bb..b185e58f 100644 --- a/src/app/services/github.ts +++ b/src/app/services/github.ts @@ -6,11 +6,13 @@ 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"; +import { APPROVE_PR_MUTATION, MARK_PR_READY_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, isReadOnlyGraphqlQuery } from "../../shared/validation"; -export { APPROVE_PR_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, isReadOnlyGraphqlQuery }; +export { APPROVE_PR_MUTATION, MARK_PR_READY_MUTATION, GITHUB_NODE_ID_RE, GIT_SHA_RE, isReadOnlyGraphqlQuery }; const NORMALIZED_APPROVE_MUTATION = APPROVE_PR_MUTATION.replace(/\s+/g, " "); +const NORMALIZED_MARK_READY_MUTATION = MARK_PR_READY_MUTATION.replace(/\s+/g, " "); +const APPROVE_ALLOWED_KEYS = new Set(["pullRequestId", "commitOID", "event"]); function isAllowedGraphqlRequest(options: { query?: unknown; variables?: unknown }): boolean { if (typeof options.query !== "string") return false; @@ -20,26 +22,42 @@ function isAllowedGraphqlRequest(options: { query?: unknown; variables?: unknown return true; } - // 2. Allow ONLY the exact canonical ApprovePullRequest mutation + // 2. Allow ONLY the exact canonical ApprovePullRequest or MarkPullRequestReadyForReview mutations 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 || typeof vars !== "object" || Array.isArray(vars)) return false; + + if (normalized === NORMALIZED_APPROVE_MUTATION) { + if (!Object.keys(vars).every((k) => APPROVE_ALLOWED_KEYS.has(k))) { + 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; } - if (vars.event !== undefined && vars.event !== "APPROVE") { - return false; + + if (normalized === NORMALIZED_MARK_READY_MUTATION) { + const keys = Object.keys(vars); + if (keys.length !== 1 || keys[0] !== "pullRequestId") { + return false; + } + if (typeof vars.pullRequestId !== "string" || !GITHUB_NODE_ID_RE.test(vars.pullRequestId)) { + return false; + } + return true; } - return true; + + return false; } // ── Plugin-extended Octokit class ──────────────────────────────────────────── @@ -169,13 +187,13 @@ export function createGitHubClient(token: string): GitHubOctokitInstance { }); // 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). + // but this app only permits GET requests, read-only GraphQL queries, and explicit + // user-confirmed mutations (APPROVE_PR_MUTATION and MARK_PR_READY_MUTATION). client.hook.before("request", (options) => { const method = (options.method ?? "GET").toUpperCase(); if (method === "GET") return; 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.`); + throw new Error(`[github] Write operation blocked: ${method} ${options.url}. Only read queries, PR approvals, and marking draft PRs ready are permitted.`); }); // Track every API request for usage analytics + update rate limit display diff --git a/src/app/services/poll.ts b/src/app/services/poll.ts index b622db5a..cfb33dbf 100644 --- a/src/app/services/poll.ts +++ b/src/app/services/poll.ts @@ -547,7 +547,7 @@ export async function fetchHotData(priorConsecutiveFailures = 0): Promise<{ if ( upd.state === "CLOSED" || upd.state === "MERGED" || - (upd.checkStatus !== "pending" && upd.checkStatus !== null) + upd.checkStatus !== "pending" ) { const nodeId = _hotPRsByDbId.get(databaseId); if (nodeId) { diff --git a/src/shared/format.ts b/src/shared/format.ts index d23f4f99..2d972114 100644 --- a/src/shared/format.ts +++ b/src/shared/format.ts @@ -140,7 +140,7 @@ export function formatStarCount(count: number): string { /** * 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 + * - PR is OPEN, enriched, not a draft, CI checks are not failing, 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)`) @@ -151,7 +151,19 @@ 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.checkStatus === "failure") 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; } + +/** + * Returns true when the authenticated user can mark a draft PR as ready for review: + * - PR is OPEN, currently a draft, and has a valid GraphQL nodeId + * - Authenticated user is the PR author (case-insensitive) + */ +export function canMarkPRReady(pr: PullRequest, userLogin: string): boolean { + if (!userLogin || !pr.nodeId) return false; + if (pr.state !== "OPEN" || !pr.draft) return false; + return pr.userLogin.toLowerCase() === userLogin.toLowerCase(); +} diff --git a/src/shared/validation.ts b/src/shared/validation.ts index eecae657..8b872852 100644 --- a/src/shared/validation.ts +++ b/src/shared/validation.ts @@ -22,6 +22,17 @@ export const APPROVE_PR_MUTATION = ` } `.trim(); +export const MARK_PR_READY_MUTATION = ` + mutation MarkPullRequestReadyForReview($pullRequestId: ID!) { + markPullRequestReadyForReview(input: { pullRequestId: $pullRequestId }) { + pullRequest { + isDraft + 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; diff --git a/tests/components/DashboardPage.test.tsx b/tests/components/DashboardPage.test.tsx index 969e9ec9..21212867 100644 --- a/tests/components/DashboardPage.test.tsx +++ b/tests/components/DashboardPage.test.tsx @@ -6,7 +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"; +import { APPROVE_PR_MUTATION, MARK_PR_READY_MUTATION } from "../../src/shared/validation"; const mockLocationReplace = vi.fn(); @@ -4376,3 +4376,450 @@ describe("DashboardPage — PR approval integration", () => { expect(screen.getByText("Changes")).toBeTruthy(); }); }); + +// ── Mark PR Ready Integration ──────────────────────────────────────────────── + +describe("DashboardPage — Mark PR ready integration", () => { + it("completes two-step Draft -> Ready? flow on a self-authored draft PR, removes Draft badge, seeds hot sets, preserves ready state across hot/targeted/full polls within 60s, and evicts after TTL", async () => { + const user = userEvent.setup(); + const graphqlMock = vi.fn().mockResolvedValue({ + markPullRequestReadyForReview: { + pullRequest: { + isDraft: false, + reviewDecision: "REVIEW_REQUIRED", + }, + }, + rateLimit: { limit: 5000, remaining: 4999, resetAt: "2026-04-20T00:00:00Z" }, + }); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const makeStaleDraftPR = () => + makePullRequest({ + id: 77, + number: 77, + title: "Ship draft feature", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: true, + nodeId: "PR_kwDOtest0077", + reviewDecision: null, + checkStatus: "success", + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [makeStaleDraftPR()], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const draftBtn = await waitFor(() => screen.getByLabelText("Mark #77 Ship draft feature ready for review")); + expect(draftBtn.textContent).toBe("Draft"); + + // Step 1: Enter confirmation mode + await user.click(draftBtn); + expect(graphqlMock).not.toHaveBeenCalled(); + expect(draftBtn.textContent).toBe("Ready?"); + expect(draftBtn.getAttribute("aria-label")).toBe("Confirm mark #77 Ship draft feature ready for review"); + + // Step 2: Confirm mark ready + await user.click(draftBtn); + await waitFor(() => { + expect(graphqlMock).toHaveBeenCalledOnce(); + }); + + expect(graphqlMock).toHaveBeenCalledWith(MARK_PR_READY_MUTATION, { + pullRequestId: "PR_kwDOtest0077", + request: { apiSource: "markPRReady", retries: 0 }, + }); + + expect(errorsLib.dismissNotificationBySource).toHaveBeenCalledWith("mark-ready-pr:77"); + expect(pollService.seedHotSetsFromTargeted).toHaveBeenCalledWith({ + issues: [], + pullRequests: [ + expect.objectContaining({ + id: 77, + nodeId: "PR_kwDOtest0077", + draft: false, + enriched: true, + checkStatus: "pending", + }), + ], + workflowRuns: [], + errors: [], + }); + + await waitFor(() => { + expect(screen.queryByTestId("draft-badge")).toBeNull(); + expect(screen.getByText("Review needed")).toBeTruthy(); + }); + expect(errorsLib.pushNotification).not.toHaveBeenCalled(); + + // 1. Subsequent hot poll reporting stale draft: true and reviewDecision: null within 60s + capturedOnHotData!( + new Map([[77, { + state: "OPEN", + draft: true, + checkStatus: "pending", + mergeStateStatus: "DRAFT", + reviewDecision: null, + }]]), + new Map(), + 0 + ); + expect(screen.queryByTestId("draft-badge")).toBeNull(); + expect(screen.getByText("Review needed")).toBeTruthy(); + + // 2. Subsequent targeted poll reporting stale draft: true within 60s + capturedOnTargetedData!( + { issues: [], pullRequests: [makeStaleDraftPR()], workflowRuns: [], errors: [] }, + ["owner/repo"] + ); + expect(screen.queryByTestId("draft-badge")).toBeNull(); + expect(screen.getByText("Review needed")).toBeTruthy(); + + // 3. Subsequent full poll reporting stale draft: true within 60s keeps pr.draft === false + // and preserves hot-set membership (checkStatus: "pending" passed to rebuildHotSets) + vi.mocked(pollService.rebuildHotSets).mockClear(); + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [makeStaleDraftPR()], + workflowRuns: [], + errors: [], + }); + await capturedFetchAll!(); + expect(screen.queryByTestId("draft-badge")).toBeNull(); + expect(screen.getByText("Review needed")).toBeTruthy(); + expect(pollService.rebuildHotSets).toHaveBeenCalledWith( + expect.objectContaining({ + pullRequests: [ + expect.objectContaining({ + id: 77, + nodeId: "PR_kwDOtest0077", + enriched: true, + checkStatus: "pending", + }), + ], + }) + ); + + // 3b. Subsequent poll within 60s returning a non-null reviewDecision ("APPROVED") preserves + // "APPROVED" rather than overwriting it with entry.reviewDecision ("REVIEW_REQUIRED"), + // while still guarding pr.draft === false + capturedOnHotData!( + new Map([[77, { + state: "OPEN", + draft: true, + checkStatus: "success", + mergeStateStatus: "CLEAN", + reviewDecision: "APPROVED", + }]]), + new Map(), + 0 + ); + expect(screen.queryByTestId("draft-badge")).toBeNull(); + expect(screen.getByText("Approved")).toBeTruthy(); + expect(screen.queryByText("Review needed")).toBeNull(); + + // 4. Advance Date.now past the 60_000ms TTL and run a full poll -> guard entry is evicted + const expiredNow = Date.now() + 60_001; + const nowSpy = vi.spyOn(Date, "now").mockReturnValue(expiredNow); + try { + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [makeStaleDraftPR()], + workflowRuns: [], + errors: [], + }); + await capturedFetchAll!(); + } finally { + nowSpy.mockRestore(); + } + + await waitFor(() => { + expect(screen.getByTestId("draft-badge")).toBeTruthy(); + }); + }); + + it("merges Phase 2 draft state, reviewDecision, and recent ready guard when Phase 1 onLightData fires", async () => { + const user = userEvent.setup(); + const graphqlMock = vi.fn().mockResolvedValue({ + markPullRequestReadyForReview: { + pullRequest: { + isDraft: false, + reviewDecision: "REVIEW_REQUIRED", + }, + }, + rateLimit: { limit: 5000, remaining: 4999, resetAt: "2026-04-20T00:00:00Z" }, + }); + vi.mocked(githubService.getClient).mockReturnValue( + { graphql: graphqlMock } as unknown as ReturnType + ); + + const lightPR1 = makePullRequest({ + id: 201, + number: 201, + title: "Phase 1 draft PR", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: true, + enriched: false, + nodeId: "PR_kwDOtest0201", + reviewDecision: null, + checkStatus: null, + }); + const lightPR2 = makePullRequest({ + id: 202, + number: 202, + title: "Mark ready during Phase 1", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: false, + nodeId: "PR_kwDOtest0202", + reviewDecision: null, + checkStatus: 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; mark PR #202 ready before Phase 2 resolves + const draftBtn = await waitFor(() => screen.getByLabelText("Mark #202 Mark ready during Phase 1 ready for review")); + await user.click(draftBtn); + await user.click(draftBtn); + await waitFor(() => expect(graphqlMock).toHaveBeenCalledOnce()); + + // Resolve Phase 2: PR #201 transitions draft: true -> false with reviewDecision: "CHANGES_REQUESTED", + // while PR #202 returns stale draft: true and reviewDecision: null that applyRecentReadyGuard must override + const enrichedPR1 = makePullRequest({ + id: 201, + number: 201, + title: "Phase 1 draft PR", + repoFullName: "owner/repo", + userLogin: "otheruser", + state: "OPEN", + draft: false, + enriched: true, + nodeId: "PR_kwDOtest0201", + reviewDecision: "CHANGES_REQUESTED", + checkStatus: "success", + }); + const staleEnrichedPR2 = makePullRequest({ + id: 202, + number: 202, + title: "Mark ready during Phase 1", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: true, + nodeId: "PR_kwDOtest0202", + reviewDecision: null, + checkStatus: "success", + }); + + resolvePhase2({ + issues: [], + pullRequests: [enrichedPR1, staleEnrichedPR2], + workflowRuns: [], + errors: [], + }); + + await waitFor(() => { + expect(screen.queryByTestId("draft-badge")).toBeNull(); + expect(screen.getByText("Changes")).toBeTruthy(); + expect(screen.getByText("Review needed")).toBeTruthy(); + }); + }); + + it("handles 403 / FORBIDDEN error from markPullRequestReady by pushing mark-ready-pr: PAT permission notification without calling expireToken", 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 draftPR = makePullRequest({ + id: 77, + number: 77, + title: "Ship draft feature", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: true, + nodeId: "PR_kwDOtest0077", + reviewDecision: null, + checkStatus: "success", + }); + + vi.mocked(pollService.fetchAllData).mockResolvedValue({ + issues: [], + pullRequests: [draftPR], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const draftBtn = await waitFor(() => screen.getByLabelText("Mark #77 Ship draft feature ready for review") as HTMLButtonElement); + await user.click(draftBtn); + await user.click(draftBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "mark-ready-pr:77", + "Unable to mark PR ready: 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(); + const btnAfter = screen.getByLabelText("Mark #77 Ship draft feature ready for review") as HTMLButtonElement; + expect(btnAfter.disabled).toBe(false); + expect(btnAfter.textContent).toBe("Draft"); + }); + + it("treats 403 with rate-limit headers (x-ratelimit-remaining: 0 or retry-after) as a generic error instead of permission denied when marking PR ready", 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: 77, + number: 77, + title: "Ship draft feature", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: true, + nodeId: "PR_kwDOtest0077", + reviewDecision: null, + checkStatus: "success", + }), + ], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const draftBtn = await waitFor(() => screen.getByLabelText("Mark #77 Ship draft feature ready for review")); + await user.click(draftBtn); + await user.click(draftBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "mark-ready-pr:77", + "Failed to mark owner/repo#77 ready for review: API rate limit exceeded", + "error" + ); + }); + + // Second attempt: 403 with retry-after header + const retryBtn = await waitFor(() => screen.getByLabelText("Mark #77 Ship draft feature ready for review")); + await user.click(retryBtn); + await user.click(retryBtn); + + await waitFor(() => { + expect(errorsLib.pushNotification).toHaveBeenCalledWith( + "mark-ready-pr:77", + "Failed to mark owner/repo#77 ready for review: Secondary rate limit", + "error" + ); + }); + }); + + it("handles 401 error when marking PR ready 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: 77, + number: 77, + title: "Ship draft feature", + repoFullName: "owner/repo", + userLogin: "testuser", + state: "OPEN", + draft: true, + enriched: true, + nodeId: "PR_kwDOtest0077", + reviewDecision: null, + checkStatus: "success", + }), + ], + workflowRuns: [], + errors: [], + }); + + render(() => ); + await user.click(screen.getByText("Pull Requests")); + await waitFor(() => screen.getByText("owner/repo")); + await user.click(screen.getByText("owner/repo")); + + const draftBtn = await waitFor(() => screen.getByLabelText("Mark #77 Ship draft feature ready for review")); + await user.click(draftBtn); + await user.click(draftBtn); + + await waitFor(() => { + expect(authStore.expireToken).toHaveBeenCalledOnce(); + expect(mockLocationReplace).toHaveBeenCalledWith("/login"); + }); + expect(errorsLib.pushNotification).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/components/PullRequestsTab.test.tsx b/tests/components/PullRequestsTab.test.tsx index 22a7de99..40e41464 100644 --- a/tests/components/PullRequestsTab.test.tsx +++ b/tests/components/PullRequestsTab.test.tsx @@ -784,5 +784,119 @@ describe("PullRequestsTab", () => { expect(onApprovePR).toHaveBeenCalledOnce(); expect(onApprovePR).toHaveBeenCalledWith(eligiblePR); }); + + it("hides Approve button when pr.checkStatus is 'failure'", () => { + setAllExpanded("pullRequests", true); + const onApprovePR = vi.fn(); + + const failingPR = makePullRequest({ + id: 14, + number: 14, + title: "Failing CI PR", + repoFullName: "org/repo", + userLogin: "bob", + nodeId: "PR_kwDOtest0014", + headSha: validSha, + checkStatus: "failure", + reviewDecision: "REVIEW_REQUIRED", + viewerReviewRequested: true, + enriched: true, + }); + + render(() => ( + + )); + + expect(screen.queryByLabelText(/Approve #14/)).toBeNull(); + }); + + it("renders interactive DraftBadge button for self-authored draft PRs (in comfortable and compact density) and read-only span for another author's draft PR", () => { + setAllExpanded("pullRequests", true); + const onMarkPRReady = vi.fn(); + + const ownDraftPR = makePullRequest({ + id: 20, + number: 20, + title: "My Draft PR", + repoFullName: "org/repo", + userLogin: "alice", + nodeId: "PR_kwDOtest0020", + draft: true, + enriched: true, + }); + const otherDraftPR = makePullRequest({ + id: 21, + number: 21, + title: "Bob Draft PR", + repoFullName: "org/repo", + userLogin: "bob", + reviewerLogins: ["alice"], + nodeId: "PR_kwDOtest0021", + draft: true, + enriched: true, + }); + + const { unmount } = render(() => ( + + )); + + const badges = screen.getAllByTestId("draft-badge"); + expect(badges).toHaveLength(2); + + const ownBtn = screen.getByLabelText("Mark #20 My Draft PR ready for review") as HTMLButtonElement; + expect(ownBtn.tagName.toLowerCase()).toBe("button"); + expect(ownBtn.textContent).toBe("Draft"); + + const otherSpan = badges.find((el) => el !== ownBtn)!; + expect(otherSpan.tagName.toLowerCase()).toBe("span"); + expect(otherSpan.textContent).toBe("Draft"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).not.toHaveBeenCalled(); + expect(ownBtn.textContent).toBe("Ready?"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(ownDraftPR); + unmount(); + + // Compact density + onMarkPRReady.mockClear(); + setConfig("viewDensity", "compact"); + render(() => ( + + )); + + const compactBadges = screen.getAllByTestId("draft-badge"); + expect(compactBadges).toHaveLength(2); + + const compactOwnBtn = screen.getByLabelText("Mark #20 My Draft PR ready for review") as HTMLButtonElement; + expect(compactOwnBtn.tagName.toLowerCase()).toBe("button"); + expect(compactOwnBtn.textContent).toBe("D"); + + const compactOtherSpan = compactBadges.find((el) => el !== compactOwnBtn)!; + expect(compactOtherSpan.tagName.toLowerCase()).toBe("span"); + expect(compactOtherSpan.textContent).toBe("D"); + + fireEvent.click(compactOwnBtn); + expect(compactOwnBtn.textContent).toBe("Ready?"); + expect(onMarkPRReady).not.toHaveBeenCalled(); + + fireEvent.click(compactOwnBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(ownDraftPR); + }); }); }); diff --git a/tests/components/dashboard/DashboardPage.test.tsx b/tests/components/dashboard/DashboardPage.test.tsx index 6a501239..1098e5b9 100644 --- a/tests/components/dashboard/DashboardPage.test.tsx +++ b/tests/components/dashboard/DashboardPage.test.tsx @@ -138,4 +138,26 @@ describe("hot poll terminal PR splice logic", () => { expect(state.pullRequests[0].viewerReviewRequested).toBe(false); expect(state.pullRequests[0].reviewerLogins).toEqual(["testuser"]); }); + + it("updates pr.draft when update.draft is boolean and preserves pr.draft when update.draft is undefined", () => { + const state = { + pullRequests: [ + makePullRequest({ id: 11, draft: true }), + makePullRequest({ id: 12, draft: false }), + makePullRequest({ id: 13, draft: true }), + ], + }; + + const prUpdates = new Map([ + [11, { state: "OPEN", draft: false, checkStatus: "pending", mergeStateStatus: "BLOCKED", reviewDecision: "REVIEW_REQUIRED" }], + [12, { state: "OPEN", draft: true, checkStatus: "pending", mergeStateStatus: "DRAFT", reviewDecision: null }], + [13, { state: "OPEN", checkStatus: "success", mergeStateStatus: "CLEAN", reviewDecision: null }], + ]); + + applyHotPollPRUpdates(state, prUpdates); + + expect(state.pullRequests[0].draft).toBe(false); + expect(state.pullRequests[1].draft).toBe(true); + expect(state.pullRequests[2].draft).toBe(true); + }); }); diff --git a/tests/components/dashboard/DependenciesTab.test.tsx b/tests/components/dashboard/DependenciesTab.test.tsx index 2d3dfc89..4bf19de2 100644 --- a/tests/components/dashboard/DependenciesTab.test.tsx +++ b/tests/components/dashboard/DependenciesTab.test.tsx @@ -861,6 +861,166 @@ describe("DependenciesTab — auto-merge badge and Approve action", () => { expect(onApprovePR).toHaveBeenCalledOnce(); expect(onApprovePR).toHaveBeenCalledWith(eligibleDepPR); }); + + it("hides Approve button when pr.checkStatus is 'failure'", () => { + setDependencyExpandedGroups(["mergeable", "needs-action"]); + const onApprovePR = vi.fn(); + const failingDepPR = makeNeedsActionPR({ + id: 8012, + number: 812, + title: "Bump axios from 0.27.2 to 1.0.0", + nodeId: "PR_kwDOdep8012", + headSha: validSha, + checkStatus: "failure", + reviewDecision: "REVIEW_REQUIRED", + viewerReviewRequested: true, + enriched: true, + }); + + renderTab({ + pullRequests: [failingDepPR], + userLogin: "testuser", + onApprovePR, + }); + + expect(screen.queryByLabelText(/^Approve #812 /)).toBeNull(); + }); + + it("renders interactive DraftBadge button for self-authored draft PRs in 'Needs Action' and invokes onMarkPRReady(pr) on second click", () => { + setDependencyExpandedGroups(["mergeable", "needs-action"]); + const onMarkPRReady = vi.fn(); + const selfDraftDepPR = makeNeedsActionPR({ + id: 8020, + number: 820, + userLogin: "testuser", + title: "Bump axios from 0.27.2 to 1.0.0", + nodeId: "PR_kwDOdep8020", + draft: true, + checkStatus: "success", + enriched: true, + }); + const botDraftDepPR = makeNeedsActionPR({ + id: 8021, + number: 821, + userLogin: "dependabot[bot]", + title: "Bump lodash from 4.17.20 to 4.17.21", + nodeId: "PR_kwDOdep8021", + draft: true, + checkStatus: "success", + enriched: true, + }); + + renderTab({ + pullRequests: [selfDraftDepPR, botDraftDepPR], + userLogin: "testuser", + onMarkPRReady, + }); + + const needsActionGroup = document.getElementById("dep-group-needs-action")!; + expect(needsActionGroup).not.toBeNull(); + + const badges = screen.getAllByTestId("draft-badge"); + expect(badges).toHaveLength(2); + + const ownBtn = screen.getByLabelText("Mark #820 axios: 0.27.2 → 1.0.0 ready for review") as HTMLButtonElement; + expect(ownBtn.tagName.toLowerCase()).toBe("button"); + expect(ownBtn.textContent).toBe("Draft"); + + const botSpan = badges.find((el) => el !== ownBtn)!; + expect(botSpan.tagName.toLowerCase()).toBe("span"); + expect(botSpan.textContent).toBe("Draft"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).not.toHaveBeenCalled(); + expect(ownBtn.textContent).toBe("Ready?"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(selfDraftDepPR); + }); + + it("renders 'Merge conflict', 'Failing checks', and 'Checks running' badges in 'Needs Action' and links StatusDot to /checks", () => { + setDependencyExpandedGroups(["mergeable", "needs-action"]); + const conflictPR = makeNeedsActionPR({ + id: 8030, + number: 830, + title: "Bump axios from 0.27.2 to 1.0.0", + htmlUrl: "https://github.com/owner/repo/pull/830", + checkStatus: "conflict", + enriched: true, + }); + const failingPR = makeNeedsActionPR({ + id: 8031, + number: 831, + title: "Bump lodash from 4.17.20 to 4.17.21", + htmlUrl: "https://github.com/owner/repo/pull/831", + checkStatus: "failure", + enriched: true, + }); + const pendingPR = makeNeedsActionPR({ + id: 8032, + number: 832, + title: "Bump react from 17.0.0 to 18.0.0", + htmlUrl: "https://github.com/owner/repo/pull/832", + checkStatus: "pending", + enriched: true, + }); + + renderTab({ + pullRequests: [conflictPR, failingPR, pendingPR], + userLogin: "testuser", + }); + + expect(screen.getByText("Merge conflict")).toBeDefined(); + expect(screen.getByText("Failing checks")).toBeDefined(); + expect(screen.getByText("Checks running")).toBeDefined(); + + const conflictDotLink = screen.getByLabelText("Checks blocked by merge conflict").closest("a"); + expect(conflictDotLink?.getAttribute("href")).toBe("https://github.com/owner/repo/pull/830/checks"); + + const failingDotLink = screen.getByLabelText("Checks failing").closest("a"); + expect(failingDotLink?.getAttribute("href")).toBe("https://github.com/owner/repo/pull/831/checks"); + + const pendingDotLink = screen.getByLabelText("Checks in progress").closest("a"); + expect(pendingDotLink?.getAttribute("href")).toBe("https://github.com/owner/repo/pull/832/checks"); + }); + + it("classifies enriched non-draft PRs with checkStatus: null or reviewDecision: 'APPROVED' into 'Mergeable' and 'CHANGES_REQUESTED' into 'Needs Action'", () => { + setDependencyExpandedGroups(["mergeable", "needs-action"]); + const noCiPR = makeMergeablePR({ + id: 8040, + number: 840, + title: "Bump axios from 0.27.1 to 0.27.2", + checkStatus: null, + reviewDecision: null, + }); + const approvedPR = makeMergeablePR({ + id: 8041, + number: 841, + title: "Bump lodash from 4.17.20 to 4.17.21", + checkStatus: "success", + reviewDecision: "APPROVED", + }); + const changesRequestedPR = makeNeedsActionPR({ + id: 8042, + number: 842, + title: "Bump react from 17.0.0 to 18.0.0", + checkStatus: "success", + reviewDecision: "CHANGES_REQUESTED", + }); + + renderTab({ + pullRequests: [noCiPR, approvedPR, changesRequestedPR], + userLogin: "testuser", + }); + + const mergeableGroup = document.getElementById("dep-group-mergeable")!; + expect(mergeableGroup.textContent).toContain("axios: 0.27.1 → 0.27.2"); + expect(mergeableGroup.textContent).toContain("lodash: 4.17.20 → 4.17.21"); + + const needsActionGroup = document.getElementById("dep-group-needs-action")!; + expect(needsActionGroup.textContent).toContain("react: 17.0.0 → 18.0.0"); + }); }); // ── Ignore button ───────────────────────────────────────────────────────────── diff --git a/tests/components/dashboard/TrackedTab.test.tsx b/tests/components/dashboard/TrackedTab.test.tsx index d0f417d9..27c03d17 100644 --- a/tests/components/dashboard/TrackedTab.test.tsx +++ b/tests/components/dashboard/TrackedTab.test.tsx @@ -451,4 +451,115 @@ describe("TrackedTab — auto-merge badge and Approve action", () => { expect(onApprovePR).toHaveBeenCalledOnce(); expect(onApprovePR).toHaveBeenCalledWith(eligiblePR); }); + + it("hides Approve button on tracked PR when pr.checkStatus is 'failure'", () => { + const onApprovePR = vi.fn(); + const failingPR = makePullRequest({ + id: 920, + number: 920, + title: "Failing Tracked PR", + userLogin: "otheruser", + nodeId: "PR_kwDOtrack920", + headSha: validSha, + checkStatus: "failure", + reviewDecision: "REVIEW_REQUIRED", + viewerReviewRequested: true, + enriched: true, + }); + + updateViewState({ + trackedItems: [ + makeTrackedItem({ id: 920, number: 920, type: "pullRequest", title: "Failing Tracked PR" }), + ], + }); + + render(() => ( + + )); + + expect(screen.queryByLabelText(/Approve #920/)).toBeNull(); + }); + + it("renders interactive DraftBadge button on live self-authored draft PR rows and invokes onMarkPRReady(pr) on confirmation", () => { + const onMarkPRReady = vi.fn(); + const ownDraftPR = makePullRequest({ + id: 930, + number: 930, + title: "My Tracked Draft PR", + userLogin: "testuser", + nodeId: "PR_kwDOtrack930", + draft: true, + enriched: true, + }); + const otherDraftPR = makePullRequest({ + id: 931, + number: 931, + title: "Other Tracked Draft PR", + userLogin: "otheruser", + nodeId: "PR_kwDOtrack931", + draft: true, + enriched: true, + }); + + updateViewState({ + trackedItems: [ + makeTrackedItem({ id: 930, number: 930, type: "pullRequest", title: "My Tracked Draft PR" }), + makeTrackedItem({ id: 931, number: 931, type: "pullRequest", title: "Other Tracked Draft PR" }), + ], + }); + + const { unmount } = render(() => ( + + )); + + const badges = screen.getAllByTestId("draft-badge"); + expect(badges).toHaveLength(2); + + const ownBtn = screen.getByLabelText("Mark #930 My Tracked Draft PR ready for review") as HTMLButtonElement; + expect(ownBtn.tagName.toLowerCase()).toBe("button"); + expect(ownBtn.textContent).toBe("Draft"); + + const otherSpan = badges.find((el) => el !== ownBtn)!; + expect(otherSpan.tagName.toLowerCase()).toBe("span"); + expect(otherSpan.textContent).toBe("Draft"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).not.toHaveBeenCalled(); + expect(ownBtn.textContent).toBe("Ready?"); + + fireEvent.click(ownBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(ownDraftPR); + unmount(); + + // Compact density + onMarkPRReady.mockClear(); + setConfig("viewDensity", "compact"); + render(() => ( + + )); + + const compactOwnBtn = screen.getByLabelText("Mark #930 My Tracked Draft PR ready for review") as HTMLButtonElement; + expect(compactOwnBtn.textContent).toBe("D"); + fireEvent.click(compactOwnBtn); + expect(compactOwnBtn.textContent).toBe("Ready?"); + fireEvent.click(compactOwnBtn); + expect(onMarkPRReady).toHaveBeenCalledOnce(); + expect(onMarkPRReady).toHaveBeenCalledWith(ownDraftPR); + }); }); diff --git a/tests/components/shared-badges.test.tsx b/tests/components/shared-badges.test.tsx index a65bc9e2..98bb5973 100644 --- a/tests/components/shared-badges.test.tsx +++ b/tests/components/shared-badges.test.tsx @@ -1,9 +1,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { render, screen, fireEvent } from "@solidjs/testing-library"; +import { createSignal } from "solid-js"; 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"; +import DraftBadge from "../../src/app/components/shared/DraftBadge"; describe("RoleBadge", () => { it("renders nothing for empty roles", () => { @@ -199,3 +201,165 @@ describe("AutoMergeBadge", () => { vi.useRealTimers(); }); }); + +describe("DraftBadge", () => { + it("renders nothing when draft={false}", () => { + const { container } = render(() => ); + expect(container.textContent).toBe(""); + expect(screen.queryByTestId("draft-badge")).toBeNull(); + }); + + it("renders read-only ('Draft' in comfortable, 'D' in compact) when onMarkReady is undefined", () => { + const { unmount } = render(() => ); + const comfortable = screen.getByTestId("draft-badge"); + expect(comfortable.tagName.toLowerCase()).toBe("span"); + expect(comfortable.textContent).toBe("Draft"); + expect(comfortable.className).toContain("badge-sm"); + unmount(); + + render(() => ); + const compact = screen.getByTestId("draft-badge"); + expect(compact.tagName.toLowerCase()).toBe("span"); + expect(compact.textContent).toBe("D"); + expect(compact.className).toContain("badge-xs"); + }); + + it("renders