From bb404f8d14519e0e29f01ea11de83943abb58637 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Mon, 27 Apr 2026 22:07:55 -0700 Subject: [PATCH] =?UTF-8?q?feat:=20stacked=20PR=20review=20=E2=80=94=20PR?= =?UTF-8?q?=20switching,=20scope=20toggling,=20multi-PR=20posting=20(#620)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted. --- AGENTS.md | 3 + apps/hook/server/index.ts | 35 +- .../src/content/docs/commands/code-review.md | 10 + .../src/content/docs/guides/ai-code-review.md | 7 + apps/pi-extension/plannotator-browser.ts | 33 +- apps/pi-extension/server/agent-jobs.ts | 14 +- apps/pi-extension/server/pr.ts | 18 + apps/pi-extension/server/serverReview.ts | 312 ++++++++++++- apps/pi-extension/vendor.sh | 2 +- packages/ai/providers/claude-agent-sdk.ts | 4 + packages/review-editor/App.tsx | 412 ++++++++++-------- .../components/DiffTypePicker.tsx | 3 +- .../review-editor/components/PRSelector.tsx | 115 +++++ .../review-editor/components/PRSummaryTab.tsx | 8 + .../components/PRSwitchOverlay.tsx | 12 + .../components/ReviewSidebar.tsx | 212 +++++---- .../components/ReviewSubmissionDialog.tsx | 379 ++++++++++++++++ .../components/StackedPRLabel.tsx | 301 +++++++++++++ .../review-editor/dock/ReviewStateContext.tsx | 4 + .../dock/panels/ReviewAgentJobDetailPanel.tsx | 19 +- .../dock/panels/ReviewDiffPanel.tsx | 13 +- .../hooks/useAnnotationFactory.ts | 24 + packages/review-editor/hooks/usePRContext.ts | 20 +- packages/review-editor/hooks/usePRSession.ts | 43 ++ packages/review-editor/hooks/usePRStack.ts | 74 ++++ packages/review-editor/index.css | 75 ++++ .../utils/exportFeedback.test.ts | 110 ++++- .../review-editor/utils/exportFeedback.ts | 203 ++++++--- packages/server/agent-jobs.ts | 14 +- packages/server/codex-review.ts | 14 +- packages/server/pr.ts | 21 +- packages/server/review.ts | 348 +++++++++++++-- packages/server/tour/tour-review.ts | 14 +- packages/shared/agent-jobs.ts | 4 + packages/shared/config.ts | 7 +- packages/shared/package.json | 2 + packages/shared/pr-github.ts | 169 ++++++- packages/shared/pr-gitlab.ts | 14 + packages/shared/pr-provider.test.ts | 95 ++++ packages/shared/pr-provider.ts | 80 +++- packages/shared/pr-stack.test.ts | 104 +++++ packages/shared/pr-stack.ts | 194 +++++++++ packages/shared/review-core.ts | 3 +- packages/shared/worktree-pool.test.ts | 162 +++++++ packages/shared/worktree-pool.ts | 103 +++++ packages/ui/components/AgentsTab.tsx | 6 +- .../ui/components/DiffTypeSetupDialog.tsx | 13 +- packages/ui/components/Popover.tsx | 27 ++ packages/ui/components/SearchableSelect.tsx | 153 +++++++ packages/ui/components/Settings.tsx | 65 ++- packages/ui/config/settings.ts | 8 +- packages/ui/types.ts | 5 + 52 files changed, 3641 insertions(+), 449 deletions(-) create mode 100644 packages/review-editor/components/PRSelector.tsx create mode 100644 packages/review-editor/components/PRSwitchOverlay.tsx create mode 100644 packages/review-editor/components/ReviewSubmissionDialog.tsx create mode 100644 packages/review-editor/components/StackedPRLabel.tsx create mode 100644 packages/review-editor/hooks/useAnnotationFactory.ts create mode 100644 packages/review-editor/hooks/usePRSession.ts create mode 100644 packages/review-editor/hooks/usePRStack.ts create mode 100644 packages/shared/pr-stack.test.ts create mode 100644 packages/shared/pr-stack.ts create mode 100644 packages/shared/worktree-pool.test.ts create mode 100644 packages/shared/worktree-pool.ts create mode 100644 packages/ui/components/Popover.tsx create mode 100644 packages/ui/components/SearchableSelect.tsx diff --git a/AGENTS.md b/AGENTS.md index cec0f38..2f3ecbb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -250,6 +250,9 @@ During normal plan review, an Archive sidebar tab provides the same browsing via | `/api/agents/jobs` | POST | Launch an agent job (body: `{ provider, command, label }`) | | `/api/agents/jobs` | DELETE | Kill all running agent jobs | | `/api/agents/jobs/:id` | DELETE | Kill a specific agent job | +| `/api/pr-diff-scope` | POST | Switch between layer and full-stack diff scope | +| `/api/pr-list` | GET | List PRs for the current repo (cached 30s) | +| `/api/pr-switch` | POST | Switch to a different PR in-place (body: `{ url }`) | | `/api/tour/:jobId` | GET | Fetch Code Tour result (greeting, stops, checklist) for a completed tour job | | `/api/tour/:jobId/checklist` | PUT | Persist checklist item state for a Code Tour | diff --git a/apps/hook/server/index.ts b/apps/hook/server/index.ts index 8d1f302..ede38ae 100644 --- a/apps/hook/server/index.ts +++ b/apps/hook/server/index.ts @@ -69,6 +69,7 @@ import { stripAtPrefix, resolveAtReference } from "@plannotator/shared/at-refere import { htmlToMarkdown } from "@plannotator/shared/html-to-markdown"; import { urlToMarkdown } from "@plannotator/shared/url-to-markdown"; import { fetchRef, createWorktree, removeWorktree, ensureObjectAvailable } from "@plannotator/shared/worktree"; +import { createWorktreePool, type WorktreePool } from "@plannotator/shared/worktree-pool"; import { parsePRUrl, checkPRAuth, fetchPR, getCliName, getCliInstallUrl, getMRLabel, getMRNumberLabel, getDisplayRepo } from "@plannotator/server/pr"; import { writeRemoteShareLink } from "@plannotator/server/share-url"; import { resolveMarkdownFile, resolveUserPath, hasMarkdownFiles } from "@plannotator/shared/resolve-file"; @@ -293,6 +294,7 @@ if (args[0] === "sessions") { let prMetadata: Awaited>["metadata"] | undefined; let initialDiffType: DiffType | undefined; let agentCwd: string | undefined; + let worktreePool: WorktreePool | undefined; let worktreeCleanup: (() => void | Promise) | undefined; if (isPRMode) { @@ -337,6 +339,7 @@ if (args[0] === "sessions") { if (useLocal && prMetadata) { // Hoisted so catch block can clean up partially-created directories let localPath: string | undefined; + let sessionDir: string | undefined; try { const repoDir = process.cwd(); const identifier = prMetadata.platform === "github" @@ -345,7 +348,9 @@ if (args[0] === "sessions") { const suffix = Math.random().toString(36).slice(2, 8); // Resolve tmpdir to its real path — on macOS, tmpdir() returns /var/folders/... // but processes report /private/var/folders/... which breaks path stripping. - localPath = path.join(realpathSync(tmpdir()), `plannotator-pr-${identifier}-${suffix}`); + sessionDir = path.join(realpathSync(tmpdir()), `plannotator-pr-${identifier}-${suffix}`); + const prNumber = prMetadata.platform === "github" ? prMetadata.number : prMetadata.iid; + localPath = path.join(sessionDir, "pool", `pr-${prNumber}`); const fetchRefStr = prMetadata.platform === "github" ? `refs/pull/${prMetadata.number}/head` : `refs/merge-requests/${prMetadata.iid}/head`; @@ -393,9 +398,18 @@ if (args[0] === "sessions") { cwd: repoDir, }); - worktreeCleanup = () => removeWorktree(gitRuntime, localPath, { force: true, cwd: repoDir }); + worktreeCleanup = async () => { + if (worktreePool) await worktreePool.cleanup(gitRuntime); + try { rmSync(sessionDir, { recursive: true, force: true }); } catch {} + }; process.once("exit", () => { - try { Bun.spawnSync(["git", "worktree", "remove", "--force", localPath]); } catch {} + // Best-effort sync cleanup: remove each pool worktree from git, then rm session dir + try { + for (const entry of worktreePool?.entries() ?? []) { + Bun.spawnSync(["git", "worktree", "remove", "--force", entry.path], { cwd: repoDir }); + } + } catch {} + try { Bun.spawnSync(["rm", "-rf", sessionDir]); } catch {} }); } else { // ── Cross-repo: shallow clone + fetch PR head ── @@ -443,9 +457,9 @@ if (args[0] === "sessions") { Bun.spawnSync(["git", "branch", "--", prMetadata.baseBranch, prMetadata.baseSha], { cwd: localPath, stderr: "pipe" }); Bun.spawnSync(["git", "update-ref", `refs/remotes/origin/${prMetadata.baseBranch}`, prMetadata.baseSha], { cwd: localPath, stderr: "pipe" }); - worktreeCleanup = () => { try { rmSync(localPath, { recursive: true, force: true }); } catch {} }; + worktreeCleanup = () => { try { rmSync(sessionDir, { recursive: true, force: true }); } catch {} }; process.once("exit", () => { - try { Bun.spawnSync(["rm", "-rf", localPath]); } catch {} + try { Bun.spawnSync(["rm", "-rf", sessionDir]); } catch {} }); } @@ -453,13 +467,19 @@ if (args[0] === "sessions") { // Do NOT set gitContext — that would contaminate the diff pipeline. agentCwd = localPath; + // Create worktree pool with the initial PR as the first entry + worktreePool = createWorktreePool( + { sessionDir, repoDir, isSameRepo }, + { path: localPath, prUrl: prMetadata.url, number: prNumber, ready: true }, + ); + console.error(`Local checkout ready at ${localPath}`); } catch (err) { console.error(`Warning: --local failed, falling back to remote diff`); console.error(err instanceof Error ? err.message : String(err)); - // Clean up partially-created directory (clone may have succeeded before fetch/checkout failed) - if (localPath) try { rmSync(localPath, { recursive: true, force: true }); } catch {} + if (sessionDir) try { rmSync(sessionDir, { recursive: true, force: true }); } catch {} agentCwd = undefined; + worktreePool = undefined; worktreeCleanup = undefined; } } @@ -485,6 +505,7 @@ if (args[0] === "sessions") { gitContext, prMetadata, agentCwd, + worktreePool, sharingEnabled, shareBaseUrl, htmlContent: reviewHtmlContent, diff --git a/apps/marketing/src/content/docs/commands/code-review.md b/apps/marketing/src/content/docs/commands/code-review.md index 6d5a210..877cac0 100644 --- a/apps/marketing/src/content/docs/commands/code-review.md +++ b/apps/marketing/src/content/docs/commands/code-review.md @@ -24,6 +24,8 @@ The `/plannotator-review` command opens an interactive code review UI for your l PR review uses the `gh` CLI for authentication, so private repos work automatically if you're authenticated with `gh auth login`. +GitLab merge request URLs are also supported when the `glab` CLI is installed and authenticated. + ## How it works **Local review:** @@ -60,6 +62,14 @@ Send Feedback → PR context included in feedback Approve → "LGTM" sent to agent ``` +## Stacked PRs and MRs + +When a PR or MR targets a non-default branch, Plannotator marks it as stacked in the review header. The default view remains **Layer**, which matches the platform diff and is the safe mode for posting inline review comments. + +If Plannotator has a local checkout for the PR or MR, the header also offers **Full stack**. Full stack shows everything from the repository default branch through the current checked-out head, which helps you understand the whole chain before reviewing the current layer. + +Platform posting is intentionally limited to **Layer** because GitHub and GitLab inline comments are anchored to the PR or MR's own diff. Use **Full stack** for comprehension and agent review, then switch back to **Layer** before posting to the platform. + ## Switching diff types By default the review opens showing uncommitted changes, but you can switch what you're comparing using the diff type dropdown in the toolbar. The available options are: diff --git a/apps/marketing/src/content/docs/guides/ai-code-review.md b/apps/marketing/src/content/docs/guides/ai-code-review.md index 5d79ad2..cdba907 100644 --- a/apps/marketing/src/content/docs/guides/ai-code-review.md +++ b/apps/marketing/src/content/docs/guides/ai-code-review.md @@ -24,6 +24,13 @@ Both integrations are derived from official tooling. Claude's review model is ba For PR reviews, a temporary local checkout is created by default so the agent has file access beyond the diff. Pass `--no-local` to skip this. +For stacked PRs and MRs, the review header lets you choose what the agent sees: + +- **Layer** reviews only the current PR or MR relative to its parent branch. +- **Full stack** reviews the cumulative diff from the repository default branch through the current head. + +Layer review is best for avoiding duplicate feedback on parent PRs. Full stack review is useful for integration issues that only appear when the whole chain is considered together. Posting inline comments back to GitHub or GitLab stays limited to Layer because platform comments must anchor to the platform diff. + ## Findings Each finding includes a file path, line range, description, and severity or priority. Claude findings also include a reasoning trace that explains how the issue was verified. diff --git a/apps/pi-extension/plannotator-browser.ts b/apps/pi-extension/plannotator-browser.ts index 11ecb2a..0bdd8cb 100644 --- a/apps/pi-extension/plannotator-browser.ts +++ b/apps/pi-extension/plannotator-browser.ts @@ -2,6 +2,7 @@ import { existsSync, readFileSync, realpathSync, rmSync, statSync } from "node:f import { dirname, join, resolve } from "node:path"; import { tmpdir } from "node:os"; import { spawnSync } from "node:child_process"; +import { createWorktreePool, type WorktreePool } from "./generated/worktree-pool.js"; import { fileURLToPath } from "node:url"; import type { ExtensionContext } from "@mariozechner/pi-coding-agent"; import { @@ -183,6 +184,7 @@ export async function openCodeReview( let agentCwd: string | undefined; let initialBase: string | undefined; let worktreeCleanup: (() => void | Promise) | undefined; + let worktreePool: WorktreePool | undefined; let exitHandler: (() => void) | undefined; if (isPRMode && urlArg) { @@ -218,13 +220,16 @@ export async function openCodeReview( // Create local worktree for agent file access (--local is the default for PR reviews) let localPath: string | undefined; + let sessionDir: string | undefined; try { const repoDir = options.cwd ?? ctx.cwd; const identifier = prMetadata.platform === "github" ? `${prMetadata.owner}-${prMetadata.repo}-${prMetadata.number}` : `${prMetadata.projectPath.replace(/\//g, "-")}-${prMetadata.iid}`; const suffix = Math.random().toString(36).slice(2, 8); - localPath = join(realpathSync(tmpdir()), `plannotator-pr-${identifier}-${suffix}`); + const prNumber = prMetadata.platform === "github" ? prMetadata.number : prMetadata.iid; + sessionDir = join(realpathSync(tmpdir()), `plannotator-pr-${identifier}-${suffix}`); + localPath = join(sessionDir, "pool", `pr-${prNumber}`); const fetchRefStr = prMetadata.platform === "github" ? `refs/pull/${prMetadata.number}/head` : `refs/merge-requests/${prMetadata.iid}/head`; @@ -266,14 +271,19 @@ export async function openCodeReview( cwd: repoDir, }); - const worktreePath = localPath; const wtRepoDir = repoDir; exitHandler = () => { - try { spawnSync("git", ["worktree", "remove", "--force", worktreePath], { cwd: wtRepoDir }); } catch {} + try { + for (const entry of worktreePool?.entries() ?? []) { + spawnSync("git", ["worktree", "remove", "--force", entry.path], { cwd: wtRepoDir }); + } + } catch {} + if (sessionDir) try { rmSync(sessionDir, { recursive: true, force: true }); } catch {} }; - worktreeCleanup = () => { + worktreeCleanup = async () => { if (exitHandler) { process.removeListener("exit", exitHandler); exitHandler = undefined; } - return removeWorktree(reviewRuntime, worktreePath, { force: true, cwd: wtRepoDir }); + if (worktreePool) await worktreePool.cleanup(reviewRuntime); + if (sessionDir) try { rmSync(sessionDir, { recursive: true, force: true }); } catch {} }; process.once("exit", exitHandler); } else { @@ -312,25 +322,29 @@ export async function openCodeReview( await reviewRuntime.runGit(["branch", "--", prMetadata.baseBranch, prMetadata.baseSha], { cwd: localPath }); await reviewRuntime.runGit(["update-ref", `refs/remotes/origin/${prMetadata.baseBranch}`, prMetadata.baseSha], { cwd: localPath }); - const clonePath = localPath; exitHandler = () => { - try { rmSync(clonePath, { recursive: true, force: true }); } catch {} + if (sessionDir) try { rmSync(sessionDir, { recursive: true, force: true }); } catch {} }; worktreeCleanup = () => { if (exitHandler) { process.removeListener("exit", exitHandler); exitHandler = undefined; } - try { rmSync(clonePath, { recursive: true, force: true }); } catch {} + if (sessionDir) try { rmSync(sessionDir, { recursive: true, force: true }); } catch {} }; process.once("exit", exitHandler); } agentCwd = localPath; + worktreePool = createWorktreePool( + { sessionDir: sessionDir!, repoDir, isSameRepo }, + { path: localPath, prUrl: prMetadata.url, number: prNumber, ready: true }, + ); console.error(`Local checkout ready at ${localPath}`); } catch (err) { console.error("Warning: local worktree creation failed, falling back to remote diff"); console.error(err instanceof Error ? err.message : String(err)); if (exitHandler) { process.removeListener("exit", exitHandler); exitHandler = undefined; } - if (localPath) try { rmSync(localPath, { recursive: true, force: true }); } catch {} + if (sessionDir) try { rmSync(sessionDir, { recursive: true, force: true }); } catch {} agentCwd = undefined; + worktreePool = undefined; worktreeCleanup = undefined; } } else { @@ -359,6 +373,7 @@ export async function openCodeReview( initialBase, prMetadata, agentCwd, + worktreePool, htmlContent: reviewHtmlContent, sharingEnabled: process.env.PLANNOTATOR_SHARE !== "disabled", shareBaseUrl: process.env.PLANNOTATOR_SHARE_URL || undefined, diff --git a/apps/pi-extension/server/agent-jobs.ts b/apps/pi-extension/server/agent-jobs.ts index c4ec278..8711189 100644 --- a/apps/pi-extension/server/agent-jobs.ts +++ b/apps/pi-extension/server/agent-jobs.ts @@ -73,6 +73,10 @@ export interface AgentJobHandlerOptions { reasoningEffort?: string; /** Whether Codex fast mode was enabled. */ fastMode?: boolean; + /** PR URL at launch time. */ + prUrl?: string; + /** PR diff scope at launch time. */ + diffScope?: string; /** Diff context snapshot at launch (stored on AgentJobInfo for per-job "Copy All"). */ diffContext?: AgentJobInfo["diffContext"]; } | null>; @@ -120,7 +124,7 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { command: string[], label: string, outputPath?: string, - spawnOptions?: { captureStdout?: boolean; stdinPrompt?: string; cwd?: string; prompt?: string; engine?: string; model?: string; effort?: string; reasoningEffort?: string; fastMode?: boolean; diffContext?: AgentJobInfo["diffContext"] }, + spawnOptions?: { captureStdout?: boolean; stdinPrompt?: string; cwd?: string; prompt?: string; engine?: string; model?: string; effort?: string; reasoningEffort?: string; fastMode?: boolean; prUrl?: string; diffScope?: string; diffContext?: AgentJobInfo["diffContext"] }, ): AgentJobInfo { const id = crypto.randomUUID(); const source = jobSource(id); @@ -139,6 +143,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { ...(spawnOptions?.effort && { effort: spawnOptions.effort }), ...(spawnOptions?.reasoningEffort && { reasoningEffort: spawnOptions.reasoningEffort }), ...(spawnOptions?.fastMode && { fastMode: spawnOptions.fastMode }), + ...(spawnOptions?.prUrl && { prUrl: spawnOptions.prUrl }), + ...(spawnOptions?.diffScope && { diffScope: spawnOptions.diffScope }), ...(spawnOptions?.diffContext && { diffContext: spawnOptions.diffContext }), }; @@ -422,6 +428,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { let jobEffort: string | undefined; let jobReasoningEffort: string | undefined; let jobFastMode: boolean | undefined; + let jobPrUrl: string | undefined; + let jobDiffScope: string | undefined; let jobDiffContext: AgentJobInfo["diffContext"] | undefined; if (options.buildCommand) { // Thread config from POST body to buildCommand @@ -445,6 +453,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { jobEffort = built.effort; jobReasoningEffort = built.reasoningEffort; jobFastMode = built.fastMode; + jobPrUrl = built.prUrl; + jobDiffScope = built.diffScope; jobDiffContext = built.diffContext; } } @@ -464,6 +474,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { effort: jobEffort, reasoningEffort: jobReasoningEffort, fastMode: jobFastMode, + prUrl: jobPrUrl, + diffScope: jobDiffScope, diffContext: jobDiffContext, }); json(res, { job }, 201); diff --git a/apps/pi-extension/server/pr.ts b/apps/pi-extension/server/pr.ts index f6c3c86..0c14b81 100644 --- a/apps/pi-extension/server/pr.ts +++ b/apps/pi-extension/server/pr.ts @@ -11,11 +11,16 @@ import { fetchPR as fetchPRCore, fetchPRFileContent as fetchPRFileContentCore, fetchPRViewedFiles as fetchPRViewedFilesCore, + fetchPRStack as fetchPRStackCore, + fetchPRList as fetchPRListCore, getUser as getUserCore, markPRFilesViewed as markPRFilesViewedCore, + type PRMetadata, type PRRef, type PRReviewFileComment, type PRRuntime, + type PRStackTree, + type PRListItem, parsePRUrl as parsePRUrlCore, submitPRReview as submitPRReviewCore, } from "../generated/pr-provider.js"; @@ -104,3 +109,16 @@ export function markPRFilesViewed( ): Promise { return markPRFilesViewedCore(prRuntime, ref, prNodeId, filePaths, viewed); } + +export function fetchPRStack( + ref: PRRef, + metadata: PRMetadata, +): Promise { + return fetchPRStackCore(prRuntime, ref, metadata); +} + +export function fetchPRList( + ref: PRRef, +): Promise { + return fetchPRListCore(prRuntime, ref); +} diff --git a/apps/pi-extension/server/serverReview.ts b/apps/pi-extension/server/serverReview.ts index 2c99255..0a71009 100644 --- a/apps/pi-extension/server/serverReview.ts +++ b/apps/pi-extension/server/serverReview.ts @@ -18,6 +18,7 @@ import { getDisplayRepo, getMRLabel, getMRNumberLabel, + isSameProject, type PRMetadata, type PRReviewFileComment, prRefFromMetadata, @@ -37,6 +38,17 @@ import { runGitDiff as runGitDiffCore, validateFilePath, } from "../generated/review-core.js"; +import { + checkoutPRHead, + getPRDiffScopeOptions, + getPRStackInfo, + resolveStackInfo, + resolvePRFullStackBaseRef, + runPRFullStackDiff, + type PRDiffScope, +} from "../generated/pr-stack.js"; + +import type { WorktreePool } from "../generated/worktree-pool.js"; import { createEditorAnnotationHandler } from "./annotations.js"; import { createAgentJobHandler } from "./agent-jobs.js"; @@ -52,11 +64,15 @@ import { html, json, parseBody, requestUrl, toWebRequest } from "./helpers.js"; import { isRemoteSession, listenOnPort } from "./network.js"; import { + fetchPR, fetchPRContext, fetchPRFileContent, + fetchPRList, + fetchPRStack, fetchPRViewedFiles, getPRUser, markPRFilesViewed, + parsePRUrl, submitPRReview, } from "./pr.js"; import { getRepoInfo } from "./project.js"; @@ -184,20 +200,49 @@ export async function startReviewServer(options: { prMetadata?: PRMetadata; /** Working directory for agent processes (e.g., --local worktree). Independent of diff pipeline. */ agentCwd?: string; + /** Per-PR worktree pool. When set, pr-switch creates worktrees instead of checking out. */ + worktreePool?: WorktreePool; /** Cleanup callback invoked when server stops (e.g., remove temp worktree) */ onCleanup?: () => void | Promise; /** Called when server starts with the URL, remote status, and port */ onReady?: (url: string, isRemote: boolean, port: number) => void; }): Promise { const gitUser = detectGitUser(); - const draftKey = contentHash(options.rawPatch); - const prMeta = options.prMetadata; + let draftKey = contentHash(options.rawPatch); + let prMeta = options.prMetadata; const isPRMode = !!prMeta; const hasLocalAccess = !!options.gitContext; const isRemote = isRemoteSession(); const wslFlag = detectWSL(); - const prRef = prMeta ? prRefFromMetadata(prMeta) : null; + let prRef = prMeta ? prRefFromMetadata(prMeta) : null; const platformUser = prRef ? await getPRUser(prRef) : null; + let prStackInfo = isPRMode ? getPRStackInfo(prMeta) : null; + let prDiffScopeOptions = isPRMode + ? getPRDiffScopeOptions(prMeta, !!(options.worktreePool || options.agentCwd)) + : []; + + let prListCache: import("../generated/pr-provider.js").PRListItem[] | null = null; + let prListCacheTime = 0; + const prSwitchCache = new Map(); + if (isPRMode && prMeta) prSwitchCache.set(prMeta.url, { metadata: prMeta, rawPatch: options.rawPatch }); + const prStackTreeCache = new Map(); + + // Fetch full stack tree (best-effort — always try in PR mode so root PRs + // that target the default branch can still discover descendant PRs) + let prStackTree: import("../generated/pr-provider.js").PRStackTree | null = null; + if (prRef && prMeta) { + try { + prStackTree = await fetchPRStack(prRef, prMeta); + } catch { + // Non-fatal: client falls back to buildMinimalStackTree() + } + prStackTreeCache.set(prMeta.url, prStackTree); + const resolved = resolveStackInfo(prMeta, prStackTree, prStackInfo); + if (resolved && !prStackInfo) { + prStackInfo = resolved; + prDiffScopeOptions = getPRDiffScopeOptions(prMeta, !!(options.worktreePool || options.agentCwd)); + } + } // Fetch GitHub viewed file state (non-blocking — errors are silently ignored) let initialViewedFiles: string[] = []; @@ -211,7 +256,7 @@ export async function startReviewServer(options: { // Non-fatal: viewed state is best-effort } } - const repoInfo = prMeta + let repoInfo = prMeta ? { display: getDisplayRepo(prMeta), branch: `${getMRLabel(prMeta)} ${getMRNumberLabel(prMeta)}`, @@ -224,6 +269,10 @@ export async function startReviewServer(options: { let currentGitRef = options.gitRef; let currentDiffType: DiffType = options.diffType || "uncommitted"; let currentError = options.error; + let originalPRPatch = options.rawPatch; + let originalPRGitRef = options.gitRef; + let originalPRError = options.error; + let currentPRDiffScope: PRDiffScope = "layer"; // Tracks the base branch the user picked from the UI. Agent review prompts // read this (not gitContext.defaultBranch) so they analyze the same diff // the reviewer is currently looking at. Honors an explicit initialBase from @@ -241,6 +290,10 @@ export async function startReviewServer(options: { // Agent jobs — background process manager (late-binds serverUrl via getter) let serverUrl = ""; function resolveAgentCwd(): string { + if (options.worktreePool && prMeta) { + const poolPath = options.worktreePool.resolve(prMeta.url); + if (poolPath) return poolPath; + } if (options.agentCwd) return options.agentCwd; if (currentDiffType.startsWith("worktree:")) { const parsed = parseWorktreeDiffType(currentDiffType); @@ -257,8 +310,8 @@ export async function startReviewServer(options: { async buildCommand(provider, config) { const cwd = resolveAgentCwd(); - const hasAgentLocalAccess = !!options.agentCwd || !!options.gitContext; - const userMessageOptions = { defaultBranch: currentBase, hasLocalAccess: hasAgentLocalAccess }; + const hasAgentLocalAccess = !!options.worktreePool || !!options.agentCwd || !!options.gitContext; + const userMessageOptions = { defaultBranch: currentBase, hasLocalAccess: hasAgentLocalAccess, prDiffScope: currentPRDiffScope }; // Snapshot the diff context at launch (see review.ts buildCommand // for the rationale — keeps downstream "Copy All" honest across @@ -266,7 +319,9 @@ export async function startReviewServer(options: { const worktreeParts = currentDiffType.startsWith("worktree:") ? parseWorktreeDiffType(currentDiffType) : null; - const diffContext: AgentJobInfo["diffContext"] | undefined = options.prMetadata + const launchPrUrl = prMeta?.url; + const launchDiffScope = isPRMode ? currentPRDiffScope : undefined; + const diffContext: AgentJobInfo["diffContext"] | undefined = prMeta ? undefined : { mode: (worktreeParts?.subType ?? currentDiffType) as string, @@ -280,13 +335,13 @@ export async function startReviewServer(options: { patch: currentPatch, diffType: currentDiffType, options: userMessageOptions, - prMetadata: options.prMetadata, + prMetadata: prMeta, config, }); - return built ? { ...built, diffContext } : built; + return built ? { ...built, prUrl: launchPrUrl, diffScope: launchDiffScope, diffContext } : built; } - const userMessage = buildCodexReviewUserMessage(currentPatch, currentDiffType, userMessageOptions, options.prMetadata); + const userMessage = buildCodexReviewUserMessage(currentPatch, currentDiffType, userMessageOptions, prMeta); if (provider === "codex") { const model = typeof config?.model === "string" && config.model ? config.model : undefined; @@ -295,7 +350,7 @@ export async function startReviewServer(options: { const outputPath = generateOutputPath(); const prompt = CODEX_REVIEW_SYSTEM_PROMPT + "\n\n---\n\n" + userMessage; const command = await buildCodexCommand({ cwd, outputPath, prompt, model, reasoningEffort, fastMode }); - return { command, outputPath, prompt, label: "Code Review", model, reasoningEffort, fastMode: fastMode || undefined, diffContext }; + return { command, outputPath, prompt, cwd, label: "Code Review", model, reasoningEffort, fastMode: fastMode || undefined, prUrl: launchPrUrl, diffScope: launchDiffScope, diffContext }; } if (provider === "claude") { @@ -303,21 +358,28 @@ export async function startReviewServer(options: { const effort = typeof config?.effort === "string" && config.effort ? config.effort : undefined; const prompt = CLAUDE_REVIEW_PROMPT + "\n\n---\n\n" + userMessage; const { command, stdinPrompt } = buildClaudeCommand(prompt, model, effort); - return { command, stdinPrompt, prompt, cwd, label: "Code Review", captureStdout: true, model, effort, diffContext }; + return { command, stdinPrompt, prompt, cwd, label: "Code Review", captureStdout: true, model, effort, prUrl: launchPrUrl, diffScope: launchDiffScope, diffContext }; } return null; }, async onJobComplete(job, meta) { - const cwd = resolveAgentCwd(); + const cwd = meta.cwd ?? resolveAgentCwd(); + const jobPrUrl = job.prUrl; + const jobDiffScope = job.diffScope; + const jobPrMeta = jobPrUrl ? prSwitchCache.get(jobPrUrl)?.metadata : undefined; + const jobPrContext = jobPrMeta ? { + prUrl: jobPrUrl, + prNumber: jobPrMeta.platform === "github" ? jobPrMeta.number : jobPrMeta.iid, + prTitle: jobPrMeta.title, + prRepo: getDisplayRepo(jobPrMeta), + } : jobPrUrl ? { prUrl: jobPrUrl } : {}; if (job.provider === "codex" && meta.outputPath) { const output = await parseCodexOutput(meta.outputPath); if (!output) return; - // Override verdict if there are blocking findings (P0/P1) — Codex's - // freeform correctness string can say "mostly correct" with real bugs. const hasBlockingFindings = output.findings.some(f => f.priority !== null && f.priority <= 1); job.summary = { correctness: hasBlockingFindings ? "Issues Found" : output.overall_correctness, @@ -326,7 +388,8 @@ export async function startReviewServer(options: { }; if (output.findings.length > 0) { - const annotations = transformReviewFindings(output.findings, job.source, cwd, "Codex"); + const annotations = transformReviewFindings(output.findings, job.source, cwd, "Codex") + .map(a => ({ ...a, ...jobPrContext, ...(jobDiffScope && { diffScope: jobDiffScope }) })); const result = externalAnnotations.addAnnotations({ annotations }); if ("error" in result) console.error(`[codex-review] addAnnotations error:`, result.error); } @@ -348,7 +411,8 @@ export async function startReviewServer(options: { }; if (output.findings.length > 0) { - const annotations = transformClaudeFindings(output.findings, job.source, cwd); + const annotations = transformClaudeFindings(output.findings, job.source, cwd) + .map(a => ({ ...a, ...jobPrContext, ...(jobDiffScope && { diffScope: jobDiffScope }) })); const result = externalAnnotations.addAnnotations({ annotations }); if ("error" in result) console.error(`[claude-review] addAnnotations error:`, result.error); } @@ -549,7 +613,14 @@ export async function startReviewServer(options: { repoInfo, isWSL: wslFlag, ...(options.agentCwd && { agentCwd: options.agentCwd }), - ...(isPRMode && { prMetadata: prMeta, platformUser }), + ...(isPRMode && { + prMetadata: prMeta, + platformUser, + prStackInfo, + prStackTree, + prDiffScope: currentPRDiffScope, + prDiffScopeOptions, + }), ...(isPRMode && initialViewedFiles.length > 0 && { viewedFiles: initialViewedFiles }), ...(currentError && { error: currentError }), serverConfig: getServerConfig(gitUser), @@ -610,6 +681,155 @@ export async function startReviewServer(options: { const message = err instanceof Error ? err.message : "Failed to switch diff"; json(res, { error: message }, 500); } + } else if (url.pathname === "/api/pr-diff-scope" && req.method === "POST") { + if (!isPRMode || !prMeta) { + json(res, { error: "Not in PR mode" }, 400); + return; + } + try { + const body = await parseBody(req) as { scope?: PRDiffScope }; + if (body.scope !== "layer" && body.scope !== "full-stack") { + json(res, { error: "Invalid PR diff scope" }, 400); + return; + } + + if (body.scope === "layer") { + currentPatch = originalPRPatch; + currentGitRef = originalPRGitRef; + currentError = originalPRError; + currentPRDiffScope = "layer"; + json(res, { + rawPatch: currentPatch, + gitRef: currentGitRef, + prDiffScope: currentPRDiffScope, + ...(currentError ? { error: currentError } : {}), + }); + return; + } + + const fullStackOption = prDiffScopeOptions.find((option) => option.id === "full-stack"); + if (!fullStackOption?.enabled || !(options.worktreePool || options.agentCwd)) { + json(res, { error: "Full stack diff requires a stacked PR and a local checkout" }, 400); + return; + } + + const fullStackCwd = (options.worktreePool && prMeta ? options.worktreePool.resolve(prMeta.url) : undefined) ?? options.agentCwd; + const result = await runPRFullStackDiff(reviewRuntime, prMeta, fullStackCwd); + + if (result.error) { + json(res, { error: result.error }, 400); + return; + } + + currentPatch = result.patch; + currentGitRef = result.label; + currentError = undefined; + currentPRDiffScope = "full-stack"; + json(res, { + rawPatch: currentPatch, + gitRef: currentGitRef, + prDiffScope: currentPRDiffScope, + }); + } catch (err) { + const message = err instanceof Error ? err.message : "Failed to switch PR diff scope"; + json(res, { error: message }, 500); + } + } else if (url.pathname === "/api/pr-switch" && req.method === "POST") { + if (!isPRMode || !prRef) { + return json(res, { error: "Not in PR mode" }, 400); + } + try { + const body = (await parseBody(req)) as { url?: string }; + if (!body?.url) return json(res, { error: "Missing PR URL" }, 400); + const newRef = parsePRUrl(body.url); + if (!newRef) return json(res, { error: "Invalid PR URL" }, 400); + if (!isSameProject(newRef, prRef!)) return json(res, { error: "Cannot switch to a PR in a different repository" }, 400); + + const cached = prSwitchCache.get(body.url); + const pr = cached ?? await fetchPR(newRef); + if (!cached) prSwitchCache.set(body.url, pr); + prMeta = pr.metadata; + prRef = prRefFromMetadata(pr.metadata); + currentPatch = pr.rawPatch; + currentGitRef = `${getMRLabel(pr.metadata)} ${getMRNumberLabel(pr.metadata)}`; + currentError = undefined; + originalPRPatch = pr.rawPatch; + originalPRGitRef = currentGitRef; + originalPRError = undefined; + currentPRDiffScope = "layer"; + draftKey = contentHash(pr.rawPatch); + prListCache = null; + + prStackInfo = getPRStackInfo(pr.metadata); + if (prStackTreeCache.has(body.url)) { + prStackTree = prStackTreeCache.get(body.url) ?? null; + } else { + try { + prStackTree = await fetchPRStack(prRef, pr.metadata); + } catch { prStackTree = null; } + prStackTreeCache.set(body.url, prStackTree); + } + + let hasLocalForNewPR = false; + if (options.worktreePool) { + try { + await options.worktreePool.ensure(reviewRuntime, pr.metadata); + hasLocalForNewPR = true; + } catch {} + } else if (options.agentCwd) { + hasLocalForNewPR = await checkoutPRHead(reviewRuntime, pr.metadata, options.agentCwd); + } + + prStackInfo = resolveStackInfo(pr.metadata, prStackTree, prStackInfo); + + prDiffScopeOptions = prStackInfo + ? getPRDiffScopeOptions(pr.metadata, hasLocalForNewPR) + : []; + + let switchedViewedFiles: string[] = []; + try { + const viewedMap = await fetchPRViewedFiles(prRef); + switchedViewedFiles = Object.entries(viewedMap) + .filter(([, v]) => v).map(([p]) => p); + } catch {} + initialViewedFiles = switchedViewedFiles; + + repoInfo = { + display: getDisplayRepo(pr.metadata), + branch: `${getMRLabel(pr.metadata)} ${getMRNumberLabel(pr.metadata)}`, + }; + + return json(res, { + rawPatch: currentPatch, + gitRef: currentGitRef, + prMetadata: pr.metadata, + prStackInfo, + prStackTree, + prDiffScope: currentPRDiffScope, + prDiffScopeOptions, + repoInfo, + ...(switchedViewedFiles.length > 0 && { viewedFiles: switchedViewedFiles }), + ...(currentError ? { error: currentError } : {}), + }); + } catch (err) { + return json(res, { error: err instanceof Error ? err.message : "Failed to switch PR" }, 500); + } + } else if (url.pathname === "/api/pr-list" && req.method === "GET") { + if (!isPRMode || !prRef) { + return json(res, { error: "Not in PR mode" }, 400); + } + try { + const now = Date.now(); + if (prListCache && now - prListCacheTime < 30_000) { + return json(res, { prs: prListCache }); + } + const prs = await fetchPRList(prRef); + prListCache = prs; + prListCacheTime = now; + return json(res, { prs }); + } catch { + return json(res, { error: "Failed to fetch PR list" }, 500); + } } else if (url.pathname === "/api/pr-context" && req.method === "GET") { if (!isPRMode || !prRef) { json(res, { error: "Not in PR mode" }, 400); @@ -636,16 +856,36 @@ export async function startReviewServer(options: { try { const body = await parseBody(req); const fileComments = (body.fileComments as PRReviewFileComment[]) || []; - console.error(`[pr-action] ${body.action} with ${fileComments.length} file comment(s), headSha=${prMeta.headSha}`); + const targetPrUrl = body.targetPrUrl as string | undefined; + + let targetRef = prRef; + let targetHeadSha = prMeta.headSha; + let targetUrl = prMeta.url; + + if (targetPrUrl) { + const cached = prSwitchCache.get(targetPrUrl); + if (!cached) { + json(res, { error: "Target PR not found in session" }, 400); + return; + } + targetRef = prRefFromMetadata(cached.metadata); + targetHeadSha = cached.metadata.headSha; + targetUrl = cached.metadata.url; + } else if (currentPRDiffScope !== "layer") { + json(res, { error: "Switch to Layer diff before posting a platform review" }, 400); + return; + } + + console.error(`[pr-action] ${body.action} with ${fileComments.length} file comment(s), target=${targetUrl}, headSha=${targetHeadSha}`); await submitPRReview( - prRef, - prMeta.headSha, + targetRef, + targetHeadSha, body.action as "approve" | "comment", body.body as string, fileComments, ); console.error(`[pr-action] Success`); - json(res, { ok: true, prUrl: prMeta.url }); + json(res, { ok: true, prUrl: targetUrl }); } catch (err) { const message = err instanceof Error ? err.message : "Failed to submit PR review"; console.error(`[pr-action] Failed: ${message}`); @@ -701,6 +941,34 @@ export async function startReviewServer(options: { } } + const fileContentCwd = (options.worktreePool && prMeta) ? options.worktreePool.resolve(prMeta.url) : options.agentCwd; + if ( + isPRMode && + currentPRDiffScope === "full-stack" && + fileContentCwd && + prMeta?.defaultBranch + ) { + const baseRef = await resolvePRFullStackBaseRef( + reviewRuntime, + prMeta.defaultBranch, + fileContentCwd, + ); + if (!baseRef) { + json(res, { oldContent: null, newContent: null }); + return; + } + const result = await getFileContentsForDiffCore( + reviewRuntime, + "merge-base", + baseRef, + filePath, + oldPath, + fileContentCwd, + ); + json(res, result); + return; + } + // Local mode first (matches Bun server priority) if (hasLocalAccess && !isPRMode) { const detectedBase = options.gitContext?.defaultBranch || "main"; diff --git a/apps/pi-extension/vendor.sh b/apps/pi-extension/vendor.sh index 48cb847..f24b2ab 100755 --- a/apps/pi-extension/vendor.sh +++ b/apps/pi-extension/vendor.sh @@ -6,7 +6,7 @@ cd "$(dirname "$0")" mkdir -p generated generated/ai/providers -for f in feedback-templates review-core storage draft project pr-provider pr-github pr-gitlab checklist integrations-common repo reference-common favicon resolve-file config external-annotation agent-jobs worktree html-to-markdown url-to-markdown tour annotate-args at-reference; do +for f in feedback-templates review-core storage draft project pr-provider pr-stack pr-github pr-gitlab checklist integrations-common repo reference-common favicon resolve-file config external-annotation agent-jobs worktree worktree-pool html-to-markdown url-to-markdown tour annotate-args at-reference; do src="../../packages/shared/$f.ts" printf '// @generated — DO NOT EDIT. Source: packages/shared/%s.ts\n' "$f" | cat - "$src" > "generated/$f.ts" done diff --git a/packages/ai/providers/claude-agent-sdk.ts b/packages/ai/providers/claude-agent-sdk.ts index 9cf800c..05f69ee 100644 --- a/packages/ai/providers/claude-agent-sdk.ts +++ b/packages/ai/providers/claude-agent-sdk.ts @@ -70,7 +70,11 @@ export class ClaudeAgentSDKProvider implements AIProvider { }; readonly models = [ { id: 'claude-sonnet-4-6', label: 'Sonnet 4.6', default: true }, + { id: 'claude-sonnet-4-6[1m]', label: 'Sonnet 4.6 (1M)' }, + { id: 'claude-opus-4-7', label: 'Opus 4.7' }, + { id: 'claude-opus-4-7[1m]', label: 'Opus 4.7 (1M)' }, { id: 'claude-opus-4-6', label: 'Opus 4.6' }, + { id: 'claude-opus-4-6[1m]', label: 'Opus 4.6 (1M)' }, { id: 'claude-haiku-4-5', label: 'Haiku 4.5' }, ] as const; diff --git a/packages/review-editor/App.tsx b/packages/review-editor/App.tsx index cc20e42..e3cac19 100644 --- a/packages/review-editor/App.tsx +++ b/packages/review-editor/App.tsx @@ -39,8 +39,15 @@ import { DockviewReact, type DockviewReadyEvent, type DockviewApi } from 'dockvi import { ReviewHeaderMenu } from './components/ReviewHeaderMenu'; import { ReviewSidebar } from './components/ReviewSidebar'; import { FileTree } from './components/FileTree'; +import { StackedPRLabel } from './components/StackedPRLabel'; +import { PRSelector } from './components/PRSelector'; +import { PRSwitchOverlay } from './components/PRSwitchOverlay'; +import { usePRStack } from './hooks/usePRStack'; +import { usePRSession, type PRSessionUpdate } from './hooks/usePRSession'; +import { useAnnotationFactory } from './hooks/useAnnotationFactory'; import { DEMO_DIFF } from './demoData'; -import { exportReviewFeedback, formatConventionalPrefix } from './utils/exportFeedback'; +import { exportReviewFeedback } from './utils/exportFeedback'; +import { ReviewSubmissionDialog, buildReviewSubmission, type ReviewSubmission, type SubmissionTarget } from './components/ReviewSubmissionDialog'; import { ReviewStateProvider, type ReviewState } from './dock/ReviewStateContext'; import { JobLogsProvider } from './dock/JobLogsContext'; import { reviewPanelComponents } from './dock/reviewPanelComponents'; @@ -59,6 +66,7 @@ import { import type { DiffFile } from './types'; import type { DiffOption, WorktreeInfo, GitContext } from '@plannotator/shared/types'; import type { PRMetadata } from '@plannotator/shared/pr-provider'; +import type { PRDiffScope, PRDiffScopeOption, PRStackInfo, PRStackTree } from '@plannotator/shared/pr-stack'; import { altKey } from '@plannotator/ui/utils/platform'; import { TourDialog } from './components/tour/TourDialog'; import { DEMO_TOUR_ID } from './demoTour'; @@ -73,6 +81,9 @@ interface DiffData { diffType?: string; gitContext?: GitContext; sharingEnabled?: boolean; + prStackInfo?: PRStackInfo | null; + prDiffScope?: PRDiffScope; + prDiffScopeOptions?: PRDiffScopeOption[]; } // Simple diff parser to extract files from unified diff @@ -186,7 +197,15 @@ const ReviewApp: React.FC = () => { document.title = repoInfo ? `${repoInfo.display} · Code Review` : "Code Review"; }, [repoInfo]); - const [prMetadata, setPrMetadata] = useState(null); + const { prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions, updatePRSession } = usePRSession(); + const { withPRContext } = useAnnotationFactory(prMetadata, prStackInfo ? prDiffScope : undefined); + + const prStackCallbacksRef = useRef(null); + const { + isSwitchingPRScope, + handleScopeSelect: handlePRDiffScopeSelect, + handlePRSwitch, + } = usePRStack(prStackCallbacksRef); const [reviewDestination, setReviewDestination] = useState<'agent' | 'platform'>(() => { const stored = storage.getItem('plannotator-review-dest'); return stored === 'agent' ? 'agent' : 'platform'; // 'github' (legacy) → 'platform' @@ -195,7 +214,7 @@ const ReviewApp: React.FC = () => { const [isPlatformActioning, setIsPlatformActioning] = useState(false); const [platformActionError, setPlatformActionError] = useState(null); const [platformUser, setPlatformUser] = useState(null); - const [platformCommentDialog, setPlatformCommentDialog] = useState<{ action: 'approve' | 'comment' } | null>(null); + const [platformCommentDialog, setPlatformCommentDialog] = useState<{ action: 'approve' | 'comment'; plan: ReviewSubmission } | null>(null); const [platformGeneralComment, setPlatformGeneralComment] = useState(''); const [platformOpenPR, setPlatformOpenPR] = useState(() => { const platformSetting = storage.getItem('plannotator-platform-open-pr'); @@ -684,6 +703,10 @@ const ReviewApp: React.FC = () => { sharingEnabled?: boolean; repoInfo?: { display: string; branch?: string }; prMetadata?: PRMetadata; + prStackInfo?: PRStackInfo | null; + prStackTree?: PRStackTree | null; + prDiffScope?: PRDiffScope; + prDiffScopeOptions?: PRDiffScopeOption[]; platformUser?: string; viewedFiles?: string[]; error?: string; @@ -719,7 +742,13 @@ const ReviewApp: React.FC = () => { if (data.agentCwd) setAgentCwd(data.agentCwd); if (data.sharingEnabled !== undefined) setSharingEnabled(data.sharingEnabled); if (data.repoInfo) setRepoInfo(data.repoInfo); - if (data.prMetadata) setPrMetadata(data.prMetadata); + updatePRSession({ + ...(data.prMetadata && { prMetadata: data.prMetadata }), + ...(data.prStackInfo !== undefined && { prStackInfo: data.prStackInfo }), + ...(data.prStackTree !== undefined && { prStackTree: data.prStackTree }), + ...(data.prDiffScope && { prDiffScope: data.prDiffScope }), + ...(data.prDiffScopeOptions && { prDiffScopeOptions: data.prDiffScopeOptions }), + }); if (data.platformUser) setPlatformUser(data.platformUser); // Initialize viewed files from GitHub's state (set before draft restore so draft takes precedence) if (data.viewedFiles && data.viewedFiles.length > 0) { @@ -800,9 +829,9 @@ const ReviewApp: React.FC = () => { decorations, }; - setAnnotations(prev => [...prev, newAnnotation]); + setAnnotations(prev => [...prev, withPRContext(newAnnotation)]); setPendingSelection(null); - }, [pendingSelection, files, activeFileIndex, identity]); + }, [pendingSelection, files, activeFileIndex, identity, withPRContext]); const handleAddFileComment = useCallback((text: string) => { const activeFile = files[activeFileIndex]; @@ -822,8 +851,8 @@ const ReviewApp: React.FC = () => { author: identity, }; - setAnnotations(prev => [...prev, newAnnotation]); - }, [files, activeFileIndex, identity]); + setAnnotations(prev => [...prev, withPRContext(newAnnotation)]); + }, [files, activeFileIndex, identity, withPRContext]); // Edit annotation const handleEditAnnotation = useCallback(( @@ -946,6 +975,46 @@ const ReviewApp: React.FC = () => { // Staging is never available in PR review mode — the server rejects it and the UI shouldn't offer it. const canStageFiles = canStageRaw && !prMetadata; + // Shared function: apply a PR response (used by both initial load and PR switch) + function applyPRResponse(data: PRSessionUpdate & { + rawPatch: string; gitRef: string; + repoInfo?: { display: string; branch?: string }; + viewedFiles?: string[]; error?: string; + }) { + const isPRSwitch = !!data.prMetadata; + const nextFiles = parseDiffToFiles(data.rawPatch); + dockApi?.getPanel(REVIEW_DIFF_PANEL_ID)?.api.close(); + needsInitialDiffPanel.current = true; + setDiffData(prev => prev ? { ...prev, rawPatch: data.rawPatch, gitRef: data.gitRef } : prev); + setFiles(nextFiles); + if (isPRSwitch) { + setActiveFileIndex(0); + } else { + const currentFile = files[activeFileIndex]; + const preserved = currentFile ? nextFiles.findIndex(f => f.path === currentFile.path) : -1; + setActiveFileIndex(preserved >= 0 ? preserved : 0); + } + setPendingSelection(null); + updatePRSession({ + ...(data.prMetadata && { prMetadata: data.prMetadata }), + ...(data.prStackInfo !== undefined && { prStackInfo: data.prStackInfo }), + ...(data.prStackTree !== undefined && { prStackTree: data.prStackTree }), + ...(data.prDiffScope && { prDiffScope: data.prDiffScope }), + ...(data.prDiffScopeOptions && { prDiffScopeOptions: data.prDiffScopeOptions }), + }); + if (data.repoInfo) setRepoInfo(data.repoInfo); + if (data.prMetadata) { + setViewedFiles(data.viewedFiles ? new Set(data.viewedFiles) : new Set()); + } + setDiffError(data.error || null); + resetStagedFiles(); + } + + prStackCallbacksRef.current = { + applyPRResponse, + onError: (message) => setDiffError(message), + }; + // Shared helper: fetch a diff switch and update state. // Returns true on success, false on failure — callers that optimistically // updated UI state (e.g. the base picker) can use this to revert. @@ -1106,6 +1175,14 @@ const ReviewApp: React.FC = () => { [prMetadata, activeDiffBase, committedBase, activeWorktreePath], ); + const prReviewScopeLabel = useMemo(() => { + if (!prMetadata || !prStackInfo) return undefined; + if (prDiffScope === 'full-stack') { + return `Diff vs \`${prMetadata.defaultBranch ?? 'default branch'}\``; + } + return `Diff vs \`${prMetadata.baseBranch}\``; + }, [prMetadata, prStackInfo, prDiffScope]); + // Build ReviewState value for dock panel context const reviewStateValue = useMemo(() => ({ files, @@ -1130,6 +1207,8 @@ const ReviewApp: React.FC = () => { : undefined, activeDiffBase, feedbackDiffContext, + prReviewScope: prReviewScopeLabel, + prDiffScope, allAnnotations, externalAnnotations, selectedAnnotationId, @@ -1172,7 +1251,7 @@ const ReviewApp: React.FC = () => { }), [ files, activeFileIndex, diffStyle, diffOverflow, diffIndicators, diffLineDiffType, diffShowLineNumbers, diffShowBackground, - diffFontFamily, diffFontSize, activeDiffBase, committedBase, feedbackDiffContext, + diffFontFamily, diffFontSize, activeDiffBase, committedBase, feedbackDiffContext, prReviewScopeLabel, prDiffScope, allAnnotations, externalAnnotations, selectedAnnotationId, pendingSelection, handleLineSelection, handleAddAnnotation, handleAddFileComment, handleEditAnnotation, @@ -1211,7 +1290,7 @@ const ReviewApp: React.FC = () => { return; } try { - const feedback = exportReviewFeedback(allAnnotations, prMetadata, feedbackDiffContext); + const feedback = exportReviewFeedback(allAnnotations, prMetadata, feedbackDiffContext, prReviewScopeLabel); await navigator.clipboard.writeText(feedback); setCopyFeedback('Feedback copied!'); setTimeout(() => setCopyFeedback(null), 2000); @@ -1220,15 +1299,15 @@ const ReviewApp: React.FC = () => { setCopyFeedback('Failed to copy'); setTimeout(() => setCopyFeedback(null), 2000); } - }, [allAnnotations, prMetadata, feedbackDiffContext]); + }, [allAnnotations, prMetadata, feedbackDiffContext, prReviewScopeLabel]); const feedbackMarkdown = useMemo(() => { - let output = exportReviewFeedback(allAnnotations, prMetadata, feedbackDiffContext); + let output = exportReviewFeedback(allAnnotations, prMetadata, feedbackDiffContext, prReviewScopeLabel); if (editorAnnotations.length > 0) { output += exportEditorAnnotations(editorAnnotations); } return output; - }, [allAnnotations, prMetadata, feedbackDiffContext, editorAnnotations]); + }, [allAnnotations, prMetadata, feedbackDiffContext, prReviewScopeLabel, editorAnnotations]); const totalAnnotationCount = allAnnotations.length + editorAnnotations.length; @@ -1308,112 +1387,114 @@ const ReviewApp: React.FC = () => { } }, []); - // Build the payload for /api/pr-action from current annotations - const buildPRReviewPayload = useCallback((action: 'approve' | 'comment', generalComment?: string) => { - const fileAnnotations = allAnnotations.filter(a => (a.scope ?? 'line') === 'line'); - const fileScoped = allAnnotations.filter(a => a.scope === 'file'); + // Submit reviews to one or more PRs via /api/pr-action + const handlePlatformAction = useCallback(async (action: 'approve' | 'comment', plan: ReviewSubmission, generalComment?: string) => { + setIsPlatformActioning(true); + setPlatformActionError(null); - // Top-level body: file-scoped comments - const bodyParts: string[] = []; - if (fileScoped.length > 0) { - for (const ann of fileScoped) { - if (ann.text) bodyParts.push(`**${ann.filePath}:** ${ann.text}`); - } - } - const body = bodyParts.length > 0 - ? `${generalComment ? generalComment + '\n\n' : ''}Review from Plannotator\n\n${bodyParts.join('\n\n')}` - : generalComment || 'Review from Plannotator'; - - // Inline file comments - const fileComments = fileAnnotations.map(ann => { - const ccPrefix = formatConventionalPrefix(ann.conventionalLabel, ann.decorations); - let commentBody = ccPrefix + (ann.text ?? ''); - if (ann.suggestedCode) { - commentBody += `\n\n\`\`\`suggestion\n${ann.suggestedCode}\n\`\`\``; - } - const side = (ann.side === 'old' ? 'LEFT' : 'RIGHT') as 'LEFT' | 'RIGHT'; - const isMultiLine = ann.lineStart != null && ann.lineEnd != null && ann.lineStart !== ann.lineEnd; - return { - path: ann.filePath, - line: ann.lineEnd ?? ann.lineStart, - side, - body: commentBody.trim(), - ...(isMultiLine && { - start_line: ann.lineStart, - start_side: side, - }), + try { + const bodyForTarget = (target: SubmissionTarget) => { + const parts: string[] = []; + if (generalComment) parts.push(generalComment); + parts.push('Review from Plannotator'); + if (target.fileScopedBody) parts.push(target.fileScopedBody); + return parts.join('\n\n'); }; - }).filter(c => c.body.length > 0); - - // Editor annotations (VS Code extension) — always on new/RIGHT side - // Only include annotations targeting files in the diff to avoid GitHub API rejection - const diffPaths = new Set(files.map(f => f.path)); - for (const ea of editorAnnotations) { - if (!diffPaths.has(ea.filePath)) continue; - const body = ea.comment || `> ${ea.selectedText}`; - if (!body.trim()) continue; - const isMultiLine = ea.lineStart !== ea.lineEnd; - fileComments.push({ - path: ea.filePath, - line: ea.lineEnd, - side: 'RIGHT' as const, - body: ea.comment ? `> ${ea.selectedText}\n\n${ea.comment}` : `> ${ea.selectedText}`, - ...(isMultiLine && { - start_line: ea.lineStart, - start_side: 'RIGHT' as const, - }), - }); - } - return { action, body, fileComments }; - }, [allAnnotations, editorAnnotations, files]); + // For approve, only post to the currently viewed PR. + // For comment with no targets but a general comment, create a minimal target. + let targets = plan.targets; + if (action === 'approve' || (targets.length === 0 && generalComment?.trim())) { + const currentTarget = plan.targets.find(t => t.prUrl === prMetadata?.url); + targets = currentTarget ? [currentTarget] : [{ + prUrl: prMetadata?.url ?? '', + prNumber: prMetadata ? (prMetadata.platform === 'github' ? prMetadata.number : prMetadata.iid) : 0, + prTitle: prMetadata?.title ?? '', + prRepo: prMetadata ? getDisplayRepo(prMetadata) : '', + fileComments: [], fileScopedBody: '', + fileCount: 0, annotationCount: 0, status: 'pending' as const, + }]; + } - // Submit a review directly to GitHub - const handlePlatformAction = useCallback(async (action: 'approve' | 'comment', generalComment?: string) => { - setIsPlatformActioning(true); - setPlatformActionError(null); - try { - const payload = buildPRReviewPayload(action, generalComment); - const prRes = await fetch('/api/pr-action', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(payload), - }); - const prData = await prRes.json() as { ok?: boolean; prUrl?: string; error?: string }; - if (!prRes.ok || prData.error) { - setPlatformActionError(prData.error ?? 'Failed to submit PR review'); - setIsPlatformActioning(false); + const openUrls: string[] = []; + const results = await Promise.allSettled( + targets.map(async (target): Promise => { + if (target.status === 'success') return target; + try { + const prRes = await fetch('/api/pr-action', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + action, + body: bodyForTarget(target), + fileComments: target.fileComments, + targetPrUrl: target.prUrl || undefined, + }), + }); + const prData = await prRes.json() as { ok?: boolean; prUrl?: string; error?: string }; + if (!prRes.ok || prData.error) { + return { ...target, status: 'failed', error: prData.error ?? 'Failed to submit' }; + } + if (prData.prUrl) openUrls.push(prData.prUrl); + return { ...target, status: 'success' }; + } catch (err) { + return { ...target, status: 'failed', error: err instanceof Error ? err.message : 'Network error' }; + } + }), + ); + const updatedTargets = results.map((r, i) => r.status === 'fulfilled' ? r.value : { ...targets[i], status: 'failed' as const, error: 'Unexpected error' }); + const allOk = updatedTargets.every(t => t.status === 'success'); + + if (!allOk) { + setPlatformCommentDialog(prev => prev ? { + ...prev, + plan: { ...plan, targets: updatedTargets }, + } : null); return; } - // Open PR in browser (if opted in) - if (prData.prUrl && platformOpenPR) { - window.open(prData.prUrl, '_blank'); + setPlatformCommentDialog(null); + setSubmitted(action === 'approve' ? 'approved' : 'feedback'); + + if (platformOpenPR) { + for (const url of openUrls) window.open(url, '_blank'); } - // Close the local session with a neutral message — don't send annotations to the agent const agentSwitchSettings = getAgentSwitchSettings(); const effectiveAgent = getEffectiveAgentName(agentSwitchSettings); - const prLink = prData.prUrl ?? ''; + const prLinks = openUrls.join(', '); const statusMessage = action === 'approve' - ? `${mrLabel === 'MR' ? 'Merge request' : 'Pull request'} approved on ${platformLabel}${prLink ? ': ' + prLink : ''}` - : `${mrLabel === 'MR' ? 'Merge request' : 'Pull request'} reviewed on ${platformLabel}${prLink ? ': ' + prLink : ''}`; - await fetch('/api/feedback', { + ? `${mrLabel === 'MR' ? 'Merge request' : 'Pull request'} approved on ${platformLabel}${prLinks ? ': ' + prLinks : ''}` + : `${mrLabel === 'MR' ? 'Merge request' : 'Pull request'} reviewed on ${platformLabel}${prLinks ? ': ' + prLinks : ''}`; + fetch('/api/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json' }, + keepalive: true, body: JSON.stringify({ approved: false, feedback: statusMessage, annotations: [], ...(effectiveAgent && { agentSwitch: effectiveAgent }), }), - }); - setSubmitted(action === 'approve' ? 'approved' : 'feedback'); + }).catch(() => {}); } catch (err) { - setPlatformActionError(err instanceof Error ? err.message : 'Failed to submit PR review'); + setPlatformActionError(err instanceof Error ? err.message : 'Failed to submit review'); + } finally { setIsPlatformActioning(false); } - }, [buildPRReviewPayload, platformOpenPR]); + }, [platformOpenPR, platformLabel, mrLabel, prMetadata]); + + const openPlatformDialog = useCallback((action: 'approve' | 'comment') => { + const diffPaths = new Set(files.map(f => f.path)); + const prMeta = prMetadata ? { + number: prMetadata.platform === 'github' ? prMetadata.number : prMetadata.iid, + title: prMetadata.title, + repo: getDisplayRepo(prMetadata), + } : undefined; + const plan = buildReviewSubmission(allAnnotations, editorAnnotations, prMetadata?.url, diffPaths, prMeta); + setPlatformGeneralComment(''); + setPlatformCommentDialog({ action, plan }); + }, [allAnnotations, editorAnnotations, files, prMetadata]); // Double-tap Option/Alt to toggle review destination (PR mode only) useEffect(() => { @@ -1456,16 +1537,15 @@ const ReviewApp: React.FC = () => { const handleKeyDown = (e: KeyboardEvent) => { if (e.key !== 'Enter' || !(e.metaKey || e.ctrlKey)) return; - // If the GitHub comment dialog is open, Cmd+Enter submits it + // If the platform post dialog is open, Cmd+Enter submits it if (platformCommentDialog) { if (submitted || isPlatformActioning) return; const isApproveAction = platformCommentDialog.action === 'approve'; - const canSubmit = isApproveAction || totalAnnotationCount > 0 || platformGeneralComment.trim(); + const hasTargets = platformCommentDialog.plan.targets.length > 0; + const canSubmit = isApproveAction || hasTargets || platformGeneralComment.trim(); if (!canSubmit) return; e.preventDefault(); - const { action } = platformCommentDialog; - setPlatformCommentDialog(null); - handlePlatformAction(action, platformGeneralComment); + handlePlatformAction(platformCommentDialog.action, platformCommentDialog.plan, platformGeneralComment); return; } @@ -1481,11 +1561,9 @@ const ReviewApp: React.FC = () => { // GitHub mode: No annotations → Approve on GitHub, otherwise → Post Review const isOwnPR = !!platformUser && prMetadata?.author === platformUser; if (totalAnnotationCount === 0 && !isOwnPR) { - setPlatformGeneralComment(''); - setPlatformCommentDialog({ action: 'approve' }); + openPlatformDialog('approve'); } else { - setPlatformGeneralComment(''); - setPlatformCommentDialog({ action: 'comment' }); + openPlatformDialog('comment'); } } else { // Agent mode: No annotations → Approve, otherwise → Send Feedback @@ -1503,7 +1581,7 @@ const ReviewApp: React.FC = () => { showExportModal, showNoAnnotationsDialog, showApproveWarning, showExitWarning, platformCommentDialog, platformGeneralComment, submitted, isSendingFeedback, isApproving, isExiting, isPlatformActioning, - origin, platformMode, platformUser, prMetadata, totalAnnotationCount, + origin, platformMode, platformLabel, platformUser, prMetadata, totalAnnotationCount, openPlatformDialog, handleApprove, handleSendFeedback, handlePlatformAction ]); @@ -1522,13 +1600,14 @@ const ReviewApp: React.FC = () => { + {isSwitchingPRScope && }
{/* Header */}
{prMetadata ? (
- {prMetadata && (gitContext || agentCwd) && ( + {(gitContext || agentCwd) && ( )} {displayRepo} - - - {mrNumberLabel} - {prMetadata.title} - + +