mirror of
https://github.com/backnotprop/plannotator.git
synced 2026-09-14 14:17:26 +08:00
feat/opencode2-native-commands
4 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
cb6667e991 |
fix(ai): drive Codex Ask AI via codex app-server (#971)
* fix(ai): drive Codex Ask AI via app-server + answer-first review prompts (#971) Codex Ask AI previously ran via @openai/codex-sdk (codex exec), which forces approval_policy=never and breaks in enterprise-managed Codex environments that ban it (#971). Replace the transport with a long-lived 'codex app-server' process over JSON-RPC. - New provider packages/ai/providers/codex-app-server.ts (registered as 'codex-sdk' to preserve cookie/agents.ts/UI-gate); omits approvalPolicy so Codex resolves the user's + managed policy, pins read-only sandbox, and surfaces interactive approvals through the existing PermissionCard. - Delete codex-sdk.ts and drop the @openai/codex-sdk dependency (and its 6 prebuilt platform binaries); gate registration on 'which codex'. - SessionManager: additive, optional dispose?() hook to kill the spawned process on evict/remove — a no-op for Claude/OpenCode/Pi (they don't implement it). Also rework the Ask AI prompts (all providers, separate from the transport): - Every mode now instructs the agent to answer the user's message directly and not launch an unprompted review of the context. - Code review stops pasting the whole diff for git-reproducible diff types and instead tells the agent how to inspect it (git diff <base>..HEAD, three-dot for merge-base); non-git/PR/workspace types still paste. - Claude gains the Bash tool so it can run git (still gated by approvals). - The UI passes diffType/base (session) and what the user is viewing (per question) into the context. Verified: full typecheck, full test suite (101 ai tests), and a live end-to-end smoke against codex app-server. * fix(review): pin AI approval card above the input/model bar Render pending approval cards just above the input + provider/model bar in both the document chat (DocumentAIChatPanel) and code-review AI tab, instead of at the top of the scroll, so the user sees them where they act. * fix(ai): harden Codex abort/cancel + add Ask AI Stop button Addresses code-review findings on the codex app-server provider: - turn/interrupt was sent as a notification (no id) so Codex ignored it and abort never took effect. It's now a proper JSON-RPC request. - Filter turn events/approvals by turnId and reject an aborted turn's stragglers, so a stopped turn can no longer leak output into — or prematurely finish — the next turn (ask-stop-ask race). - Guard listeners by query generation and end the drain loop on the abort signal, so a superseded/stopped turn can't touch the live one and abort returns promptly instead of waiting for turn/completed. - Handle abort during startup: once the turn id is known, interrupt it instead of running it in the background. - Add a sendAndWait timeout so a stalled (alive-but-unresponsive) process errors instead of hanging forever. - Drain stderr (stdio 'ignore') to avoid a pipe-buffer deadlock. Also add a Stop button to both Ask AI surfaces (plan/annotate DocumentAIChatPanel and code-review AITab via ReviewSidebar). It replaces Send while streaming and calls the hook's abort -> /api/ai/abort -> session.abort(); the hook already exposed abort but nothing surfaced it. * feat(ai): drive Codex models + reasoning levels from model/list - Codex provider fetches model/list at startup (throwaway app-server, like Pi/OpenCode) and populates the real models plus each model's actual supportedReasoningEfforts + defaultReasoningEffort. Replaces the hardcoded model list and the static AI_REASONING_EFFORTS (which mislabeled xhigh as 'Max' and omitted minimal). - AIProviderBar + AIConfigBar now show the selected model's real efforts and hide the control when a model reports none. xhigh is shown verbatim. - Fix: the Stop button now also appears in the populated code-review chat state (a prior edit missed the second GeneralInput due to indentation). * fix(ai): scope Claude Ask AI Bash to read-only git; clear stale approval cards on Stop - Claude Ask AI no longer auto-allows bare Bash (which ran arbitrary shell with no Allow/Deny prompt). Replace it with scoped read-only git rules (Bash(git diff:*), show, log, status, rev-parse, merge-base, ls-files). git reads auto-run so the agent can inspect large diffs itself; any other command (write git, arbitrary, or injected compound) falls through to the permission card. Keeps the git-inspect approach (large diffs don't fit in the prompt) while closing the auto-exec hole. - useAIChat.abort() now drops still-undecided permission cards: abort cancels them server-side, so leaving them visible was a dead Allow/Deny. * feat(ai): code-review Ask AI shares the agent-review prompt machine, delivered as user messages Code-review Ask AI built its own diff description (gitInspectInstruction) in the system prompt from just diffType+base, which was wrong for full-stack, hide-whitespace, untracked files, and PR worktrees. Replace it with the same machine the review jobs use, delivered on the user's messages. - Server: buildCurrentAiReviewContext() reuses buildAgentReviewUserMessageForTarget (contextOnly) for the current view and ships it as aiReviewContext in every diff payload (/api/diff + switch/PR/scope). Mirrored in the Pi server. - Client: review-editor latches aiReviewContext onto each question via the pure buildReviewContextPreamble (packages/ui/utils/aiPrompt.ts) and buildDefaultPrompt — full block on the first message / when the view changes (incl. after a provider switch via the !sessionId fresh-session check), a short reminder otherwise (never re-pastes a large diff). - context.ts: delete the duplicate gitInspectInstruction; code-review system prompt is now role-only. Providers untouched (provider-agnostic user message). - Tests: machine scenario gaps (plain PR, full-stack default, PR-worktree origin/<base> + stale-main warning, untracked mention, jj-evolog, workspace lines); composition (first/reminder, command/pasted, preamble ordering). * fix(ai): agentic remote-PR context, UTF-8 stream decode, real Stop on supersede/disconnect Addresses review findings on the Ask AI prompt work: - Remote PR without a confirmed local checkout no longer gets URL-only. The agent is told it's in a PR worktree that's being prepared, to verify the PR files exist before relying on them, and to diff with git diff origin/<base>... HEAD (URL fallback). Inform + trust the agent rather than pasting. Shared machine, so review jobs get the same framing. - Decode Codex stdout with a streaming TextDecoder instead of per-chunk toString(), so multi-byte UTF-8 split across chunks no longer corrupts into U+FFFD (matches the Pi provider). - Stop now actually stops the server turn: ask() awaits /api/ai/abort when a new question supersedes a streaming one (awaiting avoids racing the new query into session_busy), and the /api/ai/query SSE stream gains a cancel handler so tab-close/navigation aborts the turn too. Both reuse the existing per-provider session.abort(); factored a shared postServerAbort helper. * fix(ai): per-model reasoning effort, shared PR-checkout readiness, Stop-then-ask race, type hole - Reasoning effort is now tracked per model (a map keyed by model) instead of one global value, so switching to a model that doesn't support the prior level (e.g. xhigh) no longer posts a stale/unsupported effort that Codex rejects. Each model keeps its own level; nothing leaks across. - Extract resolvePoolCwd into packages/shared/worktree-pool.ts (ready/pending/ absent) and use it from both servers' resolvePRLocalCwd so the readiness rule can't drift. Fix the Pi Ask AI helper to ready-check like Bun, so a warming PR checkout no longer claims 'checked out at PR head' and misdirects the diff. - Stop-then-ask no longer races into session_busy: the abort promise (from Stop or a superseding question) is stashed and the next ask() awaits it before sending. Stop still kills the turn instantly; a follow-up just waits the one abort round-trip. - Declare aiReviewContext on the initial /api/diff response type. * fix(ai): surface real Codex error messages, skip transient retries, auto-deny permission escalations Validated against codex-rs: - Codex's ErrorNotification nests the text at params.error.message (TurnError.message); we read params.message → always 'Unknown error'. Read the nested field (top-level fallback) so auth/usage-limit/stream failures show their real, actionable text. - Skip transient error notifications (willRetry=true): Codex retries on its own and the turn continues, so surfacing them flashed a spurious failure before the real answer. - Handle item/permissions/requestApproval: respond {permissions:{}, scope:'turn'} — byte-for-byte Codex's own cancel response (codex_delegate.rs) — instead of 'Unsupported request'. Ask AI is read-only, so denying the escalation lets the turn continue sandboxed rather than failing. Interactive grant deferred. * refactor(ai): share AI provider/model config in one hook; aggregate paginated model/list - Extract useAIProviderConfig (packages/ui/hooks): one home for provider/model/ reasoning-effort selection — initial state, auto-resolve on capabilities load, per-model effort (no leak across models), and persistence. Both the plan and code-review apps now call it and only compose the session reset (the hook can't own reset without a cycle through useAIChat). Plan editor adapted to the effect-based resolve (adds aiDefaultProvider state). This fixes the plan editor's stale-effort-on-model-switch bug by construction and stops the two apps' copies from drifting again. - fetchModels now follows model/list's nextCursor and aggregates every page into one list, so larger model catalogs aren't silently truncated (with a page guard against a misbehaving cursor). Skipped per discussion: legacy v1 approval methods (we're a v2 client). * feat(agents): per-agent review default; bound Codex model discovery so it can't stall the AI panel - The selected review profile is now tracked per review engine (claude/codex/ cursor/opencode) instead of one flat global value, so each agent keeps its own review default. Public hook API (reviewProfileId/setReviewProfileId) is unchanged — getter derives the current engine's value, setter writes it — so AgentsTab needs no changes. One-shot migration seeds every engine with any existing flat pick. Adds parseReviewProfileByEngine + tests. - fetchModels (Codex model discovery) now uses a short 6s timeout for its initialize + model/list RPCs instead of the 30s default. /api/ai/capabilities awaits model discovery, so an installed-but-unauthenticated codex could otherwise block the AI panel for ~30s; it now falls back to the static model list fast. Authed codex is unaffected (discovery completes in tens of ms). |
||
|
|
6ec1a66c9b |
feat(review): large-PR pipeline, instant-open checkout, scroll perf, and worker-pool highlighting (#893)
* feat(review): large GitHub PR fallback + non-blocking PR checkout
Two PR-mode improvements:
1. Large GitHub PRs no longer fail to load. When `gh pr diff` is refused
(HTTP 406 for oversized diffs), fetchGhPR pages through the pulls files
API and stitches the per-file patches into a unified diff — mirroring
the existing GitLab raw_diffs fallback. Path quoting matches git's
exact rules (bare spaces unquoted) so downstream parsers round-trip;
truncation at the API's 3000-file cap is surfaced, never silent.
2. The --local worktree/clone no longer blocks startup. The review server
opens as soon as the platform diff arrives; the checkout warms in the
background as a seeded not-ready pool entry. Consumers that need real
files (agent jobs, full-stack diff, code-nav, semantic diff, AI
sessions) await pool.ensure(), with creations serialized so concurrent
fetches can't clobber the shared FETCH_HEAD. Cross-repo clone steps
converted from spawnSync to async spawns; warmup children are killed
on exit (plus `git worktree prune`) so aborted sessions can't leak
stale registrations; failed checkouts degrade honestly (no agent runs
in the wrong directory claiming local access) with a 30s retry
cooldown.
* fix(review): survive long PR checkout warmups + classify reconstructed renames
Stress-testing against oven-sh/bun#30412 (2,188 files) surfaced three bugs:
- Bun.serve's default 10s idleTimeout killed /api/semantic-diff while it
parked on the background checkout warmup (a clone that can take minutes).
Disable the idle timeout on all servers — AI SSE streams can also stall
>10s between bytes while a permission prompt waits.
- The file-badge hook memoized that failed fetch in a module-level cache
keyed by patch, pinning every badge to empty until a hard refresh. Never
cache failures; retry with backoff (5s/15s/30s).
- reconstructGhPatch/reconstructPatch omitted the `similarity index` line,
which Pierre's parser keys rename classification off — pure renames
rendered as blank plain changes with no old path. Emit 100% for
patch-less renames/copies (exactly accurate) and a synthetic 99% for
patched ones (consumers only branch on 100% vs not).
* feat(review): local full-diff upgrade for PRs whose API diff is truncated
On oversized PRs the platform APIs withhold per-file patch content entirely
(bun#30412: 1,066 of 2,188 files came back with status added/modified, zeroed
counts, and no patch). Those files rendered as empty stubs with no diff.
- fetchGhPR/fetchGlMR flag the result `patchIncomplete` when patch-less
non-rename entries exist or the 3000-file cap truncates the listing.
- New runPRLayerLocalDiff (pr-stack.ts) recomputes the exact layer diff in
the local checkout: platform merge-base + head SHA two-dot diff (three-dot
vs baseSha fallback), fetch-by-SHA for objects missing from shallow clones,
-l0 so rename detection doesn't silently degrade on huge PRs.
- The review UI shows a "Partial diff · Load full diff" notice in layer
scope; clicking re-requests the layer scope and the server swaps in the
recomputed full diff (waiting out the background clone if needed).
- PR scope/switch state writes are epoch-guarded: a request parked on the
checkout warmup can no longer overwrite a newer scope select or pr-switch.
- draftKey follows the upgraded patch so annotation drafts survive pr-switch
round-trips; recompute failures surface in the response error field.
- Pi server mirrors all of it, including an agentCwd fallback so the upgrade
works for PRs switched-to under a cross-repo clone pool.
* fix(review): use GitLab's too_large/collapsed flags for withheld-diff detection
External review caught a false negative: a too-large ADDED file comes back
new_file:true with an empty diff — indistinguishable from a legitimately
empty new file under the old heuristic, so the partial-diff upgrade was
never offered for exactly the files that matter most on big MRs.
The REST /diffs endpoint marks withheld content explicitly per entry
(verified against gitlab.com): too_large/collapsed are now authoritative in
both directions — withheld adds/deletes are flagged, binaries and empty
files are never misflagged. Older GitLab without the fields keeps the
empty-diff-on-modification heuristic.
* feat(prompts): unify review-denied suffix — triage first, no coding off raw feedback
The per-runtime defaults map (#627) gave OpenCode and Pi a different
review-denied suffix than every other runtime; updating one meant the
others silently kept "you must address all of them" — an instruction to
start coding immediately. Claude Code, Amp, Droid, Codex, Copilot, Gemini,
and Kiro were all still on it.
One default for every runtime now: triage the feedback, verify it against
the code, discuss before changing anything. Per-runtime customization
remains available via config (prompts.review.runtimes.<rt>.denied), which
resolves above the built-in default as before.
* fix(prompts): generalize review-denied suffix — 'from review', not 'external AI reviewers'
Review feedback isn't always from AI reviewers or agent jobs; often it's
the human reviewer's own annotations. Neutral wording covers both.
* fix(review): non-blocking 'Load full diff' + flag-handling hardenings
Self-review findings:
- The partial-diff upgrade reused the scope-switch handler, so clicking
"Load full diff" raised the full-screen PRSwitchOverlay — blocking the
entire UI, potentially for minutes behind a cold clone, with no text and
no cancel. The upgrade now has its own loading state: the notice shows a
spinner ("Loading full diff…") and the reviewer keeps working with the
partial diff while the request parks. Server-side epoch guards already
handle scope/PR changes made during the wait.
- GitLab too_large/collapsed: treat explicit null like absent (flags
inconclusive → legacy heuristic decides) instead of silently exonerating.
- Rename-limit lift uses -l100000 instead of -l0 ("0 = unlimited" only
holds on git >= 2.29; on older git it could disable detection outright).
* fix(review): stop scroll-driven sem stampede when semantic diff is failing
The badge retry change (
|
||
|
|
3fb0b9cf03 |
fix(gitlab): persist unposted inline comments + split pr-provider from browser-safe pr-types (#719)
Closes #680. Two changes that landed together because the persistence fix exposed a hidden architectural constraint. 1. GitLab inline comments: when one or more discussion POSTs failed (e.g. transient `i/o timeout`), the failed comment bodies were lost. Now `submitGlMRReview` writes them to `~/.plannotator/failed-comments/{host}-{project}-mr{iid}-{ts}.json` in both the all-fail and partial-fail branches. The throw-vs-warn split is preserved deliberately: all-fail throws so the UI retries from a clean state, partial-fail warns so the UI doesn't resubmit already-posted content. 2. Split `packages/shared/pr-provider.ts` into `pr-types.ts` (browser-safe types + pure label/URL helpers) and `pr-provider.ts` (server-only dispatch that imports pr-github / pr-gitlab). The review-editor browser bundle previously dragged pr-gitlab.ts in as dead code via static imports, which silently constrained the file to never use Node built-ins. Adding `fs`/`os`/`path` for (1) broke the review build until we routed browser imports to pr-types and left server callers on the now server-only pr-provider facade. Server-only `pr-provider.ts` re-exports `pr-types` so existing server-side imports keep working unchanged. |
||
|
|
bb404f8d14 |
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620)
* 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. |