2026-01-12 19:36:09 -08:00
|
|
|
/**
|
|
|
|
|
* Code Review Server
|
|
|
|
|
*
|
|
|
|
|
* Provides a server implementation for code review with git diff rendering.
|
|
|
|
|
* Follows the same patterns as the plan server.
|
|
|
|
|
*
|
|
|
|
|
* Environment variables:
|
2026-04-05 05:17:16 +09:00
|
|
|
* PLANNOTATOR_REMOTE - Set to "1"/"true" for remote, "0"/"false" for local
|
2026-01-12 19:36:09 -08:00
|
|
|
* PLANNOTATOR_PORT - Fixed port to use (default: random locally, 19432 for remote)
|
|
|
|
|
*/
|
|
|
|
|
|
2026-04-13 23:00:05 +09:00
|
|
|
import { isRemoteSession, getServerHostname, getServerPort } from "./remote";
|
2026-03-28 16:37:56 -07:00
|
|
|
import type { Origin } from "@plannotator/shared/agents";
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
import { type DiffType, type GitContext, runVcsDiff, getVcsFileContentsForDiff, canStageFiles, stageFile, unstageFile, resolveVcsCwd, validateFilePath } from "./vcs";
|
2026-01-28 10:29:52 -08:00
|
|
|
import { getRepoInfo } from "./repo";
|
2026-03-16 15:45:00 +01:00
|
|
|
import { handleImage, handleUpload, handleAgents, handleServerReady, handleDraftSave, handleDraftLoad, handleDraftDelete, handleFavicon, type OpencodeClient } from "./shared-handlers";
|
2026-03-04 10:12:58 -08:00
|
|
|
import { contentHash, deleteDraft } from "./draft";
|
feat: VS Code editor annotations + theme integration (#239)
* feat: add shared EditorAnnotation type
Single source of truth for the editor annotation interface,
imported by both @plannotator/server and @plannotator/ui.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation server endpoints
In-memory store with POST/GET/DELETE endpoints for editor annotations.
The array lives in the handler closure and dies with the server session.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation UI — polling hook, card, panel, and export
- useEditorAnnotations hook with auto-disable polling (500ms interval)
- EditorAnnotationCard with file path, code preview, and comment
- AnnotationPanel conditionally renders editor annotation section
- exportEditorAnnotations formats annotations for Claude feedback
- App.tsx wires hook, includes in output memo and send feedback gate
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code extension editor annotation command
Cmd+Shift+. or right-click to capture selected text as an annotation.
POSTs through the cookie proxy to the plannotator server. Adds amber
left-border decorations on annotated lines, cleared on panel close.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: inline comment threads, lightbulb menu, and stronger decorations
Replace showInputBox with VS Code CommentController for inline annotation
threads anchored to selected code. Add CodeActionProvider for lightbulb
discoverability. Stronger decoration styling with gutter icon.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code theme integration for webview
Bridge VS Code CSS variables to Plannotator's CSS variable system via
postMessage between wrapper page and proxied iframe. Automatically adopts
the active VS Code color theme (dark/light/custom) without touching any
UI components or CSS files.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: gate editor annotation polling behind VS Code detection
Only poll /api/editor-annotations when running inside a VS Code webview
(window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have
zero network cost from the editor annotations feature. Also fixes poll
interval from 500ms to 2000ms.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: faster polling, prevent unnecessary re-renders, unify HTTP helper
- Poll interval 2s → 500ms for snappier annotation pickup
- Shallow equality check on annotation IDs prevents React re-renders
when poll data is unchanged
- Merge postToProxy/deleteFromProxy into single requestProxy function
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotations support in code review
Wire existing editor annotation infrastructure into the review flow
so VS Code users can annotate files outside the diff during code review.
- Add editor annotation endpoints to review server (same 3-line pattern)
- Call useEditorAnnotations hook in review App.tsx
- Display editor annotations in ReviewPanel with "Editor" divider
- Include editor annotations in feedback export and gating logic
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
|
|
|
import { createEditorAnnotationHandler } from "./editor-annotations";
|
feat: external annotations API with real-time SSE (#400)
Adds a general-purpose External Annotations API that allows external programs (linters, AI tools, security scanners) to push annotations into a live Plannotator session via HTTP, with real-time delivery over SSE.
## What's included
- **Shared core** (`packages/shared/external-annotation.ts`): types, in-memory store, input validation, SSE serialization
- **Server handlers**: Bun + Pi implementations with full CRUD (GET/POST/PATCH/DELETE) + SSE streaming
- **Client hook** (`useExternalAnnotations`): EventSource with polling fallback, optimistic updates
- **Editor integration**: two-array state model (local + external), content-aware dedup, ID-based routing
- **Persistence**: source field preserved through share URLs and crash-recovery drafts
- **Docs**: new Integrations category with API overview page, updated API reference
## API surface
All three servers (plan, review, annotate) expose:
- `GET /api/external-annotations/stream` - SSE stream
- `GET /api/external-annotations` - JSON snapshot (polling fallback)
- `POST /api/external-annotations` - Add annotations (single or batch)
- `PATCH /api/external-annotations?id=` - Update fields
- `DELETE /api/external-annotations` - Remove by id, source, or clear all
For provenance purposes, this commit was AI assisted.
2026-03-29 17:18:31 -07:00
|
|
|
import { createExternalAnnotationHandler } from "./external-annotations";
|
feat: agentic review — background job runner with SSE streaming (#443)
* feat(server): add agent job manager with process lifecycle and SSE streaming
Introduces the backend for agentic review — a server-agnostic job runner
that spawns agent processes, monitors their lifecycle via proc.exited, and
broadcasts status updates over a dedicated SSE stream.
New files:
- packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine
- packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes
Wired into the review server with late-bound serverUrl, killAll on stop
and process exit for defense-in-depth cleanup. Capability detection via
Bun.which() for Claude Code, Codex CLI, and shell.
For provenance purposes, this commit was AI assisted.
* feat(ui): add Review Agents tab with job management and live status
Adds the client-side UI for agentic review:
- useAgentJobs hook: SSE primary with polling fallback, capabilities fetch
- AgentsTab: shared component with provider dropdown, job cards, kill controls
- ReviewAgentsIcon: magnifying glass with cog icon
- ReviewPanel: new "Review Agents" tab conditional on detected capabilities
- App.tsx: initializes hook and passes props to ReviewPanel
Jobs show live elapsed time, status badges, annotation counts per source,
and expandable error details. Stub command (sleep 10-30s) for initial testing.
For provenance purposes, this commit was AI assisted.
* fix(server): narrow proc.stderr type to satisfy TS
Bun types proc.stderr as ReadableStream | number. Add typeof guard
to narrow before passing to Response constructor.
For provenance purposes, this commit was AI assisted.
* fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch
- Change stdout from "pipe" to "ignore" — agents post findings via the
annotations API, not stdout. Unconsumed pipe buffer caused deadlock.
- Drain stderr continuously instead of reading after exit — prevents
pipe-full stall on chatty agents.
- Make agent getCwd worktree-aware using the same currentDiffType check
the AI endpoints use, so agents spawn in the correct checkout.
- Exclude 'agents' tab from PR context fetch guard in ReviewPanel.
For provenance purposes, this commit was AI assisted.
* feat(pi): mirror agent-job endpoints in Pi review server
Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun
agent-jobs handler using child_process.spawn, res.write() SSE, and
execFileSync for capability detection.
Wire into serverReview.ts: route delegation, killAll in stop(),
process.on("exit") guard, worktree-aware getCwd, and serverUrl
late-binding. Add agent-jobs to vendor.sh for shared type vendoring.
For provenance purposes, this commit was AI assisted.
* fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs
- Use process.once instead of process.on to prevent exit listener accumulation
- Validate provider against known capabilities before spawning (rejects unknown providers)
- Use platform-aware which/where for CLI detection on Windows
- Broadcast jobs:cleared event from kill-all endpoint (was dead client code)
- Document all /api/agents/* endpoints in CLAUDE.md Review Server table
For provenance purposes, this commit was AI assisted.
* fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup
- Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback
activates correctly on subsequent tab switches
- Remove jobs:cleared broadcast from kill-all — killAll() already fires
individual job:completed events, so the UI shows status transitions
instead of going blank
- Store exit handler ref so stop() can removeListener, preventing
accumulation in long-lived hosts (OpenCode, Pi)
For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
|
|
|
import { createAgentJobHandler } from "./agent-jobs";
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
import {
|
|
|
|
|
CODEX_REVIEW_SYSTEM_PROMPT,
|
|
|
|
|
buildCodexReviewUserMessage,
|
|
|
|
|
buildCodexCommand,
|
|
|
|
|
generateOutputPath,
|
|
|
|
|
parseCodexOutput,
|
|
|
|
|
transformReviewFindings,
|
|
|
|
|
} from "./codex-review";
|
|
|
|
|
import {
|
|
|
|
|
CLAUDE_REVIEW_PROMPT,
|
|
|
|
|
buildClaudeCommand,
|
|
|
|
|
parseClaudeStreamOutput,
|
|
|
|
|
transformClaudeFindings,
|
|
|
|
|
} from "./claude-review";
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
import { createTourSession, TOUR_EMPTY_OUTPUT_ERROR } from "./tour/tour-review";
|
2026-03-26 11:54:22 -07:00
|
|
|
import { saveConfig, detectGitUser, getServerConfig } from "./config";
|
2026-03-25 21:33:33 +01:00
|
|
|
import { type PRMetadata, type PRReviewFileComment, fetchPRFileContent, fetchPRContext, submitPRReview, fetchPRViewedFiles, markPRFilesViewed, getPRUser, prRefFromMetadata, getDisplayRepo, getMRLabel, getMRNumberLabel } from "./pr";
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
import { createAIEndpoints, ProviderRegistry, SessionManager, createProvider, type AIEndpoints, type PiSDKConfig } from "@plannotator/ai";
|
2026-03-25 15:06:29 -03:00
|
|
|
import { isWSL } from "./browser";
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
// Re-export utilities
|
|
|
|
|
export { isRemoteSession, getServerPort } from "./remote";
|
|
|
|
|
export { openBrowser } from "./browser";
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
export { type DiffType, type DiffOption, type GitContext, type WorktreeInfo } from "./vcs";
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
export { type PRMetadata } from "./pr";
|
2026-03-03 23:17:16 -08:00
|
|
|
export { handleServerReady as handleReviewServerReady } from "./shared-handlers";
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
// --- Types ---
|
|
|
|
|
|
|
|
|
|
export interface ReviewServerOptions {
|
|
|
|
|
/** Raw git diff patch string */
|
|
|
|
|
rawPatch: string;
|
|
|
|
|
/** Git ref used for the diff (e.g., "HEAD", "main..HEAD", "--staged") */
|
|
|
|
|
gitRef: string;
|
2026-03-02 15:26:07 +09:00
|
|
|
/** Error message if git diff failed */
|
|
|
|
|
error?: string;
|
2026-01-12 19:36:09 -08:00
|
|
|
/** HTML content to serve for the UI */
|
|
|
|
|
htmlContent: string;
|
|
|
|
|
/** Origin identifier for UI customization */
|
2026-03-28 16:37:56 -07:00
|
|
|
origin?: Origin;
|
2026-01-12 19:36:09 -08:00
|
|
|
/** Current diff type being displayed */
|
|
|
|
|
diffType?: DiffType;
|
|
|
|
|
/** Git context with branch info and available diff options */
|
|
|
|
|
gitContext?: GitContext;
|
2026-01-14 13:12:37 -08:00
|
|
|
/** Whether URL sharing is enabled (default: true) */
|
|
|
|
|
sharingEnabled?: boolean;
|
2026-02-12 15:07:43 -08:00
|
|
|
/** Custom base URL for share links (default: https://share.plannotator.ai) */
|
|
|
|
|
shareBaseUrl?: string;
|
2026-01-12 19:36:09 -08:00
|
|
|
/** Called when server starts with the URL, remote status, and port */
|
|
|
|
|
onReady?: (url: string, isRemote: boolean, port: number) => void;
|
2026-01-19 11:07:22 -08:00
|
|
|
/** OpenCode client for querying available agents (OpenCode only) */
|
2026-03-03 23:17:16 -08:00
|
|
|
opencodeClient?: OpencodeClient;
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
/** PR metadata when reviewing a pull request (PR mode) */
|
|
|
|
|
prMetadata?: PRMetadata;
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
/** Working directory for agent processes (e.g., --local worktree). Independent of diff pipeline. */
|
|
|
|
|
agentCwd?: string;
|
|
|
|
|
/** Cleanup callback invoked when server stops (e.g., remove temp worktree) */
|
|
|
|
|
onCleanup?: () => void | Promise<void>;
|
2026-01-12 19:36:09 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface ReviewServerResult {
|
|
|
|
|
/** The port the server is running on */
|
|
|
|
|
port: number;
|
|
|
|
|
/** The full URL to access the server */
|
|
|
|
|
url: string;
|
|
|
|
|
/** Whether running in remote mode */
|
|
|
|
|
isRemote: boolean;
|
2026-03-14 17:58:57 -07:00
|
|
|
/** Wait for user review decision */
|
2026-01-12 19:36:09 -08:00
|
|
|
waitForDecision: () => Promise<{
|
2026-03-14 17:58:57 -07:00
|
|
|
approved: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: string;
|
|
|
|
|
annotations: unknown[];
|
|
|
|
|
agentSwitch?: string;
|
2026-04-10 03:22:01 +01:00
|
|
|
exit?: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
}>;
|
|
|
|
|
/** Stop the server */
|
|
|
|
|
stop: () => void;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- Server Implementation ---
|
|
|
|
|
|
|
|
|
|
const MAX_RETRIES = 5;
|
|
|
|
|
const RETRY_DELAY_MS = 500;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Start the Code Review server
|
|
|
|
|
*
|
|
|
|
|
* Handles:
|
|
|
|
|
* - Remote detection and port configuration
|
|
|
|
|
* - API routes (/api/diff, /api/feedback)
|
|
|
|
|
* - Port conflict retries
|
|
|
|
|
*/
|
|
|
|
|
export async function startReviewServer(
|
|
|
|
|
options: ReviewServerOptions
|
|
|
|
|
): Promise<ReviewServerResult> {
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
const { htmlContent, origin, gitContext, sharingEnabled = true, shareBaseUrl, onReady, prMetadata } = options;
|
2026-01-12 19:36:09 -08:00
|
|
|
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
const isPRMode = !!prMetadata;
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
const hasLocalAccess = !!gitContext;
|
2026-03-04 10:12:58 -08:00
|
|
|
const draftKey = contentHash(options.rawPatch);
|
feat: VS Code editor annotations + theme integration (#239)
* feat: add shared EditorAnnotation type
Single source of truth for the editor annotation interface,
imported by both @plannotator/server and @plannotator/ui.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation server endpoints
In-memory store with POST/GET/DELETE endpoints for editor annotations.
The array lives in the handler closure and dies with the server session.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation UI — polling hook, card, panel, and export
- useEditorAnnotations hook with auto-disable polling (500ms interval)
- EditorAnnotationCard with file path, code preview, and comment
- AnnotationPanel conditionally renders editor annotation section
- exportEditorAnnotations formats annotations for Claude feedback
- App.tsx wires hook, includes in output memo and send feedback gate
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code extension editor annotation command
Cmd+Shift+. or right-click to capture selected text as an annotation.
POSTs through the cookie proxy to the plannotator server. Adds amber
left-border decorations on annotated lines, cleared on panel close.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: inline comment threads, lightbulb menu, and stronger decorations
Replace showInputBox with VS Code CommentController for inline annotation
threads anchored to selected code. Add CodeActionProvider for lightbulb
discoverability. Stronger decoration styling with gutter icon.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code theme integration for webview
Bridge VS Code CSS variables to Plannotator's CSS variable system via
postMessage between wrapper page and proxied iframe. Automatically adopts
the active VS Code color theme (dark/light/custom) without touching any
UI components or CSS files.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: gate editor annotation polling behind VS Code detection
Only poll /api/editor-annotations when running inside a VS Code webview
(window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have
zero network cost from the editor annotations feature. Also fixes poll
interval from 500ms to 2000ms.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: faster polling, prevent unnecessary re-renders, unify HTTP helper
- Poll interval 2s → 500ms for snappier annotation pickup
- Shallow equality check on annotation IDs prevents React re-renders
when poll data is unchanged
- Merge postToProxy/deleteFromProxy into single requestProxy function
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotations support in code review
Wire existing editor annotation infrastructure into the review flow
so VS Code users can annotate files outside the diff during code review.
- Add editor annotation endpoints to review server (same 3-line pattern)
- Call useEditorAnnotations hook in review App.tsx
- Display editor annotations in ReviewPanel with "Editor" divider
- Include editor annotations in feedback export and gating logic
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
|
|
|
const editorAnnotations = createEditorAnnotationHandler();
|
feat: external annotations API with real-time SSE (#400)
Adds a general-purpose External Annotations API that allows external programs (linters, AI tools, security scanners) to push annotations into a live Plannotator session via HTTP, with real-time delivery over SSE.
## What's included
- **Shared core** (`packages/shared/external-annotation.ts`): types, in-memory store, input validation, SSE serialization
- **Server handlers**: Bun + Pi implementations with full CRUD (GET/POST/PATCH/DELETE) + SSE streaming
- **Client hook** (`useExternalAnnotations`): EventSource with polling fallback, optimistic updates
- **Editor integration**: two-array state model (local + external), content-aware dedup, ID-based routing
- **Persistence**: source field preserved through share URLs and crash-recovery drafts
- **Docs**: new Integrations category with API overview page, updated API reference
## API surface
All three servers (plan, review, annotate) expose:
- `GET /api/external-annotations/stream` - SSE stream
- `GET /api/external-annotations` - JSON snapshot (polling fallback)
- `POST /api/external-annotations` - Add annotations (single or batch)
- `PATCH /api/external-annotations?id=` - Update fields
- `DELETE /api/external-annotations` - Remove by id, source, or clear all
For provenance purposes, this commit was AI assisted.
2026-03-29 17:18:31 -07:00
|
|
|
const externalAnnotations = createExternalAnnotationHandler("review");
|
2026-03-04 10:12:58 -08:00
|
|
|
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
const tour = createTourSession();
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// Mutable state for diff switching
|
|
|
|
|
let currentPatch = options.rawPatch;
|
|
|
|
|
let currentGitRef = options.gitRef;
|
|
|
|
|
let currentDiffType: DiffType = options.diffType || "uncommitted";
|
2026-03-02 15:26:07 +09:00
|
|
|
let currentError = options.error;
|
2026-01-12 19:36:09 -08:00
|
|
|
|
feat: agentic review — background job runner with SSE streaming (#443)
* feat(server): add agent job manager with process lifecycle and SSE streaming
Introduces the backend for agentic review — a server-agnostic job runner
that spawns agent processes, monitors their lifecycle via proc.exited, and
broadcasts status updates over a dedicated SSE stream.
New files:
- packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine
- packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes
Wired into the review server with late-bound serverUrl, killAll on stop
and process exit for defense-in-depth cleanup. Capability detection via
Bun.which() for Claude Code, Codex CLI, and shell.
For provenance purposes, this commit was AI assisted.
* feat(ui): add Review Agents tab with job management and live status
Adds the client-side UI for agentic review:
- useAgentJobs hook: SSE primary with polling fallback, capabilities fetch
- AgentsTab: shared component with provider dropdown, job cards, kill controls
- ReviewAgentsIcon: magnifying glass with cog icon
- ReviewPanel: new "Review Agents" tab conditional on detected capabilities
- App.tsx: initializes hook and passes props to ReviewPanel
Jobs show live elapsed time, status badges, annotation counts per source,
and expandable error details. Stub command (sleep 10-30s) for initial testing.
For provenance purposes, this commit was AI assisted.
* fix(server): narrow proc.stderr type to satisfy TS
Bun types proc.stderr as ReadableStream | number. Add typeof guard
to narrow before passing to Response constructor.
For provenance purposes, this commit was AI assisted.
* fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch
- Change stdout from "pipe" to "ignore" — agents post findings via the
annotations API, not stdout. Unconsumed pipe buffer caused deadlock.
- Drain stderr continuously instead of reading after exit — prevents
pipe-full stall on chatty agents.
- Make agent getCwd worktree-aware using the same currentDiffType check
the AI endpoints use, so agents spawn in the correct checkout.
- Exclude 'agents' tab from PR context fetch guard in ReviewPanel.
For provenance purposes, this commit was AI assisted.
* feat(pi): mirror agent-job endpoints in Pi review server
Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun
agent-jobs handler using child_process.spawn, res.write() SSE, and
execFileSync for capability detection.
Wire into serverReview.ts: route delegation, killAll in stop(),
process.on("exit") guard, worktree-aware getCwd, and serverUrl
late-binding. Add agent-jobs to vendor.sh for shared type vendoring.
For provenance purposes, this commit was AI assisted.
* fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs
- Use process.once instead of process.on to prevent exit listener accumulation
- Validate provider against known capabilities before spawning (rejects unknown providers)
- Use platform-aware which/where for CLI detection on Windows
- Broadcast jobs:cleared event from kill-all endpoint (was dead client code)
- Document all /api/agents/* endpoints in CLAUDE.md Review Server table
For provenance purposes, this commit was AI assisted.
* fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup
- Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback
activates correctly on subsequent tab switches
- Remove jobs:cleared broadcast from kill-all — killAll() already fires
individual job:completed events, so the UI shows status transitions
instead of going blank
- Store exit handler ref so stop() can removeListener, preventing
accumulation in long-lived hosts (OpenCode, Pi)
For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
|
|
|
// Agent jobs — background process manager (late-binds serverUrl via getter)
|
|
|
|
|
let serverUrl = "";
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
const resolveAgentCwd = (): string =>
|
|
|
|
|
options.agentCwd ?? resolveVcsCwd(currentDiffType, gitContext?.cwd) ?? process.cwd();
|
feat: agentic review — background job runner with SSE streaming (#443)
* feat(server): add agent job manager with process lifecycle and SSE streaming
Introduces the backend for agentic review — a server-agnostic job runner
that spawns agent processes, monitors their lifecycle via proc.exited, and
broadcasts status updates over a dedicated SSE stream.
New files:
- packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine
- packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes
Wired into the review server with late-bound serverUrl, killAll on stop
and process exit for defense-in-depth cleanup. Capability detection via
Bun.which() for Claude Code, Codex CLI, and shell.
For provenance purposes, this commit was AI assisted.
* feat(ui): add Review Agents tab with job management and live status
Adds the client-side UI for agentic review:
- useAgentJobs hook: SSE primary with polling fallback, capabilities fetch
- AgentsTab: shared component with provider dropdown, job cards, kill controls
- ReviewAgentsIcon: magnifying glass with cog icon
- ReviewPanel: new "Review Agents" tab conditional on detected capabilities
- App.tsx: initializes hook and passes props to ReviewPanel
Jobs show live elapsed time, status badges, annotation counts per source,
and expandable error details. Stub command (sleep 10-30s) for initial testing.
For provenance purposes, this commit was AI assisted.
* fix(server): narrow proc.stderr type to satisfy TS
Bun types proc.stderr as ReadableStream | number. Add typeof guard
to narrow before passing to Response constructor.
For provenance purposes, this commit was AI assisted.
* fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch
- Change stdout from "pipe" to "ignore" — agents post findings via the
annotations API, not stdout. Unconsumed pipe buffer caused deadlock.
- Drain stderr continuously instead of reading after exit — prevents
pipe-full stall on chatty agents.
- Make agent getCwd worktree-aware using the same currentDiffType check
the AI endpoints use, so agents spawn in the correct checkout.
- Exclude 'agents' tab from PR context fetch guard in ReviewPanel.
For provenance purposes, this commit was AI assisted.
* feat(pi): mirror agent-job endpoints in Pi review server
Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun
agent-jobs handler using child_process.spawn, res.write() SSE, and
execFileSync for capability detection.
Wire into serverReview.ts: route delegation, killAll in stop(),
process.on("exit") guard, worktree-aware getCwd, and serverUrl
late-binding. Add agent-jobs to vendor.sh for shared type vendoring.
For provenance purposes, this commit was AI assisted.
* fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs
- Use process.once instead of process.on to prevent exit listener accumulation
- Validate provider against known capabilities before spawning (rejects unknown providers)
- Use platform-aware which/where for CLI detection on Windows
- Broadcast jobs:cleared event from kill-all endpoint (was dead client code)
- Document all /api/agents/* endpoints in CLAUDE.md Review Server table
For provenance purposes, this commit was AI assisted.
* fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup
- Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback
activates correctly on subsequent tab switches
- Remove jobs:cleared broadcast from kill-all — killAll() already fires
individual job:completed events, so the UI shows status transitions
instead of going blank
- Store exit handler ref so stop() can removeListener, preventing
accumulation in long-lived hosts (OpenCode, Pi)
For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
|
|
|
const agentJobs = createAgentJobHandler({
|
|
|
|
|
mode: "review",
|
|
|
|
|
getServerUrl: () => serverUrl,
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
getCwd: resolveAgentCwd,
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
async buildCommand(provider, config) {
|
|
|
|
|
const cwd = resolveAgentCwd();
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
const hasAgentLocalAccess = !!options.agentCwd || !!gitContext;
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
const userMessageOptions = { defaultBranch: gitContext?.defaultBranch, hasLocalAccess: hasAgentLocalAccess };
|
|
|
|
|
|
|
|
|
|
if (provider === "tour") {
|
|
|
|
|
return tour.buildCommand({
|
|
|
|
|
cwd,
|
|
|
|
|
patch: currentPatch,
|
|
|
|
|
diffType: currentDiffType,
|
|
|
|
|
options: userMessageOptions,
|
|
|
|
|
prMetadata,
|
|
|
|
|
config,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const userMessage = buildCodexReviewUserMessage(currentPatch, currentDiffType, userMessageOptions, prMetadata);
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
|
|
|
|
|
if (provider === "codex") {
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
const model = typeof config?.model === "string" && config.model ? config.model : undefined;
|
|
|
|
|
const reasoningEffort = typeof config?.reasoningEffort === "string" && config.reasoningEffort ? config.reasoningEffort : undefined;
|
|
|
|
|
const fastMode = config?.fastMode === true;
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
const outputPath = generateOutputPath();
|
|
|
|
|
const prompt = CODEX_REVIEW_SYSTEM_PROMPT + "\n\n---\n\n" + userMessage;
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
const command = await buildCodexCommand({ cwd, outputPath, prompt, model, reasoningEffort, fastMode });
|
|
|
|
|
return { command, outputPath, prompt, label: "Code Review", model, reasoningEffort, fastMode: fastMode || undefined };
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (provider === "claude") {
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
const model = typeof config?.model === "string" && config.model ? config.model : undefined;
|
|
|
|
|
const effort = typeof config?.effort === "string" && config.effort ? config.effort : undefined;
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
const prompt = CLAUDE_REVIEW_PROMPT + "\n\n---\n\n" + userMessage;
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
const { command, stdinPrompt } = buildClaudeCommand(prompt, model, effort);
|
|
|
|
|
return { command, stdinPrompt, prompt, cwd, label: "Code Review", captureStdout: true, model, effort };
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
async onJobComplete(job, meta) {
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
const cwd = resolveAgentCwd();
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
|
|
|
|
|
// --- Codex path ---
|
|
|
|
|
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,
|
|
|
|
|
explanation: output.overall_explanation,
|
|
|
|
|
confidence: output.overall_confidence_score,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (output.findings.length > 0) {
|
|
|
|
|
const annotations = transformReviewFindings(output.findings, job.source, cwd, "Codex");
|
|
|
|
|
const result = externalAnnotations.addAnnotations({ annotations });
|
|
|
|
|
if ("error" in result) console.error(`[codex-review] addAnnotations error:`, result.error);
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- Claude path ---
|
|
|
|
|
if (job.provider === "claude" && meta.stdout) {
|
|
|
|
|
const output = parseClaudeStreamOutput(meta.stdout);
|
|
|
|
|
if (!output) {
|
|
|
|
|
console.error(`[claude-review] Failed to parse output (${meta.stdout.length} bytes, last 200: ${meta.stdout.slice(-200)})`);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const total = output.summary.important + output.summary.nit + output.summary.pre_existing;
|
|
|
|
|
job.summary = {
|
|
|
|
|
correctness: output.summary.important === 0 ? "Correct" : "Issues Found",
|
|
|
|
|
explanation: `${output.summary.important} important, ${output.summary.nit} nit, ${output.summary.pre_existing} pre-existing`,
|
|
|
|
|
confidence: total === 0 ? 1.0 : Math.max(0, 1.0 - (output.summary.important * 0.2)),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (output.findings.length > 0) {
|
|
|
|
|
const annotations = transformClaudeFindings(output.findings, job.source, cwd);
|
|
|
|
|
const result = externalAnnotations.addAnnotations({ annotations });
|
|
|
|
|
if ("error" in result) console.error(`[claude-review] addAnnotations error:`, result.error);
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
|
|
|
|
|
// --- Tour path ---
|
|
|
|
|
if (job.provider === "tour") {
|
|
|
|
|
const { summary } = await tour.onJobComplete({ job, meta });
|
|
|
|
|
if (summary) {
|
|
|
|
|
job.summary = summary;
|
|
|
|
|
} else {
|
|
|
|
|
// The process exited 0 but the model returned empty or malformed output
|
|
|
|
|
// and nothing was stored. Flip status so the client doesn't auto-open
|
|
|
|
|
// a successful-looking card that 404s on /api/tour/:id.
|
|
|
|
|
job.status = "failed";
|
|
|
|
|
job.error = TOUR_EMPTY_OUTPUT_ERROR;
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
},
|
feat: agentic review — background job runner with SSE streaming (#443)
* feat(server): add agent job manager with process lifecycle and SSE streaming
Introduces the backend for agentic review — a server-agnostic job runner
that spawns agent processes, monitors their lifecycle via proc.exited, and
broadcasts status updates over a dedicated SSE stream.
New files:
- packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine
- packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes
Wired into the review server with late-bound serverUrl, killAll on stop
and process exit for defense-in-depth cleanup. Capability detection via
Bun.which() for Claude Code, Codex CLI, and shell.
For provenance purposes, this commit was AI assisted.
* feat(ui): add Review Agents tab with job management and live status
Adds the client-side UI for agentic review:
- useAgentJobs hook: SSE primary with polling fallback, capabilities fetch
- AgentsTab: shared component with provider dropdown, job cards, kill controls
- ReviewAgentsIcon: magnifying glass with cog icon
- ReviewPanel: new "Review Agents" tab conditional on detected capabilities
- App.tsx: initializes hook and passes props to ReviewPanel
Jobs show live elapsed time, status badges, annotation counts per source,
and expandable error details. Stub command (sleep 10-30s) for initial testing.
For provenance purposes, this commit was AI assisted.
* fix(server): narrow proc.stderr type to satisfy TS
Bun types proc.stderr as ReadableStream | number. Add typeof guard
to narrow before passing to Response constructor.
For provenance purposes, this commit was AI assisted.
* fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch
- Change stdout from "pipe" to "ignore" — agents post findings via the
annotations API, not stdout. Unconsumed pipe buffer caused deadlock.
- Drain stderr continuously instead of reading after exit — prevents
pipe-full stall on chatty agents.
- Make agent getCwd worktree-aware using the same currentDiffType check
the AI endpoints use, so agents spawn in the correct checkout.
- Exclude 'agents' tab from PR context fetch guard in ReviewPanel.
For provenance purposes, this commit was AI assisted.
* feat(pi): mirror agent-job endpoints in Pi review server
Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun
agent-jobs handler using child_process.spawn, res.write() SSE, and
execFileSync for capability detection.
Wire into serverReview.ts: route delegation, killAll in stop(),
process.on("exit") guard, worktree-aware getCwd, and serverUrl
late-binding. Add agent-jobs to vendor.sh for shared type vendoring.
For provenance purposes, this commit was AI assisted.
* fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs
- Use process.once instead of process.on to prevent exit listener accumulation
- Validate provider against known capabilities before spawning (rejects unknown providers)
- Use platform-aware which/where for CLI detection on Windows
- Broadcast jobs:cleared event from kill-all endpoint (was dead client code)
- Document all /api/agents/* endpoints in CLAUDE.md Review Server table
For provenance purposes, this commit was AI assisted.
* fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup
- Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback
activates correctly on subsequent tab switches
- Remove jobs:cleared broadcast from kill-all — killAll() already fires
individual job:completed events, so the UI shows status transitions
instead of going blank
- Store exit handler ref so stop() can removeListener, preventing
accumulation in long-lived hosts (OpenCode, Pi)
For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
|
|
|
});
|
|
|
|
|
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
// AI provider setup (graceful — AI features degrade if SDK unavailable)
|
|
|
|
|
const aiRegistry = new ProviderRegistry();
|
|
|
|
|
const aiSessionManager = new SessionManager();
|
|
|
|
|
let aiEndpoints: AIEndpoints | null = null;
|
|
|
|
|
|
|
|
|
|
// Try Claude Agent SDK
|
|
|
|
|
try {
|
|
|
|
|
await import("@plannotator/ai/providers/claude-agent-sdk");
|
|
|
|
|
const claudePath = Bun.which("claude");
|
|
|
|
|
const provider = await createProvider({
|
|
|
|
|
type: "claude-agent-sdk",
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
...(claudePath && { claudeExecutablePath: claudePath }),
|
|
|
|
|
});
|
|
|
|
|
aiRegistry.register(provider);
|
|
|
|
|
} catch {
|
|
|
|
|
// Claude SDK not available
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Try Codex SDK
|
|
|
|
|
try {
|
|
|
|
|
await import("@plannotator/ai/providers/codex-sdk");
|
|
|
|
|
// Eagerly verify the SDK is importable so we don't advertise a broken provider.
|
|
|
|
|
await import("@openai/codex-sdk");
|
|
|
|
|
const codexPath = Bun.which("codex");
|
|
|
|
|
const provider = await createProvider({
|
|
|
|
|
type: "codex-sdk",
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
...(codexPath && { codexExecutablePath: codexPath }),
|
|
|
|
|
});
|
|
|
|
|
aiRegistry.register(provider);
|
|
|
|
|
} catch {
|
|
|
|
|
// Codex SDK not available
|
|
|
|
|
}
|
|
|
|
|
|
feat(ai): Pi provider via RPC subprocess (#377)
* refactor(ai): extract BaseSession and buildEffectivePrompt
Pull shared session lifecycle (~80 lines duplicated across Claude and
Codex providers) into BaseSession: query guard, abort, ID resolution,
generation counter. Extract first-query prompt prepending into
buildEffectivePrompt() in context.ts.
Both providers now extend BaseSession. Behavior-preserving — all 54
existing tests pass unchanged.
For provenance purposes, this commit was AI assisted.
* feat(ai): add Pi provider via RPC subprocess
Spawns `pi --mode rpc` and communicates via JSONL over stdio. No Pi SDK
bundled — user must have the pi CLI installed. Provider auto-discovers
available models at startup via get_available_models.
Includes: PiProcess (JSONL client), PiSDKProvider, PiSDKSession extending
BaseSession, mapPiEvent for streaming, Pi icon in provider UI, and 12
new tests (9 event mapping + 3 buildEffectivePrompt).
For provenance purposes, this commit was AI assisted.
* fix(ai): harden Pi provider error paths
- Surface startup errors when Pi process dies (bad config, missing API keys)
instead of hanging the chat indefinitely
- Map tool-call errors as non-terminal tool_result instead of AIErrorMessage,
so Pi can continue reasoning after a failed tool call
- Fix subprocess leak in fetchModels() by moving proc.kill() to finally block
For provenance purposes, this commit was AI assisted.
* fix(ai): detect Pi prompt rejections and process crashes
- Use sendAndWait for prompt command so RPC-level rejections (expired
credentials, invalid session) surface as errors instead of hanging
- Emit process_exited instead of synthetic agent_end when Pi subprocess
dies, so crashes show as errors instead of silent empty successes
For provenance purposes, this commit was AI assisted.
* docs(ai): add Pi to AI features guide, code review docs, and installation
For provenance purposes, this commit was AI assisted.
* style(ai): apply biome formatting to new files
For provenance purposes, this commit was AI assisted.
2026-03-23 15:50:30 -07:00
|
|
|
// Try Pi
|
|
|
|
|
try {
|
|
|
|
|
const { PiSDKProvider } = await import("@plannotator/ai/providers/pi-sdk");
|
|
|
|
|
const piPath = Bun.which("pi");
|
|
|
|
|
if (piPath) {
|
|
|
|
|
const provider = await createProvider({
|
|
|
|
|
type: "pi-sdk",
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
piExecutablePath: piPath,
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
} as PiSDKConfig);
|
feat(ai): Pi provider via RPC subprocess (#377)
* refactor(ai): extract BaseSession and buildEffectivePrompt
Pull shared session lifecycle (~80 lines duplicated across Claude and
Codex providers) into BaseSession: query guard, abort, ID resolution,
generation counter. Extract first-query prompt prepending into
buildEffectivePrompt() in context.ts.
Both providers now extend BaseSession. Behavior-preserving — all 54
existing tests pass unchanged.
For provenance purposes, this commit was AI assisted.
* feat(ai): add Pi provider via RPC subprocess
Spawns `pi --mode rpc` and communicates via JSONL over stdio. No Pi SDK
bundled — user must have the pi CLI installed. Provider auto-discovers
available models at startup via get_available_models.
Includes: PiProcess (JSONL client), PiSDKProvider, PiSDKSession extending
BaseSession, mapPiEvent for streaming, Pi icon in provider UI, and 12
new tests (9 event mapping + 3 buildEffectivePrompt).
For provenance purposes, this commit was AI assisted.
* fix(ai): harden Pi provider error paths
- Surface startup errors when Pi process dies (bad config, missing API keys)
instead of hanging the chat indefinitely
- Map tool-call errors as non-terminal tool_result instead of AIErrorMessage,
so Pi can continue reasoning after a failed tool call
- Fix subprocess leak in fetchModels() by moving proc.kill() to finally block
For provenance purposes, this commit was AI assisted.
* fix(ai): detect Pi prompt rejections and process crashes
- Use sendAndWait for prompt command so RPC-level rejections (expired
credentials, invalid session) surface as errors instead of hanging
- Emit process_exited instead of synthetic agent_end when Pi subprocess
dies, so crashes show as errors instead of silent empty successes
For provenance purposes, this commit was AI assisted.
* docs(ai): add Pi to AI features guide, code review docs, and installation
For provenance purposes, this commit was AI assisted.
* style(ai): apply biome formatting to new files
For provenance purposes, this commit was AI assisted.
2026-03-23 15:50:30 -07:00
|
|
|
if (provider instanceof PiSDKProvider) {
|
|
|
|
|
await provider.fetchModels();
|
|
|
|
|
}
|
|
|
|
|
aiRegistry.register(provider);
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// Pi not available
|
|
|
|
|
}
|
|
|
|
|
|
feat(ai): OpenCode provider via HTTP + SSE (#379)
* feat(ai): add OpenCode provider via HTTP + SSE
Bundle @opencode-ai/sdk to spawn `opencode serve` and communicate via
HTTP REST + SSE. Richest provider: fork, resume, streaming, tools, and
runtime permission approvals all work natively.
- OpenCodeProvider: lazy server spawn, shared HTTP client, dynamic model
discovery via GET /provider
- OpenCodeSession: SSE event drain loop, system prompt via API field,
permission reply (once/reject), abort via HTTP
- mapOpenCodeEvent: SSE → AIMessage mapping (text deltas, tool lifecycle,
permissions, session status, errors)
- 11 new event mapping tests (78 total, 157 expect calls)
For provenance purposes, this commit was AI assisted.
* docs(ai): add OpenCode to AI features guide and code review docs
For provenance purposes, this commit was AI assisted.
* fix(ai): prevent double server spawn in OpenCode ensureServer()
Use a promise-mutex pattern so concurrent callers (e.g. fetchModels +
createSession) share a single server spawn instead of racing to create two.
Also remove empty finally block from SSE drain loop.
For provenance purposes, this commit was AI assisted.
* fix(ai): await SSE subscribe in OpenCode provider
The SDK's event.subscribe() is async — must be awaited before
destructuring the stream.
For provenance purposes, this commit was AI assisted.
* fix(ui): scrollable model dropdown with search filter
Cap dropdown height at min(320px, 50vh) so it doesn't overflow the
viewport when providers expose many models (e.g. OpenCode with 20+).
Add a search/filter input when there are more than 8 models.
For provenance purposes, this commit was AI assisted.
* fix(ai): close SSE stream, rename to opencode-sdk, move dep to root
- Close SSE stream in finally block to prevent connection leak on
abort/early return
- Rename provider from opencode to opencode-sdk for consistency with
claude-agent-sdk, codex-sdk, pi-sdk
- Move @opencode-ai/sdk dependency to root package.json alongside the
other SDK dependencies
For provenance purposes, this commit was AI assisted.
* feat(ui): add first-run AI setup dialog for provider selection
Show a one-time modal on first review when AI providers are available.
Users pick a default provider and model from a 2-column grid, with a
brief feature intro and auth disclaimer. Persists via cookie, can be
changed later in Settings.
For provenance purposes, this commit was AI assisted.
* fix(ai): clear startPromise on failure so OpenCode provider can retry
If doStart() fails (port conflict, timeout, binary crash), the cached
rejected promise prevented all future ensureServer() calls from
retrying. Now cleared on failure and on dispose().
Also updates stale "future" comment in types.ts.
For provenance purposes, this commit was AI assisted.
2026-03-23 17:37:56 -07:00
|
|
|
// Try OpenCode
|
|
|
|
|
try {
|
|
|
|
|
const { OpenCodeProvider } = await import("@plannotator/ai/providers/opencode-sdk");
|
|
|
|
|
const opencodePath = Bun.which("opencode");
|
|
|
|
|
if (opencodePath) {
|
|
|
|
|
const provider = await createProvider({
|
|
|
|
|
type: "opencode-sdk",
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
});
|
|
|
|
|
if (provider instanceof OpenCodeProvider) {
|
|
|
|
|
await provider.fetchModels();
|
|
|
|
|
}
|
|
|
|
|
aiRegistry.register(provider);
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// OpenCode not available
|
|
|
|
|
}
|
|
|
|
|
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
// Create endpoints if any provider registered
|
|
|
|
|
if (aiRegistry.size > 0) {
|
|
|
|
|
aiEndpoints = createAIEndpoints({
|
|
|
|
|
registry: aiRegistry,
|
|
|
|
|
sessionManager: aiSessionManager,
|
|
|
|
|
getCwd: () => {
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
if (options.agentCwd) return options.agentCwd;
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
return resolveVcsCwd(currentDiffType, gitContext?.cwd) ?? process.cwd();
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
const isRemote = isRemoteSession();
|
|
|
|
|
const configuredPort = getServerPort();
|
2026-03-25 15:06:29 -03:00
|
|
|
const wslFlag = await isWSL();
|
2026-03-26 11:54:22 -07:00
|
|
|
const gitUser = detectGitUser();
|
2026-01-12 19:36:09 -08:00
|
|
|
|
2026-01-28 10:29:52 -08:00
|
|
|
// Detect repo info (cached for this session)
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
// In PR mode, derive from metadata instead of local git
|
|
|
|
|
const repoInfo = isPRMode
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
? { display: getDisplayRepo(prMetadata), branch: `${getMRLabel(prMetadata)} ${getMRNumberLabel(prMetadata)}` }
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
: await getRepoInfo();
|
2026-01-28 10:29:52 -08:00
|
|
|
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
// Fetch current platform user (for own-PR/MR detection)
|
|
|
|
|
const prRef = isPRMode ? prRefFromMetadata(prMetadata) : null;
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
const platformUser = prRef ? await getPRUser(prRef) : null;
|
2026-03-21 00:48:26 +01:00
|
|
|
|
2026-03-25 21:33:33 +01:00
|
|
|
// Fetch GitHub viewed file state (non-blocking — errors are silently ignored)
|
|
|
|
|
let initialViewedFiles: string[] = [];
|
|
|
|
|
if (isPRMode && prRef) {
|
|
|
|
|
try {
|
|
|
|
|
const viewedMap = await fetchPRViewedFiles(prRef);
|
|
|
|
|
initialViewedFiles = Object.entries(viewedMap)
|
|
|
|
|
.filter(([, isViewed]) => isViewed)
|
|
|
|
|
.map(([path]) => path);
|
2026-03-30 10:51:27 -07:00
|
|
|
} catch {
|
2026-03-25 21:33:33 +01:00
|
|
|
// Non-fatal: viewed state is best-effort
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// Decision promise
|
|
|
|
|
let resolveDecision: (result: {
|
2026-03-14 17:58:57 -07:00
|
|
|
approved: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: string;
|
|
|
|
|
annotations: unknown[];
|
|
|
|
|
agentSwitch?: string;
|
2026-04-10 03:22:01 +01:00
|
|
|
exit?: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
}) => void;
|
|
|
|
|
const decisionPromise = new Promise<{
|
2026-03-14 17:58:57 -07:00
|
|
|
approved: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: string;
|
|
|
|
|
annotations: unknown[];
|
|
|
|
|
agentSwitch?: string;
|
2026-04-10 03:22:01 +01:00
|
|
|
exit?: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
}>((resolve) => {
|
|
|
|
|
resolveDecision = resolve;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Start server with retry logic
|
|
|
|
|
let server: ReturnType<typeof Bun.serve> | null = null;
|
|
|
|
|
|
|
|
|
|
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
|
|
|
|
try {
|
|
|
|
|
server = Bun.serve({
|
2026-04-13 23:00:05 +09:00
|
|
|
hostname: getServerHostname(),
|
2026-01-12 19:36:09 -08:00
|
|
|
port: configuredPort,
|
|
|
|
|
|
2026-03-31 00:49:34 +09:00
|
|
|
async fetch(req, server) {
|
2026-01-12 19:36:09 -08:00
|
|
|
const url = new URL(req.url);
|
|
|
|
|
|
feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider
Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.
- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
(file output) command builders, and parsers for both. Prompt frames
the agent as a colleague giving a casual tour, orders stops by reading
flow (not impact), chunks by logical change (not per-file), and writes
QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
bug where Codex was defaulting to "sonnet", a Claude model), an
onJobComplete handler that parses and stores the tour, plus GET
/api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
can render tour jobs with their chosen provider + model.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): Code Tour dialog with animated walkthrough
Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.
- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
uses a composition cascade (greeting, Intent/Before/After cards with
one-shot color-dot pulse, key takeaways table) with a pinned Start
Tour button and a bottom fade so content scrolls cleanly under it.
Page slides between Overview/Walkthrough/Checklist are ease-out
springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
AnimatePresence for height + opacity springs with staggered children
for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
on first open to keep mount costs low. Callout labels (Important,
Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
questions with per-item spring entrance and persistent checkbox state
that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
contrast tuning across structural surfaces (borders, surface tints,
callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
and the intro composition cascade.
For provenance purposes, this commit was AI assisted.
* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview
Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.
- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
when launching a tour job. Resets model to blank when falling back to
Codex-only so Codex uses its own default instead of inheriting
"sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
through to the POST /api/agents/jobs body so the server's tour
provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
Replaces the "Findings" tab with a "Status" card for tour jobs and
surfaces an "Open Tour" button that opens the dialog overlay when
the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
useState lazy initializer so the first render (inside a tooltip) is
already themed; robust hunk parser that handles bare @@ hunks, file-
level --- hunks, and full git diffs; "Diff not available" fallback
for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
wiring changes to expose openTourPanel from the review state context.
Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.
For provenance purposes, this commit was AI assisted.
* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity
The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).
A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.
Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.
- tour-review.ts: new createTourSession() at the bottom of the module.
Encapsulates tourResults + tourChecklists maps, buildCommand (with
the Claude-vs-Codex model-default fix baked in), onJobComplete
(parse/store/summarize), plus getTour/saveChecklist lookup helpers
for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
onJobComplete, and both route handlers collapse to one-line calls
into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
../generated/tour-review.js; add tour branch to buildCommand (one
line), tour branch to onJobComplete (three lines), and GET/PUT route
handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
and return engine/model; thread config from POST body; extend
spawnJob to persist engine/model on AgentJobInfo; add tour to
capability list.
Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.
Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).
For provenance purposes, this commit was AI assisted.
* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim
Two small cleanups surfaced by a self-review pass:
- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
the checklist sub-route, while Bun uses `includes("/", ...)`. The two
are not equivalent: a URL like /api/tour/abc/extra would be accepted
by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
local to the card. State is now lifted to TourDialog, so the shim
just aliases onToggle and ignores its argument. Replace with a
direct `onClick={onToggle}` on the trigger button.
520/0 tests still pass.
For provenance purposes, this commit was AI assisted.
* feat(review): per-provider model + effort controls across all review agents
Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.
UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.
Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.
For provenance purposes, this commit was AI assisted.
* docs: add Prompts reference page
Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).
Linked from the Code Review command page.
For provenance purposes, this commit was AI assisted.
* feat(review): persist per-agent, per-model settings in a single cookie
Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.
Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.
For provenance purposes, this commit was AI assisted.
* fix(tour): unblock reduced-motion nav + flush pending checklist save on close
Two P2 issues surfaced in review:
- Under prefers-reduced-motion, tour page animations are suppressed, so
onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
walkthrough/checklist gated out. navigate() now swaps pages directly when
reduced motion is on, mirroring the pattern already used in the wrapper.
- Checklist toggles are debounced 500ms before the PUT, but unmount only
cleared the timer — checking an item and closing within the window dropped
the save. Cleanup now flushes the pending payload with keepalive: true.
For provenance purposes, this commit was AI assisted.
* feat(review): surface Claude model + effort in job badge, trim redundant labels
Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.
Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.
For provenance purposes, this commit was AI assisted.
* polish(review): prefix agent dropdown options with the action name
The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.
For provenance purposes, this commit was AI assisted.
* fix(review): drop invalid codex reasoning option + fail tour on empty output
Two P2 issues from PR review:
- Tour jobs exited 0 but returned null output would still be marked "done",
and the auto-open watcher would greet the user with a 404 "Tour not found"
dialog. onJobComplete now flips the job to failed with an error message
when nothing was stored, so the card reflects the real state.
- The codex reasoning dropdown offered "None", but codex-rs only accepts
minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
and launched a broken job. Removed the option; added a one-shot cookie
migration so users who already saved "none" don't keep shipping it.
For provenance purposes, this commit was AI assisted.
* fix(tour): format Claude-engine logs + allow reading linked issues
Two P2/P3 issues from PR review:
- The stdout formatter keyed only on provider === "claude", so Code Tour
jobs running on the Claude engine streamed raw JSONL to the log panel
while Claude review jobs got formatted text. Widened the check to also
catch spawnOptions.engine === "claude" and mirrored the fix into Pi.
- The tour Claude allowlist permitted PR/MR commands but not issue reads,
yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
owner/repo#456` targets for deeper context. Claude was being denied
those commands mid-tour. Added gh issue view + gh api issues + glab
issue view to the allowlist.
For provenance purposes, this commit was AI assisted.
* cleanup(review): e2e punchlist — Pi parity + dedup + tests
- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
perModel sanitizer
For provenance purposes, this commit was AI assisted.
* test(tour-review): use real TourStop shape in fixtures
The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.
For provenance purposes, this commit was AI assisted.
* cleanup(tour): hoist shared types + subfolder server module + dedup
- Hoist tour output types to packages/shared/tour.ts so server and UI
share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
diffType, options, prMetadata), so Bun and Pi no longer duplicate the
buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
is built once on the shared non-tour path instead of unconditionally
(dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
helper; memoize intro-page card array so unrelated state churn doesn't
recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
added by this PR; keep non-obvious WHY.
For provenance purposes, this commit was AI assisted.
* fix(tour): hoist introCards useMemo above early returns + subfolder hook
The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.
Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).
For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
|
|
|
// API: Get tour result
|
|
|
|
|
if (url.pathname.match(/^\/api\/tour\/[^/]+$/) && req.method === "GET") {
|
|
|
|
|
const jobId = url.pathname.slice("/api/tour/".length);
|
|
|
|
|
const result = tour.getTour(jobId);
|
|
|
|
|
if (!result) return Response.json({ error: "Tour not found" }, { status: 404 });
|
|
|
|
|
return Response.json(result);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// API: Save tour checklist state
|
|
|
|
|
const checklistMatch = url.pathname.match(/^\/api\/tour\/([^/]+)\/checklist$/);
|
|
|
|
|
if (checklistMatch && req.method === "PUT") {
|
|
|
|
|
const jobId = checklistMatch[1];
|
|
|
|
|
try {
|
|
|
|
|
const body = await req.json() as { checked: boolean[] };
|
|
|
|
|
if (Array.isArray(body.checked)) tour.saveChecklist(jobId, body.checked);
|
|
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
} catch {
|
|
|
|
|
return Response.json({ error: "Invalid JSON" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// API: Get diff content
|
|
|
|
|
if (url.pathname === "/api/diff" && req.method === "GET") {
|
|
|
|
|
return Response.json({
|
|
|
|
|
rawPatch: currentPatch,
|
|
|
|
|
gitRef: currentGitRef,
|
|
|
|
|
origin,
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
diffType: hasLocalAccess ? currentDiffType : undefined,
|
|
|
|
|
gitContext: hasLocalAccess ? gitContext : undefined,
|
2026-01-14 13:12:37 -08:00
|
|
|
sharingEnabled,
|
2026-02-12 15:07:43 -08:00
|
|
|
shareBaseUrl,
|
2026-01-28 10:29:52 -08:00
|
|
|
repoInfo,
|
2026-03-25 15:06:29 -03:00
|
|
|
isWSL: wslFlag,
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
...(options.agentCwd && { agentCwd: options.agentCwd }),
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
...(isPRMode && { prMetadata, platformUser }),
|
2026-03-25 21:33:33 +01:00
|
|
|
...(isPRMode && initialViewedFiles.length > 0 && { viewedFiles: initialViewedFiles }),
|
2026-03-02 15:26:07 +09:00
|
|
|
...(currentError && { error: currentError }),
|
2026-03-26 11:54:22 -07:00
|
|
|
serverConfig: getServerConfig(gitUser),
|
2026-01-12 19:36:09 -08:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
// API: Switch diff type (requires local file access)
|
2026-01-12 19:36:09 -08:00
|
|
|
if (url.pathname === "/api/diff/switch" && req.method === "POST") {
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
if (!hasLocalAccess) {
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
return Response.json(
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
{ error: "Not available without local file access" },
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
{ status: 400 },
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-01-12 19:36:09 -08:00
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as { diffType: DiffType };
|
2026-03-07 10:06:55 -08:00
|
|
|
let newDiffType = body.diffType;
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
if (!newDiffType) {
|
|
|
|
|
return Response.json(
|
|
|
|
|
{ error: "Missing diffType" },
|
|
|
|
|
{ status: 400 }
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const defaultBranch = gitContext?.defaultBranch || "main";
|
2026-03-17 20:29:09 -04:00
|
|
|
const defaultCwd = gitContext?.cwd;
|
2026-03-07 10:06:55 -08:00
|
|
|
|
|
|
|
|
// Run the new diff
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
const result = await runVcsDiff(newDiffType, defaultBranch, defaultCwd);
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
// Update state
|
|
|
|
|
currentPatch = result.patch;
|
|
|
|
|
currentGitRef = result.label;
|
|
|
|
|
currentDiffType = newDiffType;
|
2026-03-02 15:26:07 +09:00
|
|
|
currentError = result.error;
|
2026-01-12 19:36:09 -08:00
|
|
|
|
2026-03-08 16:15:14 -07:00
|
|
|
return Response.json({
|
2026-01-12 19:36:09 -08:00
|
|
|
rawPatch: currentPatch,
|
|
|
|
|
gitRef: currentGitRef,
|
|
|
|
|
diffType: currentDiffType,
|
2026-03-02 15:26:07 +09:00
|
|
|
...(currentError && { error: currentError }),
|
2026-03-08 16:15:14 -07:00
|
|
|
});
|
2026-01-12 19:36:09 -08:00
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to switch diff";
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
feat(review): PR context panel — summary, comments, and checks (#350)
* feat(review): add PR context panel with summary, comments, and checks tabs
When reviewing a GitHub PR, the ReviewPanel now shows icon tabs for
Summary (PR body, labels, linked issues), Comments (chronological
thread of comments + reviews), and Checks (CI status, merge readiness).
Tabs only appear in PR mode; local review is unchanged.
Data fetched lazily via new /api/pr-context endpoint on first tab click.
Uses DOMPurify for safe HTML rendering of GitHub markdown content.
Inline markdown renderer extended with link and bare URL support.
Closes #348
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): reset fetch guard on error and detect inline HTML in PR bodies
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 23:14:21 -07:00
|
|
|
// API: Fetch PR context (comments, checks, merge status) — PR mode only
|
|
|
|
|
if (url.pathname === "/api/pr-context" && req.method === "GET") {
|
|
|
|
|
if (!isPRMode) {
|
|
|
|
|
return Response.json(
|
|
|
|
|
{ error: "Not in PR mode" },
|
|
|
|
|
{ status: 400 },
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
try {
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
const context = await fetchPRContext(prRef!);
|
feat(review): PR context panel — summary, comments, and checks (#350)
* feat(review): add PR context panel with summary, comments, and checks tabs
When reviewing a GitHub PR, the ReviewPanel now shows icon tabs for
Summary (PR body, labels, linked issues), Comments (chronological
thread of comments + reviews), and Checks (CI status, merge readiness).
Tabs only appear in PR mode; local review is unchanged.
Data fetched lazily via new /api/pr-context endpoint on first tab click.
Uses DOMPurify for safe HTML rendering of GitHub markdown content.
Inline markdown renderer extended with link and bare URL support.
Closes #348
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): reset fetch guard on error and detect inline HTML in PR bodies
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 23:14:21 -07:00
|
|
|
return Response.json(context);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to fetch PR context";
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-08 14:00:43 -07:00
|
|
|
// API: Get file content for expandable diff context
|
|
|
|
|
if (url.pathname === "/api/file-content" && req.method === "GET") {
|
|
|
|
|
const filePath = url.searchParams.get("path");
|
|
|
|
|
if (!filePath) {
|
|
|
|
|
return Response.json({ error: "Missing path" }, { status: 400 });
|
|
|
|
|
}
|
2026-03-09 07:31:17 -07:00
|
|
|
try { validateFilePath(filePath); } catch {
|
2026-03-08 14:00:43 -07:00
|
|
|
return Response.json({ error: "Invalid path" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
const oldPath = url.searchParams.get("oldPath") || undefined;
|
2026-03-09 07:31:17 -07:00
|
|
|
if (oldPath) {
|
|
|
|
|
try { validateFilePath(oldPath); } catch {
|
|
|
|
|
return Response.json({ error: "Invalid path" }, { status: 400 });
|
|
|
|
|
}
|
2026-03-08 14:00:43 -07:00
|
|
|
}
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
// Local review: read file contents from local git
|
|
|
|
|
if (hasLocalAccess) {
|
|
|
|
|
const defaultBranch = gitContext?.defaultBranch || "main";
|
|
|
|
|
const defaultCwd = gitContext?.cwd;
|
|
|
|
|
const result = await getVcsFileContentsForDiff(
|
|
|
|
|
currentDiffType,
|
|
|
|
|
defaultBranch,
|
|
|
|
|
filePath,
|
|
|
|
|
oldPath,
|
|
|
|
|
defaultCwd,
|
|
|
|
|
);
|
|
|
|
|
return Response.json(result);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-06 13:05:30 -07:00
|
|
|
// PR mode: fetch from platform API using merge-base/head SHAs.
|
|
|
|
|
// The diff is computed against the merge-base (common ancestor), not the
|
|
|
|
|
// base branch tip. File contents must match the diff for hunk expansion.
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
if (isPRMode) {
|
2026-04-06 13:05:30 -07:00
|
|
|
const oldSha = prMetadata.mergeBaseSha ?? prMetadata.baseSha;
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
const [oldContent, newContent] = await Promise.all([
|
2026-04-06 13:05:30 -07:00
|
|
|
fetchPRFileContent(prRef!, oldSha, oldPath || filePath),
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
fetchPRFileContent(prRef!, prMetadata.headSha, filePath),
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
]);
|
|
|
|
|
return Response.json({ oldContent, newContent });
|
|
|
|
|
}
|
|
|
|
|
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
return Response.json({ error: "No file access available" }, { status: 400 });
|
2026-03-08 14:00:43 -07:00
|
|
|
}
|
|
|
|
|
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
// API: Stage / unstage a file (disabled when VCS doesn't support it)
|
2026-03-09 07:31:17 -07:00
|
|
|
if (url.pathname === "/api/git-add" && req.method === "POST") {
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
if (isPRMode || !canStageFiles(currentDiffType)) {
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
return Response.json(
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
{ error: "Staging not available" },
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
{ status: 400 },
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-03-09 07:31:17 -07:00
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as { filePath: string; undo?: boolean };
|
|
|
|
|
if (!body.filePath) {
|
|
|
|
|
return Response.json({ error: "Missing filePath" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
const cwd = resolveVcsCwd(currentDiffType, gitContext?.cwd);
|
2026-03-09 07:31:17 -07:00
|
|
|
|
|
|
|
|
if (body.undo) {
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
await unstageFile(currentDiffType, body.filePath, cwd);
|
2026-03-09 07:31:17 -07:00
|
|
|
} else {
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
await stageFile(currentDiffType, body.filePath, cwd);
|
2026-03-09 07:31:17 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
} catch (err) {
|
feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review
Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.
- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: introduce VcsProvider interface for extensible VCS support
Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.
- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints
Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
|
|
|
const message = err instanceof Error ? err.message : "Failed to stage file";
|
2026-03-09 07:31:17 -07:00
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-26 11:54:22 -07:00
|
|
|
// API: Update user config (write-back to ~/.plannotator/config.json)
|
|
|
|
|
if (url.pathname === "/api/config" && req.method === "POST") {
|
|
|
|
|
try {
|
feat: add Conventional Comments support to code review (#501)
* feat: add Conventional Comments support to code review
Add structured label system based on the Conventional Comments spec
(conventionalcomments.org) to the code review annotation toolbar.
- Label picker with 9 default labels (suggestion, nit, question, issue,
praise, thought, note, todo, chore) shown above the comment textarea
- Per-label blocking/non-blocking toggle for labels where severity is
ambiguous (issue, suggestion, todo, chore)
- Labels exported as `**label** (decoration): text` in markdown feedback,
naturally readable on GitHub and machine-parseable
- Label badges shown on inline annotations and sidebar cards
- Settings tab (Comments) with: master on/off toggle, editable label
list with add/remove/rename, per-label blocking decorator toggle,
educational intro with spec link and example output
- Feature is off by default, persisted via config store
- Custom labels supported via settings (up to 12)
For provenance purposes, this commit was AI assisted.
* fix(review): address conventional comments review feedback
Fix label clearing bug where editing an annotation to remove its
conventional label silently preserved the old value. Fix parseCCLabels
accepting 'non-blocking' as a truthy blocking value. Fix duplicate
custom label identities when adding multiple labels. Prepend
conventional prefix to platform PR/MR inline comments.
For provenance purposes, this commit was AI assisted.
* fix(server): persist conventionalComments setting to config.json
All six server config handlers (bun plan/review/annotate + pi
plan/review/annotate) now accept and save the conventionalComments
boolean, so the setting survives server restarts.
For provenance purposes, this commit was AI assisted.
* fix: add conventionalComments to server config round-trip
getServerConfig() was not returning the conventionalComments value
from config.json, so the setting silently reset to false on cookie
clear or new browser sessions. Also adds the field to the
PlannotatorConfig interface so saveConfig() is properly typed.
For provenance purposes, this commit was AI assisted.
* fix: label display, export, and draft persistence for conventional comments
- Remove slug derivation from label editing — store display text
verbatim so badges and exports show what the user typed
- Emit conventional prefix in export even when annotation has no
prose text (suggestion-only annotations were losing their label)
- Include conventionalLabel in draft save condition so label
selection persists across file switches
For provenance purposes, this commit was AI assisted.
* fix: spec-compliant export format and empty label support
- Wrap label + decorations + colon in markdown bold per the
Conventional Comments spec examples (was bolding only the label)
- Allow users to clear all labels — empty array no longer falls
back to defaults in either the picker or the settings parser
- Enable blocking decorator on the question label by default; the
spec permits blocking questions and they sometimes are critical
For provenance purposes, this commit was AI assisted.
* fix: server-sync conventionalLabels and small cleanups
- Sync conventionalLabels to ~/.plannotator/config.json so custom
label configurations survive cookie clears and remote/SSH
sessions, matching the persistence story for conventionalComments.
Stored as a parsed array on disk; serialized as JSON string in
the local config store to match the cookie format.
- Remove no-op intermediate variable in handleSubmitAnnotation;
pass conventionalLabel/decorations directly with proper coalescing
per call path (edit preserves null, add coalesces to undefined).
- Use index-prefixed key in the picker label list to avoid React
warnings if duplicate labels ever exist.
For provenance purposes, this commit was AI assisted.
2026-04-06 22:27:47 -07:00
|
|
|
const body = (await req.json()) as { displayName?: string; diffOptions?: Record<string, unknown>; conventionalComments?: boolean; conventionalLabels?: unknown[] | null };
|
feat(review): diff display options with ConfigStore integration (#428)
* feat(config): add DiffOptions to PlannotatorConfig with deep-merge support
Extends the server-side config system to support diff display options
namespaced under `diffOptions` in ~/.plannotator/config.json. The
saveConfig deep-merge ensures partial writes (e.g. changing only
overflow) don't clobber sibling keys.
For provenance purposes, this commit was AI assisted.
* feat(server): accept diffOptions in POST /api/config handlers
All six server handlers (plan, review, annotate x Bun + Pi) now
whitelist diffOptions alongside displayName, forwarding it to
saveConfig for deep-merged disk persistence.
For provenance purposes, this commit was AI assisted.
* feat(config): register diff display settings with deep-merge write batching
Adds 6 diff option settings to the ConfigStore registry (diffStyle,
diffOverflow, diffIndicators, diffLineDiffType, diffShowLineNumbers,
diffShowBackground), all synced to disk under the diffOptions namespace.
Fixes write batching for nested server keys — replaces Object.assign
with deepMerge so rapid changes to multiple diff options within the
300ms debounce window don't clobber each other. Includes legacy cookie
migration for the old review-diff-style key.
For provenance purposes, this commit was AI assisted.
* feat(review): wire diff display options through to @pierre/diffs
Migrates diffStyle from raw cookie storage to ConfigStore. Reads all 6
diff options via useConfigValue and forwards them to FileDiff: overflow,
diffIndicators, lineDiffType, disableLineNumbers, disableBackground.
Adds a Scroll/Wrap toolbar toggle alongside the existing Split/Unified
toggle. Disables the custom resizable split dragger in wrap mode since
Pierre manages its own grid layout. Fixes the unsafeCSS grid override
to only target scroll mode, preventing per-character wrapping in split
view.
For provenance purposes, this commit was AI assisted.
* feat(review): add Display tab to review-mode Settings dialog
Adds a Display tab when Settings is in review mode, exposing all 6 diff
options: Diff Style, Line Overflow, Change Indicators, Inline Diff
Granularity, Show Line Numbers, and Show Diff Background. Changes take
effect immediately and persist via ConfigStore (cookie + disk).
Extracts reusable SegmentedControl and ToggleSwitch helpers for the
review display controls.
For provenance purposes, this commit was AI assisted.
* chore: update bun.lock
For provenance purposes, this commit was AI assisted.
* fix(review): reapply search highlights after display option changes
Add new diff display props to the search highlight and scroll-to-match
effect dependency arrays so highlights are restored after Pierre re-renders.
For provenance purposes, this commit was AI assisted.
2026-03-29 13:20:22 -07:00
|
|
|
const toSave: Record<string, unknown> = {};
|
|
|
|
|
if (body.displayName !== undefined) toSave.displayName = body.displayName;
|
|
|
|
|
if (body.diffOptions !== undefined) toSave.diffOptions = body.diffOptions;
|
feat: add Conventional Comments support to code review (#501)
* feat: add Conventional Comments support to code review
Add structured label system based on the Conventional Comments spec
(conventionalcomments.org) to the code review annotation toolbar.
- Label picker with 9 default labels (suggestion, nit, question, issue,
praise, thought, note, todo, chore) shown above the comment textarea
- Per-label blocking/non-blocking toggle for labels where severity is
ambiguous (issue, suggestion, todo, chore)
- Labels exported as `**label** (decoration): text` in markdown feedback,
naturally readable on GitHub and machine-parseable
- Label badges shown on inline annotations and sidebar cards
- Settings tab (Comments) with: master on/off toggle, editable label
list with add/remove/rename, per-label blocking decorator toggle,
educational intro with spec link and example output
- Feature is off by default, persisted via config store
- Custom labels supported via settings (up to 12)
For provenance purposes, this commit was AI assisted.
* fix(review): address conventional comments review feedback
Fix label clearing bug where editing an annotation to remove its
conventional label silently preserved the old value. Fix parseCCLabels
accepting 'non-blocking' as a truthy blocking value. Fix duplicate
custom label identities when adding multiple labels. Prepend
conventional prefix to platform PR/MR inline comments.
For provenance purposes, this commit was AI assisted.
* fix(server): persist conventionalComments setting to config.json
All six server config handlers (bun plan/review/annotate + pi
plan/review/annotate) now accept and save the conventionalComments
boolean, so the setting survives server restarts.
For provenance purposes, this commit was AI assisted.
* fix: add conventionalComments to server config round-trip
getServerConfig() was not returning the conventionalComments value
from config.json, so the setting silently reset to false on cookie
clear or new browser sessions. Also adds the field to the
PlannotatorConfig interface so saveConfig() is properly typed.
For provenance purposes, this commit was AI assisted.
* fix: label display, export, and draft persistence for conventional comments
- Remove slug derivation from label editing — store display text
verbatim so badges and exports show what the user typed
- Emit conventional prefix in export even when annotation has no
prose text (suggestion-only annotations were losing their label)
- Include conventionalLabel in draft save condition so label
selection persists across file switches
For provenance purposes, this commit was AI assisted.
* fix: spec-compliant export format and empty label support
- Wrap label + decorations + colon in markdown bold per the
Conventional Comments spec examples (was bolding only the label)
- Allow users to clear all labels — empty array no longer falls
back to defaults in either the picker or the settings parser
- Enable blocking decorator on the question label by default; the
spec permits blocking questions and they sometimes are critical
For provenance purposes, this commit was AI assisted.
* fix: server-sync conventionalLabels and small cleanups
- Sync conventionalLabels to ~/.plannotator/config.json so custom
label configurations survive cookie clears and remote/SSH
sessions, matching the persistence story for conventionalComments.
Stored as a parsed array on disk; serialized as JSON string in
the local config store to match the cookie format.
- Remove no-op intermediate variable in handleSubmitAnnotation;
pass conventionalLabel/decorations directly with proper coalescing
per call path (edit preserves null, add coalesces to undefined).
- Use index-prefixed key in the picker label list to avoid React
warnings if duplicate labels ever exist.
For provenance purposes, this commit was AI assisted.
2026-04-06 22:27:47 -07:00
|
|
|
if (body.conventionalComments !== undefined) toSave.conventionalComments = body.conventionalComments;
|
|
|
|
|
if (body.conventionalLabels !== undefined) toSave.conventionalLabels = body.conventionalLabels;
|
feat(review): diff display options with ConfigStore integration (#428)
* feat(config): add DiffOptions to PlannotatorConfig with deep-merge support
Extends the server-side config system to support diff display options
namespaced under `diffOptions` in ~/.plannotator/config.json. The
saveConfig deep-merge ensures partial writes (e.g. changing only
overflow) don't clobber sibling keys.
For provenance purposes, this commit was AI assisted.
* feat(server): accept diffOptions in POST /api/config handlers
All six server handlers (plan, review, annotate x Bun + Pi) now
whitelist diffOptions alongside displayName, forwarding it to
saveConfig for deep-merged disk persistence.
For provenance purposes, this commit was AI assisted.
* feat(config): register diff display settings with deep-merge write batching
Adds 6 diff option settings to the ConfigStore registry (diffStyle,
diffOverflow, diffIndicators, diffLineDiffType, diffShowLineNumbers,
diffShowBackground), all synced to disk under the diffOptions namespace.
Fixes write batching for nested server keys — replaces Object.assign
with deepMerge so rapid changes to multiple diff options within the
300ms debounce window don't clobber each other. Includes legacy cookie
migration for the old review-diff-style key.
For provenance purposes, this commit was AI assisted.
* feat(review): wire diff display options through to @pierre/diffs
Migrates diffStyle from raw cookie storage to ConfigStore. Reads all 6
diff options via useConfigValue and forwards them to FileDiff: overflow,
diffIndicators, lineDiffType, disableLineNumbers, disableBackground.
Adds a Scroll/Wrap toolbar toggle alongside the existing Split/Unified
toggle. Disables the custom resizable split dragger in wrap mode since
Pierre manages its own grid layout. Fixes the unsafeCSS grid override
to only target scroll mode, preventing per-character wrapping in split
view.
For provenance purposes, this commit was AI assisted.
* feat(review): add Display tab to review-mode Settings dialog
Adds a Display tab when Settings is in review mode, exposing all 6 diff
options: Diff Style, Line Overflow, Change Indicators, Inline Diff
Granularity, Show Line Numbers, and Show Diff Background. Changes take
effect immediately and persist via ConfigStore (cookie + disk).
Extracts reusable SegmentedControl and ToggleSwitch helpers for the
review display controls.
For provenance purposes, this commit was AI assisted.
* chore: update bun.lock
For provenance purposes, this commit was AI assisted.
* fix(review): reapply search highlights after display option changes
Add new diff display props to the search highlight and scroll-to-match
effect dependency arrays so highlights are restored after Pierre re-renders.
For provenance purposes, this commit was AI assisted.
2026-03-29 13:20:22 -07:00
|
|
|
if (Object.keys(toSave).length > 0) saveConfig(toSave as Parameters<typeof saveConfig>[0]);
|
2026-03-26 11:54:22 -07:00
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
} catch {
|
|
|
|
|
return Response.json({ error: "Invalid request" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// API: Serve images (local paths or temp uploads)
|
|
|
|
|
if (url.pathname === "/api/image") {
|
2026-03-03 23:17:16 -08:00
|
|
|
return handleImage(req);
|
2026-01-12 19:36:09 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// API: Upload image -> save to temp -> return path
|
|
|
|
|
if (url.pathname === "/api/upload" && req.method === "POST") {
|
2026-03-03 23:17:16 -08:00
|
|
|
return handleUpload(req);
|
2026-01-12 19:36:09 -08:00
|
|
|
}
|
|
|
|
|
|
2026-01-19 11:07:22 -08:00
|
|
|
// API: Get available agents (OpenCode only)
|
|
|
|
|
if (url.pathname === "/api/agents") {
|
2026-03-03 23:17:16 -08:00
|
|
|
return handleAgents(options.opencodeClient);
|
2026-01-19 11:07:22 -08:00
|
|
|
}
|
|
|
|
|
|
2026-03-04 10:12:58 -08:00
|
|
|
// API: Annotation draft persistence
|
|
|
|
|
if (url.pathname === "/api/draft") {
|
|
|
|
|
if (req.method === "POST") return handleDraftSave(req, draftKey);
|
|
|
|
|
if (req.method === "DELETE") return handleDraftDelete(draftKey);
|
|
|
|
|
return handleDraftLoad(draftKey);
|
|
|
|
|
}
|
|
|
|
|
|
feat: VS Code editor annotations + theme integration (#239)
* feat: add shared EditorAnnotation type
Single source of truth for the editor annotation interface,
imported by both @plannotator/server and @plannotator/ui.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation server endpoints
In-memory store with POST/GET/DELETE endpoints for editor annotations.
The array lives in the handler closure and dies with the server session.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation UI — polling hook, card, panel, and export
- useEditorAnnotations hook with auto-disable polling (500ms interval)
- EditorAnnotationCard with file path, code preview, and comment
- AnnotationPanel conditionally renders editor annotation section
- exportEditorAnnotations formats annotations for Claude feedback
- App.tsx wires hook, includes in output memo and send feedback gate
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code extension editor annotation command
Cmd+Shift+. or right-click to capture selected text as an annotation.
POSTs through the cookie proxy to the plannotator server. Adds amber
left-border decorations on annotated lines, cleared on panel close.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: inline comment threads, lightbulb menu, and stronger decorations
Replace showInputBox with VS Code CommentController for inline annotation
threads anchored to selected code. Add CodeActionProvider for lightbulb
discoverability. Stronger decoration styling with gutter icon.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code theme integration for webview
Bridge VS Code CSS variables to Plannotator's CSS variable system via
postMessage between wrapper page and proxied iframe. Automatically adopts
the active VS Code color theme (dark/light/custom) without touching any
UI components or CSS files.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: gate editor annotation polling behind VS Code detection
Only poll /api/editor-annotations when running inside a VS Code webview
(window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have
zero network cost from the editor annotations feature. Also fixes poll
interval from 500ms to 2000ms.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: faster polling, prevent unnecessary re-renders, unify HTTP helper
- Poll interval 2s → 500ms for snappier annotation pickup
- Shallow equality check on annotation IDs prevents React re-renders
when poll data is unchanged
- Merge postToProxy/deleteFromProxy into single requestProxy function
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotations support in code review
Wire existing editor annotation infrastructure into the review flow
so VS Code users can annotate files outside the diff during code review.
- Add editor annotation endpoints to review server (same 3-line pattern)
- Call useEditorAnnotations hook in review App.tsx
- Display editor annotations in ReviewPanel with "Editor" divider
- Include editor annotations in feedback export and gating logic
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
|
|
|
// API: Editor annotations (VS Code extension)
|
|
|
|
|
const editorResponse = await editorAnnotations.handle(req, url);
|
|
|
|
|
if (editorResponse) return editorResponse;
|
|
|
|
|
|
feat: external annotations API with real-time SSE (#400)
Adds a general-purpose External Annotations API that allows external programs (linters, AI tools, security scanners) to push annotations into a live Plannotator session via HTTP, with real-time delivery over SSE.
## What's included
- **Shared core** (`packages/shared/external-annotation.ts`): types, in-memory store, input validation, SSE serialization
- **Server handlers**: Bun + Pi implementations with full CRUD (GET/POST/PATCH/DELETE) + SSE streaming
- **Client hook** (`useExternalAnnotations`): EventSource with polling fallback, optimistic updates
- **Editor integration**: two-array state model (local + external), content-aware dedup, ID-based routing
- **Persistence**: source field preserved through share URLs and crash-recovery drafts
- **Docs**: new Integrations category with API overview page, updated API reference
## API surface
All three servers (plan, review, annotate) expose:
- `GET /api/external-annotations/stream` - SSE stream
- `GET /api/external-annotations` - JSON snapshot (polling fallback)
- `POST /api/external-annotations` - Add annotations (single or batch)
- `PATCH /api/external-annotations?id=` - Update fields
- `DELETE /api/external-annotations` - Remove by id, source, or clear all
For provenance purposes, this commit was AI assisted.
2026-03-29 17:18:31 -07:00
|
|
|
// API: External annotations (SSE-based, for any external tool)
|
2026-03-31 00:49:34 +09:00
|
|
|
const externalResponse = await externalAnnotations.handle(req, url, {
|
|
|
|
|
disableIdleTimeout: () => server.timeout(req, 0),
|
|
|
|
|
});
|
feat: external annotations API with real-time SSE (#400)
Adds a general-purpose External Annotations API that allows external programs (linters, AI tools, security scanners) to push annotations into a live Plannotator session via HTTP, with real-time delivery over SSE.
## What's included
- **Shared core** (`packages/shared/external-annotation.ts`): types, in-memory store, input validation, SSE serialization
- **Server handlers**: Bun + Pi implementations with full CRUD (GET/POST/PATCH/DELETE) + SSE streaming
- **Client hook** (`useExternalAnnotations`): EventSource with polling fallback, optimistic updates
- **Editor integration**: two-array state model (local + external), content-aware dedup, ID-based routing
- **Persistence**: source field preserved through share URLs and crash-recovery drafts
- **Docs**: new Integrations category with API overview page, updated API reference
## API surface
All three servers (plan, review, annotate) expose:
- `GET /api/external-annotations/stream` - SSE stream
- `GET /api/external-annotations` - JSON snapshot (polling fallback)
- `POST /api/external-annotations` - Add annotations (single or batch)
- `PATCH /api/external-annotations?id=` - Update fields
- `DELETE /api/external-annotations` - Remove by id, source, or clear all
For provenance purposes, this commit was AI assisted.
2026-03-29 17:18:31 -07:00
|
|
|
if (externalResponse) return externalResponse;
|
|
|
|
|
|
feat: agentic review — background job runner with SSE streaming (#443)
* feat(server): add agent job manager with process lifecycle and SSE streaming
Introduces the backend for agentic review — a server-agnostic job runner
that spawns agent processes, monitors their lifecycle via proc.exited, and
broadcasts status updates over a dedicated SSE stream.
New files:
- packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine
- packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes
Wired into the review server with late-bound serverUrl, killAll on stop
and process exit for defense-in-depth cleanup. Capability detection via
Bun.which() for Claude Code, Codex CLI, and shell.
For provenance purposes, this commit was AI assisted.
* feat(ui): add Review Agents tab with job management and live status
Adds the client-side UI for agentic review:
- useAgentJobs hook: SSE primary with polling fallback, capabilities fetch
- AgentsTab: shared component with provider dropdown, job cards, kill controls
- ReviewAgentsIcon: magnifying glass with cog icon
- ReviewPanel: new "Review Agents" tab conditional on detected capabilities
- App.tsx: initializes hook and passes props to ReviewPanel
Jobs show live elapsed time, status badges, annotation counts per source,
and expandable error details. Stub command (sleep 10-30s) for initial testing.
For provenance purposes, this commit was AI assisted.
* fix(server): narrow proc.stderr type to satisfy TS
Bun types proc.stderr as ReadableStream | number. Add typeof guard
to narrow before passing to Response constructor.
For provenance purposes, this commit was AI assisted.
* fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch
- Change stdout from "pipe" to "ignore" — agents post findings via the
annotations API, not stdout. Unconsumed pipe buffer caused deadlock.
- Drain stderr continuously instead of reading after exit — prevents
pipe-full stall on chatty agents.
- Make agent getCwd worktree-aware using the same currentDiffType check
the AI endpoints use, so agents spawn in the correct checkout.
- Exclude 'agents' tab from PR context fetch guard in ReviewPanel.
For provenance purposes, this commit was AI assisted.
* feat(pi): mirror agent-job endpoints in Pi review server
Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun
agent-jobs handler using child_process.spawn, res.write() SSE, and
execFileSync for capability detection.
Wire into serverReview.ts: route delegation, killAll in stop(),
process.on("exit") guard, worktree-aware getCwd, and serverUrl
late-binding. Add agent-jobs to vendor.sh for shared type vendoring.
For provenance purposes, this commit was AI assisted.
* fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs
- Use process.once instead of process.on to prevent exit listener accumulation
- Validate provider against known capabilities before spawning (rejects unknown providers)
- Use platform-aware which/where for CLI detection on Windows
- Broadcast jobs:cleared event from kill-all endpoint (was dead client code)
- Document all /api/agents/* endpoints in CLAUDE.md Review Server table
For provenance purposes, this commit was AI assisted.
* fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup
- Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback
activates correctly on subsequent tab switches
- Remove jobs:cleared broadcast from kill-all — killAll() already fires
individual job:completed events, so the UI shows status transitions
instead of going blank
- Store exit handler ref so stop() can removeListener, preventing
accumulation in long-lived hosts (OpenCode, Pi)
For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
|
|
|
// API: Agent jobs (background review agents)
|
|
|
|
|
const agentResponse = await agentJobs.handle(req, url, {
|
|
|
|
|
disableIdleTimeout: () => server.timeout(req, 0),
|
|
|
|
|
});
|
|
|
|
|
if (agentResponse) return agentResponse;
|
|
|
|
|
|
2026-04-10 03:22:01 +01:00
|
|
|
// API: Exit review session without feedback
|
|
|
|
|
if (url.pathname === "/api/exit" && req.method === "POST") {
|
|
|
|
|
deleteDraft(draftKey);
|
|
|
|
|
resolveDecision({ approved: false, feedback: "", annotations: [], exit: true });
|
|
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// API: Submit review feedback
|
|
|
|
|
if (url.pathname === "/api/feedback" && req.method === "POST") {
|
|
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as {
|
2026-03-14 17:58:57 -07:00
|
|
|
approved?: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: string;
|
|
|
|
|
annotations: unknown[];
|
|
|
|
|
agentSwitch?: string;
|
|
|
|
|
};
|
|
|
|
|
|
2026-03-04 10:12:58 -08:00
|
|
|
deleteDraft(draftKey);
|
2026-01-12 19:36:09 -08:00
|
|
|
resolveDecision({
|
2026-03-14 17:58:57 -07:00
|
|
|
approved: body.approved ?? false,
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: body.feedback || "",
|
|
|
|
|
annotations: body.annotations || [],
|
|
|
|
|
agentSwitch: body.agentSwitch,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to process feedback";
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-21 00:48:26 +01:00
|
|
|
// API: Submit PR review directly to GitHub (PR mode only)
|
|
|
|
|
if (url.pathname === "/api/pr-action" && req.method === "POST") {
|
|
|
|
|
if (!isPRMode || !prMetadata) {
|
|
|
|
|
return Response.json({ error: "Not in PR mode" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as {
|
|
|
|
|
action: "approve" | "comment";
|
|
|
|
|
body: string;
|
|
|
|
|
fileComments: PRReviewFileComment[];
|
|
|
|
|
};
|
|
|
|
|
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
console.error(`[pr-action] ${body.action} with ${body.fileComments.length} file comment(s), headSha=${prMetadata.headSha}`);
|
|
|
|
|
|
2026-03-21 00:48:26 +01:00
|
|
|
await submitPRReview(
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
prRef!,
|
2026-03-21 00:48:26 +01:00
|
|
|
prMetadata.headSha,
|
|
|
|
|
body.action,
|
|
|
|
|
body.body,
|
|
|
|
|
body.fileComments,
|
|
|
|
|
);
|
|
|
|
|
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
console.error(`[pr-action] Success`);
|
2026-03-21 00:48:26 +01:00
|
|
|
return Response.json({ ok: true, prUrl: prMetadata.url });
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to submit PR review";
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
console.error(`[pr-action] Failed: ${message}`);
|
2026-03-21 00:48:26 +01:00
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-25 21:33:33 +01:00
|
|
|
// API: Mark/unmark PR files as viewed on GitHub (PR mode, GitHub only)
|
|
|
|
|
if (url.pathname === "/api/pr-viewed" && req.method === "POST") {
|
|
|
|
|
if (!isPRMode || !prMetadata) {
|
|
|
|
|
return Response.json({ error: "Not in PR mode" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
if (prMetadata.platform !== "github") {
|
|
|
|
|
return Response.json({ error: "Viewed sync only supported for GitHub" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
const prNodeId = prMetadata.prNodeId;
|
|
|
|
|
if (!prNodeId) {
|
|
|
|
|
return Response.json({ error: "PR node ID not available" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as {
|
|
|
|
|
filePaths: string[];
|
|
|
|
|
viewed: boolean;
|
|
|
|
|
};
|
|
|
|
|
await markPRFilesViewed(prRef!, prNodeId, body.filePaths, body.viewed);
|
|
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to update viewed state";
|
|
|
|
|
console.error("[plannotator] /api/pr-viewed error:", message);
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
// AI endpoints
|
|
|
|
|
if (aiEndpoints && url.pathname.startsWith("/api/ai/")) {
|
|
|
|
|
const handler = aiEndpoints[url.pathname as keyof AIEndpoints];
|
|
|
|
|
if (handler) return handler(req);
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
return Response.json({ error: "Not found" }, { status: 404 });
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
}
|
|
|
|
|
|
2026-03-16 15:45:00 +01:00
|
|
|
// Favicon
|
|
|
|
|
if (url.pathname === "/favicon.svg") return handleFavicon();
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// Serve embedded HTML for all other routes (SPA)
|
|
|
|
|
return new Response(htmlContent, {
|
|
|
|
|
headers: { "Content-Type": "text/html" },
|
|
|
|
|
});
|
|
|
|
|
},
|
2026-04-09 08:05:34 -07:00
|
|
|
|
|
|
|
|
error(err) {
|
|
|
|
|
console.error("[plannotator] Server error:", err);
|
|
|
|
|
return new Response(
|
|
|
|
|
`Internal Server Error: ${err instanceof Error ? err.message : String(err)}`,
|
|
|
|
|
{ status: 500, headers: { "Content-Type": "text/plain" } },
|
|
|
|
|
);
|
|
|
|
|
},
|
2026-01-12 19:36:09 -08:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
break; // Success, exit retry loop
|
|
|
|
|
} catch (err: unknown) {
|
|
|
|
|
const isAddressInUse =
|
|
|
|
|
err instanceof Error && err.message.includes("EADDRINUSE");
|
|
|
|
|
|
|
|
|
|
if (isAddressInUse && attempt < MAX_RETRIES) {
|
|
|
|
|
await Bun.sleep(RETRY_DELAY_MS);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (isAddressInUse) {
|
|
|
|
|
const hint = isRemote ? " (set PLANNOTATOR_PORT to use different port)" : "";
|
|
|
|
|
throw new Error(`Port ${configuredPort} in use after ${MAX_RETRIES} retries${hint}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw err;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!server) {
|
|
|
|
|
throw new Error("Failed to start server");
|
|
|
|
|
}
|
|
|
|
|
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
const port = server.port!;
|
feat: agentic review — background job runner with SSE streaming (#443)
* feat(server): add agent job manager with process lifecycle and SSE streaming
Introduces the backend for agentic review — a server-agnostic job runner
that spawns agent processes, monitors their lifecycle via proc.exited, and
broadcasts status updates over a dedicated SSE stream.
New files:
- packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine
- packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes
Wired into the review server with late-bound serverUrl, killAll on stop
and process exit for defense-in-depth cleanup. Capability detection via
Bun.which() for Claude Code, Codex CLI, and shell.
For provenance purposes, this commit was AI assisted.
* feat(ui): add Review Agents tab with job management and live status
Adds the client-side UI for agentic review:
- useAgentJobs hook: SSE primary with polling fallback, capabilities fetch
- AgentsTab: shared component with provider dropdown, job cards, kill controls
- ReviewAgentsIcon: magnifying glass with cog icon
- ReviewPanel: new "Review Agents" tab conditional on detected capabilities
- App.tsx: initializes hook and passes props to ReviewPanel
Jobs show live elapsed time, status badges, annotation counts per source,
and expandable error details. Stub command (sleep 10-30s) for initial testing.
For provenance purposes, this commit was AI assisted.
* fix(server): narrow proc.stderr type to satisfy TS
Bun types proc.stderr as ReadableStream | number. Add typeof guard
to narrow before passing to Response constructor.
For provenance purposes, this commit was AI assisted.
* fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch
- Change stdout from "pipe" to "ignore" — agents post findings via the
annotations API, not stdout. Unconsumed pipe buffer caused deadlock.
- Drain stderr continuously instead of reading after exit — prevents
pipe-full stall on chatty agents.
- Make agent getCwd worktree-aware using the same currentDiffType check
the AI endpoints use, so agents spawn in the correct checkout.
- Exclude 'agents' tab from PR context fetch guard in ReviewPanel.
For provenance purposes, this commit was AI assisted.
* feat(pi): mirror agent-job endpoints in Pi review server
Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun
agent-jobs handler using child_process.spawn, res.write() SSE, and
execFileSync for capability detection.
Wire into serverReview.ts: route delegation, killAll in stop(),
process.on("exit") guard, worktree-aware getCwd, and serverUrl
late-binding. Add agent-jobs to vendor.sh for shared type vendoring.
For provenance purposes, this commit was AI assisted.
* fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs
- Use process.once instead of process.on to prevent exit listener accumulation
- Validate provider against known capabilities before spawning (rejects unknown providers)
- Use platform-aware which/where for CLI detection on Windows
- Broadcast jobs:cleared event from kill-all endpoint (was dead client code)
- Document all /api/agents/* endpoints in CLAUDE.md Review Server table
For provenance purposes, this commit was AI assisted.
* fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup
- Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback
activates correctly on subsequent tab switches
- Remove jobs:cleared broadcast from kill-all — killAll() already fires
individual job:completed events, so the UI shows status transitions
instead of going blank
- Store exit handler ref so stop() can removeListener, preventing
accumulation in long-lived hosts (OpenCode, Pi)
For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
|
|
|
serverUrl = `http://localhost:${port}`;
|
|
|
|
|
const exitHandler = () => agentJobs.killAll();
|
|
|
|
|
process.once("exit", exitHandler);
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
// Notify caller that server is ready
|
|
|
|
|
if (onReady) {
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
onReady(serverUrl, isRemote, port);
|
2026-01-12 19:36:09 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
port,
|
2026-01-12 19:36:09 -08:00
|
|
|
url: serverUrl,
|
|
|
|
|
isRemote,
|
|
|
|
|
waitForDecision: () => decisionPromise,
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
stop: () => {
|
feat: agentic review — background job runner with SSE streaming (#443)
* feat(server): add agent job manager with process lifecycle and SSE streaming
Introduces the backend for agentic review — a server-agnostic job runner
that spawns agent processes, monitors their lifecycle via proc.exited, and
broadcasts status updates over a dedicated SSE stream.
New files:
- packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine
- packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes
Wired into the review server with late-bound serverUrl, killAll on stop
and process exit for defense-in-depth cleanup. Capability detection via
Bun.which() for Claude Code, Codex CLI, and shell.
For provenance purposes, this commit was AI assisted.
* feat(ui): add Review Agents tab with job management and live status
Adds the client-side UI for agentic review:
- useAgentJobs hook: SSE primary with polling fallback, capabilities fetch
- AgentsTab: shared component with provider dropdown, job cards, kill controls
- ReviewAgentsIcon: magnifying glass with cog icon
- ReviewPanel: new "Review Agents" tab conditional on detected capabilities
- App.tsx: initializes hook and passes props to ReviewPanel
Jobs show live elapsed time, status badges, annotation counts per source,
and expandable error details. Stub command (sleep 10-30s) for initial testing.
For provenance purposes, this commit was AI assisted.
* fix(server): narrow proc.stderr type to satisfy TS
Bun types proc.stderr as ReadableStream | number. Add typeof guard
to narrow before passing to Response constructor.
For provenance purposes, this commit was AI assisted.
* fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch
- Change stdout from "pipe" to "ignore" — agents post findings via the
annotations API, not stdout. Unconsumed pipe buffer caused deadlock.
- Drain stderr continuously instead of reading after exit — prevents
pipe-full stall on chatty agents.
- Make agent getCwd worktree-aware using the same currentDiffType check
the AI endpoints use, so agents spawn in the correct checkout.
- Exclude 'agents' tab from PR context fetch guard in ReviewPanel.
For provenance purposes, this commit was AI assisted.
* feat(pi): mirror agent-job endpoints in Pi review server
Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun
agent-jobs handler using child_process.spawn, res.write() SSE, and
execFileSync for capability detection.
Wire into serverReview.ts: route delegation, killAll in stop(),
process.on("exit") guard, worktree-aware getCwd, and serverUrl
late-binding. Add agent-jobs to vendor.sh for shared type vendoring.
For provenance purposes, this commit was AI assisted.
* fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs
- Use process.once instead of process.on to prevent exit listener accumulation
- Validate provider against known capabilities before spawning (rejects unknown providers)
- Use platform-aware which/where for CLI detection on Windows
- Broadcast jobs:cleared event from kill-all endpoint (was dead client code)
- Document all /api/agents/* endpoints in CLAUDE.md Review Server table
For provenance purposes, this commit was AI assisted.
* fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup
- Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback
activates correctly on subsequent tab switches
- Remove jobs:cleared broadcast from kill-all — killAll() already fires
individual job:completed events, so the UI shows status transitions
instead of going blank
- Store exit handler ref so stop() can removeListener, preventing
accumulation in long-lived hosts (OpenCode, Pi)
For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
|
|
|
process.removeListener("exit", exitHandler);
|
|
|
|
|
agentJobs.killAll();
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
aiSessionManager.disposeAll();
|
|
|
|
|
aiRegistry.disposeAll();
|
|
|
|
|
server.stop();
|
feat(review): AI review agents, local worktree, and UI polish (#491)
* feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI
Hook up Codex as the first AI review agent in the code review system:
- Spawn `codex exec` with Codex's native review prompt and output schema
- Parse structured findings (ReviewOutputEvent) and push as external annotations
- Annotations appear inline in the diff viewer pinned to specific lines
- Review verdict (correct/incorrect + confidence + explanation) displayed in panel
Agent job infrastructure enhancements:
- Server-side command building via `buildCommand` callback (providers don't need frontend commands)
- Result ingestion via `onJobComplete` callback (reads output file, transforms findings)
- `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers)
- Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush
- `cwd` and `summary` fields on AgentJobInfo
PR review with --local worktree:
- `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch
- Agent gets full local file access without touching the user's working tree
- Hybrid server mode: both prMetadata (platform features) and gitContext (local access)
- Automatic worktree cleanup on session end
- Runtime-agnostic worktree primitives in packages/shared/worktree.ts
Panel UI redesign:
- Findings | Logs tab system with underline-style tabs
- LiveLogViewer component with auto-scroll, truncation, and copy
- Review verdict card (correct/incorrect with confidence and explanation)
- Pending state with labeled "Review Verdict — Pending..." (not skeleton bars)
- Job card click opens detail panel directly (removed separate icon button)
- Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel)
- Copy all annotations as formatted markdown
- Worktree badge in header with info dialog showing path
- CopyButton extended with inline variant for reuse
- ConfirmDialog extended with wide option
For provenance purposes, this commit was AI assisted.
* style(review): UX polish pass — visual quality improvements across code review UI
- VerdictCard: remove AI-template left-border, use background-only tint
- Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale
- File tree: tighter indentation (4 + depth*10), reduced container padding
- Select dropdowns: normalized to 4px border-radius matching pierre diffs
- Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity
- PR icons moved from sidebar to header (next to PR link)
- AnnotationRow: translate-x hover feedback
- Border-radius normalized to `rounded` (4px) across all components
- Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs
- Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons)
- Sticky file group headers in annotation sidebar
- FileTree controls collapsed (worktree + diff selectors share one row)
- Tab micro-animations (transition-all duration-150)
- ScrollFade component for gradient indicators on scrollable containers
- Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels
- MarkdownBody: leading-relaxed for comfortable reading
- PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold
- PR Checks: link affordance (text-primary, underline on hover, external link icon)
For provenance purposes, this commit was AI assisted.
* feat(review): PR comments panel — search, filter, collapse, navigation, and polish
Comments panel enhancements:
- Search: real-time text filter across author and body, match count display
- Keyboard navigation: j/k to move between comments, scroll-to-selected
- Sort: toggle between oldest/newest first
- Collapsible comments: click header to collapse, collapse/expand all controls
- Author exclusion filter: click authors to hide their comments (not inclusion)
- Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right)
- Review URLs: PRReview type now includes optional url field, populated from GitHub API
PR Summary fixes:
- Label contrast: use theme foreground color for label text instead of raw GitHub hex
- Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon
Data plumbing:
- platformUser exposed through ReviewStateContext for "Mine" filtering
- Panel wrapper changed to overflow-hidden for sticky toolbar support
- "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed)
For provenance purposes, this commit was AI assisted.
* feat(review): inline review threads with outdated/resolved state and diff hunk previews
PR Review Threads:
- Fetch inline code review comments via GitHub GraphQL (reviewThreads query)
- PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide
- ThreadCard component: file/line context, Outdated/Resolved badges, nested replies
- Resolved/outdated threads: gradient fade on body with "Show full comment" expand
- GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes)
DiffHunkPreview:
- Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact)
- Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer)
- Respects user font settings from ReviewState context
- Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing)
Comments Panel Polish:
- Comment cards: bg-card + subtle shadow for depth and isolation from panel background
- Hover: shadow elevation (0_2px_6px) for interactive feedback
- Thread cards: dimmed shadow for resolved/outdated, full shadow for active
- Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings)
For provenance purposes, this commit was AI assisted.
* feat(review): Claude Code agent, cross-repo --local, render fixes
Claude Code review agent:
- claude-review.ts: prompt (adapted from code-review plugin), command builder
(dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser
- Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts
- stream-json --verbose for live JSONL streaming + final structured_output
- Same schema as Codex — transformReviewFindings is now provider-agnostic
Agent jobs infrastructure:
- stdout capture (captureStdout option) for providers that return results on stdout
- stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin
- cwd override in buildCommand return for providers without -C flag
- await stdoutDone before onJobComplete to prevent drain race condition
- job.prompt field for transparent prompt display in detail panel
Cross-repo --local:
- Detect same-repo vs cross-repo via parseRemoteUrl comparison
- Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch)
- Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access
- Same-repo: existing worktree path unchanged
- Cleanup: rmSync for clones, worktree remove for same-repo
Performance: jobLogs context split
- Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels
- Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider
- Standard React pattern: split contexts by update frequency
Image error handling:
- SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers
- Broken images (expired GitHub JWTs) hide on first 404 instead of flickering
- Prevents console 404 flood from re-render retry loops
For provenance purposes, this commit was AI assisted.
* fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs
The --local flag was setting gitContext from the worktree, which contaminated
the diff rendering pipeline — causing pierre "trailing context mismatch" errors
because /api/file-content read worktree files instead of using the GitHub API.
Root cause: gitContext serves two purposes — diff pipeline (file contents, diff
switching, staging) and agent sandbox (cwd for agent processes). These are now
properly separated via a new agentCwd option on ReviewServerOptions.
Changes:
- Add agentCwd to ReviewServerOptions, independent of gitContext
- Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd
- Stop setting gitContext in --local PR path — diff pipeline untouched
- Revert band-aid !isPRMode guards (no longer needed)
- Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff
- Fix cross-repo clone: create local branch at baseSha for git diff accuracy
- Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip)
- Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly
- Change buildCodexReviewUserMessage signature from GitContext to focused options
- Make --local the default for PR/MR reviews (--no-local to opt out)
- Pass agentCwd to client for worktree badge display
For provenance purposes, this commit was AI assisted.
* style(review): unify panel headers, responsive buttons, dockview polish
- Unify all panel headers at 33px via --panel-header-h CSS variable
- FileHeader now uses shared variable instead of hardcoded 30px
- Dockview tab bar height, font size, and padding aligned with sidebars
- FileTree header uses fixed height instead of padding-based sizing
- Consistent border opacity (border-border/50) across all panels
- Consistent font weight (font-semibold) on all header labels
- Remove dockview tab focus outline (::after pseudo-element)
- Dockview tab close button pushed to right edge
- Tab bar void area uses muted background
- Top app header compacted from h-12 to py-1
- Sidebar footer: copy button and diff stats side by side
- FeedbackButton responsive labels (Send/Post at md, full labels at lg)
- Move ReviewAgentsIcon to packages/ui for shared use
- Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG
- Sidebar header label truncates when narrow (tabs never clip)
- Detail panel prompt disclosures get proper spacing
- React.memo on PR tab components (PRSummaryTab, PRCommentsTab)
- Inline onerror on img tags for broken GitHub image handling
For provenance purposes, this commit was AI assisted.
* fix: type assertion for Bun stdin FileSink
Bun's proc.stdin is typed as `number | FileSink` but we need to call
.write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit.
For provenance purposes, this commit was AI assisted.
* fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch
Security:
- Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS
execution via PR descriptions containing `<img onerror="...">`. Replace
with SafeHtml component that attaches error handlers via useEffect + ref.
- Add `--` end-of-options separator to git fetch and git branch calls to
prevent flag injection via crafted branch names from API responses.
Bug fix:
- Cross-repo clones now create both local branch AND remote-tracking ref
(`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either
`git diff main...HEAD` or `git diff origin/main...HEAD`.
Polish:
- Add copy button to verdict card in agent detail panel
- Remove hover:translate-x animation from finding rows
- Reduce file tree indent per level, remove extra file offset
- Add pr-action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12
The beta pin was needed for processFile() API (expandable diff context),
which shipped in 1.1.0 stable on March 14. We were 13 releases behind.
Notable fixes in the upgrade path:
- 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata
- 1.1.6: Patch parsing fix for renames and dotfiles
- 1.1.8: Fix maxLineDiffLength regression
May resolve intermittent "trailing context mismatch" errors in diff rendering.
For provenance purposes, this commit was AI assisted.
* fix(review): remove shell provider, flag injection, Claude log formatting, copy UX
Security:
- Remove shell provider from agent capabilities (unauthenticated RCE vector)
- Move `--` before prRepo in `gh repo clone` to prevent flag injection
Features:
- Wire up formatClaudeLogEvent — Claude live logs now show readable text
instead of raw JSONL
- Sidebar annotations: copy + delete buttons appear on hover (no overlap)
- Agent finding rows: copy button on hover (progressive disclosure)
- Verdict card: copy button pushed to the right
- File tree: reduced indent per level, files aligned with folders
Infra:
- PR action endpoint logging for debugging submit failures
For provenance purposes, this commit was AI assisted.
* fix: validate repo identifier to prevent flag injection in gh repo clone
The `--` separator in `gh repo clone` separates gh args from git args,
not positional args from flags. Using `--` before prRepo would break
the git flags. Instead, validate that the repo identifier doesn't start
with `-` to prevent flag injection via crafted PR URLs.
For provenance purposes, this commit was AI assisted.
* feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt
Claude review agent now has its own schema, prompt, and transform — separate
from Codex's P0-P3 priority model. Each provider uses its natural review style.
Schema changes:
- Claude findings use severity (important/nit/pre_existing) instead of priority (0-3)
- Flat structure: file, line, end_line instead of nested code_location
- description (single field) instead of title + body
- reasoning field captures the validation chain per finding
- summary with counts instead of overall_correctness/confidence
Prompt: Converges the open-source Claude Code review prompt with the remote
review service model. 4 parallel agents (Bug+Regression at Opus, Security at
Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step,
deduplication, severity classification. CLAUDE.md and REVIEW.md awareness.
UI: Severity markers (colored dots) on finding rows. Collapsible reasoning
section via <details>. New optional severity/reasoning fields on CodeAnnotation
and the external annotation store — backward compatible, only set by Claude.
Transform: transformClaudeFindings normalizes Claude output into the shared
annotation format. Codex path (transformReviewFindings) is completely untouched.
For provenance purposes, this commit was AI assisted.
* fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined)
For provenance purposes, this commit was AI assisted.
* fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX
Security:
- Add -- separator to ensureObjectAvailable git fetch (worktree.ts)
- Validate baseBranch against path traversal (..) before git ref operations
- Use process.once('exit') instead of process.on for worktree cleanup
Debug:
- Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes)
- Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk
Deduplication:
- Extract toRelativePath to packages/server/path-utils.ts (was duplicated
in codex-review.ts and claude-review.ts)
Pi extension:
- Remove shell provider from capabilities
- Add buildCommand callback to AgentJobHandlerOptions
- POST handler calls buildCommand for server-side command synthesis
UI:
- Findings sorted by severity (important → nit → pre_existing)
- Severity legend under findings header (colored dots)
- Reasoning always visible (not collapsible) — fixes click navigation bug
where <details> captured click events and broke annotation linkage
- Full finding text shown (removed line-clamp-2 truncation)
- Sidebar annotation hover actions aligned to the right
- DiffHunkPreview: cancel requestAnimationFrame on unmount
For provenance purposes, this commit was AI assisted.
* fix: move toRelativePath import to top of claude-review.ts
For provenance purposes, this commit was AI assisted.
* fix: same-repo detection compares host, platform-aware comment links, remove design docs
- Same-repo detection now compares both owner/repo AND hostname from the
git remote URL against prMetadata.host. Prevents false positives on
GitHub Enterprise where different instances share org/repo names.
- "View on GitHub" label in PR comments tab now shows "View on GitLab"
for GitLab MR comments based on the comment URL.
- Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md)
that were development artifacts, not user-facing documentation.
For provenance purposes, this commit was AI assisted.
* fix(review): show severity markers and reasoning in inline diff annotations
The severity and reasoning fields from Claude findings were only visible in
the agent detail panel, not in the inline diff annotations. Now:
- DiffAnnotationMetadata carries severity and reasoning fields
- DiffViewer passes them through when mapping annotations
- InlineAnnotation renders colored severity dot and reasoning text
For provenance purposes, this commit was AI assisted.
* fix: prefix Claude findings text with [severity] tag
Findings now show as "[important] description", "[nit] description",
"[pre_existing] description" — consistent with Codex's [P0]/[P1] tags.
For provenance purposes, this commit was AI assisted.
* feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion
Pi extension agent-jobs handler now mirrors the Bun server's full capabilities:
- stdin piping for Claude prompt delivery
- stdout capture for Claude JSONL stream parsing
- Live stderr streaming with 200ms buffer-and-flush for job:log events
- Claude JSONL formatting via vendored formatClaudeLogEvent
- onJobComplete callback for result parsing and annotation push
- Full buildCommand integration in POST handler
- jobOutputPaths tracking with cleanup on kill
Pi serverReview.ts now wires buildCommand and onJobComplete with the same
logic as the Bun review server — Codex and Claude commands are built
server-side, results are parsed and transformed into external annotations.
Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with
node:fs/promises equivalents (writeFile, readFile, existsSync) that work on
both Bun and Node. Verified Bun build passes.
Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and
path-utils.ts from packages/server/ with import path rewriting for the
generated/ layout.
Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs.
For provenance purposes, this commit was AI assisted.
* fix: remove duplicate isPRMode declaration in Pi serverReview.ts
For provenance purposes, this commit was AI assisted.
* fix: include reasoning in all copy and feedback export paths
- exportReviewFeedback: appends **Reasoning:** after finding text
- Per-finding copy button: appends reasoning to copy text
- Sidebar annotation copy: appends reasoning to copy text
This ensures reasoning flows through Copy All, Send Feedback, and
individual copy actions — not just the visual rendering.
For provenance purposes, this commit was AI assisted.
* fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths
1. openDiffFile: clicking a finding now navigates to the correct file
before selecting the annotation (was silently selecting in wrong file)
2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant,
imported in both ReviewAgentJobDetailPanel and InlineAnnotation
(was duplicated with per-render rebuild in InlineAnnotation)
3. killJob: added jobOutputPaths.delete calls to match Pi's version
(was leaking two strings per killed job)
4. CommentActions: replaced hand-rolled copy with CopyButton inline
variant (was reimplementing useState/clipboard/setTimeout pattern)
5. Branch mode prompt: changed from three-dot to two-dot to match
the UI's actual diff computation (agent was reviewing different diff)
6. toRelativePath: uses path.relative + forward-slash normalization
for Windows compatibility (was string prefix matching with / only)
For provenance purposes, this commit was AI assisted.
* perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming
Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders
App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even
though its props (agentJobs.jobs, capabilities, callbacks) haven't changed.
This caused visible flickering when a review tab was open during agent runs.
React.memo shallow-compares props — all sidebar props are stable references
(jobs array only changes on status events, callbacks are useCallback-wrapped),
so the sidebar correctly skips re-renders during log streaming.
For provenance purposes, this commit was AI assisted.
* fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI
Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses
that bypassed --disallowedTools. Removed find, ls, and cat — Claude has
Glob, Read, and Grep built-in which cover file access without shell exec.
Feature: Added glab mr view/diff/list and glab api to allowed tools so
Claude can inspect GitLab MR context in remote-mode reviews.
For provenance purposes, this commit was AI assisted.
* fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes
Pi extension:
- Add addAnnotations() to external-annotations.ts return object —
serverReview.ts calls it when agent jobs complete but the method
was missing (build/runtime error)
- Change proc.on('exit') to proc.on('close') in agent-jobs.ts —
Node's 'exit' fires before stdio streams drain, so stdoutBuf could
be incomplete when onJobComplete parses Claude's JSONL result
Cross-repo --local:
- Check git checkout FETCH_HEAD exit code — throw if it fails so the
outer catch falls back to remote-only with a clear warning
- Log warning if baseSha fetch fails (non-fatal, agents just can't
diff locally)
For provenance purposes, this commit was AI assisted.
* fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted
Critical:
- Move ensureObjectAvailable before PR head fetch — it can overwrite
FETCH_HEAD if baseSha needs fetching, causing createWorktree to
check out the base commit instead of the PR head
- Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd,
buildCommand, and onJobComplete — was bypassing worktree-aware path
resolution, causing agents to run in wrong directory
Cleanup:
- Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel
(was recreated inside component body on every render)
For provenance purposes, this commit was AI assisted.
* fix: Bun/Pi parity — provider default, annotation error logging
- Bun agent-jobs: change provider default from "shell" to "" (shell was
removed from capabilities, default should match Pi)
- Pi serverReview: log errors from addAnnotations in onJobComplete
(Bun logs them, Pi was silently ignoring)
For provenance purposes, this commit was AI assisted.
* docs: add AI Code Review Agents guide with full prompt transparency
New docs page covering:
- Overview of Codex and Claude review agents
- How findings work (severity/priority, reasoning, navigation)
- Local worktree behavior (same-repo vs cross-repo)
- Full transparency section with:
- Claude multi-agent pipeline prompt (all 6 steps)
- Claude command and allowed/blocked tools
- Codex review prompt and command
- Both output schemas (Claude severity + Codex priority)
- Security notes (read-only, no network, local execution, no commenting)
- Customization via CLAUDE.md and REVIEW.md
For provenance purposes, this commit was AI assisted.
* docs: add provenance links for Claude and Codex review integrations
Credit Anthropic's Claude Code Review service, the open-source
code-review plugin, and OpenAI's Codex CLI as the foundations
for our review agent integrations.
For provenance purposes, this commit was AI assisted.
* fix: temp clone leak, j/k key conflict, thread header null line
- Cross-repo: clean up localPath in catch block when fetch/checkout
fails after clone succeeds (directory was leaking in /tmp)
- Remove j/k/arrow keyboard navigation from PR comments panel —
these shortcuts belong to the file tree only, both registering
global handlers caused double-navigation
- Thread header null guard: check thread.line before building range
label to prevent "L12–null" for outdated GitHub threads
For provenance purposes, this commit was AI assisted.
* fix: hoist localPath for catch-block scope, validate baseSha format
The previous rmSync(localPath) in the catch block was dead code —
const declarations inside try are not in scope in catch (separate
lexical environments per ECMAScript spec). The ReferenceError was
silently swallowed by the inner try/catch, so temp directories
still leaked on failed fetch/checkout.
Fix: hoist `let localPath` before the try block so it's accessible
in catch. Guard with `if (localPath)` since the error could occur
before assignment.
Also: validate baseSha is a hex SHA (40-64 chars) to prevent git
flag injection via crafted API responses. Validate baseBranch
rejects both '..' and '-' prefixes.
For provenance purposes, this commit was AI assisted.
* docs: rewrite AI Code Review guide for clarity and readability
Restructured for a technical audience: shorter paragraphs, cleaner
tables, removed em-dashes and filler prose, tightened the pipeline
diagram, streamlined security section into scannable single-line items.
For provenance purposes, this commit was AI assisted.
* docs: rewrite transparency section with exact prompts and commands
Replaced summarized/paraphrased transparency section with the actual
prompts, commands, schemas, and tool allowlists as they exist in the
code. One short security note at the top, then raw content.
For provenance purposes, this commit was AI assisted.
* docs: add mini TOC to transparency section
For provenance purposes, this commit was AI assisted.
* fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal
Critical:
- Race stdoutDone against 2s timeout after proc.exited — prevents
permanent job hang when Bun's ReadableStream doesn't close after
process exit. The process is dead; 2s is a cleanup deadline.
Bug fix:
- Codex verdict: override to "Issues Found" when P0/P1 findings exist,
regardless of the freeform overall_correctness string. Prevents green
"Correct" badge when Codex says "mostly correct but has issues."
P2/P3-only findings still trust Codex's verdict.
Observability:
- Log Claude parse failures with buffer size and last 200 bytes so we
can diagnose empty-findings cases.
Performance:
- Remove React.memo from ReviewSidebar — was blocking legitimate
re-renders (job status, findings) to prevent cosmetic log flickering.
The tradeoff was wrong.
Docs:
- Remove "shell" from CLAUDE.md capabilities table (provider was removed).
For provenance purposes, this commit was AI assisted.
* fix: type assertions for Bun ReadableStream async iteration
Bun's proc.stdout/stderr support for-await at runtime but TypeScript's
ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through
unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same
pattern as the FileSink cast for stdin.
For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
|
|
|
// Invoke cleanup callback (e.g., remove temp worktree)
|
|
|
|
|
if (options.onCleanup) {
|
|
|
|
|
try {
|
|
|
|
|
const result = options.onCleanup();
|
|
|
|
|
if (result instanceof Promise) result.catch(() => {});
|
|
|
|
|
} catch { /* best effort */ }
|
|
|
|
|
}
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
},
|
2026-01-12 19:36:09 -08:00
|
|
|
};
|
|
|
|
|
}
|