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.
This commit is contained in:
Michael Ramos
2026-04-06 12:15:27 -07:00
committed by GitHub
parent 70b0cfb34e
commit b375a804b2
57 changed files with 3536 additions and 556 deletions
+1 -1
View File
@@ -234,7 +234,7 @@ During normal plan review, an Archive sidebar tab provides the same browsing via
| `/api/external-annotations` | POST | Add external annotations (single or batch `{ annotations: [...] }`) |
| `/api/external-annotations` | PATCH | Update fields on a single annotation (`?id=`) |
| `/api/external-annotations` | DELETE | Remove by `?id=`, `?source=`, or clear all |
| `/api/agents/capabilities` | GET | Check available agent providers (claude, codex, shell) |
| `/api/agents/capabilities` | GET | Check available agent providers (claude, codex) |
| `/api/agents/jobs/stream` | GET | SSE stream for real-time agent job status updates |
| `/api/agents/jobs` | GET | Snapshot of agent jobs (polling fallback, `?since=N` for version gating) |
| `/api/agents/jobs` | POST | Launch an agent job (body: `{ provider, command, label }`) |
+145 -3
View File
@@ -63,12 +63,14 @@ import {
startAnnotateServer,
handleAnnotateServerReady,
} from "@plannotator/server/annotate";
import { type DiffType, getVcsContext, runVcsDiff } from "@plannotator/server/vcs";
import { type DiffType, getVcsContext, runVcsDiff, gitRuntime } from "@plannotator/server/vcs";
import { fetchRef, createWorktree, removeWorktree, ensureObjectAvailable } from "@plannotator/shared/worktree";
import { parsePRUrl, checkPRAuth, fetchPR, getCliName, getCliInstallUrl, getMRLabel, getMRNumberLabel, getDisplayRepo } from "@plannotator/server/pr";
import { writeRemoteShareLink } from "@plannotator/server/share-url";
import { resolveMarkdownFile, hasMarkdownFiles } from "@plannotator/shared/resolve-file";
import { FILE_BROWSER_EXCLUDED } from "@plannotator/shared/reference-common";
import { statSync } from "fs";
import { statSync, rmSync, realpathSync } from "fs";
import { parseRemoteUrl } from "@plannotator/shared/repo";
import { registerSession, unregisterSession, listSessions } from "@plannotator/server/sessions";
import { openBrowser } from "@plannotator/server/browser";
import { detectProjectName } from "@plannotator/server/project";
@@ -85,6 +87,7 @@ import {
isTopLevelHelpInvocation,
} from "./cli";
import path from "path";
import { tmpdir } from "os";
// Embed the built HTML at compile time
// @ts-ignore - Bun import attribute for text
@@ -184,8 +187,17 @@ if (args[0] === "sessions") {
// CODE REVIEW MODE
// ============================================
// Parse local flags (strip before URL detection)
// --local is now the default for PR/MR reviews; --no-local opts out.
// --local kept for backwards compat (no-op).
const localIdx = args.indexOf("--local");
if (localIdx !== -1) args.splice(localIdx, 1);
const noLocalIdx = args.indexOf("--no-local");
if (noLocalIdx !== -1) args.splice(noLocalIdx, 1);
const urlArg = args[1];
const isPRMode = urlArg?.startsWith("http://") || urlArg?.startsWith("https://");
const useLocal = isPRMode && noLocalIdx === -1;
let rawPatch: string;
let gitRef: string;
@@ -193,6 +205,8 @@ if (args[0] === "sessions") {
let gitContext: Awaited<ReturnType<typeof getVcsContext>> | undefined;
let prMetadata: Awaited<ReturnType<typeof fetchPR>>["metadata"] | undefined;
let initialDiffType: DiffType | undefined;
let agentCwd: string | undefined;
let worktreeCleanup: (() => void | Promise<void>) | undefined;
if (isPRMode) {
// --- PR Review Mode ---
@@ -231,6 +245,132 @@ if (args[0] === "sessions") {
console.error(err instanceof Error ? err.message : "Failed to fetch PR");
process.exit(1);
}
// --local: create a local checkout with the PR head for full file access
if (useLocal && prMetadata) {
// Hoisted so catch block can clean up partially-created directories
let localPath: string | undefined;
try {
const repoDir = process.cwd();
const identifier = prMetadata.platform === "github"
? `${prMetadata.owner}-${prMetadata.repo}-${prMetadata.number}`
: `${prMetadata.projectPath.replace(/\//g, "-")}-${prMetadata.iid}`;
const suffix = Math.random().toString(36).slice(2, 8);
// Resolve tmpdir to its real path — on macOS, tmpdir() returns /var/folders/...
// but processes report /private/var/folders/... which breaks path stripping.
localPath = path.join(realpathSync(tmpdir()), `plannotator-pr-${identifier}-${suffix}`);
const fetchRefStr = prMetadata.platform === "github"
? `refs/pull/${prMetadata.number}/head`
: `refs/merge-requests/${prMetadata.iid}/head`;
// Validate inputs from platform API to prevent git flag/path injection
if (prMetadata.baseBranch.includes('..') || prMetadata.baseBranch.startsWith('-')) throw new Error(`Invalid base branch: ${prMetadata.baseBranch}`);
if (!/^[0-9a-f]{40,64}$/i.test(prMetadata.baseSha)) throw new Error(`Invalid base SHA: ${prMetadata.baseSha}`);
// Detect same-repo vs cross-repo (must match both owner/repo AND host)
let isSameRepo = false;
try {
const remoteResult = await gitRuntime.runGit(["remote", "get-url", "origin"]);
if (remoteResult.exitCode === 0) {
const remoteUrl = remoteResult.stdout.trim();
const currentRepo = parseRemoteUrl(remoteUrl);
const prRepo = prMetadata.platform === "github"
? `${prMetadata.owner}/${prMetadata.repo}`
: prMetadata.projectPath;
const repoMatches = !!currentRepo && currentRepo.toLowerCase() === prRepo.toLowerCase();
// Extract host from remote URL to avoid cross-instance false positives (GHE)
const sshHost = remoteUrl.match(/^[^@]+@([^:]+):/)?.[1];
const httpsHost = (() => { try { return new URL(remoteUrl).hostname; } catch { return null; } })();
const remoteHost = (sshHost || httpsHost || "").toLowerCase();
const prHost = prMetadata.host.toLowerCase();
isSameRepo = repoMatches && remoteHost === prHost;
}
} catch { /* not in a git repo — cross-repo path */ }
if (isSameRepo) {
// ── Same-repo: fast worktree path ──
console.error("Fetching PR branch and creating local worktree...");
// Fetch base branch so origin/<baseBranch> is current for agent diffs.
// Ensure baseSha is available (may fetch, which overwrites FETCH_HEAD).
// Both MUST happen before the PR head fetch since FETCH_HEAD is what
// createWorktree uses — the PR head fetch must be last.
await fetchRef(gitRuntime, prMetadata.baseBranch, { cwd: repoDir });
await ensureObjectAvailable(gitRuntime, prMetadata.baseSha, { cwd: repoDir });
// Fetch PR head LAST — sets FETCH_HEAD to the PR tip for createWorktree.
await fetchRef(gitRuntime, fetchRefStr, { cwd: repoDir });
await createWorktree(gitRuntime, {
ref: "FETCH_HEAD",
path: localPath,
detach: true,
cwd: repoDir,
});
worktreeCleanup = () => removeWorktree(gitRuntime, localPath, { force: true, cwd: repoDir });
process.once("exit", () => {
try { Bun.spawnSync(["git", "worktree", "remove", "--force", localPath]); } catch {}
});
} else {
// ── Cross-repo: shallow clone + fetch PR head ──
const prRepo = prMetadata.platform === "github"
? `${prMetadata.owner}/${prMetadata.repo}`
: prMetadata.projectPath;
// Validate repo identifier to prevent flag injection via crafted URLs
if (/^-/.test(prRepo)) throw new Error(`Invalid repository identifier: ${prRepo}`);
const cli = prMetadata.platform === "github" ? "gh" : "glab";
const host = prMetadata.host;
const hostnameArgs = (host === "github.com" || host === "gitlab.com") ? [] : ["--hostname", host];
// Step 1: Fast skeleton clone (no checkout, depth 1 — minimal data transfer)
console.error(`Cloning ${prRepo} (shallow)...`);
const cloneResult = Bun.spawnSync(
[cli, "repo", "clone", prRepo, localPath, ...hostnameArgs, "--", "--depth=1", "--no-checkout"],
{ stderr: "pipe" },
);
if (cloneResult.exitCode !== 0) {
throw new Error(`${cli} repo clone failed: ${new TextDecoder().decode(cloneResult.stderr).trim()}`);
}
// Step 2: Fetch only the PR head ref (targeted, much faster than full fetch)
console.error("Fetching PR branch...");
const fetchResult = Bun.spawnSync(
["git", "fetch", "--depth=50", "origin", fetchRefStr],
{ cwd: localPath, stderr: "pipe" },
);
if (fetchResult.exitCode !== 0) throw new Error(`Failed to fetch PR head ref: ${new TextDecoder().decode(fetchResult.stderr).trim()}`);
// Step 3: Checkout PR head (critical — if this fails, worktree is empty)
const checkoutResult = Bun.spawnSync(["git", "checkout", "FETCH_HEAD"], { cwd: localPath, stderr: "pipe" });
if (checkoutResult.exitCode !== 0) {
throw new Error(`git checkout FETCH_HEAD failed: ${new TextDecoder().decode(checkoutResult.stderr).trim()}`);
}
// Best-effort: create base refs so `git diff main...HEAD` and `git diff origin/main...HEAD` work
const baseFetch = Bun.spawnSync(["git", "fetch", "--depth=50", "origin", prMetadata.baseSha], { cwd: localPath, stderr: "pipe" });
if (baseFetch.exitCode !== 0) console.error("Warning: failed to fetch baseSha, agent diffs may be inaccurate");
Bun.spawnSync(["git", "branch", "--", prMetadata.baseBranch, prMetadata.baseSha], { cwd: localPath, stderr: "pipe" });
Bun.spawnSync(["git", "update-ref", `refs/remotes/origin/${prMetadata.baseBranch}`, prMetadata.baseSha], { cwd: localPath, stderr: "pipe" });
worktreeCleanup = () => { try { rmSync(localPath, { recursive: true, force: true }); } catch {} };
process.once("exit", () => {
try { Bun.spawnSync(["rm", "-rf", localPath]); } catch {}
});
}
// --local only provides a sandbox path for agent processes.
// Do NOT set gitContext — that would contaminate the diff pipeline.
agentCwd = localPath;
console.error(`Local checkout ready at ${localPath}`);
} catch (err) {
console.error(`Warning: --local failed, falling back to remote diff`);
console.error(err instanceof Error ? err.message : String(err));
// Clean up partially-created directory (clone may have succeeded before fetch/checkout failed)
if (localPath) try { rmSync(localPath, { recursive: true, force: true }); } catch {}
agentCwd = undefined;
worktreeCleanup = undefined;
}
}
} else {
// --- Local Review Mode ---
gitContext = await getVcsContext();
@@ -249,12 +389,14 @@ if (args[0] === "sessions") {
gitRef,
error: diffError,
origin: detectedOrigin,
diffType: isPRMode ? undefined : (initialDiffType ?? "uncommitted"),
diffType: gitContext ? (initialDiffType ?? "uncommitted") : undefined,
gitContext,
prMetadata,
agentCwd,
sharingEnabled,
shareBaseUrl,
htmlContent: reviewHtmlContent,
onCleanup: worktreeCleanup,
onReady: async (url, isRemote, port) => {
handleReviewServerReady(url, isRemote, port);
@@ -0,0 +1,315 @@
---
title: "AI Code Review Agents"
description: "Automated code review using Codex and Claude Code agents with live findings, severity classification, and full prompt transparency."
sidebar:
order: 26
section: "Guides"
---
Launch AI review agents from the Plannotator diff viewer. Agents analyze your changes in the background and produce structured findings inline.
Two providers are supported:
- **Codex CLI** uses priority-based findings (P0 through P3)
- **Claude Code** uses a multi-agent pipeline with severity-based findings (Important, Nit, Pre-existing)
Both integrations are derived from official tooling. Claude's review model is based on Anthropic's [Claude Code Review](https://code.claude.com/docs/en/code-review) service and the open-source [code-review plugin](https://github.com/anthropics/claude-code/blob/main/plugins/code-review/README.md). Codex uses [OpenAI Codex CLI](https://github.com/openai/codex) structured output.
## Flow
1. Click **Run Agent** in the Agents tab (choose Codex or Claude)
2. The server builds the command with the appropriate prompt and schema
3. Agent runs in the background; live logs stream to the Logs tab
4. On completion, findings are parsed and appear as inline annotations
For PR reviews, a temporary local checkout is created by default so the agent has file access beyond the diff. Pass `--no-local` to skip this.
## Findings
Each finding includes a file path, line range, description, and severity or priority. Claude findings also include a reasoning trace that explains how the issue was verified.
Click any finding to navigate to the relevant file and line. Use the copy button on individual findings or "Copy All" to export as markdown.
### Severity (Claude)
| Level | Meaning |
|-------|---------|
| **Important** | Fix before merging. Build failures, logic errors, security issues. |
| **Nit** | Worth fixing, not blocking. Style, edge cases, code quality. |
| **Pre-existing** | Bug in surrounding code, not introduced by this PR. |
### Priority (Codex)
| Level | Meaning |
|-------|---------|
| **P0** | Blocking. Drop everything. |
| **P1** | Urgent. Next cycle. |
| **P2** | Normal. Fix eventually. |
| **P3** | Low. Nice to have. |
## Local worktree
PR and MR reviews automatically create a temporary checkout so agents can read files, follow imports, and understand the codebase.
- **Same-repo**: git worktree (shared objects, fast)
- **Cross-repo**: shallow clone with targeted PR head fetch
Cleaned up when the session ends. Use `--no-local` to review in remote-only mode.
## Transparency
Agents are read-only. They cannot modify code, access the network, or post comments. All AI communication goes directly to your provider (Anthropic or OpenAI). No code passes through Plannotator servers. Prompts and commands are visible in the review UI.
Below are the exact prompts, commands, and schemas used.
- [Claude Code: full prompt](#claude-code-full-prompt)
- [Claude Code: command](#claude-code-command)
- [Codex: full prompt](#codex-full-prompt)
- [Codex: command](#codex-command)
- [Codex: output schema](#codex-output-schema)
---
### Claude Code: full prompt
```
# Claude Code Review System Prompt
## Identity
You are a code review system. Your job is to find bugs that would break
production. You are not a linter, formatter, or style checker unless
project guidance files explicitly expand your scope.
## Pipeline
Step 1: Gather context
- Retrieve the PR diff (gh pr diff or git diff)
- Read CLAUDE.md and REVIEW.md at the repo root and in every directory
containing modified files
- Build a map of which rules apply to which file paths
- Identify any skip rules (paths, patterns, or file types to ignore)
Step 2: Launch 4 parallel review agents
Agent 1 — Bug + Regression (Opus-level reasoning)
Scan for logic errors, regressions, broken edge cases, build failures,
and code that will produce wrong results. Focus on the diff but read
surrounding code to understand call sites and data flow. Flag only
issues where the code is demonstrably wrong — not stylistic concerns,
not missing tests, not "could be cleaner."
Agent 2 — Security + Deep Analysis (Opus-level reasoning)
Look for security vulnerabilities with concrete exploit paths, race
conditions, incorrect assumptions about trust boundaries, and subtle
issues in introduced code. Read surrounding code for context. Do not
flag theoretical risks without a plausible path to harm.
Agent 3 — Code Quality + Reusability (Sonnet-level reasoning)
Look for code smells, unnecessary duplication, missed opportunities to
reuse existing utilities or patterns in the codebase, overly complex
implementations that could be simpler, and elegance issues. Read the
surrounding codebase to understand existing patterns before flagging.
Only flag issues a senior engineer would care about.
Agent 4 — Guideline Compliance (Haiku-level reasoning)
Audit changes against rules from CLAUDE.md and REVIEW.md gathered in
Step 1. Only flag clear, unambiguous violations where you can cite the
exact rule broken. If a PR makes a CLAUDE.md statement outdated, flag
that the docs need updating. Respect all skip rules — never flag files
or patterns that guidance says to ignore.
All agents:
- Do not duplicate each other's findings
- Do not flag issues in paths excluded by guidance files
- Provide file, line number, and a concise description for each candidate
Step 3: Validate each candidate finding
For each candidate, launch a validation agent. The validator:
- Traces the actual code path to confirm the issue is real
- Checks whether the issue is handled elsewhere (try/catch, upstream
guard, fallback logic, type system guarantees)
- Confirms the finding is not a false positive with high confidence
- If validation fails, drop the finding silently
- If validation passes, write a clear reasoning chain explaining how
the issue was confirmed — this becomes the reasoning field
Step 4: Classify each validated finding
Assign exactly one severity:
important — A bug that should be fixed before merging. Build failures,
clear logic errors, security vulnerabilities with exploit paths, data
loss risks, race conditions with observable consequences.
nit — A minor issue worth fixing but non-blocking. Style deviations
from project guidelines, code quality concerns, edge cases that are
unlikely but worth noting, convention violations that don't affect
correctness.
pre_existing — A bug that exists in the surrounding codebase but was
NOT introduced by this PR. Only flag when directly relevant to the
changed code path.
Step 5: Deduplicate and rank
- Merge findings that describe the same underlying issue from different
agents — keep the most specific description and the highest severity
- Sort by severity: important → nit → pre_existing
- Within each severity, sort by file path and line number
Step 6: Return structured JSON output matching the schema.
If no issues are found, return an empty findings array with zeroed summary.
## Hard constraints
- Never approve or block the PR
- Never comment on formatting or code style unless guidance files say to
- Never flag missing test coverage unless guidance files say to
- Never invent rules — only enforce what CLAUDE.md or REVIEW.md state
- Never flag issues in skipped paths or generated files unless guidance
explicitly includes them
- Prefer silence over false positives — when in doubt, drop the finding
- Do NOT post any comments to GitHub or GitLab
- Do NOT use gh pr comment or any commenting tool
- Your only output is the structured JSON findings
```
### Claude Code: command
```bash
claude -p \
--permission-mode dontAsk \
--output-format stream-json \
--verbose \
--json-schema '{"type":"object","properties":{"findings":{"type":"array","items":{"type":"object","properties":{"severity":{"type":"string","enum":["important","nit","pre_existing"]},"file":{"type":"string"},"line":{"type":"integer"},"end_line":{"type":"integer"},"description":{"type":"string"},"reasoning":{"type":"string"}},"required":["severity","file","line","end_line","description","reasoning"],"additionalProperties":false}},"summary":{"type":"object","properties":{"important":{"type":"integer"},"nit":{"type":"integer"},"pre_existing":{"type":"integer"}},"required":["important","nit","pre_existing"],"additionalProperties":false}},"required":["findings","summary"],"additionalProperties":false}' \
--no-session-persistence \
--model sonnet \
--tools Agent,Bash,Read,Glob,Grep \
--allowedTools Agent,Read,Glob,Grep,Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh pr list:*),Bash(gh issue view:*),Bash(gh issue list:*),Bash(gh api repos/*/*/pulls/*),Bash(gh api repos/*/*/pulls/*/files*),Bash(gh api repos/*/*/pulls/*/comments*),Bash(gh api repos/*/*/issues/*/comments*),Bash(glab mr view:*),Bash(glab mr diff:*),Bash(glab mr list:*),Bash(glab api:*),Bash(git status:*),Bash(git diff:*),Bash(git log:*),Bash(git show:*),Bash(git blame:*),Bash(git branch:*),Bash(git grep:*),Bash(git ls-remote:*),Bash(git ls-tree:*),Bash(git merge-base:*),Bash(git remote:*),Bash(git rev-parse:*),Bash(git show-ref:*),Bash(wc:*) \
--disallowedTools Edit,Write,NotebookEdit,WebFetch,WebSearch,Bash(python:*),Bash(python3:*),Bash(node:*),Bash(npx:*),Bash(bun:*),Bash(bunx:*),Bash(sh:*),Bash(bash:*),Bash(zsh:*),Bash(curl:*),Bash(wget:*)
```
Prompt is written to stdin.
---
### Codex: full prompt
```
# Review guidelines:
You are acting as a reviewer for a proposed code change made by another engineer.
Below are some default guidelines for determining whether the original author
would appreciate the issue being flagged.
These are not the final word in determining whether an issue is a bug. In many
cases, you will encounter other, more specific guidelines. These may be present
elsewhere in a developer message, a user message, a file, or even elsewhere in
this system message. Those guidelines should be considered to override these
general instructions.
Here are the general guidelines for determining whether something is a bug and
should be flagged.
1. It meaningfully impacts the accuracy, performance, security, or
maintainability of the code.
2. The bug is discrete and actionable (i.e. not a general issue with the
codebase or a combination of multiple issues).
3. Fixing the bug does not demand a level of rigor that is not present in the
rest of the codebase.
4. The bug was introduced in the commit (pre-existing bugs should not be
flagged).
5. The author of the original PR would likely fix the issue if they were made
aware of it.
6. The bug does not rely on unstated assumptions about the codebase or
author's intent.
7. It is not enough to speculate that a change may disrupt another part of the
codebase; to be considered a bug, one must identify the other parts of the
code that are provably affected.
8. The bug is clearly not just an intentional change by the original author.
Comment guidelines:
1. Clear about why the issue is a bug.
2. Appropriately communicates severity. Does not overclaim.
3. Brief. Body is at most 1 paragraph.
4. No code chunks longer than 3 lines.
5. Clearly communicates the scenarios or inputs necessary for the bug to arise.
6. Tone is matter-of-fact, not accusatory or overly positive.
7. Written so the original author can immediately grasp the idea.
8. Avoids flattery ("Great job ...", "Thanks for ...").
Output all findings that the original author would fix if they knew about it. If
there is no finding that a person would definitely love to see and fix, prefer
outputting no findings.
Priority tags: [P0] Blocking. [P1] Urgent. [P2] Normal. [P3] Low.
At the end, output an overall correctness verdict.
```
### Codex: command
```bash
codex exec \
--output-schema ~/.plannotator/codex-review-schema.json \
-o /tmp/plannotator-codex-<uuid>.json \
--full-auto \
--ephemeral \
-C <working-directory> \
"<system-prompt>\n\n---\n\n<user-message>"
```
### Codex: output schema
```json
{
"type": "object",
"properties": {
"findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": { "type": "string" },
"body": { "type": "string" },
"confidence_score": { "type": "number" },
"priority": { "type": ["integer", "null"] },
"code_location": {
"type": "object",
"properties": {
"absolute_file_path": { "type": "string" },
"line_range": {
"type": "object",
"properties": {
"start": { "type": "integer" },
"end": { "type": "integer" }
},
"required": ["start", "end"]
}
},
"required": ["absolute_file_path", "line_range"]
}
},
"required": ["title", "body", "confidence_score", "priority", "code_location"]
}
},
"overall_correctness": { "type": "string" },
"overall_explanation": { "type": "string" },
"overall_confidence_score": { "type": "number" }
},
"required": ["findings", "overall_correctness", "overall_explanation", "overall_confidence_score"]
}
```
## Customization
Add `CLAUDE.md` or `REVIEW.md` to your repo root or any subdirectory. The Claude agent reads them to understand project rules.
```markdown
# Review Rules
- Check for SQL injection in database queries
- Skip files in test-fixtures/
- Enforce snake_case in Python
```
Both files are additive. REVIEW.md extends CLAUDE.md for review-specific guidance.
+142 -15
View File
@@ -20,6 +20,7 @@ import {
AGENT_HEARTBEAT_COMMENT,
AGENT_HEARTBEAT_INTERVAL_MS,
} from "../generated/agent-jobs.js";
import { formatClaudeLogEvent } from "../generated/claude-review.js";
import { json, parseBody } from "./helpers.js";
// ---------------------------------------------------------------------------
@@ -53,6 +54,18 @@ export interface AgentJobHandlerOptions {
mode: "plan" | "review" | "annotate";
getServerUrl: () => string;
getCwd: () => string;
/** Server-side command builder for known providers (codex, claude). */
buildCommand?: (provider: string) => Promise<{
command: string[];
outputPath?: string;
captureStdout?: boolean;
stdinPrompt?: string;
cwd?: string;
prompt?: string;
label?: string;
} | null>;
/** Called when a job completes successfully — parse results and push annotations. */
onJobComplete?: (job: AgentJobInfo, meta: { outputPath?: string; stdout?: string; cwd?: string }) => void | Promise<void>;
}
export function createAgentJobHandler(options: AgentJobHandlerOptions) {
@@ -60,6 +73,7 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) {
// --- State ---
const jobs = new Map<string, { info: AgentJobInfo; proc: ChildProcess | null }>();
const jobOutputPaths = new Map<string, string>();
const subscribers = new Set<ServerResponse>();
let version = 0;
@@ -67,7 +81,6 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) {
const capabilities: AgentCapability[] = [
{ id: "claude", name: "Claude Code", available: whichCmd("claude") },
{ id: "codex", name: "Codex CLI", available: whichCmd("codex") },
{ id: "shell", name: "Shell Command", available: true },
];
const capabilitiesResponse: AgentCapabilities = {
mode,
@@ -93,6 +106,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) {
provider: string,
command: string[],
label: string,
outputPath?: string,
spawnOptions?: { captureStdout?: boolean; stdinPrompt?: string; cwd?: string; prompt?: string },
): AgentJobInfo {
const id = crypto.randomUUID();
const source = jobSource(id);
@@ -105,14 +120,23 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) {
status: "starting",
startedAt: Date.now(),
command,
cwd: getCwd(),
};
let proc: ChildProcess | null = null;
try {
const spawnCwd = spawnOptions?.cwd ?? getCwd();
const captureStdout = spawnOptions?.captureStdout ?? false;
const hasStdinPrompt = !!spawnOptions?.stdinPrompt;
proc = spawn(command[0], command.slice(1), {
cwd: getCwd(),
stdio: ["ignore", "ignore", "pipe"],
cwd: spawnCwd,
stdio: [
hasStdinPrompt ? "pipe" : "ignore",
captureStdout ? "pipe" : "ignore",
"pipe",
],
env: {
...process.env,
PLANNOTATOR_AGENT_SOURCE: source,
@@ -120,20 +144,80 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) {
},
});
// Write prompt to stdin and close (for providers that read prompt from stdin)
if (hasStdinPrompt && proc.stdin) {
proc.stdin.write(spawnOptions!.stdinPrompt!);
proc.stdin.end();
}
info.status = "running";
info.cwd = spawnCwd;
if (spawnOptions?.prompt) info.prompt = spawnOptions.prompt;
jobs.set(id, { info, proc });
if (outputPath) jobOutputPaths.set(id, outputPath);
if (spawnOptions?.cwd) jobOutputPaths.set(`${id}:cwd`, spawnOptions.cwd);
broadcast({ type: "job:started", job: { ...info } });
// Accumulate stderr continuously (must attach before exit fires)
let stderrBuf = "";
if (proc.stderr) {
proc.stderr.on("data", (chunk: Buffer) => {
stderrBuf = (stderrBuf + chunk.toString()).slice(-500);
// --- Stdout capture (Claude JSONL streaming) ---
let stdoutBuf = "";
if (captureStdout && proc.stdout) {
proc.stdout.on("data", (chunk: Buffer) => {
const text = chunk.toString();
stdoutBuf += text;
// Forward JSONL lines as log events
const lines = text.split('\n');
for (const line of lines) {
if (!line.trim()) continue;
if (provider === "claude") {
const formatted = formatClaudeLogEvent(line);
if (formatted !== null) {
broadcast({ type: "job:log", jobId: id, delta: formatted + '\n' });
}
continue;
}
try {
const event = JSON.parse(line);
if (event.type === 'result') continue;
} catch { /* not JSON — forward as raw log */ }
broadcast({ type: "job:log", jobId: id, delta: line + '\n' });
}
});
}
// Monitor process exit
proc.on("exit", (exitCode) => {
// --- Stderr: buffer tail for errors + live log streaming ---
let stderrBuf = "";
let logPending = "";
let logFlushTimer: ReturnType<typeof setTimeout> | null = null;
if (proc.stderr) {
proc.stderr.on("data", (chunk: Buffer) => {
const text = chunk.toString();
stderrBuf = (stderrBuf + text).slice(-500);
logPending += text;
if (!logFlushTimer) {
logFlushTimer = setTimeout(() => {
if (logPending) {
broadcast({ type: "job:log", jobId: id, delta: logPending });
logPending = "";
}
logFlushTimer = null;
}, 200);
}
});
}
// Monitor process close (fires after stdio streams are fully drained,
// unlike 'exit' which fires before — critical for stdout capture)
proc.on("close", async (exitCode) => {
// Flush remaining stderr
if (logFlushTimer) { clearTimeout(logFlushTimer); logFlushTimer = null; }
if (logPending) {
broadcast({ type: "job:log", jobId: id, delta: logPending });
logPending = "";
}
const entry = jobs.get(id);
if (!entry || isTerminalStatus(entry.info.status)) return;
@@ -145,6 +229,23 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) {
entry.info.error = stderrBuf;
}
// Ingest results before broadcasting completion
const jobOutputPath = jobOutputPaths.get(id);
const jobCwd = jobOutputPaths.get(`${id}:cwd`);
if (exitCode === 0 && options.onJobComplete) {
try {
await options.onJobComplete(entry.info, {
outputPath: jobOutputPath,
stdout: captureStdout ? stdoutBuf : undefined,
cwd: jobCwd,
});
} catch {
// Result ingestion failure shouldn't prevent job completion broadcast
}
}
jobOutputPaths.delete(id);
jobOutputPaths.delete(`${id}:cwd`);
broadcast({ type: "job:completed", job: { ...entry.info } });
});
@@ -185,6 +286,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) {
entry.info.status = "killed";
entry.info.endedAt = Date.now();
jobOutputPaths.delete(id);
jobOutputPaths.delete(`${id}:cwd`);
broadcast({ type: "job:completed", job: { ...entry.info } });
return true;
}
@@ -276,10 +379,11 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) {
if (url.pathname === JOBS && req.method === "POST") {
try {
const body = await parseBody(req);
const provider = typeof body.provider === "string" ? body.provider : "shell";
const rawCommand = Array.isArray(body.command) ? body.command : [];
const command = rawCommand.filter((c: unknown): c is string => typeof c === "string");
const label = typeof body.label === "string" ? body.label : `${provider} agent`;
const provider = typeof body.provider === "string" ? body.provider : "";
let rawCommand = Array.isArray(body.command) ? body.command : [];
let command = rawCommand.filter((c: unknown): c is string => typeof c === "string");
let label = typeof body.label === "string" ? body.label : `${provider} agent`;
let outputPath: string | undefined;
// Validate provider is a known, available capability
const cap = capabilities.find((c) => c.id === provider);
@@ -288,12 +392,35 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) {
return true;
}
// Try server-side command building for known providers
let captureStdout = false;
let stdinPrompt: string | undefined;
let spawnCwd: string | undefined;
let promptText: string | undefined;
if (options.buildCommand) {
const built = await options.buildCommand(provider);
if (built) {
command = built.command;
outputPath = built.outputPath;
captureStdout = built.captureStdout ?? false;
stdinPrompt = built.stdinPrompt;
spawnCwd = built.cwd;
promptText = built.prompt;
if (built.label) label = built.label;
}
}
if (command.length === 0) {
json(res, { error: 'Missing "command" array' }, 400);
return true;
}
const job = spawnJob(provider, command, label);
const job = spawnJob(provider, command, label, outputPath, {
captureStdout,
stdinPrompt,
cwd: spawnCwd,
prompt: promptText,
});
json(res, { job }, 201);
} catch {
json(res, { error: "Invalid JSON" }, 400);
@@ -49,6 +49,14 @@ export function createExternalAnnotationHandler(mode: "plan" | "review") {
});
return {
/** Push annotations directly into the store (bypasses HTTP, reuses same validation). */
addAnnotations(body: unknown): { ids: string[] } | { error: string } {
const parsed = transform(body);
if ("error" in parsed) return { error: parsed.error };
const created = store.add(parsed.annotations);
return { ids: created.map((a: { id: string }) => a.id) };
},
async handle(
req: IncomingMessage,
res: ServerResponse,
+87 -4
View File
@@ -56,6 +56,20 @@ import {
submitPRReview,
} from "./pr.js";
import { getRepoInfo } from "./project.js";
import {
CODEX_REVIEW_SYSTEM_PROMPT,
buildCodexReviewUserMessage,
buildCodexCommand,
generateOutputPath,
parseCodexOutput,
transformReviewFindings,
} from "../generated/codex-review.js";
import {
CLAUDE_REVIEW_PROMPT,
buildClaudeCommand,
parseClaudeStreamOutput,
transformClaudeFindings,
} from "../generated/claude-review.js";
export interface ReviewServerResult {
port: number;
@@ -154,15 +168,84 @@ export async function startReviewServer(options: {
// Agent jobs — background process manager (late-binds serverUrl via getter)
let serverUrl = "";
const agentJobs = createAgentJobHandler({
mode: "review",
getServerUrl: () => serverUrl,
getCwd: () => {
// Worktree-aware cwd resolver — shared by getCwd, buildCommand, and onJobComplete
function resolveAgentCwd(): string {
if (currentDiffType.startsWith("worktree:")) {
const parsed = parseWorktreeDiffType(currentDiffType);
if (parsed) return parsed.path;
}
return options.gitContext?.cwd ?? process.cwd();
}
const agentJobs = createAgentJobHandler({
mode: "review",
getServerUrl: () => serverUrl,
getCwd: resolveAgentCwd,
async buildCommand(provider) {
const cwd = resolveAgentCwd();
const hasLocalAccess = !!options.gitContext;
const userMessage = buildCodexReviewUserMessage(
currentPatch,
currentDiffType,
{ defaultBranch: options.gitContext?.defaultBranch, hasLocalAccess },
options.prMetadata,
);
if (provider === "codex") {
const outputPath = generateOutputPath();
const prompt = CODEX_REVIEW_SYSTEM_PROMPT + "\n\n---\n\n" + userMessage;
const command = await buildCodexCommand({ cwd, outputPath, prompt });
return { command, outputPath, prompt, label: "Codex Review" };
}
if (provider === "claude") {
const prompt = CLAUDE_REVIEW_PROMPT + "\n\n---\n\n" + userMessage;
const { command, stdinPrompt } = buildClaudeCommand(prompt);
return { command, stdinPrompt, prompt, cwd, label: "Claude Code Review", captureStdout: true };
}
return null;
},
async onJobComplete(job, meta) {
const cwd = resolveAgentCwd();
if (job.provider === "codex" && meta.outputPath) {
const output = await parseCodexOutput(meta.outputPath);
if (!output) return;
job.summary = {
correctness: 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;
}
if (job.provider === "claude" && meta.stdout) {
const output = parseClaudeStreamOutput(meta.stdout);
if (!output) 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;
}
},
});
const sharingEnabled =
+11 -1
View File
@@ -6,11 +6,21 @@ cd "$(dirname "$0")"
mkdir -p generated generated/ai/providers
for f in feedback-templates review-core storage draft project pr-provider pr-github pr-gitlab checklist integrations-common repo reference-common favicon resolve-file config external-annotation agent-jobs; do
for f in feedback-templates review-core storage draft project pr-provider pr-github pr-gitlab checklist integrations-common repo reference-common favicon resolve-file config external-annotation agent-jobs worktree; do
src="../../packages/shared/$f.ts"
printf '// @generated — DO NOT EDIT. Source: packages/shared/%s.ts\n' "$f" | cat - "$src" > "generated/$f.ts"
done
# Vendor review agent modules from packages/server/ — rewrite imports for generated/ layout
for f in codex-review claude-review path-utils; do
src="../../packages/server/$f.ts"
printf '// @generated — DO NOT EDIT. Source: packages/server/%s.ts\n' "$f" | cat - "$src" \
| sed 's|from "./vcs"|from "./review-core.js"|' \
| sed 's|from "./pr"|from "./pr-provider.js"|' \
| sed 's|from "./path-utils"|from "./path-utils.js"|' \
> "generated/$f.ts"
done
for f in index types provider session-manager endpoints context base-session; do
src="../../packages/ai/$f.ts"
printf '// @generated — DO NOT EDIT. Source: packages/ai/%s.ts\n' "$f" | cat - "$src" > "generated/ai/$f.ts"
+1 -1
View File
@@ -12,7 +12,7 @@
"@plannotator/review-editor": "workspace:*",
"@plannotator/server": "workspace:*",
"@plannotator/ui": "workspace:*",
"@pierre/diffs": "^1.1.0-beta.19",
"@pierre/diffs": "^1.1.12",
"dompurify": "^3.3.3",
"react": "^19.2.3",
"react-dom": "^19.2.3",
+8 -8
View File
@@ -7,7 +7,7 @@
"@anthropic-ai/claude-agent-sdk": "^0.2.81",
"@openai/codex-sdk": "^0.116.0",
"@opencode-ai/sdk": "^1.3.0",
"@pierre/diffs": "^1.1.0-beta.19",
"@pierre/diffs": "^1.1.12",
"diff": "^8.0.3",
"dockview-react": "^5.2.0",
"dompurify": "^3.3.3",
@@ -62,7 +62,7 @@
},
"apps/opencode-plugin": {
"name": "@plannotator/opencode",
"version": "0.16.6",
"version": "0.16.7",
"dependencies": {
"@opencode-ai/plugin": "^1.1.10",
},
@@ -84,7 +84,7 @@
},
"apps/pi-extension": {
"name": "@plannotator/pi-extension",
"version": "0.16.6",
"version": "0.16.7",
"peerDependencies": {
"@mariozechner/pi-coding-agent": ">=0.53.0",
},
@@ -111,7 +111,7 @@
"name": "@plannotator/review",
"version": "0.0.1",
"dependencies": {
"@pierre/diffs": "^1.1.0-beta.19",
"@pierre/diffs": "^1.1.12",
"@plannotator/review-editor": "workspace:*",
"@plannotator/server": "workspace:*",
"@plannotator/ui": "workspace:*",
@@ -159,7 +159,7 @@
"name": "@plannotator/review-editor",
"version": "0.0.1",
"dependencies": {
"@pierre/diffs": "^1.1.0-beta.19",
"@pierre/diffs": "^1.1.12",
"@plannotator/shared": "workspace:*",
"@plannotator/ui": "workspace:*",
"highlight.js": "^11.11.1",
@@ -170,7 +170,7 @@
},
"packages/server": {
"name": "@plannotator/server",
"version": "0.16.6",
"version": "0.16.7",
"dependencies": {
"@plannotator/ai": "workspace:*",
"@plannotator/shared": "workspace:*",
@@ -613,9 +613,9 @@
"@oven/bun-windows-x64-baseline": ["@oven/bun-windows-x64-baseline@1.3.5", "", { "os": "win32", "cpu": "x64" }, "sha512-rtVQB9/1XK8FWJgFtsOthbPifRMYypgJwxu+pK3NHx8WvFKmq7HcPDqNr8xLzGULjQEO7eAo2aOZfONOwYz+5g=="],
"@pierre/diffs": ["@pierre/diffs@1.1.0-beta.19", "", { "dependencies": { "@pierre/theme": "0.0.22", "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-XxGPKkVW+1t2KJQfgjmSnS+93nI9+ACJl1XjhF3Lo4BdQJOxV3pHeyix31ySn/m/1llq6O/7bXucE0OYCK6Kog=="],
"@pierre/diffs": ["@pierre/diffs@1.1.12", "", { "dependencies": { "@pierre/theme": "0.0.28", "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-InssHHM7f0nkazIRkuaiNCy6GkBLfwJlqc7LtTkMD/KSqsuc6bnL2V9sIQoG5PZu9jwinQiXUb/gT7itFa6U9A=="],
"@pierre/theme": ["@pierre/theme@0.0.22", "", {}, "sha512-ePUIdQRNGjrveELTU7fY89Xa7YGHHEy5Po5jQy/18lm32eRn96+tnYJEtFooGdffrx55KBUtOXfvVy/7LDFFhA=="],
"@pierre/theme": ["@pierre/theme@0.0.28", "", {}, "sha512-1j/H/fECBuc9dEvntdWI+l435HZapw+RCJTlqCA6BboQ5TjlnE005j/ROWutXIs8aq5OAc82JI2Kwk4A1WWBgw=="],
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
+4
View File
@@ -0,0 +1,4 @@
<svg height="1024" width="1024" xmlns="http://www.w3.org/2000/svg">
<path d="M704 316.03099999999995l-96 96L768 576l256-256-96-96L769.25 382.781 704 316.03099999999995zM512 832c-176.781 0-320-143.25-320-320 0-176.781 143.219-320 320-320 88.375 0 168.375 35.844 226.25 93.75l90.562-90.5C747.75 114.125 635.75 64 512 64 264.562 64 64 264.562 64 512c0 247.438 200.562 448 448 448 247.438 0 448-200.562 448-448L759.75 712.25C768.688 701.25 684.75 832 512 832zM576 256H448v320h128V256zM448 768h128V640H448V768z" />
</svg>

After

Width:  |  Height:  |  Size: 520 B

+4
View File
@@ -0,0 +1,4 @@
<svg height="1024" width="896" xmlns="http://www.w3.org/2000/svg">
<path d="M448 64C200.562 64 0 264.562 0 512c0 247.438 200.562 448 448 448 247.438 0 448-200.562 448-448C896 264.562 695.438 64 448 64zM448 832c-176.781 0-320-143.25-320-320 0-176.781 143.219-320 320-320 176.75 0 320 143.219 320 320C768 688.75 624.75 832 448 832zM384 768h128V640H384V768zM384 576h128V256H384V576z" />
</svg>

After

Width:  |  Height:  |  Size: 394 B

+4
View File
@@ -0,0 +1,4 @@
<svg height="1024" width="896" xmlns="http://www.w3.org/2000/svg">
<path d="M639.125 767.25C585.75 807.375 520 832 448 832c-176.781 0-320-143.25-320-320 0-45.562 9.781-88.781 27-128H64v-99.469C24.312 351.438 0 428.594 0 512c0 247.438 200.562 448 448 448 107.375 0 204.5-39.312 281.75-102.25L768 896V704H576L639.125 767.25zM384 768h128V640H384V768zM512 256H384v320h128V256zM896 512c0-247.438-200.562-448-448-448-107.406 0-204.531 39.312-281.656 102.344L128 128v192h192l-63.156-63.156C310.281 216.688 376 192 448 192c176.75 0 320 143.219 320 320 0 45.562-9.75 88.75-27 128h91v99.5C871.688 672.562 896 595.5 896 512z" />
</svg>

After

Width:  |  Height:  |  Size: 628 B

+1 -1
View File
@@ -36,7 +36,7 @@
"@anthropic-ai/claude-agent-sdk": "^0.2.81",
"@openai/codex-sdk": "^0.116.0",
"@opencode-ai/sdk": "^1.3.0",
"@pierre/diffs": "^1.1.0-beta.19",
"@pierre/diffs": "^1.1.12",
"diff": "^8.0.3",
"dockview-react": "^5.2.0",
"dompurify": "^3.3.3",
+61 -2
View File
@@ -38,6 +38,7 @@ import { FileTree } from './components/FileTree';
import { DEMO_DIFF } from './demoData';
import { exportReviewFeedback } from './utils/exportFeedback';
import { ReviewStateProvider, type ReviewState } from './dock/ReviewStateContext';
import { JobLogsProvider } from './dock/JobLogsContext';
import { reviewPanelComponents } from './dock/reviewPanelComponents';
import { ReviewDockTabRenderer } from './dock/ReviewDockTabRenderer';
import { usePRContext } from './hooks/usePRContext';
@@ -114,6 +115,7 @@ const ReviewApp: React.FC = () => {
const [selectedAnnotationId, setSelectedAnnotationId] = useState<string | null>(null);
const [pendingSelection, setPendingSelection] = useState<SelectedLineRange | null>(null);
const [showExportModal, setShowExportModal] = useState(false);
const [showWorktreeDialog, setShowWorktreeDialog] = useState(false);
const [openSettingsMenu, setOpenSettingsMenu] = useState(false);
const [showNoAnnotationsDialog, setShowNoAnnotationsDialog] = useState(false);
const [isLoading, setIsLoading] = useState(true);
@@ -151,6 +153,7 @@ const ReviewApp: React.FC = () => {
const [isWSL, setIsWSL] = useState(false);
const [diffType, setDiffType] = useState<string>('uncommitted');
const [gitContext, setGitContext] = useState<GitContext | null>(null);
const [agentCwd, setAgentCwd] = useState<string | null>(null);
const [isLoadingDiff, setIsLoadingDiff] = useState(false);
const [diffError, setDiffError] = useState<string | null>(null);
const [isSendingFeedback, setIsSendingFeedback] = useState(false);
@@ -617,6 +620,7 @@ const ReviewApp: React.FC = () => {
origin?: Origin;
diffType?: string;
gitContext?: GitContext;
agentCwd?: string;
sharingEnabled?: boolean;
repoInfo?: { display: string; branch?: string };
prMetadata?: PRMetadata;
@@ -644,6 +648,7 @@ const ReviewApp: React.FC = () => {
if (data.origin) setOrigin(data.origin);
if (data.diffType) setDiffType(data.diffType);
if (data.gitContext) setGitContext(data.gitContext);
if (data.agentCwd) setAgentCwd(data.agentCwd);
if (data.sharingEnabled !== undefined) setSharingEnabled(data.sharingEnabled);
if (data.repoInfo) setRepoInfo(data.repoInfo);
if (data.prMetadata) setPrMetadata(data.prMetadata);
@@ -970,6 +975,7 @@ const ReviewApp: React.FC = () => {
isPRContextLoading,
prContextError,
fetchPRContext,
platformUser,
openDiffFile,
}), [
files, activeFileIndex, diffStyle, diffOverflow, diffIndicators,
@@ -984,9 +990,12 @@ const ReviewApp: React.FC = () => {
aiAvailable, aiChat.messages, aiChat.isCreatingSession, aiChat.isStreaming,
handleAskAI, handleViewAIResponse, handleClickAIMarker,
aiHistoryForSelection, agentJobs.jobs, prMetadata, prContext,
isPRContextLoading, prContextError, fetchPRContext, openDiffFile,
isPRContextLoading, prContextError, fetchPRContext, platformUser, openDiffFile,
]);
// Separate context for high-frequency job logs — prevents re-rendering all panels on every SSE event
const jobLogsValue = useMemo(() => ({ jobLogs: agentJobs.jobLogs }), [agentJobs.jobLogs]);
// Copy raw diff to clipboard
const handleCopyDiff = useCallback(async () => {
if (!diffData) return;
@@ -1300,12 +1309,21 @@ const ReviewApp: React.FC = () => {
return (
<ThemeProvider defaultTheme="dark">
<ReviewStateProvider value={reviewStateValue}>
<JobLogsProvider value={jobLogsValue}>
<div className="h-screen flex flex-col bg-background overflow-hidden">
{/* Header */}
<header className="h-12 flex items-center justify-between px-2 md:px-4 border-b border-border/50 bg-card/50 backdrop-blur-xl z-50">
<header className="py-1 flex items-center justify-between px-2 md:px-4 border-b border-border/50 bg-card/50 backdrop-blur-xl z-50">
<div className="min-w-0 flex items-center gap-2 md:gap-3">
{prMetadata ? (
<div className="min-w-0 flex items-center gap-2 md:gap-3">
{prMetadata && (gitContext || agentCwd) && (
<button
onClick={() => setShowWorktreeDialog(true)}
className="text-[10px] font-medium text-primary/80 bg-primary/10 hover:bg-primary/20 px-1.5 py-0.5 rounded transition-colors cursor-pointer"
>
worktree
</button>
)}
<span
className="text-xs text-muted-foreground/60 inline-flex items-center gap-1 truncate max-w-[200px]"
title={displayRepo}
@@ -1324,6 +1342,17 @@ const ReviewApp: React.FC = () => {
<span className="font-mono whitespace-nowrap">{mrNumberLabel}</span>
<span className="truncate hidden md:inline">{prMetadata.title}</span>
</a>
<div className="hidden md:flex items-center gap-0.5 ml-1">
<button onClick={() => handleOpenPRPanel('summary')} className="p-1 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted/30 transition-colors duration-150" title="PR Summary">
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
</button>
<button onClick={() => handleOpenPRPanel('comments')} className="p-1 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted/30 transition-colors duration-150" title="PR Comments">
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" /></svg>
</button>
<button onClick={() => handleOpenPRPanel('checks')} className="p-1 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted/30 transition-colors duration-150" title="PR Checks">
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
</button>
</div>
</div>
) : repoInfo ? (
<div className="min-w-0 flex items-center gap-2 md:gap-3">
@@ -1469,7 +1498,9 @@ const ReviewApp: React.FC = () => {
isLoading={isSendingFeedback || isPlatformActioning}
muted={!platformMode && totalAnnotationCount === 0 && !isSendingFeedback && !isApproving && !isPlatformActioning}
label={platformMode ? 'Post Comments' : 'Send Feedback'}
shortLabel={platformMode ? 'Post' : 'Send'}
loadingLabel={platformMode ? 'Posting...' : 'Sending...'}
shortLoadingLabel={platformMode ? 'Posting...' : 'Sending...'}
title={!platformMode && totalAnnotationCount === 0 ? "Add annotations to send feedback" : "Send feedback"}
/>
@@ -1766,6 +1797,33 @@ const ReviewApp: React.FC = () => {
/>
</div>
{/* Worktree info dialog */}
{(gitContext?.cwd || agentCwd) && prMetadata && (
<ConfirmDialog
isOpen={showWorktreeDialog}
onClose={() => setShowWorktreeDialog(false)}
title="Local Worktree"
wide
message={
<div className="space-y-3">
<p>This PR is checked out locally so review agents have full file access.</p>
<div>
<span className="text-[10px] uppercase tracking-wider text-muted-foreground/60 font-semibold">Path</span>
<button
onClick={() => navigator.clipboard.writeText((agentCwd || gitContext?.cwd)!)}
className="mt-1 w-full text-left font-mono text-xs bg-muted/50 border border-border/50 rounded-md px-3 py-2 text-foreground hover:bg-muted transition-colors cursor-pointer break-all"
title="Click to copy"
>
{agentCwd || gitContext?.cwd}
</button>
</div>
<p className="text-xs text-muted-foreground/60">Automatically removed when this review session ends.</p>
</div>
}
variant="info"
/>
)}
{/* No annotations dialog */}
<ConfirmDialog
isOpen={showNoAnnotationsDialog}
@@ -1880,6 +1938,7 @@ const ReviewApp: React.FC = () => {
</div>
)}
</div>
</JobLogsProvider>
</ReviewStateProvider>
</ThemeProvider>
);
@@ -4,10 +4,27 @@ import { useState } from 'react';
interface CopyButtonProps {
text: string;
className?: string;
/** "overlay" (default): absolute-positioned, hover-reveal (parent needs group relative).
* "inline": normal flow, always visible, compact. */
variant?: 'overlay' | 'inline';
/** Optional label shown next to the icon (inline variant only). */
label?: string;
}
/** Hover-reveal copy button with "Copied" flash. Parent needs className="group relative". */
export const CopyButton: React.FC<CopyButtonProps> = ({ text, className = '' }) => {
const CopyIcon = () => (
<svg aria-hidden="true" className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
);
const CheckIcon = () => (
<svg aria-hidden="true" className="w-3 h-3 text-success" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
);
/** Copy-to-clipboard button with "Copied" flash. */
export const CopyButton: React.FC<CopyButtonProps> = ({ text, className = '', variant = 'overlay', label }) => {
const [copied, setCopied] = useState(false);
const handleCopy = async (e: React.MouseEvent) => {
@@ -21,6 +38,24 @@ export const CopyButton: React.FC<CopyButtonProps> = ({ text, className = '' })
}
};
if (variant === 'inline') {
return (
<button
type="button"
onClick={handleCopy}
className={`flex items-center gap-1 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors ${className}`}
title={copied ? 'Copied!' : 'Copy'}
>
{copied ? <CheckIcon /> : <CopyIcon />}
{label && (
<span className="text-[10px]">
{copied ? 'Copied' : label}
</span>
)}
</button>
);
}
return (
<button
type="button"
@@ -28,15 +63,7 @@ export const CopyButton: React.FC<CopyButtonProps> = ({ text, className = '' })
className={`absolute top-1.5 right-1.5 p-1 rounded-md opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-foreground hover:bg-muted ${className}`}
title={copied ? 'Copied!' : 'Copy'}
>
{copied ? (
<svg aria-hidden="true" className="w-3 h-3 text-success" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
) : (
<svg aria-hidden="true" className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
)}
{copied ? <CheckIcon /> : <CopyIcon />}
</button>
);
};
@@ -0,0 +1,116 @@
import React, { useMemo, useState, useEffect } from 'react';
import { FileDiff } from '@pierre/diffs/react';
import { getSingularPatch } from '@pierre/diffs';
import { useTheme } from '@plannotator/ui/components/ThemeProvider';
import { useReviewState } from '../dock/ReviewStateContext';
interface DiffHunkPreviewProps {
/** Raw diff hunk string (unified diff format). */
hunk: string;
/** Max height in pixels before "Show more" toggle. Default 128. */
maxHeight?: number;
className?: string;
}
/**
* Renders a small inline diff hunk using @pierre/diffs.
* Compact, read-only, no file header. Shares theme + font settings
* with the main DiffViewer via the same unsafeCSS injection pattern.
*/
export const DiffHunkPreview: React.FC<DiffHunkPreviewProps> = ({
hunk,
maxHeight = 128,
className,
}) => {
const { resolvedMode } = useTheme();
const state = useReviewState();
const [expanded, setExpanded] = useState(false);
const fileDiff = useMemo(() => {
if (!hunk) return undefined;
try {
const needsHeaders = !hunk.startsWith('diff --git') && !hunk.startsWith('--- ');
const patch = needsHeaders
? `diff --git a/file b/file\n--- a/file\n+++ b/file\n${hunk}`
: hunk;
return getSingularPatch(patch);
} catch {
return undefined;
}
}, [hunk]);
// Theme injection — same pattern as DiffViewer (reads computed CSS vars, injects via unsafeCSS)
const [pierreTheme, setPierreTheme] = useState<{ type: 'dark' | 'light'; css: string }>({
type: resolvedMode,
css: '',
});
useEffect(() => {
const rafId = requestAnimationFrame(() => {
const styles = getComputedStyle(document.documentElement);
const bg = styles.getPropertyValue('--background').trim();
const fg = styles.getPropertyValue('--foreground').trim();
if (!bg || !fg) return;
const fontFamily = state.fontFamily;
const fontSize = state.fontSize;
const fontCSS = fontFamily || fontSize ? `
pre, code, [data-line-content], [data-column-number] {
${fontFamily ? `font-family: '${fontFamily}', monospace !important;` : ''}
${fontSize ? `font-size: ${fontSize} !important; line-height: 1.5 !important;` : ''}
}` : '';
setPierreTheme({
type: resolvedMode,
css: `
:host, [data-diff], [data-file], [data-diffs-header], [data-error-wrapper], [data-virtualizer-buffer] {
--diffs-bg: ${bg} !important;
--diffs-fg: ${fg} !important;
--diffs-dark-bg: ${bg};
--diffs-light-bg: ${bg};
--diffs-dark: ${fg};
--diffs-light: ${fg};
}
pre, code { background-color: ${bg} !important; }
[data-column-number] { background-color: ${bg} !important; }
[data-file-info] { display: none !important; }
[data-diffs-header] { display: none !important; }
${fontCSS}
`,
});
});
return () => cancelAnimationFrame(rafId);
}, [resolvedMode, state.fontFamily, state.fontSize]);
if (!fileDiff) return null;
return (
<div className={`rounded overflow-hidden border border-border/20 ${className ?? ''}`}>
<div
className="overflow-hidden"
style={expanded ? undefined : { maxHeight }}
>
<FileDiff
fileDiff={fileDiff}
options={{
themeType: pierreTheme.type,
unsafeCSS: pierreTheme.css,
diffStyle: 'unified',
disableLineNumbers: true,
disableFileHeader: true,
disableBackground: true,
overflow: 'wrap',
}}
/>
</div>
{!expanded && (
<button
onClick={(e) => { e.stopPropagation(); setExpanded(true); }}
className="w-full text-[10px] text-muted-foreground hover:text-foreground py-1 bg-muted/20 border-t border-border/20 transition-colors"
>
Show full context
</button>
)}
</div>
);
};
@@ -355,6 +355,8 @@ export const DiffViewer: React.FC<DiffViewerProps> = ({
suggestedCode: ann.suggestedCode,
originalCode: ann.originalCode,
author: ann.author,
severity: ann.severity,
reasoning: ann.reasoning,
} as DiffAnnotationMetadata,
}));
}, [annotations]);
@@ -79,8 +79,8 @@ export const FileHeader: React.FC<FileHeaderProps> = ({
return (
<div
ref={headerRef}
className="flex-shrink-0 px-3 bg-card border-b border-border flex items-center justify-between gap-2"
style={{ height: '30px' }}
className="flex-shrink-0 px-3 border-b border-border/50 flex items-center justify-between gap-2"
style={{ height: 'var(--panel-header-h)' }}
>
<div className="min-w-0 flex flex-1 items-center">
<span className="min-w-0 flex items-center text-xs font-semibold leading-none whitespace-nowrap" title={filePath}>
+44 -57
View File
@@ -166,11 +166,11 @@ export const FileTree: React.FC<FileTreeProps> = ({
}, []);
return (
<aside className="border-r border-border bg-card/30 flex flex-col flex-shrink-0 overflow-hidden" style={{ width: width ?? 256 }}>
<aside className="border-r border-border/50 bg-card/30 flex flex-col flex-shrink-0 overflow-hidden" style={{ width: width ?? 256 }}>
{/* Header */}
<div className="px-3 py-2 border-b border-border/50">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
<div className="px-3 flex items-center border-b border-border/50" style={{ height: 'var(--panel-header-h)' }}>
<div className="w-full flex items-center justify-between">
<span className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
{searchQuery.trim() ? 'Results' : 'Files'}
</span>
<div className="flex items-center gap-1.5">
@@ -270,7 +270,7 @@ export const FileTree: React.FC<FileTreeProps> = ({
}
}}
placeholder="Search diff..."
className="w-full pl-7 py-1.5 pr-7 bg-muted rounded-md text-xs text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary/50"
className="w-full pl-7 py-1.5 pr-7 bg-muted rounded text-xs text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary/50"
/>
<div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1">
{searchQuery.trim() && !isSearchPending && (
@@ -292,16 +292,16 @@ export const FileTree: React.FC<FileTreeProps> = ({
</div>
)}
{/* Worktree context switcher — only shown when worktrees exist */}
{/* Worktree + diff selectors — combined row when both present */}
{((worktrees && worktrees.length > 0 && onSelectWorktree) || (diffOptions && diffOptions.length > 0 && onSelectDiff)) && (
<div className="px-2 py-1.5 border-b border-border/30 flex gap-2">
{worktrees && worktrees.length > 0 && onSelectWorktree && (
<div className="px-2 pt-2 pb-1.5 border-b border-border/30">
<div className="text-[10px] text-muted-foreground/60 uppercase tracking-wider mb-1 px-0.5">Context</div>
<div className="relative">
<div className="relative flex-1 min-w-0">
<select
value={activeWorktreePath || ''}
onChange={(e) => onSelectWorktree(e.target.value || null)}
disabled={isLoadingDiff}
className={`w-full px-2.5 py-1.5 rounded-md text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 cursor-pointer disabled:opacity-50 disabled:cursor-wait appearance-none pr-7 ${
className={`w-full px-2.5 py-1.5 rounded text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 cursor-pointer disabled:opacity-50 disabled:cursor-wait appearance-none pr-7 ${
activeWorktreePath
? 'bg-primary/10 border border-primary/30'
: 'bg-muted'
@@ -320,21 +320,14 @@ export const FileTree: React.FC<FileTreeProps> = ({
</svg>
</div>
</div>
</div>
)}
{/* Diff type selector — always the same base options */}
{diffOptions && diffOptions.length > 0 && onSelectDiff && (
<div className="px-2 py-1.5 border-b border-border/30">
{worktrees && worktrees.length > 0 && (
<div className="text-[10px] text-muted-foreground/60 uppercase tracking-wider mb-1 px-0.5">View</div>
)}
<div className="relative">
<div className="relative flex-1 min-w-0">
<select
value={activeDiffType || 'uncommitted'}
onChange={(e) => onSelectDiff(e.target.value)}
disabled={isLoadingDiff}
className="w-full px-2.5 py-1.5 bg-muted rounded-md text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 cursor-pointer disabled:opacity-50 disabled:cursor-wait appearance-none pr-7"
className="w-full px-2.5 py-1.5 bg-muted rounded text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 cursor-pointer disabled:opacity-50 disabled:cursor-wait appearance-none pr-7"
>
{diffOptions.map((option) => (
<option key={option.id} value={option.id}>
@@ -355,11 +348,12 @@ export const FileTree: React.FC<FileTreeProps> = ({
)}
</div>
</div>
)}
</div>
)}
{/* File tree or search results */}
<div className="flex-1 overflow-y-auto p-2">
<div className="flex-1 overflow-y-auto px-1 py-1">
{searchQuery.trim() ? (
isSearchPending ? (
<div className="py-6 text-center text-xs text-muted-foreground/50">
@@ -401,9 +395,33 @@ export const FileTree: React.FC<FileTreeProps> = ({
</div>
{/* Footer */}
<div className="px-2 py-1.5 border-t border-border/50 text-xs text-muted-foreground space-y-1.5">
<div className="flex justify-between">
<span>Total changes:</span>
<div className="px-2 py-1.5 border-t border-border/50 text-xs text-muted-foreground">
<div className="flex items-center justify-between">
{onCopyRawDiff ? (
<button
onClick={onCopyRawDiff}
disabled={!canCopyRawDiff}
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
title="Copy all raw diffs to clipboard (Cmd/Ctrl+Shift+C)"
>
{copyRawDiffStatus === 'success' ? (
<svg className="w-3 h-3 text-success" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
) : copyRawDiffStatus === 'error' ? (
<svg className="w-3 h-3 text-destructive" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
) : (
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
)}
{copyRawDiffStatus === 'success' ? 'Copied' : copyRawDiffStatus === 'error' ? 'Failed' : 'Copy diffs'}
</button>
) : (
<span />
)}
<span className="file-stats inline-flex items-center gap-1.5">
<span className="additions">
+{files.reduce((sum, f) => sum + f.additions, 0)}
@@ -413,37 +431,6 @@ export const FileTree: React.FC<FileTreeProps> = ({
</span>
</span>
</div>
{onCopyRawDiff && (
<button
onClick={onCopyRawDiff}
disabled={!canCopyRawDiff}
className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-md text-[11px] font-medium transition-all text-muted-foreground hover:text-foreground hover:bg-muted/50 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-muted-foreground"
title="Copy all raw diffs to clipboard (Cmd/Ctrl+Shift+C)"
>
{copyRawDiffStatus === 'success' ? (
<>
<svg className="w-3.5 h-3.5 text-success" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
Copied
</>
) : copyRawDiffStatus === 'error' ? (
<>
<svg className="w-3.5 h-3.5 text-destructive" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
Copy failed
</>
) : (
<>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
Copy All Raw Diffs
</>
)}
</button>
)}
</div>
</aside>
);
@@ -478,7 +465,7 @@ const SearchFileGroup: React.FC<{
<div className="mb-1">
{/* File header */}
<button
className="w-full flex items-center gap-1.5 px-2 py-1.5 rounded-md text-xs hover:bg-muted transition-colors group"
className="w-full flex items-center gap-1.5 px-2 py-1.5 rounded text-xs hover:bg-muted transition-colors group"
onClick={() => setCollapsed(prev => !prev)}
>
<svg className={`w-3 h-3 text-muted-foreground/50 transition-transform flex-shrink-0 ${collapsed ? '' : 'rotate-90'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
@@ -525,7 +512,7 @@ const SearchMatchRow: React.FC<{
return (
<button
className={`w-full text-left px-2 py-1 rounded-sm text-[11px] font-mono transition-colors flex items-start gap-1.5 ${
className={`w-full text-left px-2 py-1 rounded-sm text-xs font-mono transition-colors flex items-start gap-1.5 ${
isActive
? 'bg-primary/15 text-foreground'
: 'hover:bg-muted/50 text-muted-foreground'
@@ -533,7 +520,7 @@ const SearchMatchRow: React.FC<{
onClick={onSelect}
>
<span className="flex-shrink-0 text-muted-foreground/40 w-7 text-right tabular-nums">{match.lineNumber}</span>
<span className={`flex-shrink-0 w-6 text-[9px] font-semibold uppercase ${sideColor}`}>{sideLabel}</span>
<span className={`flex-shrink-0 w-6 text-[10px] font-semibold uppercase ${sideColor}`}>{sideLabel}</span>
<span className="truncate leading-relaxed">{highlightQuery(match.snippet, searchQuery)}</span>
</button>
);
@@ -45,7 +45,7 @@ export const FileTreeNodeItem: React.FC<FileTreeNodeProps> = ({
getAnnotationCount,
stagedFiles,
}) => {
const paddingLeft = 8 + node.depth * 12;
const paddingLeft = 4 + node.depth * 8;
if (node.type === 'folder') {
if (!hasVisibleChildren(node, viewedFiles, activeFileIndex, hideViewedFiles)) {
@@ -113,7 +113,7 @@ export const FileTreeNodeItem: React.FC<FileTreeNodeProps> = ({
onClick={() => onSelectFile(node.fileIndex!)}
onDoubleClick={() => onDoubleClickFile?.(node.fileIndex!)}
className={`file-tree-item w-full text-left group ${isActive ? 'active' : ''} ${annotationCount > 0 ? 'has-annotations' : ''} ${isStaged ? 'staged' : ''}`}
style={{ paddingLeft: paddingLeft + 15 }}
style={{ paddingLeft }}
>
<div className="flex items-center gap-1.5 flex-1 min-w-0">
<span
@@ -1,5 +1,5 @@
import React from 'react';
import { DiffAnnotationMetadata } from '@plannotator/ui/types';
import { SEVERITY_STYLES, DiffAnnotationMetadata } from '@plannotator/ui/types';
import { SuggestionBlock } from './SuggestionBlock';
import { renderInlineMarkdown } from '../utils/renderInlineMarkdown';
@@ -19,6 +19,8 @@ export const InlineAnnotation: React.FC<InlineAnnotationProps> = ({
onEdit,
onDelete,
}) => {
const severity = metadata.severity ? SEVERITY_STYLES[metadata.severity] : null;
return (
<div
className="review-comment"
@@ -26,7 +28,12 @@ export const InlineAnnotation: React.FC<InlineAnnotationProps> = ({
onClick={() => onSelect(metadata.annotationId)}
>
<div className="review-comment-header">
<div className="flex items-center gap-1.5">
{severity && (
<span className={`w-2 h-2 rounded-full flex-shrink-0 ${severity.dot}`} title={severity.label} />
)}
{metadata.author && <span className="text-xs text-muted-foreground">{metadata.author}</span>}
</div>
<div className="review-comment-actions">
<button
className="review-comment-action"
@@ -57,6 +64,11 @@ export const InlineAnnotation: React.FC<InlineAnnotationProps> = ({
{metadata.text && (
<div className="review-comment-body">{renderInlineMarkdown(metadata.text)}</div>
)}
{metadata.reasoning && (
<div className="review-comment-reasoning text-[11px] text-muted-foreground/60 leading-relaxed mt-1.5">
{metadata.reasoning}
</div>
)}
{metadata.suggestedCode && (
<div className="mt-2">
<SuggestionBlock code={metadata.suggestedCode} originalCode={metadata.originalCode} language={language} />
@@ -0,0 +1,84 @@
import React, { useRef, useEffect, useMemo, useCallback } from 'react';
import { CopyButton } from './CopyButton';
interface LiveLogViewerProps {
/** The full accumulated log text. */
content: string;
/** Whether the source is still producing output. */
isLive?: boolean;
/** Max bytes to render (trim from top). Default 50KB. */
maxRenderSize?: number;
/** Optional className for the outer container. */
className?: string;
}
/**
* Reusable streaming log viewer with auto-scroll, truncation, and copy.
*
* Auto-scrolls to bottom as new content arrives — unless the user has
* scrolled up to read earlier output. Follows the AITab streaming pattern.
*/
export const LiveLogViewer: React.FC<LiveLogViewerProps> = ({
content,
isLive = false,
maxRenderSize = 50_000,
className,
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const isAtBottomRef = useRef(true);
const handleScroll = useCallback(() => {
const el = containerRef.current;
if (!el) return;
isAtBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
}, []);
// Auto-scroll on new content if user is at bottom
useEffect(() => {
if (isAtBottomRef.current && containerRef.current) {
containerRef.current.scrollTop = containerRef.current.scrollHeight;
}
}, [content]);
const displayText = useMemo(() => {
if (content.length <= maxRenderSize) return content;
const sliceFrom = content.indexOf('\n', content.length - maxRenderSize);
return '[earlier output truncated]\n' + content.slice(sliceFrom === -1 ? content.length - maxRenderSize : sliceFrom + 1);
}, [content, maxRenderSize]);
if (!content && !isLive) {
return (
<div className={`flex items-center justify-center py-8 ${className ?? ''}`}>
<p className="text-xs text-muted-foreground">No output captured.</p>
</div>
);
}
return (
<div className={`group relative flex-1 min-h-0 ${className ?? ''}`}>
<div
ref={containerRef}
onScroll={handleScroll}
className="h-full overflow-y-auto rounded bg-muted/30 p-3"
>
{!content && isLive ? (
<span className="text-xs text-muted-foreground/50 animate-pulse">
Waiting for output...
</span>
) : (
<pre className="text-xs leading-relaxed font-mono whitespace-pre-wrap break-words text-foreground/80">
{displayText}
{isLive && content && (
<span className="inline-block w-1.5 h-3.5 bg-primary/60 ml-0.5 animate-pulse rounded-sm" />
)}
</pre>
)}
</div>
{content && (
<div className="absolute top-2 right-2">
<CopyButton text={content} variant="inline" />
</div>
)}
</div>
);
};
@@ -94,7 +94,7 @@ export const PRChecksTab: React.FC<PRChecksTabProps> = ({ context }) => {
const mergeableConflict = !isMerged && !isClosed && context.mergeable === 'CONFLICTING';
return (
<div className="p-3 space-y-4">
<div className="px-8 py-4 space-y-4 max-w-2xl">
{/* Merge readiness */}
<div className="space-y-2">
<h3 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
@@ -104,7 +104,7 @@ export const PRChecksTab: React.FC<PRChecksTabProps> = ({ context }) => {
<div className="space-y-1.5">
{/* Review decision */}
{decisionStyle && (
<div className={`flex items-center gap-2 px-2 py-1.5 rounded-md ${decisionStyle.bg}`}>
<div className={`flex items-center gap-2 px-2 py-1.5 rounded ${decisionStyle.bg}`}>
<span className={`text-xs font-medium ${decisionStyle.text}`}>
{decisionStyle.label}
</span>
@@ -112,7 +112,7 @@ export const PRChecksTab: React.FC<PRChecksTabProps> = ({ context }) => {
)}
{/* Merge state */}
<div className={`flex items-center gap-2 px-2 py-1.5 rounded-md ${mergeStyle.bg}`}>
<div className={`flex items-center gap-2 px-2 py-1.5 rounded ${mergeStyle.bg}`}>
<span className={`text-xs font-medium ${mergeStyle.text}`}>
{mergeableConflict ? 'Has merge conflicts' : mergeStyle.label}
</span>
@@ -134,23 +134,26 @@ export const PRChecksTab: React.FC<PRChecksTabProps> = ({ context }) => {
</span>
</div>
<div className="space-y-3">
<div className="space-y-4">
{Array.from(groupedChecks.entries()).map(([workflow, checks]) => (
<div key={workflow}>
<div className="text-[10px] font-medium text-muted-foreground mb-1">{workflow}</div>
<div className="space-y-0.5">
<div className="text-[10px] font-semibold text-muted-foreground mb-1.5 uppercase tracking-wider">{workflow}</div>
<div className="space-y-1">
{checks.map((check, i) => (
<a
key={`${check.name}-${i}`}
href={check.detailsUrl || undefined}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-2 px-2 py-1 rounded hover:bg-muted/50 transition-colors group"
className="flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/30 transition-colors group cursor-pointer"
>
<CheckIcon check={check} />
<span className="text-xs text-foreground/80 truncate group-hover:text-foreground">
<span className="text-xs text-primary/70 truncate group-hover:text-primary group-hover:underline">
{check.name}
</span>
<svg className="w-3 h-3 text-muted-foreground/30 ml-auto flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
</a>
))}
</div>
@@ -1,14 +1,22 @@
import React, { useMemo } from 'react';
import type { PRContext, PRComment, PRReview } from '@plannotator/shared/pr-provider';
import React, { useMemo, useState, useEffect, useRef, useCallback } from 'react';
import type { PRContext, PRComment, PRReview, PRReviewThread } from '@plannotator/shared/pr-provider';
import { MarkdownBody } from './PRSummaryTab';
import { CopyButton } from './CopyButton';
import { DiffHunkPreview } from './DiffHunkPreview';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface PRCommentsTabProps {
context: PRContext;
platformUser?: string | null;
}
type TimelineEntry =
| { kind: 'comment'; data: PRComment }
| { kind: 'review'; data: PRReview };
| { kind: 'review'; data: PRReview }
| { kind: 'thread'; data: PRReviewThread };
const REVIEW_STATE_STYLES: Record<string, { bg: string; text: string; label: string }> = {
APPROVED: { bg: 'bg-success/15', text: 'text-success', label: 'Approved' },
@@ -17,46 +25,166 @@ const REVIEW_STATE_STYLES: Record<string, { bg: string; text: string; label: str
DISMISSED: { bg: 'bg-muted', text: 'text-muted-foreground/60', label: 'Dismissed' },
};
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function formatRelativeTime(iso: string): string {
if (!iso) return '';
const now = Date.now();
const then = new Date(iso).getTime();
if (isNaN(then)) return '';
const diff = now - then;
const diff = Date.now() - then;
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (minutes < 1) return 'just now';
if (minutes < 60) return `${minutes}m ago`;
if (hours < 24) return `${hours}h ago`;
if (days < 30) return `${days}d ago`;
return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
export const PRCommentsTab: React.FC<PRCommentsTabProps> = ({ context }) => {
const timeline = useMemo<TimelineEntry[]>(() => {
function getEntryTime(entry: TimelineEntry): string {
if (entry.kind === 'comment') return entry.data.createdAt;
if (entry.kind === 'review') return entry.data.submittedAt;
return entry.data.comments[0]?.createdAt ?? '';
}
function getEntryAuthor(entry: TimelineEntry): string {
if (entry.kind === 'thread') return entry.data.comments[0]?.author ?? '';
return entry.data.author;
}
function getEntryBody(entry: TimelineEntry): string {
if (entry.kind === 'thread') return entry.data.comments.map((c) => c.body).join(' ');
return entry.data.body;
}
function matchesSearch(entry: TimelineEntry, query: string): boolean {
const q = query.toLowerCase();
const author = getEntryAuthor(entry).toLowerCase();
const body = getEntryBody(entry).toLowerCase();
if (entry.kind === 'thread') {
return author.includes(q) || body.includes(q) || entry.data.path.toLowerCase().includes(q);
}
return author.includes(q) || body.includes(q);
}
function isTypingTarget(target: EventTarget | null): boolean {
if (!target || !(target instanceof HTMLElement)) return false;
const tag = target.tagName;
return tag === 'INPUT' || tag === 'TEXTAREA' || target.isContentEditable;
}
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
export const PRCommentsTab: React.FC<PRCommentsTabProps> = React.memo(({ context, platformUser }) => {
// --- State ---
const [searchQuery, setSearchQuery] = useState('');
const [sortNewestFirst, setSortNewestFirst] = useState(false);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [collapsedIds, setCollapsedIds] = useState<Set<string>>(new Set());
const [excludedAuthors, setExcludedAuthors] = useState<Set<string>>(new Set());
const containerRef = useRef<HTMLDivElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);
// --- Data pipeline ---
const baseTimeline = useMemo<TimelineEntry[]>(() => {
const entries: TimelineEntry[] = [
...context.comments.map((c): TimelineEntry => ({ kind: 'comment', data: c })),
...context.reviews
.filter((r) => r.state !== 'COMMENTED' || r.body)
.map((r): TimelineEntry => ({ kind: 'review', data: r })),
...(context.reviewThreads ?? [])
.filter((t) => t.comments.length > 0)
.map((t): TimelineEntry => ({ kind: 'thread', data: t })),
];
entries.sort((a, b) => {
const timeA = a.kind === 'comment' ? a.data.createdAt : a.data.submittedAt;
const timeB = b.kind === 'comment' ? b.data.createdAt : b.data.submittedAt;
return new Date(timeA).getTime() - new Date(timeB).getTime();
});
entries.sort((a, b) => new Date(getEntryTime(a)).getTime() - new Date(getEntryTime(b)).getTime());
return entries;
}, [context.comments, context.reviews]);
}, [context.comments, context.reviews, context.reviewThreads]);
if (timeline.length === 0) {
const uniqueAuthors = useMemo(
() => [...new Set(baseTimeline.map((e) => getEntryAuthor(e)).filter(Boolean))].sort(),
[baseTimeline],
);
const filteredTimeline = useMemo(() => {
let result = baseTimeline;
if (excludedAuthors.size > 0) {
result = result.filter((e) => !excludedAuthors.has(getEntryAuthor(e)));
}
if (searchQuery.trim()) {
result = result.filter((e) => matchesSearch(e, searchQuery.trim()));
}
return result;
}, [baseTimeline, searchQuery, excludedAuthors]);
const displayTimeline = useMemo(
() => sortNewestFirst ? [...filteredTimeline].reverse() : filteredTimeline,
[filteredTimeline, sortNewestFirst],
);
// --- Scroll to selected ---
useEffect(() => {
if (!selectedId || !containerRef.current) return;
const el = containerRef.current.querySelector(`[data-comment-id="${CSS.escape(selectedId)}"]`);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
}, [selectedId]);
// --- Keyboard ---
useEffect(() => {
const handler = (e: KeyboardEvent) => {
// Cmd+Shift+F → focus search
if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === 'f') {
e.preventDefault();
searchInputRef.current?.focus();
}
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, []);
// --- Collapse helpers ---
const toggleCollapsed = useCallback((id: string) => {
setCollapsedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id); else next.add(id);
return next;
});
}, []);
const collapseAll = useCallback(() => {
setCollapsedIds(new Set(displayTimeline.map((e) => e.data.id)));
}, [displayTimeline]);
const expandAll = useCallback(() => setCollapsedIds(new Set()), []);
// --- Search input keyboard ---
const handleSearchKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Escape') {
if (searchQuery) {
setSearchQuery('');
} else {
(e.target as HTMLInputElement).blur();
}
e.stopPropagation();
}
}, [searchQuery]);
// --- Clear all filters ---
const clearFilters = useCallback(() => {
setSearchQuery('');
setExcludedAuthors(new Set());
}, []);
// --- Empty state (no comments at all) ---
if (baseTimeline.length === 0) {
return (
<div className="flex flex-col items-center justify-center h-40 text-center px-4">
<div className="h-full flex flex-col items-center justify-center text-center px-8">
<div className="w-10 h-10 rounded-full bg-muted/50 flex items-center justify-center mb-3">
<svg className="w-5 h-5 text-muted-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
@@ -67,54 +195,351 @@ export const PRCommentsTab: React.FC<PRCommentsTabProps> = ({ context }) => {
);
}
return (
<div className="p-2 space-y-2">
{timeline.map((entry) => {
if (entry.kind === 'review') {
const review = entry.data;
const style = REVIEW_STATE_STYLES[review.state] ?? REVIEW_STATE_STYLES.COMMENTED;
const hasFilters = !!searchQuery.trim() || excludedAuthors.size > 0;
return (
<div key={review.id} className="rounded-lg border border-border/50 p-2.5">
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-1.5">
<span className="text-[11px] font-medium text-foreground">
{review.author || 'unknown'}
<div ref={containerRef} className="h-full flex flex-col">
{/* ── Toolbar ── */}
<div className="flex-shrink-0 bg-background border-b border-border/30 px-8 py-2 space-y-2">
{/* Search */}
<div className="relative">
<svg className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground/40" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<input
ref={searchInputRef}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={handleSearchKeyDown}
placeholder="Search comments..."
className="w-full pl-8 py-1.5 pr-20 bg-muted rounded text-xs text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-1 focus:ring-primary/50"
/>
<div className="absolute right-2.5 top-1/2 -translate-y-1/2 flex items-center gap-1.5">
{searchQuery.trim() && (
<span className="text-[10px] text-muted-foreground tabular-nums">
{filteredTimeline.length} of {baseTimeline.length}
</span>
<span className={`text-[9px] font-medium px-1.5 py-0.5 rounded ${style.bg} ${style.text}`}>
{style.label}
</span>
</div>
<span className="text-[10px] text-muted-foreground/50">
{formatRelativeTime(review.submittedAt)}
</span>
</div>
{review.body && (
<div className="text-xs text-foreground/80 mt-1 review-comment-markdown">
<MarkdownBody markdown={review.body} />
</div>
)}
{searchQuery && (
<button
onClick={() => setSearchQuery('')}
className="p-0.5 rounded text-muted-foreground hover:text-foreground transition-colors"
>
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div>
{/* Controls row */}
<div className="flex items-center justify-between gap-2">
{/* Author pills — click to exclude, click again to re-include */}
<div className="flex items-center gap-1 overflow-x-auto min-w-0">
{excludedAuthors.size > 0 && (
<button
onClick={() => setExcludedAuthors(new Set())}
className="text-[10px] px-1.5 py-0.5 rounded text-primary hover:underline whitespace-nowrap"
>
Show all
</button>
)}
{uniqueAuthors.map((author) => (
<AuthorPill
key={author}
label={author === platformUser ? `${author} (you)` : author}
excluded={excludedAuthors.has(author)}
onClick={() => {
setExcludedAuthors((prev) => {
const next = new Set(prev);
if (next.has(author)) next.delete(author); else next.add(author);
return next;
});
}}
/>
))}
</div>
{/* Sort + collapse controls */}
<div className="flex items-center gap-1 flex-shrink-0">
<button
onClick={() => setSortNewestFirst((v) => !v)}
className="text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground hover:text-foreground transition-colors"
>
{sortNewestFirst ? 'Newest' : 'Oldest'}
</button>
<button onClick={collapseAll} className="p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted/30 transition-colors" title="Collapse all">
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M4 14h16M4 10h16" />
</svg>
</button>
<button onClick={expandAll} className="p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted/30 transition-colors" title="Expand all">
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M4 6h16M4 12h16M4 18h16" />
</svg>
</button>
</div>
</div>
</div>
{/* ── Timeline ── */}
<div className="flex-1 overflow-y-auto px-8 py-4">
<div className="space-y-3 max-w-2xl">
{displayTimeline.length === 0 ? (
<div className="text-center py-8">
<p className="text-xs text-muted-foreground mb-2">No comments match your filters.</p>
<button onClick={clearFilters} className="text-[10px] text-primary hover:underline">
Clear filters
</button>
</div>
) : (
displayTimeline.map((entry) => {
const id = entry.data.id;
const isSelected = selectedId === id;
const isCollapsed = collapsedIds.has(id);
if (entry.kind === 'thread') {
return (
<ThreadCard
key={id}
thread={entry.data}
isSelected={isSelected}
isCollapsed={isCollapsed}
onSelect={() => setSelectedId(isSelected ? null : id)}
onToggleCollapse={() => toggleCollapsed(id)}
/>
);
}
const comment = entry.data;
const isReview = entry.kind === 'review';
const review = isReview ? (entry.data as PRReview) : null;
const style = review && review.state !== 'COMMENTED'
? (REVIEW_STATE_STYLES[review.state] ?? null)
: null;
return (
<div key={comment.id} className="rounded-lg border border-border/50 p-2.5">
<div className="flex items-center justify-between mb-1">
<span className="text-[11px] font-medium text-foreground">
{comment.author || 'unknown'}
<div
key={id}
data-comment-id={id}
onClick={() => setSelectedId(isSelected ? null : id)}
className={`group/card rounded bg-card border p-3 cursor-pointer transition-all duration-150 shadow-[0_1px_3px_rgba(0,0,0,0.06)] ${
isSelected
? 'border-primary/20 bg-primary/5 ring-1 ring-primary/10'
: 'border-border/40 hover:shadow-[0_2px_6px_rgba(0,0,0,0.08)]'
}`}
>
<div
className="flex items-center justify-between"
onClick={(e) => { e.stopPropagation(); toggleCollapsed(id); }}
>
<div className="flex items-center gap-2 min-w-0">
<span className="text-xs font-semibold text-foreground truncate">
{entry.data.author || 'unknown'}
</span>
<span className="text-[10px] text-muted-foreground/50">
{formatRelativeTime(comment.createdAt)}
{style && (
<span className={`text-[10px] font-medium px-1.5 py-0.5 rounded flex-shrink-0 ${style.bg} ${style.text}`}>
{style.label}
</span>
)}
</div>
<div className="flex items-center gap-2 flex-shrink-0">
<span className="text-[10px] text-muted-foreground">
{formatRelativeTime(getEntryTime(entry))}
</span>
<svg className={`w-3 h-3 text-muted-foreground/40 transition-transform duration-150 ${isCollapsed ? '' : 'rotate-180'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
</svg>
</div>
</div>
{!isCollapsed && entry.data.body && (
<div className="mt-2 text-xs text-foreground/80 leading-relaxed review-comment-markdown">
<MarkdownBody markdown={entry.data.body} />
</div>
)}
{!isCollapsed && (
<CommentActions
url={entry.kind === 'comment' ? (entry.data as PRComment).url : (entry.data as PRReview).url}
body={entry.data.body}
/>
)}
</div>
);
})
)}
</div>
<div className="text-xs text-foreground/80 review-comment-markdown">
<MarkdownBody markdown={comment.body} />
</div>
</div>
);
})}
});
// ---------------------------------------------------------------------------
// Subcomponents
// ---------------------------------------------------------------------------
function ThreadCard({ thread, isSelected, isCollapsed, onSelect, onToggleCollapse }: {
thread: PRReviewThread;
isSelected: boolean;
isCollapsed: boolean;
onSelect: () => void;
onToggleCollapse: () => void;
}) {
const [isExpanded, setIsExpanded] = useState(false);
const first = thread.comments[0];
if (!first) return null;
const replies = thread.comments.slice(1);
const isDimmed = thread.isResolved || thread.isOutdated;
const lineLabel = thread.startLine && thread.line && thread.startLine !== thread.line
? `L${thread.startLine}–${thread.line}`
: thread.line ? `L${thread.line}` : '';
return (
<div
data-comment-id={thread.id}
onClick={onSelect}
className={`group/card rounded border p-3 cursor-pointer transition-all duration-150 ${
isDimmed ? 'bg-card/50 shadow-[0_1px_2px_rgba(0,0,0,0.03)]' : 'bg-card shadow-[0_1px_3px_rgba(0,0,0,0.06)]'
} ${
isSelected
? 'border-primary/20 bg-primary/5 ring-1 ring-primary/10'
: 'border-border/40 hover:shadow-[0_2px_6px_rgba(0,0,0,0.08)]'
}`}
>
{/* Header */}
<div
className="flex items-center justify-between"
onClick={(e) => { e.stopPropagation(); onToggleCollapse(); }}
>
<div className="flex items-center gap-2 min-w-0">
<span className={`text-xs font-semibold truncate ${thread.isResolved ? 'line-through text-muted-foreground' : 'text-foreground'}`}>
{first.author || 'unknown'}
</span>
{thread.isOutdated && (
<span className="text-[10px] font-medium px-1.5 py-0.5 rounded bg-warning/15 text-warning flex-shrink-0">
Outdated
</span>
)}
{thread.isResolved && (
<span className="text-[10px] font-medium px-1.5 py-0.5 rounded bg-success/15 text-success flex-shrink-0">
Resolved
</span>
)}
{thread.path && (
<span className="text-[10px] font-mono text-muted-foreground truncate flex-shrink min-w-0">
{thread.path.split('/').pop()}{lineLabel ? `:${lineLabel}` : ''}
</span>
)}
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{replies.length > 0 && (
<span className="text-[10px] text-muted-foreground">
{replies.length} repl{replies.length === 1 ? 'y' : 'ies'}
</span>
)}
<span className="text-[10px] text-muted-foreground">
{formatRelativeTime(first.createdAt)}
</span>
<svg className={`w-3 h-3 text-muted-foreground/40 transition-transform duration-150 ${isCollapsed ? '' : 'rotate-180'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
</svg>
</div>
</div>
{/* Body */}
{!isCollapsed && (
<>
{/* Diff hunk */}
{first.diffHunk && (
<div className="mt-2">
<DiffHunkPreview hunk={first.diffHunk} maxHeight={96} />
</div>
)}
{/* First comment body — truncated with fade for resolved/outdated */}
{first.body && (
<div className={`relative mt-2 ${isDimmed && !isExpanded ? 'max-h-16 overflow-hidden' : ''}`}>
<div className={`text-xs leading-relaxed review-comment-markdown ${isDimmed && !isExpanded ? 'text-muted-foreground' : 'text-foreground/80'}`}>
<MarkdownBody markdown={first.body} />
</div>
{isDimmed && !isExpanded && (
<div className="absolute bottom-0 left-0 right-0 h-10 bg-gradient-to-t from-card to-transparent pointer-events-none" />
)}
</div>
)}
{/* Expand button for dimmed threads */}
{isDimmed && !isExpanded && (
<button
onClick={(e) => { e.stopPropagation(); setIsExpanded(true); }}
className="mt-1 text-[10px] text-primary/70 hover:text-primary transition-colors"
>
Show full comment{replies.length > 0 ? ` + ${replies.length} repl${replies.length === 1 ? 'y' : 'ies'}` : ''}
</button>
)}
{/* Replies — only shown when expanded or not dimmed */}
{(!isDimmed || isExpanded) && replies.length > 0 && (
<div className="mt-2 ml-4 space-y-2 border-l border-border/30 pl-3">
{replies.map((reply) => (
<div key={reply.id}>
<div className="flex items-center gap-2 mb-1">
<span className="text-[10px] font-semibold text-foreground">{reply.author}</span>
<span className="text-[10px] text-muted-foreground">{formatRelativeTime(reply.createdAt)}</span>
</div>
<div className="text-xs text-foreground/80 leading-relaxed review-comment-markdown">
<MarkdownBody markdown={reply.body} />
</div>
</div>
))}
</div>
)}
{/* Actions */}
<CommentActions url={first.url} body={first.body} />
</>
)}
</div>
);
};
}
function CommentActions({ url, body }: { url?: string; body: string }) {
if (!url && !body) return null;
return (
<div className="mt-2 pt-2 border-t border-border/20 flex items-center justify-end gap-1 opacity-0 group-hover/card:opacity-100 transition-opacity duration-100">
{url && (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground px-1.5 py-0.5 rounded hover:bg-muted/30 transition-colors"
>
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
{url.includes('gitlab') ? 'View on GitLab' : 'View on GitHub'}
</a>
)}
<CopyButton text={body} variant="inline" label="Copy" />
</div>
);
}
function AuthorPill({ label, excluded, onClick }: { label: string; excluded: boolean; onClick: () => void }) {
return (
<button
onClick={onClick}
className={`text-[10px] px-1.5 py-0.5 rounded whitespace-nowrap transition-colors ${
excluded
? 'bg-muted/50 text-muted-foreground/40 line-through'
: 'bg-muted text-muted-foreground hover:text-foreground'
}`}
title={excluded ? `Show ${label}` : `Hide ${label}`}
>
{label}
</button>
);
}
@@ -1,9 +1,8 @@
import React, { useMemo } from 'react';
import React, { useMemo, useRef, useEffect } from 'react';
import DOMPurify from 'dompurify';
import { parseMarkdownToBlocks } from '@plannotator/ui/utils/parser';
import { renderInlineMarkdown } from '../utils/renderInlineMarkdown';
import type { PRContext } from '@plannotator/shared/pr-provider';
import type { PRMetadata } from '@plannotator/shared/pr-provider';
import type { PRContext, PRMetadata } from '@plannotator/shared/pr-provider';
interface PRSummaryTabProps {
context: PRContext;
@@ -29,13 +28,26 @@ function sanitizeHtml(html: string): string {
});
}
/** Renders sanitized HTML and hides broken images via ref (no inline event handlers). */
function SafeHtml({ html, as: Tag = 'div' }: { html: string; as?: 'div' | 'span' }) {
const ref = useRef<HTMLElement>(null);
useEffect(() => {
if (!ref.current) return;
const imgs = ref.current.querySelectorAll('img');
imgs.forEach((img) => {
img.onerror = () => { img.style.display = 'none'; img.onerror = null; };
});
}, [html]);
return <Tag ref={ref as any} dangerouslySetInnerHTML={{ __html: html }} />;
}
/**
* Render inline content — if it contains HTML tags, sanitize and render.
* Otherwise use our markdown renderer.
*/
function renderContent(content: string): React.ReactNode {
if (containsHtml(content)) {
return <span dangerouslySetInnerHTML={{ __html: sanitizeHtml(content) }} />;
return <SafeHtml html={sanitizeHtml(content)} as="span" />;
}
return renderInlineMarkdown(content);
}
@@ -45,7 +57,7 @@ export function MarkdownBody({ markdown }: { markdown: string }) {
const blocks = useMemo(() => parseMarkdownToBlocks(markdown), [markdown]);
return (
<div className="space-y-2 text-xs text-foreground/90">
<div className="space-y-2.5 text-xs text-foreground/90 leading-relaxed">
{blocks.map((block) => {
switch (block.type) {
case 'heading': {
@@ -86,7 +98,7 @@ export function MarkdownBody({ markdown }: { markdown: string }) {
if (!block.content) return null;
// If the entire paragraph is HTML, sanitize and render
if (containsHtml(block.content)) {
return <div key={block.id} dangerouslySetInnerHTML={{ __html: sanitizeHtml(block.content) }} />;
return <SafeHtml key={block.id} html={sanitizeHtml(block.content)} />;
}
return <p key={block.id}>{renderInlineMarkdown(block.content)}</p>;
}
@@ -95,9 +107,9 @@ export function MarkdownBody({ markdown }: { markdown: string }) {
);
}
export const PRSummaryTab: React.FC<PRSummaryTabProps> = ({ context, metadata }) => {
export const PRSummaryTab: React.FC<PRSummaryTabProps> = React.memo(({ context, metadata }) => {
return (
<div className="p-3 space-y-4">
<div className="px-8 py-4 space-y-4 max-w-2xl">
{/* PR title + state */}
<div className="space-y-2">
<div className="flex items-start gap-2">
@@ -133,11 +145,10 @@ export const PRSummaryTab: React.FC<PRSummaryTabProps> = ({ context, metadata })
{context.labels.map((label) => (
<span
key={label.name}
className="text-[10px] px-1.5 py-0.5 rounded-full font-medium"
className="text-[10px] px-1.5 py-0.5 rounded-full font-medium text-foreground"
style={{
backgroundColor: `#${label.color}20`,
color: `#${label.color}`,
border: `1px solid #${label.color}40`,
backgroundColor: `#${label.color}18`,
border: `1px solid #${label.color}50`,
}}
>
{label.name}
@@ -160,9 +171,8 @@ export const PRSummaryTab: React.FC<PRSummaryTabProps> = ({ context, metadata })
rel="noopener noreferrer"
className="flex items-center gap-1.5 text-xs text-primary hover:underline"
>
<svg className="w-3 h-3 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<circle cx="12" cy="12" r="10" />
<path d="M12 8v4m0 4h.01" />
<svg className="w-3.5 h-3.5 shrink-0" viewBox="0 0 896 1024" fill="currentColor">
<path d="M448 64C200.562 64 0 264.562 0 512c0 247.438 200.562 448 448 448 247.438 0 448-200.562 448-448C896 264.562 695.438 64 448 64zM448 832c-176.781 0-320-143.25-320-320 0-176.781 143.219-320 320-320 176.75 0 320 143.219 320 320C768 688.75 624.75 832 448 832zM384 768h128V640H384V768zM384 576h128V256H384V576z" />
</svg>
#{issue.number}
{issue.repo && <span className="text-muted-foreground text-[10px]">({issue.repo})</span>}
@@ -184,4 +194,4 @@ export const PRSummaryTab: React.FC<PRSummaryTabProps> = ({ context, metadata })
)}
</div>
);
};
});
@@ -2,13 +2,14 @@ import React, { useState, useEffect } from 'react';
import { CodeAnnotation, type EditorAnnotation } from '@plannotator/ui/types';
import { isCurrentUser } from '@plannotator/ui/utils/identity';
import { EditorAnnotationCard } from '@plannotator/ui/components/EditorAnnotationCard';
import { CopyButton } from './CopyButton';
import { HighlightedCode } from './HighlightedCode';
import { detectLanguage } from '../utils/detectLanguage';
import { renderInlineMarkdown } from '../utils/renderInlineMarkdown';
import { formatRelativeTime } from '../utils/formatRelativeTime';
import { AITab } from './AITab';
import { SparklesIcon } from './SparklesIcon';
import { ReviewAgentsIcon } from './ReviewAgentsIcon';
import { ReviewAgentsIcon } from '@plannotator/ui/components/ReviewAgentsIcon';
import { AgentsTab } from '@plannotator/ui/components/AgentsTab';
import type { PRMetadata } from '@plannotator/shared/pr-provider';
import type { AIChatEntry } from '../hooks/useAIChat';
@@ -17,9 +18,7 @@ import type { DiffFile } from '../types';
type ReviewSidebarTab = 'annotations' | 'ai' | 'agents';
// Temporary hard kill-switch for review agents in the sidebar.
// Keep local and explicit until the feature is ready to expose again.
const REVIEW_AGENTS_ENABLED = false;
const REVIEW_AGENTS_ENABLED = true;
interface ReviewSidebarProps {
isOpen: boolean;
@@ -108,7 +107,7 @@ function compareCodeAnnotations(a: CodeAnnotation, b: CodeAnnotation): number {
}
export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
export const ReviewSidebar: React.FC<ReviewSidebarProps> = /* React.memo */({
isOpen,
onToggle,
annotations,
@@ -204,8 +203,8 @@ export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
<aside className="border-l border-border/50 bg-card/30 backdrop-blur-sm flex flex-col flex-shrink-0" style={{ width: width ?? 288 }}>
{/* Header */}
<div className="px-3 flex items-center border-b border-border/50" style={{ height: 'var(--panel-header-h)' }}>
<div className="flex items-center gap-2 w-full">
<h2 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
<div className="flex items-center gap-2 w-full min-w-0">
<h2 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground truncate shrink">
{activeTab === 'annotations' ? 'Annotations' : activeTab === 'ai' ? 'AI' : activeTab === 'agents' ? 'Review Agents' : activeTab === 'summary' ? 'Summary' : activeTab === 'comments' ? 'Comments' : 'Checks'}
</h2>
{activeTab === 'annotations' && totalCount > 0 && (
@@ -224,18 +223,18 @@ export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
</span>
)}
<div className="flex items-center gap-0.5 ml-auto">
<div className="flex items-center gap-0.5 ml-auto shrink-0">
{/* Annotations tab (always visible) */}
<button
onClick={() => handleTabChange('annotations')}
className={`flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors ${
className={`flex items-center gap-1 px-2.5 py-1.5 rounded text-[10px] font-medium transition-colors duration-150 ${
activeTab === 'annotations'
? 'bg-primary/10 text-primary'
: 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
}`}
title="Annotations"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
</svg>
</button>
@@ -244,14 +243,14 @@ export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
{aiAvailable && (
<button
onClick={() => handleTabChange('ai')}
className={`relative flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors ${
className={`relative flex items-center gap-1 px-2.5 py-1.5 rounded text-[10px] font-medium transition-colors duration-150 ${
activeTab === 'ai'
? 'bg-primary/10 text-primary'
: 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
}`}
title="AI Chat"
>
<SparklesIcon className="w-3.5 h-3.5" />
<SparklesIcon className="w-4 h-4" />
{aiMessages.length > 0 && activeTab !== 'ai' && (
<span className="absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full bg-primary" />
)}
@@ -262,52 +261,21 @@ export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
{hasAgents && (
<button
onClick={() => handleTabChange('agents')}
className={`relative flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors ${
className={`relative flex items-center gap-1 px-2.5 py-1.5 rounded text-[10px] font-medium transition-colors duration-150 ${
activeTab === 'agents'
? 'bg-primary/10 text-primary'
: 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
}`}
title="Review Agents"
>
<ReviewAgentsIcon />
<ReviewAgentsIcon className="w-4 h-4" />
{runningAgentCount > 0 && activeTab !== 'agents' && (
<span className="absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full bg-primary animate-pulse" />
)}
</button>
)}
{/* PR tabs — open as center dock panels */}
{!!prMetadata && (
<>
<button
onClick={() => handleTabChange('summary')}
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors text-muted-foreground hover:text-foreground hover:bg-muted/50"
title="PR Summary"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</button>
<button
onClick={() => handleTabChange('comments')}
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors text-muted-foreground hover:text-foreground hover:bg-muted/50"
title="PR Comments"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
</svg>
</button>
<button
onClick={() => handleTabChange('checks')}
className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors text-muted-foreground hover:text-foreground hover:bg-muted/50"
title="PR Checks"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</button>
</>
)}
{/* PR tabs moved to header — see App.tsx */}
</div>
</div>
</div>
@@ -332,7 +300,7 @@ export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
<div className="p-2 space-y-4">
{Array.from(groupedAnnotations.entries()).map(([filePath, fileAnnotations]) => (
<div key={filePath}>
<div className="px-2 py-1 text-xs font-mono text-muted-foreground truncate">
<div className="sticky top-0 z-10 bg-background/95 backdrop-blur-sm px-2 py-1 text-xs font-mono text-muted-foreground truncate">
{filePath.split('/').pop()}
</div>
<div className="space-y-1">
@@ -343,10 +311,10 @@ export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
<div
key={annotation.id}
onClick={() => onSelectAnnotation(annotation.id)}
className={`group relative p-2.5 rounded-lg border cursor-pointer transition-all ${
className={`group relative p-2.5 rounded border cursor-pointer transition-colors duration-150 ${
isSelected
? 'bg-primary/5 border-primary/30 shadow-sm'
: 'border-transparent hover:bg-muted/50 hover:border-border/50'
? 'bg-primary/5 border-primary/30'
: 'border-transparent hover:bg-muted/30'
}`}
>
<div className="flex items-center justify-between mb-1.5">
@@ -382,12 +350,17 @@ export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
<SuggestionPreview code={annotation.suggestedCode} originalCode={annotation.originalCode} language={detectLanguage(annotation.filePath)} />
</div>
)}
{/* Actions — visible on hover */}
<div className="flex items-center justify-end gap-1 mt-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
{annotation.text && (
<CopyButton text={`${annotation.filePath}:${annotation.lineStart}${annotation.lineEnd !== annotation.lineStart ? `-${annotation.lineEnd}` : ''}\n${annotation.text}${annotation.reasoning ? `\n\nReasoning: ${annotation.reasoning}` : ''}`} variant="inline" />
)}
<button
onClick={(e) => {
e.stopPropagation();
onDeleteAnnotation(annotation.id);
}}
className="absolute top-2 right-2 p-1 rounded-md opacity-0 group-hover:opacity-100 hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-all"
className="p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
title="Delete annotation"
>
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
@@ -395,6 +368,7 @@ export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
</svg>
</button>
</div>
</div>
);
})}
</div>
@@ -465,7 +439,7 @@ export const ReviewSidebar: React.FC<ReviewSidebarProps> = ({
<div className="p-2 border-t border-border/50">
<button
onClick={handleQuickCopy}
className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-xs font-medium transition-all text-muted-foreground hover:text-foreground hover:bg-muted/50"
className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded text-xs font-medium transition-all text-muted-foreground hover:text-foreground hover:bg-muted/50"
>
{copied ? (
<>
@@ -0,0 +1,54 @@
import React, { useRef, useState, useCallback, useEffect } from 'react';
interface ScrollFadeProps {
children: React.ReactNode;
className?: string;
/** Height of the gradient fade in pixels. Default 20. */
fadeHeight?: number;
}
/**
* Wraps a scrollable container with gradient fade indicators at top/bottom.
* Fades appear only when content overflows in that direction.
*/
export const ScrollFade: React.FC<ScrollFadeProps> = ({ children, className, fadeHeight = 20 }) => {
const scrollRef = useRef<HTMLDivElement>(null);
const [showTop, setShowTop] = useState(false);
const [showBottom, setShowBottom] = useState(false);
const update = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
setShowTop(el.scrollTop > 2);
setShowBottom(el.scrollHeight - el.scrollTop - el.clientHeight > 2);
}, []);
useEffect(() => {
update();
const el = scrollRef.current;
if (!el) return;
const observer = new ResizeObserver(update);
observer.observe(el);
return () => observer.disconnect();
}, [update]);
return (
<div className={`relative flex-1 min-h-0 ${className ?? ''}`}>
<div
className="absolute top-0 left-0 right-0 z-10 pointer-events-none bg-gradient-to-b from-background to-transparent transition-opacity duration-150"
style={{ height: fadeHeight, opacity: showTop ? 1 : 0 }}
/>
<div
ref={scrollRef}
onScroll={update}
className="h-full overflow-y-auto"
>
{children}
</div>
<div
className="absolute bottom-0 left-0 right-0 z-10 pointer-events-none bg-gradient-to-t from-background to-transparent transition-opacity duration-150"
style={{ height: fadeHeight, opacity: showBottom ? 1 : 0 }}
/>
</div>
);
};
@@ -0,0 +1,23 @@
/**
* Separate context for live agent job logs.
*
* Split from ReviewStateContext to prevent high-frequency SSE log updates
* (every ~200ms) from re-rendering all dockview panels. Only the agent
* detail panel subscribes to this context.
*
* Pattern: Dan Abramov's "split contexts by update frequency" optimization.
*/
import { createContext, useContext } from 'react';
interface JobLogsState {
jobLogs: Map<string, string>;
}
const JobLogsContext = createContext<JobLogsState>({ jobLogs: new Map() });
export const JobLogsProvider = JobLogsContext.Provider;
export function useJobLogs(): JobLogsState {
return useContext(JobLogsContext);
}
@@ -32,7 +32,7 @@ export const ReviewDockTabRenderer: React.FC<IDockviewPanelHeaderProps> = (props
onClick={handleClose}
aria-label="Close"
>
<svg className="w-3 h-3" viewBox="0 0 16 16" fill="currentColor">
<svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="currentColor">
<path d="M8 8.707l3.646 3.647.708-.707L8.707 8l3.647-3.646-.707-.708L8 7.293 4.354 3.646l-.707.708L7.293 8l-3.646 3.646.707.708L8 8.707z" />
</svg>
</button>
@@ -74,6 +74,7 @@ export interface ReviewState {
isPRContextLoading: boolean;
prContextError: string | null;
fetchPRContext: () => void;
platformUser: string | null;
// Diff navigation
openDiffFile: (filePath: string) => void;
@@ -1,13 +1,22 @@
import React, { useMemo, useState, useEffect } from 'react';
import React, { useMemo, useState, useEffect, useCallback } from 'react';
import type { IDockviewPanelProps } from 'dockview-react';
import type { AgentJobInfo, CodeAnnotation } from '@plannotator/ui/types';
import { SEVERITY_STYLES, type AgentJobInfo, type CodeAnnotation } from '@plannotator/ui/types';
import { isTerminalStatus } from '@plannotator/shared/agent-jobs';
import { useReviewState } from '../ReviewStateContext';
import { useJobLogs } from '../JobLogsContext';
import { CopyButton } from '../../components/CopyButton';
import { LiveLogViewer } from '../../components/LiveLogViewer';
import { ScrollFade } from '../../components/ScrollFade';
import { exportReviewFeedback } from '../../utils/exportFeedback';
// ---------------------------------------------------------------------------
// Panel
// ---------------------------------------------------------------------------
type DetailTab = 'findings' | 'logs';
const SEVERITY_ORDER: Record<string, number> = { important: 0, nit: 1, pre_existing: 2 };
/**
* Center dock panel showing full detail for a single agent job.
* Displays all AgentJobInfo fields + linked annotations.
*/
export const ReviewAgentJobDetailPanel: React.FC<IDockviewPanelProps> = (props) => {
const jobId: string = props.params?.jobId ?? '';
const state = useReviewState();
@@ -17,157 +26,352 @@ export const ReviewAgentJobDetailPanel: React.FC<IDockviewPanelProps> = (props)
[state.agentJobs, jobId]
);
const linkedAnnotations = useMemo(
() =>
job
? (state.externalAnnotations.filter(
(a) => a.source === job.source
) as CodeAnnotation[])
: [],
[state.externalAnnotations, job]
);
const terminal = job ? isTerminalStatus(job.status) : false;
const [activeTab, setActiveTab] = useState<DetailTab>('findings');
if (!job) {
return (
<div className="h-full flex items-center justify-center text-muted-foreground text-sm">
Job not found
</div>
const { fullCommand, userMessage, systemPrompt } = useMemo(() => {
const cmd = job?.command ?? [];
const full = cmd.join(' ');
// Use job.prompt if available (stored explicitly for all providers),
// fallback to parsing last command arg (legacy Codex behavior)
const promptText = job?.prompt || (cmd.length > 0 ? cmd[cmd.length - 1] : '');
const sep = '\n\n---\n\n';
const i = promptText.indexOf(sep);
return {
fullCommand: full,
userMessage: i !== -1 ? promptText.substring(i + sep.length) : promptText,
systemPrompt: i !== -1 ? promptText.substring(0, i) : '',
};
}, [job]);
const [annotationSnapshot, setAnnotationSnapshot] = useState<
Map<string, { annotation: CodeAnnotation; dismissed: boolean }>
>(new Map());
useEffect(() => {
if (!job) return;
const currentIds = new Set(
state.externalAnnotations.filter((a) => a.source === job.source).map((a) => a.id)
);
setAnnotationSnapshot((prev) => {
const next = new Map(prev);
for (const ann of state.externalAnnotations) {
if (ann.source !== job.source) continue;
next.set(ann.id, { annotation: ann as CodeAnnotation, dismissed: false });
}
for (const [id, entry] of next) {
if (!entry.dismissed && !currentIds.has(id)) next.set(id, { ...entry, dismissed: true });
}
return next;
});
}, [state.externalAnnotations, job]);
const handleAnnotationClick = (ann: CodeAnnotation) => {
const displayAnnotations = useMemo(() =>
Array.from(annotationSnapshot.values()).sort((a, b) => {
if (a.dismissed !== b.dismissed) return a.dismissed ? 1 : -1;
// Sort by severity (important first), then file path, then line
const sa = SEVERITY_ORDER[a.annotation.severity ?? ''] ?? 3;
const sb = SEVERITY_ORDER[b.annotation.severity ?? ''] ?? 3;
if (sa !== sb) return sa - sb;
return a.annotation.filePath.localeCompare(b.annotation.filePath) || a.annotation.lineStart - b.annotation.lineStart;
}),
[annotationSnapshot]);
const activeAnnotations = useMemo(() => displayAnnotations.filter((d) => !d.dismissed).map((d) => d.annotation), [displayAnnotations]);
const dismissedCount = useMemo(() => displayAnnotations.filter((d) => d.dismissed).length, [displayAnnotations]);
const handleAnnotationClick = useCallback((ann: CodeAnnotation) => {
state.openDiffFile(ann.filePath);
state.onSelectAnnotation(ann.id);
};
}, [state.openDiffFile, state.onSelectAnnotation]);
const copyAllText = useMemo(
() => activeAnnotations.length > 0 ? exportReviewFeedback(activeAnnotations, state.prMetadata) : '',
[activeAnnotations, state.prMetadata]
);
const { jobLogs } = useJobLogs();
const logContent = jobLogs.get(jobId) ?? '';
if (!job) {
return <div className="h-full flex items-center justify-center text-muted-foreground text-sm">Job not found</div>;
}
const isCorrect = job.summary
? job.summary.correctness.toLowerCase().includes('correct') && !job.summary.correctness.toLowerCase().includes('incorrect')
: null;
return (
<div className="h-full overflow-y-auto">
{/* Header */}
<div className="sticky top-0 bg-card/95 backdrop-blur-sm border-b border-border/50 p-4">
<div className="flex items-center gap-2 mb-2">
<JobStatusBadge status={job.status} />
<JobProviderBadge provider={job.provider} />
{!isTerminalStatus(job.status) && (
<span className="text-xs text-muted-foreground ml-auto">
<JobElapsedTime startedAt={job.startedAt} />
<div className="h-full flex flex-col overflow-hidden bg-background">
{/* ── Header ── */}
<div className="flex-shrink-0 px-8 py-3 border-b border-border/40">
<div className="flex items-center gap-2">
<StatusDot status={job.status} />
<ProviderPill provider={job.provider} />
<span className="text-sm font-medium text-foreground truncate">{job.label}</span>
<span className="ml-auto text-[10px] font-mono text-muted-foreground">
{terminal && job.endedAt ? formatDuration(job.endedAt - job.startedAt) : <ElapsedTime startedAt={job.startedAt} />}
</span>
)}
</div>
<h2 className="text-sm font-semibold text-foreground">{job.label}</h2>
</div>
<div className="p-4 space-y-4">
{/* Metadata */}
<section>
<h3 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2">Details</h3>
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1.5 text-xs">
<dt className="text-muted-foreground">Source</dt>
<dd className="font-mono text-foreground">{job.source}</dd>
<dt className="text-muted-foreground">Command</dt>
<dd className="font-mono text-foreground truncate" title={job.command.join(' ')}>{job.command.join(' ')}</dd>
<dt className="text-muted-foreground">Started</dt>
<dd className="text-foreground">{new Date(job.startedAt).toLocaleTimeString()}</dd>
{job.endedAt && (
<>
<dt className="text-muted-foreground">Ended</dt>
<dd className="text-foreground">{new Date(job.endedAt).toLocaleTimeString()}</dd>
</>
{job.cwd && (
<p className="text-[10px] font-mono text-muted-foreground/50 mt-1 truncate" title={job.cwd}>{job.cwd}</p>
)}
{job.endedAt && (
<>
<dt className="text-muted-foreground">Duration</dt>
<dd className="text-foreground">{formatDuration(job.endedAt - job.startedAt)}</dd>
</>
)}
{/* Inline details */}
<div className="flex items-center gap-3 mt-1.5 text-[10px] text-muted-foreground">
<span>Started {new Date(job.startedAt).toLocaleTimeString()}</span>
{job.exitCode !== undefined && (
<span>Exit <span className={`font-mono ${job.exitCode === 0 ? 'text-success' : 'text-destructive'}`}>{job.exitCode}</span></span>
)}
<CopyButton text={fullCommand} variant="inline" label="Command" />
</div>
{/* Prompt disclosures in header */}
{userMessage && (
<div className="mt-3 space-y-1.5">
<Disclosure title="Prompt" copyText={userMessage} nested>
<pre className="text-xs font-mono text-foreground/80 whitespace-pre-wrap break-words max-h-48 overflow-y-auto">{userMessage}</pre>
</Disclosure>
{systemPrompt && (
<Disclosure title="Review Prompt" copyText={systemPrompt} nested>
<pre className="text-xs font-mono text-foreground/80 whitespace-pre-wrap break-words max-h-48 overflow-y-auto">{systemPrompt}</pre>
</Disclosure>
)}
</div>
)}
</div>
{/* ── Tabs ── */}
<div className="flex-shrink-0 px-8 flex gap-0.5 border-b border-border/40">
<TabButton active={activeTab === 'findings'} onClick={() => setActiveTab('findings')}>
Findings{activeAnnotations.length > 0 && ` (${activeAnnotations.length})`}
</TabButton>
<TabButton active={activeTab === 'logs'} onClick={() => setActiveTab('logs')}>
Logs
{!terminal && <span className="ml-1.5 w-1.5 h-1.5 rounded-full bg-primary animate-pulse inline-block" />}
</TabButton>
</div>
{/* ── Content ── */}
{activeTab === 'findings' ? (
<ScrollFade>
<div className="px-8 py-3 space-y-4 max-w-2xl">
{/* Verdict — scrolls with content */}
<VerdictCard summary={job.summary} isCorrect={isCorrect} terminal={terminal} />
{/* Findings list */}
{displayAnnotations.length > 0 && (
<>
<dt className="text-muted-foreground">Exit code</dt>
<dd className={`font-mono ${job.exitCode === 0 ? 'text-success' : 'text-destructive'}`}>
{job.exitCode}
</dd>
<div className="flex items-center justify-between">
<span className="text-[10px] text-muted-foreground">
{activeAnnotations.length} finding{activeAnnotations.length !== 1 ? 's' : ''}
{dismissedCount > 0 && ` · ${dismissedCount} dismissed`}
</span>
{copyAllText && <CopyButton text={copyAllText} variant="inline" label="Copy All" />}
</div>
{activeAnnotations.some(a => a.severity) && (
<div className="flex items-center gap-3 text-[10px] text-muted-foreground/60">
<span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-destructive" /> Important</span>
<span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-amber-500" /> Nit</span>
<span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-muted-foreground" /> Pre-existing</span>
</div>
)}
</>
)}
</dl>
</section>
{/* Stderr */}
{job.error && (
<section>
<h3 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2">
Stderr
</h3>
<pre className="text-[11px] leading-relaxed font-mono bg-muted/50 border border-border/50 rounded-md p-3 overflow-x-auto whitespace-pre-wrap break-words max-h-48">
{job.error}
</pre>
</section>
)}
{/* Linked Annotations */}
<section>
<h3 className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-2">
Annotations ({linkedAnnotations.length})
</h3>
{linkedAnnotations.length === 0 ? (
<p className="text-xs text-muted-foreground">
{isTerminalStatus(job.status)
? 'No annotations were produced by this job.'
: 'Annotations will appear here as the agent produces them.'}
</p>
{displayAnnotations.length === 0 ? (
<EmptyState terminal={terminal} />
) : (
<div className="space-y-1.5">
{linkedAnnotations.map((ann) => (
<button
key={ann.id}
className="w-full text-left p-2 rounded-md border border-transparent hover:border-border/50 hover:bg-muted/30 transition-colors"
onClick={() => handleAnnotationClick(ann)}
>
<div className="flex items-center gap-2 text-[10px]">
<span className="font-mono text-primary truncate">{ann.filePath}</span>
<span className="text-muted-foreground">L{ann.lineStart}{ann.lineEnd !== ann.lineStart ? `-${ann.lineEnd}` : ''}</span>
<span className={`px-1.5 py-0.5 rounded font-medium uppercase tracking-wider ${
ann.type === 'concern' ? 'bg-destructive/15 text-destructive' :
ann.type === 'suggestion' ? 'bg-success/15 text-success' :
'bg-muted text-muted-foreground'
}`}>
{ann.type}
</span>
</div>
{ann.text && (
<p className="text-xs text-foreground mt-1 line-clamp-2">{ann.text}</p>
)}
</button>
<div className="space-y-2">
{displayAnnotations.map(({ annotation: ann, dismissed }) => (
<AnnotationRow key={ann.id} annotation={ann} dismissed={dismissed} onClick={handleAnnotationClick} />
))}
</div>
)}
</section>
{/* Output placeholder */}
{!isTerminalStatus(job.status) && linkedAnnotations.length === 0 && (
<section className="text-xs text-muted-foreground/60 text-center py-4 border border-dashed border-border/30 rounded-md">
Agent output will appear as annotations in the diff.
</section>
</div>
</ScrollFade>
) : (
<div className="flex-1 flex flex-col min-h-0 px-8 py-3">
<LiveLogViewer content={logContent} isLive={!terminal} />
{!logContent && job.error && terminal && (
<div className="mt-2 flex-shrink-0">
<pre className="text-xs font-mono text-destructive bg-destructive/5 rounded p-3 whitespace-pre-wrap break-words max-h-48 overflow-y-auto">
{job.error}
</pre>
</div>
)}
</div>
)}
</div>
);
};
// --- Small helper components (mirrors from AgentsTab, kept local) ---
// ---------------------------------------------------------------------------
// Subcomponents
// ---------------------------------------------------------------------------
function formatDuration(ms: number): string {
const seconds = Math.floor(ms / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}m ${remainingSeconds}s`;
function VerdictCard({ summary, isCorrect, terminal }: {
summary: AgentJobInfo['summary'];
isCorrect: boolean | null;
terminal: boolean;
}) {
if (summary) {
const verdictText = `${isCorrect ? 'Correct' : 'Incorrect'} (${Math.round(summary.confidence * 100)}% confidence)\n\n${summary.explanation}`;
return (
<div className={`rounded px-3 py-2.5 ${
isCorrect ? 'bg-success/5' : 'bg-destructive/5'
}`}>
<div className="flex items-baseline gap-2">
<span className={`text-xs font-semibold ${isCorrect ? 'text-success' : 'text-destructive'}`}>
{isCorrect ? 'Correct' : 'Incorrect'}
</span>
<span className="text-[10px] text-muted-foreground">
Confidence {Math.round(summary.confidence * 100)}%
</span>
<span className="ml-auto"><CopyButton text={verdictText} variant="inline" /></span>
</div>
<p className="text-xs text-foreground/80 leading-relaxed mt-1.5">{summary.explanation}</p>
</div>
);
}
return (
<div className="rounded bg-muted/10 px-3 py-2.5">
<div className="flex items-center gap-2">
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/50">
Review Verdict
</span>
{!terminal && (
<span className="text-[10px] text-muted-foreground/40 animate-pulse">Pending...</span>
)}
</div>
{terminal ? (
<p className="text-xs text-muted-foreground/50 mt-1">No verdict available.</p>
) : (
<p className="text-xs text-muted-foreground/50 mt-1">Will appear when the review completes.</p>
)}
</div>
);
}
function JobElapsedTime({ startedAt }: { startedAt: number }) {
function StatusDot({ status }: { status: AgentJobInfo['status'] }) {
if (status === 'starting' || status === 'running') {
return (
<span className="relative flex h-2 w-2 flex-shrink-0">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-40" />
<span className="relative inline-flex rounded-full h-2 w-2 bg-primary" />
</span>
);
}
const c: Record<string, string> = { done: 'bg-success', failed: 'bg-destructive', killed: 'bg-muted-foreground' };
return <span className={`inline-flex rounded-full h-2 w-2 flex-shrink-0 ${c[status] ?? c.killed}`} />;
}
function ProviderPill({ provider }: { provider: string }) {
const label = provider === 'claude' ? 'Claude' : provider === 'codex' ? 'Codex' : 'Shell';
return <span className="text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground">{label}</span>;
}
function TabButton({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
return (
<button
onClick={onClick}
className={`flex items-center gap-1 px-3 py-2 text-xs font-medium border-b-2 transition-all duration-150 -mb-px ${
active
? 'border-primary text-foreground'
: 'border-transparent text-muted-foreground hover:text-foreground'
}`}
>
{children}
</button>
);
}
function Disclosure({ title, copyText, nested, children }: {
title: string;
copyText?: string;
nested?: boolean;
children: React.ReactNode;
}) {
const [open, setOpen] = useState(false);
return (
<div className={nested ? '' : 'pt-4 mt-2'}>
<div className="flex items-center justify-between">
<button
onClick={() => setOpen(!open)}
className="flex items-center gap-1.5 text-[10px] text-muted-foreground hover:text-foreground transition-colors duration-150"
>
<svg className={`w-2.5 h-2.5 transition-transform duration-150 ${open ? 'rotate-90' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
</svg>
<span className="font-medium uppercase tracking-wider">{title}</span>
</button>
{open && copyText && <CopyButton text={copyText} variant="inline" />}
</div>
{open && <div className="mt-2 ml-4">{children}</div>}
</div>
);
}
function AnnotationRow({ annotation: ann, dismissed, onClick }: {
annotation: CodeAnnotation;
dismissed: boolean;
onClick: (ann: CodeAnnotation) => void;
}) {
const copyText = ann.text ? `${ann.filePath}:${ann.lineStart}${ann.lineEnd !== ann.lineStart ? `-${ann.lineEnd}` : ''}\n${ann.text}${ann.reasoning ? `\n\nReasoning: ${ann.reasoning}` : ''}` : '';
const severity = ann.severity ? SEVERITY_STYLES[ann.severity] : null;
return (
<div
className={`group/finding w-full text-left px-3 py-2.5 rounded bg-card border transition-all duration-150 shadow-[0_1px_3px_rgba(0,0,0,0.06)] ${
dismissed ? 'opacity-30 cursor-default border-border/20' : 'border-border/40 hover:shadow-[0_2px_6px_rgba(0,0,0,0.08)] cursor-pointer'
}`}
onClick={() => !dismissed && onClick(ann)}
>
<div className="flex items-center gap-2 text-[10px]">
{severity && (
<span className={`w-2 h-2 rounded-full flex-shrink-0 ${severity.dot}`} title={severity.label} />
)}
<span className={`font-mono truncate ${dismissed ? 'line-through text-muted-foreground' : 'text-primary'}`}>
{ann.filePath}
</span>
<span className="text-muted-foreground flex-shrink-0">
L{ann.lineStart}{ann.lineEnd !== ann.lineStart ? `–${ann.lineEnd}` : ''}
</span>
{dismissed && (
<span className="px-1 py-0.5 rounded text-[10px] uppercase tracking-wider bg-muted text-muted-foreground/60">dismissed</span>
)}
{!dismissed && copyText && (
<span className="ml-auto opacity-0 group-hover/finding:opacity-100 transition-opacity" onClick={(e) => e.stopPropagation()}>
<CopyButton text={copyText} variant="inline" />
</span>
)}
</div>
{ann.text && (
<p className={`text-xs mt-1 leading-relaxed ${dismissed ? 'text-muted-foreground/40' : 'text-foreground/80'}`}>
{ann.text}
</p>
)}
{ann.reasoning && (
<p className="text-[11px] text-muted-foreground/60 leading-relaxed mt-1.5">
{ann.reasoning}
</p>
)}
</div>
);
}
function EmptyState({ terminal }: { terminal: boolean }) {
return (
<div className="text-center py-8">
<p className="text-xs text-muted-foreground">
{terminal ? 'No findings were produced.' : 'Findings will appear as the agent works.'}
</p>
</div>
);
}
function ElapsedTime({ startedAt }: { startedAt: number }) {
const [, setTick] = useState(0);
useEffect(() => {
const timer = setInterval(() => setTick((t) => t + 1), 1000);
@@ -176,33 +380,8 @@ function JobElapsedTime({ startedAt }: { startedAt: number }) {
return <>{formatDuration(Date.now() - startedAt)}</>;
}
function JobStatusBadge({ status }: { status: AgentJobInfo['status'] }) {
const config: Record<string, { className: string; label: string }> = {
starting: { className: 'text-primary', label: 'Starting' },
running: { className: 'text-primary', label: 'Running' },
done: { className: 'text-success', label: 'Done' },
failed: { className: 'text-destructive', label: 'Failed' },
killed: { className: 'text-muted-foreground', label: 'Killed' },
};
const c = config[status] ?? config.killed;
return (
<span className={`inline-flex items-center gap-1 text-[10px] font-medium ${c.className}`}>
{(status === 'starting' || status === 'running') && (
<svg className="w-3 h-3 animate-spin" viewBox="0 0 24 24" fill="none">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
)}
{c.label}
</span>
);
}
function JobProviderBadge({ provider }: { provider: string }) {
const label = provider === 'claude' ? 'Claude' : provider === 'codex' ? 'Codex' : 'Shell';
return (
<span className="text-[9px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
{label}
</span>
);
function formatDuration(ms: number): string {
const s = Math.floor(ms / 1000);
if (s < 60) return `${s}s`;
return `${Math.floor(s / 60)}m ${s % 60}s`;
}
@@ -7,7 +7,7 @@ import { PRCommentsTab } from '../../components/PRCommentsTab';
* Dock panel wrapper for PR Comments.
*/
export const ReviewPRCommentsPanel: React.FC<IDockviewPanelProps> = () => {
const { prContext, isPRContextLoading, prContextError, fetchPRContext } = useReviewState();
const { prContext, isPRContextLoading, prContextError, fetchPRContext, platformUser } = useReviewState();
useEffect(() => {
if (!prContext && !prContextError && !isPRContextLoading) fetchPRContext();
@@ -39,8 +39,8 @@ export const ReviewPRCommentsPanel: React.FC<IDockviewPanelProps> = () => {
if (!prContext) return null;
return (
<div className="h-full overflow-y-auto">
<PRCommentsTab context={prContext} />
<div className="h-full overflow-hidden">
<PRCommentsTab context={prContext} platformUser={platformUser} />
</div>
);
};
+29 -15
View File
@@ -17,7 +17,7 @@
/* Shared panel header height — keeps file header, sidebar headers, and
search bar vertically aligned across all three columns. */
:root {
--panel-header-h: 37px;
--panel-header-h: 33px;
}
/* =====================================================
@@ -30,7 +30,7 @@
.dockview-theme-light,
.dv-dockview {
--dv-group-view-background-color: var(--background);
--dv-tabs-and-actions-container-background-color: var(--card);
--dv-tabs-and-actions-container-background-color: var(--muted);
--dv-activegroup-visiblepanel-tab-background-color: var(--background);
--dv-activegroup-hiddenpanel-tab-background-color: var(--muted);
--dv-inactivegroup-visiblepanel-tab-background-color: var(--background);
@@ -45,21 +45,29 @@
--dv-drag-over-background-color: oklch(from var(--primary) l c h / 0.1);
--dv-drag-over-border-color: var(--primary);
--dv-icon-hover-background-color: var(--muted);
--dv-tabs-and-actions-container-height: 30px;
--dv-tabs-and-actions-container-font-size: 0.6875rem;
--dv-tab-font-size: 0.6875rem;
--dv-tabs-and-actions-container-height: 33px;
--dv-tabs-and-actions-container-font-size: 0.75rem;
--dv-tab-font-size: 0.75rem;
font-family: inherit;
font-size: inherit;
}
/* Remove focus outline from dockview tabs after click */
.dv-dockview .dv-tab:focus-within::after,
.dv-dockview .dv-tab:focus::after {
outline: none !important;
content: none;
}
/* Dockview custom tab renderer */
.dv-review-tab {
display: flex;
align-items: center;
gap: 0.375rem;
padding: 0 0.5rem;
gap: 0.5rem;
padding: 0 0 0 0.75rem;
width: 100%;
height: 100%;
font-size: 0.6875rem;
font-size: 0.75rem;
user-select: none;
min-width: 0;
}
@@ -73,13 +81,15 @@
.dv-review-tab-close {
flex-shrink: 0;
margin-left: auto;
margin-right: 0.375rem;
display: flex;
align-items: center;
justify-content: center;
width: 1rem;
height: 1rem;
border-radius: 3px;
opacity: 0;
opacity: 0.25;
color: var(--muted-foreground);
transition: opacity 150ms, background 150ms, color 150ms;
}
@@ -128,16 +138,18 @@ diffs-container {
min-width: 0;
background: var(--popover);
border: 1px solid var(--border);
border-radius: 2px;
padding: 0.5rem 0.625rem;
border-radius: 6px;
padding: 0.625rem 0.75rem;
font-size: 0.8125rem;
margin: 0.5rem 0;
cursor: pointer;
transition: border-color 150ms ease;
box-shadow: 0 1px 2px rgba(0,0,0,0.04);
transition: border-color 150ms, box-shadow 150ms, background 150ms;
}
.review-comment:hover {
border-color: var(--muted-foreground);
box-shadow: 0 2px 6px rgba(0,0,0,0.06);
}
.review-comment-header {
@@ -155,18 +167,20 @@ diffs-container {
display: flex;
gap: 0.125rem;
opacity: 0;
transition: opacity 150ms;
transform: scale(0.95);
transition: opacity 100ms, transform 100ms;
}
.review-comment:hover .review-comment-actions {
opacity: 1;
transform: scale(1);
}
.review-comment-action {
padding: 0.25rem;
border-radius: 2px;
border-radius: 4px;
color: var(--muted-foreground);
transition: color 150ms, background 150ms;
transition: color 100ms, background 100ms;
}
.review-comment-action:hover {
+1 -1
View File
@@ -9,7 +9,7 @@
"dependencies": {
"@plannotator/shared": "workspace:*",
"@plannotator/ui": "workspace:*",
"@pierre/diffs": "^1.1.0-beta.19",
"@pierre/diffs": "^1.1.12",
"highlight.js": "^11.11.1",
"react": "^19.2.3",
"react-dom": "^19.2.3",
@@ -71,6 +71,10 @@ export function exportReviewFeedback(
output += `${ann.text}\n`;
}
if (ann.reasoning) {
output += `\n**Reasoning:** ${ann.reasoning}\n`;
}
if (ann.suggestedCode) {
output += `\n**Suggested code:**\n\`\`\`\n${ann.suggestedCode}\n\`\`\`\n`;
}
+155 -11
View File
@@ -8,6 +8,7 @@
* Server-agnostic: takes a mode, server URL getter, and cwd getter.
*/
import { formatClaudeLogEvent } from "./claude-review";
import {
type AgentJobInfo,
type AgentJobEvent,
@@ -56,6 +57,26 @@ export interface AgentJobHandlerOptions {
getServerUrl: () => string;
/** Returns the working directory for spawned processes. */
getCwd: () => string;
/**
* Build the command server-side for a given provider.
* Return an object with the command to spawn (and optional output path for result ingestion).
* Return null to reject or fall through to frontend-supplied command.
*/
buildCommand?: (provider: string) => Promise<{
command: string[];
outputPath?: string;
captureStdout?: boolean;
stdinPrompt?: string;
cwd?: string;
label?: string;
/** The full prompt text for display in the detail panel. */
prompt?: string;
} | null>;
/**
* Called after a job process exits with exit code 0.
* Use for result ingestion (e.g., reading an output file and pushing annotations).
*/
onJobComplete?: (job: AgentJobInfo, meta: { outputPath?: string; stdout?: string; cwd?: string }) => void | Promise<void>;
}
export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJobHandler {
@@ -63,6 +84,7 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
// --- State ---
const jobs = new Map<string, { info: AgentJobInfo; proc: ReturnType<typeof Bun.spawn> | null }>();
const jobOutputPaths = new Map<string, string>();
const subscribers = new Set<ReadableStreamDefaultController>();
const encoder = new TextEncoder();
let version = 0;
@@ -71,7 +93,6 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
const capabilities: AgentCapability[] = [
{ id: "claude", name: "Claude Code", available: !!Bun.which("claude") },
{ id: "codex", name: "Codex CLI", available: !!Bun.which("codex") },
{ id: "shell", name: "Shell Command", available: true },
];
const capabilitiesResponse: AgentCapabilities = {
mode,
@@ -97,6 +118,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
provider: string,
command: string[],
label: string,
outputPath?: string,
spawnOptions?: { captureStdout?: boolean; stdinPrompt?: string; cwd?: string; prompt?: string },
): AgentJobInfo {
const id = crypto.randomUUID();
const source = jobSource(id);
@@ -109,14 +132,21 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
status: "starting",
startedAt: Date.now(),
command,
cwd: getCwd(),
};
let proc: ReturnType<typeof Bun.spawn> | null = null;
try {
const spawnCwd = spawnOptions?.cwd ?? getCwd();
const captureStdout = spawnOptions?.captureStdout ?? false;
const hasStdinPrompt = !!spawnOptions?.stdinPrompt;
proc = Bun.spawn(command, {
cwd: getCwd(),
stdout: "ignore",
cwd: spawnCwd,
stdin: hasStdinPrompt ? "pipe" : undefined,
stdout: captureStdout ? "pipe" : "ignore",
stderr: "pipe",
env: {
...process.env,
@@ -125,19 +155,50 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
},
});
// Write prompt to stdin and close (for providers that read prompt from stdin)
if (hasStdinPrompt && proc.stdin) {
const sink = proc.stdin as import("bun").FileSink;
sink.write(spawnOptions!.stdinPrompt!);
sink.end();
}
info.status = "running";
info.cwd = spawnCwd;
if (spawnOptions?.prompt) info.prompt = spawnOptions.prompt;
jobs.set(id, { info, proc });
if (outputPath) jobOutputPaths.set(id, outputPath);
if (spawnOptions?.cwd) jobOutputPaths.set(`${id}:cwd`, spawnOptions.cwd);
broadcast({ type: "job:started", job: { ...info } });
// Drain stderr continuously to prevent pipe-full deadlock
// Drain stderr: capture tail for error reporting + broadcast live log deltas
let stderrBuf = "";
let logPending = "";
let logFlushTimer: ReturnType<typeof setTimeout> | null = null;
if (proc.stderr && typeof proc.stderr !== "number") {
(async () => {
try {
const reader = proc!.stderr as ReadableStream;
const reader = proc!.stderr as unknown as AsyncIterable<Uint8Array>;
for await (const chunk of reader) {
const text = typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk);
stderrBuf = (stderrBuf + text).slice(-500);
logPending += text;
if (!logFlushTimer) {
logFlushTimer = setTimeout(() => {
if (logPending) {
broadcast({ type: "job:log", jobId: id, delta: logPending });
logPending = "";
}
logFlushTimer = null;
}, 200);
}
}
// Flush remaining on stream close
if (logFlushTimer) { clearTimeout(logFlushTimer); logFlushTimer = null; }
if (logPending) {
broadcast({ type: "job:log", jobId: id, delta: logPending });
logPending = "";
}
} catch {
// Stream closed or already consumed
@@ -145,8 +206,46 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
})();
}
// Drain stdout when capturing (for providers that return results on stdout)
let stdoutBuf = "";
const stdoutDone = (captureStdout && proc.stdout && typeof proc.stdout !== "number")
? (async () => {
try {
const reader = proc!.stdout as unknown as AsyncIterable<Uint8Array>;
for await (const chunk of reader) {
const text = typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk);
stdoutBuf += text;
// Forward JSONL lines as log events (skip result events)
const lines = text.split('\n');
for (const line of lines) {
if (!line.trim()) continue;
// Claude: format JSONL into readable text
if (provider === "claude") {
const formatted = formatClaudeLogEvent(line);
if (formatted !== null) {
broadcast({ type: "job:log", jobId: id, delta: formatted + '\n' });
}
continue;
}
try {
const event = JSON.parse(line);
if (event.type === 'result') continue; // handled in onJobComplete
} catch { /* not JSON — forward as raw log */ }
broadcast({ type: "job:log", jobId: id, delta: line + '\n' });
}
}
} catch {
// Stream closed
}
})()
: Promise.resolve();
// Monitor process exit
proc.exited.then((exitCode) => {
proc.exited.then(async (exitCode) => {
// Wait for stdout to drain — grace period in case the pipe doesn't close cleanly.
// The process is dead; if the stream hasn't flushed in 2s, the runtime has a bug.
await Promise.race([stdoutDone, new Promise(r => setTimeout(r, 2000))]);
const entry = jobs.get(id);
if (!entry || isTerminalStatus(entry.info.status)) return;
@@ -158,7 +257,26 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
entry.info.error = stderrBuf;
}
// Ingest results before broadcasting completion so annotations arrive first
const outputPath = jobOutputPaths.get(id);
const jobCwd = jobOutputPaths.get(`${id}:cwd`);
if (exitCode === 0 && options.onJobComplete) {
try {
await options.onJobComplete(entry.info, {
outputPath,
stdout: captureStdout ? stdoutBuf : undefined,
cwd: jobCwd,
});
} catch {
// Result ingestion failure shouldn't prevent job completion broadcast
}
}
jobOutputPaths.delete(id);
jobOutputPaths.delete(`${id}:cwd`);
broadcast({ type: "job:completed", job: { ...entry.info } });
}).catch(() => {
// Guard against unhandled rejection from unexpected runtime errors
});
} catch (err) {
// Spawn itself failed (e.g., command not found).
@@ -189,6 +307,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
entry.info.status = "killed";
entry.info.endedAt = Date.now();
jobOutputPaths.delete(id);
jobOutputPaths.delete(`${id}:cwd`);
broadcast({ type: "job:completed", job: { ...entry.info } });
return true;
}
@@ -283,10 +403,11 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
if (url.pathname === JOBS && req.method === "POST") {
try {
const body = await req.json();
const provider = typeof body.provider === "string" ? body.provider : "shell";
const rawCommand = Array.isArray(body.command) ? body.command : [];
const command = rawCommand.filter((c: unknown): c is string => typeof c === "string");
const label = typeof body.label === "string" ? body.label : `${provider} agent`;
const provider = typeof body.provider === "string" ? body.provider : "";
let rawCommand = Array.isArray(body.command) ? body.command : [];
let command = rawCommand.filter((c: unknown): c is string => typeof c === "string");
let label = typeof body.label === "string" ? body.label : `${provider} agent`;
let outputPath: string | undefined;
// Validate provider is a known, available capability
const cap = capabilities.find((c) => c.id === provider);
@@ -297,6 +418,24 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
);
}
// Try server-side command building for known providers
let captureStdout = false;
let stdinPrompt: string | undefined;
let spawnCwd: string | undefined;
let promptText: string | undefined;
if (options.buildCommand) {
const built = await options.buildCommand(provider);
if (built) {
command = built.command;
outputPath = built.outputPath;
captureStdout = built.captureStdout ?? false;
stdinPrompt = built.stdinPrompt;
spawnCwd = built.cwd;
promptText = built.prompt;
if (built.label) label = built.label;
}
}
if (command.length === 0) {
return Response.json(
{ error: 'Missing "command" array' },
@@ -304,7 +443,12 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions): AgentJob
);
}
const job = spawnJob(provider, command, label);
const job = spawnJob(provider, command, label, outputPath, {
captureStdout,
stdinPrompt,
cwd: spawnCwd,
prompt: promptText,
});
return Response.json({ job }, { status: 201 });
} catch {
return Response.json({ error: "Invalid JSON" }, { status: 400 });
+344
View File
@@ -0,0 +1,344 @@
import { toRelativePath } from "./path-utils";
/**
* Claude Code Review Agent — prompt, command builder, and JSONL output parser.
*
* Claude has its own review model (severity-based findings with reasoning traces)
* separate from Codex's priority-based model. The transform layer normalizes
* both into the shared annotation format.
*
* Claude uses --json-schema (inline JSON + Ajv validation with retries) and
* --output-format stream-json for live JSONL streaming. The final event is
* type:"result" with structured_output containing validated findings.
*/
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type ClaudeSeverity = "important" | "nit" | "pre_existing";
export interface ClaudeFinding {
severity: ClaudeSeverity;
file: string;
line: number;
end_line: number;
description: string;
reasoning: string;
}
export interface ClaudeReviewOutput {
findings: ClaudeFinding[];
summary: {
important: number;
nit: number;
pre_existing: number;
};
}
// ---------------------------------------------------------------------------
// Schema — Claude's own severity-based model
// ---------------------------------------------------------------------------
export const CLAUDE_REVIEW_SCHEMA_JSON = JSON.stringify({
type: "object",
properties: {
findings: {
type: "array",
items: {
type: "object",
properties: {
severity: { type: "string", enum: ["important", "nit", "pre_existing"] },
file: { type: "string" },
line: { type: "integer" },
end_line: { type: "integer" },
description: { type: "string" },
reasoning: { type: "string" },
},
required: ["severity", "file", "line", "end_line", "description", "reasoning"],
additionalProperties: false,
},
},
summary: {
type: "object",
properties: {
important: { type: "integer" },
nit: { type: "integer" },
pre_existing: { type: "integer" },
},
required: ["important", "nit", "pre_existing"],
additionalProperties: false,
},
},
required: ["findings", "summary"],
additionalProperties: false,
});
// ---------------------------------------------------------------------------
// Review prompt — converges open-source Claude Code review + remote service
// ---------------------------------------------------------------------------
export const CLAUDE_REVIEW_PROMPT = `# Claude Code Review System Prompt
## Identity
You are a code review system. Your job is to find bugs that would break
production. You are not a linter, formatter, or style checker unless
project guidance files explicitly expand your scope.
## Pipeline
Step 1: Gather context
- Retrieve the PR diff (gh pr diff or git diff)
- Read CLAUDE.md and REVIEW.md at the repo root and in every directory
containing modified files
- Build a map of which rules apply to which file paths
- Identify any skip rules (paths, patterns, or file types to ignore)
Step 2: Launch 4 parallel review agents
Agent 1 — Bug + Regression (Opus-level reasoning)
Scan for logic errors, regressions, broken edge cases, build failures,
and code that will produce wrong results. Focus on the diff but read
surrounding code to understand call sites and data flow. Flag only
issues where the code is demonstrably wrong — not stylistic concerns,
not missing tests, not "could be cleaner."
Agent 2 — Security + Deep Analysis (Opus-level reasoning)
Look for security vulnerabilities with concrete exploit paths, race
conditions, incorrect assumptions about trust boundaries, and subtle
issues in introduced code. Read surrounding code for context. Do not
flag theoretical risks without a plausible path to harm.
Agent 3 — Code Quality + Reusability (Sonnet-level reasoning)
Look for code smells, unnecessary duplication, missed opportunities to
reuse existing utilities or patterns in the codebase, overly complex
implementations that could be simpler, and elegance issues. Read the
surrounding codebase to understand existing patterns before flagging.
Only flag issues a senior engineer would care about.
Agent 4 — Guideline Compliance (Haiku-level reasoning)
Audit changes against rules from CLAUDE.md and REVIEW.md gathered in
Step 1. Only flag clear, unambiguous violations where you can cite the
exact rule broken. If a PR makes a CLAUDE.md statement outdated, flag
that the docs need updating. Respect all skip rules — never flag files
or patterns that guidance says to ignore.
All agents:
- Do not duplicate each other's findings
- Do not flag issues in paths excluded by guidance files
- Provide file, line number, and a concise description for each candidate
Step 3: Validate each candidate finding
For each candidate, launch a validation agent. The validator:
- Traces the actual code path to confirm the issue is real
- Checks whether the issue is handled elsewhere (try/catch, upstream
guard, fallback logic, type system guarantees)
- Confirms the finding is not a false positive with high confidence
- If validation fails, drop the finding silently
- If validation passes, write a clear reasoning chain explaining how
the issue was confirmed — this becomes the \`reasoning\` field
Step 4: Classify each validated finding
Assign exactly one severity:
important — A bug that should be fixed before merging. Build failures,
clear logic errors, security vulnerabilities with exploit paths, data
loss risks, race conditions with observable consequences.
nit — A minor issue worth fixing but non-blocking. Style deviations
from project guidelines, code quality concerns, edge cases that are
unlikely but worth noting, convention violations that don't affect
correctness.
pre_existing — A bug that exists in the surrounding codebase but was
NOT introduced by this PR. Only flag when directly relevant to the
changed code path.
Step 5: Deduplicate and rank
- Merge findings that describe the same underlying issue from different
agents — keep the most specific description and the highest severity
- Sort by severity: important → nit → pre_existing
- Within each severity, sort by file path and line number
Step 6: Return structured JSON output matching the schema.
If no issues are found, return an empty findings array with zeroed summary.
## Hard constraints
- Never approve or block the PR
- Never comment on formatting or code style unless guidance files say to
- Never flag missing test coverage unless guidance files say to
- Never invent rules — only enforce what CLAUDE.md or REVIEW.md state
- Never flag issues in skipped paths or generated files unless guidance
explicitly includes them
- Prefer silence over false positives — when in doubt, drop the finding
- Do NOT post any comments to GitHub or GitLab
- Do NOT use gh pr comment or any commenting tool
- Your only output is the structured JSON findings`;
// ---------------------------------------------------------------------------
// Command builder
// ---------------------------------------------------------------------------
export interface ClaudeCommandResult {
command: string[];
/** Prompt text to write to stdin (Claude reads prompt from stdin, not argv). */
stdinPrompt: string;
}
/**
* Build the `claude -p` command. Prompt is passed via stdin, not as a
* positional arg — avoids quoting issues, argv limits, and variadic flag conflicts.
*/
export function buildClaudeCommand(prompt: string): ClaudeCommandResult {
const allowedTools = [
"Agent", "Read", "Glob", "Grep",
// GitHub CLI
"Bash(gh pr view:*)", "Bash(gh pr diff:*)", "Bash(gh pr list:*)",
"Bash(gh issue view:*)", "Bash(gh issue list:*)",
"Bash(gh api repos/*/*/pulls/*)", "Bash(gh api repos/*/*/pulls/*/files*)",
"Bash(gh api repos/*/*/pulls/*/comments*)", "Bash(gh api repos/*/*/issues/*/comments*)",
// GitLab CLI
"Bash(glab mr view:*)", "Bash(glab mr diff:*)", "Bash(glab mr list:*)",
"Bash(glab api:*)",
// Git (read-only)
"Bash(git status:*)", "Bash(git diff:*)", "Bash(git log:*)",
"Bash(git show:*)", "Bash(git blame:*)", "Bash(git branch:*)",
"Bash(git grep:*)", "Bash(git ls-remote:*)", "Bash(git ls-tree:*)",
"Bash(git merge-base:*)", "Bash(git remote:*)", "Bash(git rev-parse:*)",
"Bash(git show-ref:*)",
"Bash(wc:*)",
].join(",");
const disallowedTools = [
"Edit", "Write", "NotebookEdit", "WebFetch", "WebSearch",
"Bash(python:*)", "Bash(python3:*)", "Bash(node:*)", "Bash(npx:*)",
"Bash(bun:*)", "Bash(bunx:*)", "Bash(sh:*)", "Bash(bash:*)", "Bash(zsh:*)",
"Bash(curl:*)", "Bash(wget:*)",
].join(",");
return {
command: [
"claude", "-p",
"--permission-mode", "dontAsk",
"--output-format", "stream-json",
"--verbose",
"--json-schema", CLAUDE_REVIEW_SCHEMA_JSON,
"--no-session-persistence",
"--model", "sonnet",
"--tools", "Agent,Bash,Read,Glob,Grep",
"--allowedTools", allowedTools,
"--disallowedTools", disallowedTools,
],
stdinPrompt: prompt,
};
}
// ---------------------------------------------------------------------------
// JSONL stream output parser
// ---------------------------------------------------------------------------
/**
* Parse Claude Code's stream-json output (JSONL).
* Extracts structured_output from the final type:"result" event.
*/
export function parseClaudeStreamOutput(stdout: string): ClaudeReviewOutput | null {
if (!stdout.trim()) return null;
const lines = stdout.trim().split('\n');
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i].trim();
if (!line) continue;
try {
const event = JSON.parse(line);
if (event.type === 'result') {
if (event.is_error) return null;
const output = event.structured_output;
if (!output || !Array.isArray(output.findings)) return null;
return output as ClaudeReviewOutput;
}
} catch {
// Not valid JSON — skip
}
}
return null;
}
// ---------------------------------------------------------------------------
// Finding transform — Claude findings → external annotations
// ---------------------------------------------------------------------------
/** Transform Claude findings into the external annotation format. */
export function transformClaudeFindings(
findings: ClaudeFinding[],
source: string,
cwd?: string,
): Array<{
source: string;
filePath: string;
lineStart: number;
lineEnd: number;
type: string;
side: string;
scope: string;
text: string;
severity: ClaudeSeverity;
reasoning: string;
author: string;
}> {
return findings
.filter(f => f.file && typeof f.line === "number")
.map(f => ({
source,
filePath: toRelativePath(f.file, cwd),
lineStart: f.line,
lineEnd: f.end_line ?? f.line,
type: "comment",
side: "new",
scope: "line",
text: `[${f.severity}] ${f.description}`,
severity: f.severity,
reasoning: f.reasoning,
author: "Claude Code",
}));
}
// ---------------------------------------------------------------------------
// Live log formatter
// ---------------------------------------------------------------------------
/**
* Extract log-worthy content from a JSONL line for the LiveLogViewer.
* Returns a human-readable string, or null if the line should be skipped.
*/
export function formatClaudeLogEvent(line: string): string | null {
try {
const event = JSON.parse(line);
// Skip the final result event — handled separately
if (event.type === 'result') return null;
// Assistant messages (the agent's thinking/responses)
if (event.type === 'assistant' && event.message?.content) {
const parts = Array.isArray(event.message.content) ? event.message.content : [event.message.content];
const texts = parts
.filter((p: any) => p.type === 'text' && p.text)
.map((p: any) => p.text);
if (texts.length > 0) return texts.join('\n');
// Tool use events (only reached if no text parts found)
const tools = parts.filter((p: any) => p.type === 'tool_use');
if (tools.length > 0) {
return tools.map((t: any) => `[${t.name}] ${typeof t.input === 'string' ? t.input.slice(0, 100) : JSON.stringify(t.input).slice(0, 100)}`).join('\n');
}
}
return null;
} catch {
return null;
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"type": "object",
"properties": {
"findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": { "type": "string" },
"body": { "type": "string" },
"confidence_score": { "type": "number" },
"priority": { "type": ["integer", "null"] },
"code_location": {
"type": "object",
"properties": {
"absolute_file_path": { "type": "string" },
"line_range": {
"type": "object",
"properties": {
"start": { "type": "integer" },
"end": { "type": "integer" }
},
"required": ["start", "end"],
"additionalProperties": false
}
},
"required": ["absolute_file_path", "line_range"],
"additionalProperties": false
}
},
"required": ["title", "body", "confidence_score", "priority", "code_location"],
"additionalProperties": false
}
},
"overall_correctness": { "type": "string" },
"overall_explanation": { "type": "string" },
"overall_confidence_score": { "type": "number" }
},
"required": ["findings", "overall_correctness", "overall_explanation", "overall_confidence_score"],
"additionalProperties": false
}
+381
View File
@@ -0,0 +1,381 @@
/**
* Codex Review Agent — prompt, command builder, output parser, and finding transformer.
*
* Encapsulates all Codex-specific logic for the AI review agent integration.
* The review server (review.ts) calls into this module via the agent-jobs callbacks.
*/
import { join } from "node:path";
import { homedir, tmpdir } from "node:os";
import { appendFile, mkdir, unlink, writeFile, readFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import type { DiffType } from "./vcs";
import type { PRMetadata } from "./pr";
import { toRelativePath } from "./path-utils";
// ---------------------------------------------------------------------------
// Debug log — only active when PLANNOTATOR_DEBUG is set
// ---------------------------------------------------------------------------
const DEBUG_ENABLED = !!process.env.PLANNOTATOR_DEBUG;
const DEBUG_LOG_PATH = join(homedir(), ".plannotator", "codex-review-debug.log");
async function debugLog(label: string, data?: unknown): Promise<void> {
if (!DEBUG_ENABLED) return;
try {
await mkdir(join(homedir(), ".plannotator"), { recursive: true });
const timestamp = new Date().toISOString();
const line = data !== undefined
? `[${timestamp}] ${label}: ${typeof data === "string" ? data : JSON.stringify(data, null, 2)}\n`
: `[${timestamp}] ${label}\n`;
await appendFile(DEBUG_LOG_PATH, line);
} catch { /* never fail the main flow */ }
}
// ---------------------------------------------------------------------------
// Schema — embedded as a string, written to disk on first use.
// Bun's compiled binary uses a virtual FS that external processes (codex)
// can't read, so we materialize the schema to a real file.
// ---------------------------------------------------------------------------
const CODEX_REVIEW_SCHEMA = JSON.stringify({
type: "object",
properties: {
findings: {
type: "array",
items: {
type: "object",
properties: {
title: { type: "string" },
body: { type: "string" },
confidence_score: { type: "number" },
priority: { type: ["integer", "null"] },
code_location: {
type: "object",
properties: {
absolute_file_path: { type: "string" },
line_range: {
type: "object",
properties: {
start: { type: "integer" },
end: { type: "integer" },
},
required: ["start", "end"],
additionalProperties: false,
},
},
required: ["absolute_file_path", "line_range"],
additionalProperties: false,
},
},
required: ["title", "body", "confidence_score", "priority", "code_location"],
additionalProperties: false,
},
},
overall_correctness: { type: "string" },
overall_explanation: { type: "string" },
overall_confidence_score: { type: "number" },
},
required: ["findings", "overall_correctness", "overall_explanation", "overall_confidence_score"],
additionalProperties: false,
});
const SCHEMA_DIR = join(homedir(), ".plannotator");
const SCHEMA_FILE = join(SCHEMA_DIR, "codex-review-schema.json");
let schemaMaterialized = false;
/** Ensure the schema file exists on disk and return its path. */
async function ensureSchemaFile(): Promise<string> {
if (!schemaMaterialized) {
await mkdir(SCHEMA_DIR, { recursive: true });
await writeFile(SCHEMA_FILE, CODEX_REVIEW_SCHEMA);
schemaMaterialized = true;
}
return SCHEMA_FILE;
}
export { SCHEMA_FILE as CODEX_REVIEW_SCHEMA_PATH };
// ---------------------------------------------------------------------------
// System prompt — copied verbatim from codex-rs/core/review_prompt.md
// ---------------------------------------------------------------------------
export const CODEX_REVIEW_SYSTEM_PROMPT = `# Review guidelines:
You are acting as a reviewer for a proposed code change made by another engineer.
Below are some default guidelines for determining whether the original author would appreciate the issue being flagged.
These are not the final word in determining whether an issue is a bug. In many cases, you will encounter other, more specific guidelines. These may be present elsewhere in a developer message, a user message, a file, or even elsewhere in this system message.
Those guidelines should be considered to override these general instructions.
Here are the general guidelines for determining whether something is a bug and should be flagged.
1. It meaningfully impacts the accuracy, performance, security, or maintainability of the code.
2. The bug is discrete and actionable (i.e. not a general issue with the codebase or a combination of multiple issues).
3. Fixing the bug does not demand a level of rigor that is not present in the rest of the codebase (e.g. one doesn't need very detailed comments and input validation in a repository of one-off scripts in personal projects)
4. The bug was introduced in the commit (pre-existing bugs should not be flagged).
5. The author of the original PR would likely fix the issue if they were made aware of it.
6. The bug does not rely on unstated assumptions about the codebase or author's intent.
7. It is not enough to speculate that a change may disrupt another part of the codebase, to be considered a bug, one must identify the other parts of the code that are provably affected.
8. The bug is clearly not just an intentional change by the original author.
When flagging a bug, you will also provide an accompanying comment. Once again, these guidelines are not the final word on how to construct a comment -- defer to any subsequent guidelines that you encounter.
1. The comment should be clear about why the issue is a bug.
2. The comment should appropriately communicate the severity of the issue. It should not claim that an issue is more severe than it actually is.
3. The comment should be brief. The body should be at most 1 paragraph. It should not introduce line breaks within the natural language flow unless it is necessary for the code fragment.
4. The comment should not include any chunks of code longer than 3 lines. Any code chunks should be wrapped in markdown inline code tags or a code block.
5. The comment should clearly and explicitly communicate the scenarios, environments, or inputs that are necessary for the bug to arise. The comment should immediately indicate that the issue's severity depends on these factors.
6. The comment's tone should be matter-of-fact and not accusatory or overly positive. It should read as a helpful AI assistant suggestion without sounding too much like a human reviewer.
7. The comment should be written such that the original author can immediately grasp the idea without close reading.
8. The comment should avoid excessive flattery and comments that are not helpful to the original author. The comment should avoid phrasing like "Great job ...", "Thanks for ...".
Below are some more detailed guidelines that you should apply to this specific review.
HOW MANY FINDINGS TO RETURN:
Output all findings that the original author would fix if they knew about it. If there is no finding that a person would definitely love to see and fix, prefer outputting no findings. Do not stop at the first qualifying finding. Continue until you've listed every qualifying finding.
GUIDELINES:
- Ignore trivial style unless it obscures meaning or violates documented standards.
- Use one comment per distinct issue (or a multi-line range if necessary).
- Use \`\`\`suggestion blocks ONLY for concrete replacement code (minimal lines; no commentary inside the block).
- In every \`\`\`suggestion block, preserve the exact leading whitespace of the replaced lines (spaces vs tabs, number of spaces).
- Do NOT introduce or remove outer indentation levels unless that is the actual fix.
The comments will be presented in the code review as inline comments. You should avoid providing unnecessary location details in the comment body. Always keep the line range as short as possible for interpreting the issue. Avoid ranges longer than 5–10 lines; instead, choose the most suitable subrange that pinpoints the problem.
At the beginning of the finding title, tag the bug with priority level. For example "[P1] Un-padding slices along wrong tensor dimensions". [P0] – Drop everything to fix. Blocking release, operations, or major usage. Only use for universal issues that do not depend on any assumptions about the inputs. · [P1] – Urgent. Should be addressed in the next cycle · [P2] – Normal. To be fixed eventually · [P3] – Low. Nice to have.
Additionally, include a numeric priority field in the JSON output for each finding: set "priority" to 0 for P0, 1 for P1, 2 for P2, or 3 for P3. If a priority cannot be determined, omit the field or use null.
At the end of your findings, output an "overall correctness" verdict of whether or not the patch should be considered "correct".
Correct implies that existing code and tests will not break, and the patch is free of bugs and other blocking issues.
Ignore non-blocking issues such as style, formatting, typos, documentation, and other nits.
FORMATTING GUIDELINES:
The finding description should be one paragraph.`;
// ---------------------------------------------------------------------------
// User message builder
// ---------------------------------------------------------------------------
/** Build the dynamic user message based on review context. */
export function buildCodexReviewUserMessage(
patch: string,
diffType: DiffType,
options?: { defaultBranch?: string; hasLocalAccess?: boolean },
prMetadata?: PRMetadata,
): string {
// PR/MR mode — pass the link, with local context if --local
if (prMetadata) {
if (options?.hasLocalAccess) {
return [
prMetadata.url,
"",
"You are in a local worktree checked out at the PR head. The code is available locally.",
`To see the PR changes, diff against the remote base branch: git diff origin/${prMetadata.baseBranch}...HEAD`,
"Do NOT diff against the local `main` branch — it may be stale. Always use origin/.",
].join("\n");
}
return prMetadata.url;
}
// Local mode — Codex has full file/git access
const effectiveDiffType = diffType.startsWith("worktree:")
? diffType.split(":").pop() || "uncommitted"
: diffType;
switch (effectiveDiffType) {
case "uncommitted":
return "Review the current code changes (staged, unstaged, and untracked files) and provide prioritized findings.";
case "staged":
return "Review the currently staged code changes (`git diff --staged`) and provide prioritized findings.";
case "unstaged":
return "Review the unstaged code changes (tracked modifications and untracked files) and provide prioritized findings.";
case "last-commit":
return "Review the code changes introduced in the last commit (`git diff HEAD~1..HEAD`) and provide prioritized findings.";
case "branch": {
const base = options?.defaultBranch || "main";
return `Review the code changes against the base branch '${base}'. Run \`git diff ${base}..HEAD\` to inspect the changes. Provide prioritized, actionable findings.`;
}
default:
// p4 or unknown — fall back to generic with inlined diff
return [
"Review the following code changes and provide prioritized findings.",
"",
"```diff",
patch,
"```",
].join("\n");
}
}
// ---------------------------------------------------------------------------
// Command builder
// ---------------------------------------------------------------------------
export interface CodexCommandOptions {
cwd: string;
outputPath: string;
prompt: string;
}
/** Build the `codex exec` argv array. Materializes the schema file on first call. */
export async function buildCodexCommand(options: CodexCommandOptions): Promise<string[]> {
const { cwd, outputPath, prompt } = options;
const schemaPath = await ensureSchemaFile();
const command = [
"codex",
"exec",
"--output-schema", schemaPath,
"-o", outputPath,
"--full-auto",
"--ephemeral",
"-C", cwd,
prompt,
];
debugLog("BUILD_COMMAND", {
cwd,
outputPath,
schemaPath,
promptLength: prompt.length,
command: command.map((c, i) => i === command.length - 1 ? `<prompt: ${c.length} chars>` : c),
});
return command;
}
/** Generate a unique temp file path for Codex output. */
export function generateOutputPath(): string {
return join(tmpdir(), `plannotator-codex-${crypto.randomUUID()}.json`);
}
// ---------------------------------------------------------------------------
// Output parsing — matches Codex's native ReviewOutputEvent schema
// ---------------------------------------------------------------------------
export interface CodexCodeLocation {
absolute_file_path: string;
line_range: { start: number; end: number };
}
export interface CodexFinding {
title: string;
body: string;
confidence_score: number;
priority: number | null;
code_location: CodexCodeLocation;
}
export interface CodexReviewOutput {
findings: CodexFinding[];
overall_correctness: string;
overall_explanation: string;
overall_confidence_score: number;
}
/** Read and parse the Codex -o output file. Returns null on any failure. */
export async function parseCodexOutput(outputPath: string): Promise<CodexReviewOutput | null> {
await debugLog("PARSE_OUTPUT_START", { outputPath });
try {
if (!existsSync(outputPath)) {
await debugLog("PARSE_OUTPUT_FILE_MISSING", outputPath);
return null;
}
const text = await readFile(outputPath, "utf-8");
// Clean up temp file
try { await unlink(outputPath); } catch { /* ignore */ }
if (!text.trim()) {
await debugLog("PARSE_OUTPUT_EMPTY");
return null;
}
const parsed = JSON.parse(text);
if (!parsed || !Array.isArray(parsed.findings)) {
await debugLog("PARSE_OUTPUT_INVALID_SHAPE", { hasFindings: !!parsed?.findings });
return null;
}
await debugLog("PARSE_OUTPUT_SUCCESS", {
findingsCount: parsed.findings.length,
overall_correctness: parsed.overall_correctness,
overall_confidence_score: parsed.overall_confidence_score,
});
return parsed as CodexReviewOutput;
} catch (err) {
await debugLog("PARSE_OUTPUT_ERROR", err instanceof Error ? err.message : String(err));
// Clean up on error too
try { await unlink(outputPath); } catch { /* ignore */ }
return null;
}
}
// ---------------------------------------------------------------------------
// Finding → external annotation transform
// ---------------------------------------------------------------------------
export interface ReviewAnnotationInput {
source: string;
filePath: string;
lineStart: number;
lineEnd: number;
type: string;
side: string;
scope: string;
text: string;
author: string;
}
/** Transform review findings (provider-agnostic) into the external annotation format. */
export function transformReviewFindings(
findings: CodexFinding[],
source: string,
cwd?: string,
author?: string,
): ReviewAnnotationInput[] {
const annotations = findings
.filter((f) =>
f.code_location?.absolute_file_path &&
typeof f.code_location?.line_range?.start === "number" &&
typeof f.code_location?.line_range?.end === "number"
)
.map((f) => ({
source,
filePath: toRelativePath(f.code_location.absolute_file_path, cwd),
lineStart: f.code_location.line_range.start,
lineEnd: f.code_location.line_range.end,
type: "comment",
side: "new",
scope: "line",
text: `${f.title}\n\n${f.body}`.trim(),
author: author ?? "Review Agent",
}));
debugLog("TRANSFORM_FINDINGS", {
inputCount: findings.length,
outputCount: annotations.length,
annotations: annotations.map((a) => ({
filePath: a.filePath,
lineStart: a.lineStart,
lineEnd: a.lineEnd,
textPreview: a.text.slice(0, 80),
})),
});
return annotations;
}
+9
View File
@@ -33,6 +33,8 @@ export interface ExternalAnnotationHandler {
url: URL,
options?: { disableIdleTimeout?: () => void },
) => Promise<Response | null>;
/** Push annotations directly into the store (bypasses HTTP, reuses same validation). */
addAnnotations: (body: unknown) => { ids: string[] } | { error: string };
}
// ---------------------------------------------------------------------------
@@ -68,6 +70,13 @@ export function createExternalAnnotationHandler(
});
return {
addAnnotations(body: unknown): { ids: string[] } | { error: string } {
const parsed = transform(body);
if ("error" in parsed) return { error: parsed.error };
const created = store.add(parsed.annotations);
return { ids: created.map((a) => a.id) };
},
async handle(
req: Request,
url: URL,
+2 -1
View File
@@ -53,7 +53,8 @@ async function runGit(
return { stdout, stderr, exitCode };
}
const runtime: ReviewGitRuntime = {
/** Bun-based git runtime. Exported for use with shared utilities (worktree, etc.) */
export const runtime: ReviewGitRuntime = {
runGit,
async readTextFile(path: string): Promise<string | null> {
try {
+18
View File
@@ -0,0 +1,18 @@
/**
* Strip a cwd prefix from an absolute path to get a repo-relative path.
* Used by review agent transforms to convert absolute file paths from
* agent output into diff-compatible relative paths.
*
* Uses path.relative for cross-platform support (Windows backslashes)
* and normalizes to forward slashes for git diff path matching.
*/
import { relative } from "node:path";
export function toRelativePath(absolutePath: string, cwd?: string): string {
if (!cwd) return absolutePath;
const rel = relative(cwd, absolutePath);
// Don't relativize if the result goes outside cwd (different drive, symlink escape)
if (rel.startsWith("..")) return absolutePath;
// Normalize to forward slashes for diff path matching
return rel.replace(/\\/g, "/");
}
+127 -14
View File
@@ -18,6 +18,20 @@ import { contentHash, deleteDraft } from "./draft";
import { createEditorAnnotationHandler } from "./editor-annotations";
import { createExternalAnnotationHandler } from "./external-annotations";
import { createAgentJobHandler } from "./agent-jobs";
import {
CODEX_REVIEW_SYSTEM_PROMPT,
buildCodexReviewUserMessage,
buildCodexCommand,
generateOutputPath,
parseCodexOutput,
transformReviewFindings,
} from "./codex-review";
import {
CLAUDE_REVIEW_PROMPT,
buildClaudeCommand,
parseClaudeStreamOutput,
transformClaudeFindings,
} from "./claude-review";
import { saveConfig, detectGitUser, getServerConfig } from "./config";
import { type PRMetadata, type PRReviewFileComment, fetchPRFileContent, fetchPRContext, submitPRReview, fetchPRViewedFiles, markPRFilesViewed, getPRUser, prRefFromMetadata, getDisplayRepo, getMRLabel, getMRNumberLabel } from "./pr";
import { createAIEndpoints, ProviderRegistry, SessionManager, createProvider, type AIEndpoints, type PiSDKConfig } from "@plannotator/ai";
@@ -57,6 +71,10 @@ export interface ReviewServerOptions {
opencodeClient?: OpencodeClient;
/** PR metadata when reviewing a pull request (PR mode) */
prMetadata?: PRMetadata;
/** 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>;
}
export interface ReviewServerResult {
@@ -96,6 +114,7 @@ export async function startReviewServer(
const { htmlContent, origin, gitContext, sharingEnabled = true, shareBaseUrl, onReady, prMetadata } = options;
const isPRMode = !!prMetadata;
const hasLocalAccess = !!gitContext;
const draftKey = contentHash(options.rawPatch);
const editorAnnotations = createEditorAnnotationHandler();
const externalAnnotations = createExternalAnnotationHandler("review");
@@ -112,8 +131,84 @@ export async function startReviewServer(
mode: "review",
getServerUrl: () => serverUrl,
getCwd: () => {
if (options.agentCwd) return options.agentCwd;
return resolveVcsCwd(currentDiffType, gitContext?.cwd) ?? process.cwd();
},
async buildCommand(provider) {
const cwd = options.agentCwd ?? resolveVcsCwd(currentDiffType, gitContext?.cwd) ?? process.cwd();
const hasAgentLocalAccess = !!options.agentCwd || !!gitContext;
const userMessage = buildCodexReviewUserMessage(
currentPatch,
currentDiffType,
{ defaultBranch: gitContext?.defaultBranch, hasLocalAccess: hasAgentLocalAccess },
prMetadata,
);
if (provider === "codex") {
const outputPath = generateOutputPath();
const prompt = CODEX_REVIEW_SYSTEM_PROMPT + "\n\n---\n\n" + userMessage;
const command = await buildCodexCommand({ cwd, outputPath, prompt });
return { command, outputPath, prompt, label: "Codex Review" };
}
if (provider === "claude") {
const prompt = CLAUDE_REVIEW_PROMPT + "\n\n---\n\n" + userMessage;
const { command, stdinPrompt } = buildClaudeCommand(prompt);
return { command, stdinPrompt, prompt, cwd, label: "Claude Code Review", captureStdout: true };
}
return null;
},
async onJobComplete(job, meta) {
const cwd = options.agentCwd ?? resolveVcsCwd(currentDiffType, gitContext?.cwd) ?? process.cwd();
// --- 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;
}
},
});
// AI provider setup (graceful — AI features degrade if SDK unavailable)
@@ -194,6 +289,7 @@ export async function startReviewServer(
registry: aiRegistry,
sessionManager: aiSessionManager,
getCwd: () => {
if (options.agentCwd) return options.agentCwd;
return resolveVcsCwd(currentDiffType, gitContext?.cwd) ?? process.cwd();
},
});
@@ -260,12 +356,13 @@ export async function startReviewServer(
rawPatch: currentPatch,
gitRef: currentGitRef,
origin,
diffType: isPRMode ? undefined : currentDiffType,
gitContext: isPRMode ? undefined : gitContext,
diffType: hasLocalAccess ? currentDiffType : undefined,
gitContext: hasLocalAccess ? gitContext : undefined,
sharingEnabled,
shareBaseUrl,
repoInfo,
isWSL: wslFlag,
...(options.agentCwd && { agentCwd: options.agentCwd }),
...(isPRMode && { prMetadata, platformUser }),
...(isPRMode && initialViewedFiles.length > 0 && { viewedFiles: initialViewedFiles }),
...(currentError && { error: currentError }),
@@ -273,11 +370,11 @@ export async function startReviewServer(
});
}
// API: Switch diff type (disabled in PR mode)
// API: Switch diff type (requires local file access)
if (url.pathname === "/api/diff/switch" && req.method === "POST") {
if (isPRMode) {
if (!hasLocalAccess) {
return Response.json(
{ error: "Not available for PR reviews" },
{ error: "Not available without local file access" },
{ status: 400 },
);
}
@@ -351,15 +448,8 @@ export async function startReviewServer(
}
}
if (isPRMode) {
// Fetch file content from platform API using base/head SHAs
const [oldContent, newContent] = await Promise.all([
fetchPRFileContent(prRef!, prMetadata.baseSha, oldPath || filePath),
fetchPRFileContent(prRef!, prMetadata.headSha, filePath),
]);
return Response.json({ oldContent, newContent });
}
// Local review: read file contents from local git
if (hasLocalAccess) {
const defaultBranch = gitContext?.defaultBranch || "main";
const defaultCwd = gitContext?.cwd;
const result = await getVcsFileContentsForDiff(
@@ -372,6 +462,18 @@ export async function startReviewServer(
return Response.json(result);
}
// PR mode: fetch from platform API using base/head SHAs
if (isPRMode) {
const [oldContent, newContent] = await Promise.all([
fetchPRFileContent(prRef!, prMetadata.baseSha, oldPath || filePath),
fetchPRFileContent(prRef!, prMetadata.headSha, filePath),
]);
return Response.json({ oldContent, newContent });
}
return Response.json({ error: "No file access available" }, { status: 400 });
}
// API: Stage / unstage a file (disabled when VCS doesn't support it)
if (url.pathname === "/api/git-add" && req.method === "POST") {
if (isPRMode || !canStageFiles(currentDiffType)) {
@@ -491,6 +593,8 @@ export async function startReviewServer(
fileComments: PRReviewFileComment[];
};
console.error(`[pr-action] ${body.action} with ${body.fileComments.length} file comment(s), headSha=${prMetadata.headSha}`);
await submitPRReview(
prRef!,
prMetadata.headSha,
@@ -499,10 +603,12 @@ export async function startReviewServer(
body.fileComments,
);
console.error(`[pr-action] Success`);
return Response.json({ ok: true, prUrl: prMetadata.url });
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to submit PR review";
console.error(`[pr-action] Failed: ${message}`);
return Response.json({ error: message }, { status: 500 });
}
}
@@ -595,6 +701,13 @@ export async function startReviewServer(
aiSessionManager.disposeAll();
aiRegistry.disposeAll();
server.stop();
// 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 */ }
}
},
};
}
+1 -1
View File
@@ -151,7 +151,7 @@ export type {
WorktreeInfo,
} from "./git";
export { parseWorktreeDiffType, validateFilePath } from "./git";
export { parseWorktreeDiffType, validateFilePath, runtime as gitRuntime } from "./git";
// --- Detection cache ---
+11
View File
@@ -35,6 +35,16 @@ export interface AgentJobInfo {
error?: string;
/** The actual command that was spawned (for display/debug). */
command: string[];
/** Working directory where the process was spawned. */
cwd?: string;
/** The review prompt text (system + user message). Stored separately from command for providers that use stdin. */
prompt?: string;
/** Review summary set by the agent on completion. */
summary?: {
correctness: string;
explanation: string;
confidence: number;
};
}
export interface AgentCapability {
@@ -59,6 +69,7 @@ export type AgentJobEvent =
| { type: "job:started"; job: AgentJobInfo }
| { type: "job:updated"; job: AgentJobInfo }
| { type: "job:completed"; job: AgentJobInfo }
| { type: "job:log"; jobId: string; delta: string }
| { type: "jobs:cleared" };
// ---------------------------------------------------------------------------
+6
View File
@@ -180,6 +180,9 @@ interface ReviewAnnotation {
createdAt: number;
author?: string;
source?: string;
// Agent review metadata (optional — only set by Claude review findings)
severity?: string; // "important" | "nit" | "pre_existing"
reasoning?: string; // Validation chain explaining how the issue was confirmed
}
const VALID_REVIEW_TYPES = ["comment", "suggestion", "concern"];
@@ -254,6 +257,9 @@ export function transformReviewInput(
createdAt: Date.now(),
author: typeof obj.author === "string" ? obj.author : undefined,
source,
// Agent review metadata (optional — only set by Claude review findings)
...(typeof obj.severity === "string" && { severity: obj.severity }),
...(typeof obj.reasoning === "string" && { reasoning: obj.reasoning }),
});
}
+2 -1
View File
@@ -22,6 +22,7 @@
"./external-annotation": "./external-annotation.ts",
"./agent-jobs": "./agent-jobs.ts",
"./config": "./config.ts",
"./improvement-hooks": "./improvement-hooks.ts"
"./improvement-hooks": "./improvement-hooks.ts",
"./worktree": "./worktree.ts"
}
}
+84 -2
View File
@@ -4,7 +4,7 @@
* All functions use the `gh` CLI via the PRRuntime abstraction.
*/
import type { PRRuntime, PRMetadata, PRContext, PRReviewFileComment, CommandResult } from "./pr-provider";
import type { PRRuntime, PRMetadata, PRContext, PRReviewThread, PRThreadComment, PRReviewFileComment, CommandResult } from "./pr-provider";
import { encodeApiFilePath } from "./pr-provider";
// GitHub-specific PRRef shape (used internally)
@@ -161,7 +161,9 @@ function parseGhPRContext(raw: Record<string, unknown>): PRContext {
state: str(r?.state),
body: str(r?.body),
submittedAt: str(r?.submittedAt),
...(r?.url ? { url: str(r.url) } : {}),
})),
reviewThreads: [], // populated via GraphQL after initial fetch
checks: arr(raw.statusCheckRollup).map((c: any) => ({
name: str(c?.name),
status: str(c?.status),
@@ -198,7 +200,87 @@ export async function fetchGhPRContext(
}
const raw = JSON.parse(result.stdout) as Record<string, unknown>;
return parseGhPRContext(raw);
const context = parseGhPRContext(raw);
// Fetch inline review threads via GraphQL (parallel-safe, non-blocking failure)
try {
context.reviewThreads = await fetchGhReviewThreads(runtime, ref);
} catch {
// GraphQL may not be available or may fail — degrade gracefully
context.reviewThreads = [];
}
return context;
}
// --- Review Threads (GraphQL) ---
const REVIEW_THREADS_QUERY = `
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
reviewThreads(first: 100) {
nodes {
id
isResolved
isOutdated
line
startLine
path
diffSide
comments(first: 50) {
nodes {
id
body
author { login }
createdAt
url
diffHunk
}
}
}
}
}
}
}`;
async function fetchGhReviewThreads(
runtime: PRRuntime,
ref: GhPRRef,
): Promise<PRReviewThread[]> {
const result = await runtime.runCommand("gh", hostnameArgs(ref.host, [
"api", "graphql",
"-f", `query=${REVIEW_THREADS_QUERY}`,
"-f", `owner=${ref.owner}`,
"-f", `repo=${ref.repo}`,
"-F", `number=${ref.number}`,
]));
if (result.exitCode !== 0) return [];
const data = JSON.parse(result.stdout);
const threads = data?.data?.repository?.pullRequest?.reviewThreads?.nodes;
if (!Array.isArray(threads)) return [];
return threads.map((t: any): PRReviewThread => ({
id: String(t.id ?? ''),
isResolved: t.isResolved === true,
isOutdated: t.isOutdated === true,
path: String(t.path ?? ''),
line: typeof t.line === 'number' ? t.line : null,
startLine: typeof t.startLine === 'number' ? t.startLine : null,
diffSide: t.diffSide === 'LEFT' || t.diffSide === 'RIGHT' ? t.diffSide : null,
comments: Array.isArray(t.comments?.nodes)
? t.comments.nodes.map((c: any): PRThreadComment => ({
id: String(c.id ?? ''),
author: c.author?.login ? String(c.author.login) : '',
body: String(c.body ?? ''),
createdAt: String(c.createdAt ?? ''),
url: String(c.url ?? ''),
...(c.diffHunk ? { diffHunk: String(c.diffHunk) } : {}),
}))
: [],
}));
}
// --- File Content ---
+1
View File
@@ -342,6 +342,7 @@ export async function fetchGlMRContext(
mergeStateStatus,
comments: notes,
reviews,
reviewThreads: [], // TODO: parse DiffNote positions from notes for thread support
checks,
linkedIssues,
};
+22
View File
@@ -107,6 +107,7 @@ export interface PRReview {
state: string;
body: string;
submittedAt: string;
url?: string;
}
export interface PRCheck {
@@ -123,6 +124,26 @@ export interface PRLinkedIssue {
repo: string;
}
export interface PRThreadComment {
id: string;
author: string;
body: string;
createdAt: string;
url: string;
diffHunk?: string;
}
export interface PRReviewThread {
id: string;
isResolved: boolean;
isOutdated: boolean;
path: string;
line: number | null;
startLine: number | null;
diffSide: 'LEFT' | 'RIGHT' | null;
comments: PRThreadComment[];
}
export interface PRContext {
body: string;
state: string;
@@ -133,6 +154,7 @@ export interface PRContext {
mergeStateStatus: string;
comments: PRComment[];
reviews: PRReview[];
reviewThreads: PRReviewThread[];
checks: PRCheck[];
linkedIssues: PRLinkedIssue[];
}
+119
View File
@@ -0,0 +1,119 @@
/**
* Worktree — runtime-agnostic git worktree primitives.
*
* Uses ReviewGitRuntime so both Bun and Node runtimes can use the same logic.
* Lives in packages/shared/ and gets vendored to Pi via vendor.sh.
*
* Designed as composable primitives, not tied to any specific use case.
* PR local checkout, agent sandboxes, parallel sessions — all compose from these.
*/
import type { ReviewGitRuntime } from "./review-core";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface CreateWorktreeOptions {
/** Git ref to check out (branch name, SHA, FETCH_HEAD, etc.) */
ref: string;
/** Absolute path where the worktree will be created. */
path: string;
/** Create in detached HEAD mode (no branch). Default: false. */
detach?: boolean;
/** CWD of the source repository. Defaults to process.cwd(). */
cwd?: string;
}
export interface RemoveWorktreeOptions {
/** Force removal even if the worktree has modifications. Default: false. */
force?: boolean;
/** CWD of the source repository. Required if the worktree was created from a different cwd. */
cwd?: string;
}
// ---------------------------------------------------------------------------
// Primitives
// ---------------------------------------------------------------------------
/**
* Fetch a ref from origin.
* Runs: `git fetch origin <ref>`
* Throws on failure.
*/
export async function fetchRef(
runtime: ReviewGitRuntime,
ref: string,
options?: { cwd?: string },
): Promise<void> {
const result = await runtime.runGit(["fetch", "origin", "--", ref], { cwd: options?.cwd });
if (result.exitCode !== 0) {
throw new Error(`git fetch origin ${ref} failed: ${result.stderr.trim() || `exit code ${result.exitCode}`}`);
}
}
/**
* Ensure a git object (commit SHA) is available locally.
* Checks with `git cat-file -t`, fetches from origin if missing.
* Returns true if the object is available after the attempt.
*/
export async function ensureObjectAvailable(
runtime: ReviewGitRuntime,
sha: string,
options?: { cwd?: string },
): Promise<boolean> {
const check = await runtime.runGit(["cat-file", "-t", sha], { cwd: options?.cwd });
if (check.exitCode === 0) return true;
// Object missing locally — try fetching it
const fetch = await runtime.runGit(["fetch", "origin", "--", sha], { cwd: options?.cwd });
if (fetch.exitCode !== 0) return false;
// Verify it's now available
const recheck = await runtime.runGit(["cat-file", "-t", sha], { cwd: options?.cwd });
return recheck.exitCode === 0;
}
/**
* Create a git worktree.
* Runs: `git worktree add [--detach] <path> <ref>`
* Throws on failure with a descriptive error.
*/
export async function createWorktree(
runtime: ReviewGitRuntime,
options: CreateWorktreeOptions,
): Promise<{ worktreePath: string }> {
const args = ["worktree", "add"];
if (options.detach) args.push("--detach");
args.push(options.path, options.ref);
const result = await runtime.runGit(args, { cwd: options.cwd });
if (result.exitCode !== 0) {
throw new Error(`git worktree add failed: ${result.stderr.trim() || `exit code ${result.exitCode}`}`);
}
return { worktreePath: options.path };
}
/**
* Remove a git worktree. Best-effort — logs errors but does not throw.
* Runs: `git worktree remove [--force] <path>`
*/
export async function removeWorktree(
runtime: ReviewGitRuntime,
worktreePath: string,
options?: RemoveWorktreeOptions,
): Promise<void> {
const args = ["worktree", "remove"];
if (options?.force) args.push("--force");
args.push(worktreePath);
try {
const result = await runtime.runGit(args, { cwd: options?.cwd });
if (result.exitCode !== 0) {
console.error(`Warning: git worktree remove failed for ${worktreePath}: ${result.stderr.trim()}`);
}
} catch (err) {
console.error(`Warning: worktree cleanup error: ${err instanceof Error ? err.message : String(err)}`);
}
}
+14 -31
View File
@@ -1,6 +1,7 @@
import React, { useState, useEffect, useRef, useMemo } from 'react';
import type { AgentJobInfo, AgentCapabilities } from '../types';
import { isTerminalStatus } from '@plannotator/shared/agent-jobs';
import { ReviewAgentsIcon } from './ReviewAgentsIcon';
interface AgentsTabProps {
jobs: AgentJobInfo[];
@@ -85,7 +86,7 @@ function ProviderBadge({ provider }: { provider: string }) {
provider === 'codex' ? 'Codex' :
'Shell';
return (
<span className="text-[9px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
<span className="text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
{label}
</span>
);
@@ -112,12 +113,12 @@ function JobCard({
return (
<div
className={`group relative p-2.5 rounded-lg border transition-all ${
className={`group relative p-2.5 rounded border transition-all cursor-pointer ${
expanded
? 'bg-muted/30 border-border/50'
: 'border-transparent hover:bg-muted/30 hover:border-border/50'
} ${isTerminal ? 'cursor-pointer' : ''}`}
onClick={isTerminal ? onToggle : undefined}
}`}
onClick={onViewDetails ? () => onViewDetails() : (isTerminal ? onToggle : undefined)}
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
@@ -142,27 +143,13 @@ function JobCard({
<div className="flex items-center justify-between mt-1.5">
<StatusBadge status={job.status} />
<div className="flex items-center gap-1">
{onViewDetails && (
<button
onClick={(e) => {
e.stopPropagation();
onViewDetails();
}}
className="p-1 rounded-md opacity-0 group-hover:opacity-100 hover:bg-primary/10 text-muted-foreground hover:text-primary transition-all"
title="View details"
>
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
</svg>
</button>
)}
{!isTerminal && (
<button
onClick={(e) => {
e.stopPropagation();
onKill();
}}
className="p-1 rounded-md opacity-0 group-hover:opacity-100 hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-all"
className="p-1 rounded opacity-0 group-hover:opacity-100 hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-all"
title="Kill agent"
>
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
@@ -173,8 +160,8 @@ function JobCard({
</div>
</div>
{/* Error details */}
{job.status === 'failed' && job.error && expanded && (
{/* Error details — fallback for when dockview detail panel is not available */}
{!onViewDetails && job.status === 'failed' && job.error && expanded && (
<div className="mt-2 p-2 rounded bg-destructive/5 border border-destructive/20">
<pre className="text-[10px] text-destructive/80 whitespace-pre-wrap break-all font-mono leading-relaxed max-h-24 overflow-y-auto">
{job.error}
@@ -247,9 +234,7 @@ export const AgentsTab: React.FC<AgentsTabProps> = ({
const provider = availableProviders.find((p) => p.id === selectedProvider);
onLaunch({
provider: selectedProvider,
// Stub command — will be replaced with real agent invocation
command: ['sleep', String(10 + Math.floor(Math.random() * 21))],
label: provider ? `${provider.name}` : selectedProvider,
label: provider ? `${provider.name} Review` : selectedProvider,
});
};
@@ -263,7 +248,7 @@ export const AgentsTab: React.FC<AgentsTabProps> = ({
<select
value={selectedProvider}
onChange={(e) => setSelectedProvider(e.target.value)}
className="flex-1 text-[11px] px-2 py-1.5 rounded-md bg-muted/50 border border-border/50 text-foreground focus:outline-none focus:ring-1 focus:ring-primary/30"
className="flex-1 text-xs px-2 py-1.5 rounded bg-muted/50 border border-border/50 text-foreground focus:outline-none focus:ring-1 focus:ring-primary/30"
>
{availableProviders.map((p) => (
<option key={p.id} value={p.id}>
@@ -272,14 +257,14 @@ export const AgentsTab: React.FC<AgentsTabProps> = ({
))}
</select>
) : (
<span className="flex-1 text-[11px] px-2 py-1.5 text-muted-foreground">
<span className="flex-1 text-xs px-2 py-1.5 text-muted-foreground">
{availableProviders[0]?.name}
</span>
)}
<button
onClick={handleLaunch}
disabled={!selectedProvider}
className="px-3 py-1.5 rounded-md text-[11px] font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
className="px-3 py-1.5 rounded text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Run Agent
</button>
@@ -292,9 +277,7 @@ export const AgentsTab: React.FC<AgentsTabProps> = ({
{sortedJobs.length === 0 ? (
<div className="flex flex-col items-center justify-center h-40 text-center px-4">
<div className="w-10 h-10 rounded-full bg-muted/50 flex items-center justify-center mb-3">
<svg className="w-5 h-5 text-muted-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<ReviewAgentsIcon className="w-5 h-5 text-muted-foreground" />
</div>
<p className="text-xs text-muted-foreground">
No agent jobs yet
@@ -323,7 +306,7 @@ export const AgentsTab: React.FC<AgentsTabProps> = ({
<div className="p-2 border-t border-border/50">
<button
onClick={onKillAll}
className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-xs font-medium text-destructive hover:bg-destructive/10 transition-all"
className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded text-xs font-medium text-destructive hover:bg-destructive/10 transition-all"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
+3 -1
View File
@@ -15,6 +15,7 @@ export interface ConfirmDialogProps {
cancelText?: string;
variant?: 'info' | 'warning';
showCancel?: boolean;
wide?: boolean;
}
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
@@ -28,6 +29,7 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
cancelText = 'Cancel',
variant = 'info',
showCancel = false,
wide = false,
}) => {
if (!isOpen) return null;
@@ -56,7 +58,7 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
return (
<div className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
<div className="bg-card border border-border rounded-xl w-full max-w-sm shadow-2xl p-6">
<div className={`bg-card border border-border rounded-xl w-full shadow-2xl p-6 ${wide ? 'max-w-md' : 'max-w-sm'}`}>
<div className="flex items-center gap-3 mb-4">
<div className={`w-10 h-10 rounded-full flex items-center justify-center ${iconColors[variant]}`}>
{icons[variant]}
+11
View File
@@ -5,7 +5,9 @@ interface FeedbackButtonProps {
disabled?: boolean;
isLoading?: boolean;
label?: string;
shortLabel?: string;
loadingLabel?: string;
shortLoadingLabel?: string;
title?: string;
muted?: boolean;
}
@@ -15,7 +17,9 @@ export const FeedbackButton: React.FC<FeedbackButtonProps> = ({
disabled = false,
isLoading = false,
label = 'Send Feedback',
shortLabel,
loadingLabel = 'Sending...',
shortLoadingLabel,
title = 'Send Feedback',
muted = false,
}) => (
@@ -34,7 +38,14 @@ export const FeedbackButton: React.FC<FeedbackButtonProps> = ({
<svg className="w-4 h-4 md:hidden" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
</svg>
{shortLabel ? (
<>
<span className="hidden md:inline lg:hidden">{isLoading ? (shortLoadingLabel ?? loadingLabel) : shortLabel}</span>
<span className="hidden lg:inline">{isLoading ? loadingLabel : label}</span>
</>
) : (
<span className="hidden md:inline">{isLoading ? loadingLabel : label}</span>
)}
</button>
);
+10 -1
View File
@@ -20,6 +20,7 @@ const CAPABILITIES_URL = '/api/agents/capabilities';
interface UseAgentJobsReturn {
jobs: AgentJobInfo[];
jobLogs: Map<string, string>;
capabilities: AgentCapabilities | null;
launchJob: (params: { provider?: string; command?: string[]; label?: string }) => Promise<AgentJobInfo | null>;
killJob: (id: string) => Promise<void>;
@@ -31,6 +32,7 @@ export function useAgentJobs(
): UseAgentJobsReturn {
const enabled = options?.enabled ?? true;
const [jobs, setJobs] = useState<AgentJobInfo[]>([]);
const [jobLogs, setJobLogs] = useState<Map<string, string>>(new Map());
const [capabilities, setCapabilities] = useState<AgentCapabilities | null>(null);
const versionRef = useRef(0);
const fallbackRef = useRef(false);
@@ -83,6 +85,13 @@ export function useAgentJobs(
prev.map((j) => (j.id === parsed.job.id ? parsed.job : j)),
);
break;
case 'job:log':
setJobLogs((prev) => {
const next = new Map(prev);
next.set(parsed.jobId, (prev.get(parsed.jobId) ?? '') + parsed.delta);
return next;
});
break;
case 'jobs:cleared':
// No-op: killAll() already broadcasts individual job:completed events
// for each killed job, so the UI updates incrementally.
@@ -189,5 +198,5 @@ export function useAgentJobs(
}
}, []);
return { jobs, capabilities, launchJob, killJob, killAll };
return { jobs, jobLogs, capabilities, launchJob, killJob, killAll };
}
+11
View File
@@ -76,8 +76,17 @@ export interface CodeAnnotation {
createdAt: number;
author?: string;
source?: string; // External tool identifier (e.g., "eslint") — set when annotation comes from external API
severity?: 'important' | 'nit' | 'pre_existing'; // Agent review severity (Claude)
reasoning?: string; // Validation chain — how the issue was confirmed (Claude)
}
/** Severity display styles — shared between agent detail panel and inline diff annotations. */
export const SEVERITY_STYLES: Record<string, { dot: string; label: string }> = {
important: { dot: 'bg-destructive', label: 'Important' },
nit: { dot: 'bg-amber-500', label: 'Nit' },
pre_existing: { dot: 'bg-muted-foreground', label: 'Pre-existing' },
};
// For @pierre/diffs integration
export interface DiffAnnotationMetadata {
annotationId: string;
@@ -86,6 +95,8 @@ export interface DiffAnnotationMetadata {
suggestedCode?: string;
originalCode?: string;
author?: string;
severity?: 'important' | 'nit' | 'pre_existing';
reasoning?: string;
// AI marker fields (set when kind === 'ai-marker')
kind?: 'annotation' | 'ai-marker';
questionId?: string;