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} - + +