Commit Graph

12 Commits

Author SHA1 Message Date
Michael Ramos a96e74c2f8 Make Pi browser review and annotation sessions async (#645)
* Make Pi browser review and annotation sessions async

* fix(pi-extension): harden async browser feedback

* fix(pi-extension): stop async browser sessions on failure

* fix(pi-extension): tighten async browser session helpers

* chore(pi-extension): remove stale await from message lookup

* fix(pi-extension): route stale browser feedback to active session

* fix(pi-extension): route feedback by active session identity

* fix(pi-extension): include helper modules in package
2026-05-01 16:46:41 -07:00
Michael Ramos 9b7c39d2a4 fix(review): move hide-whitespace to server-side git diff -w (#635 follow-up) (#638)
The client-side approach from PR #635 normalized file contents before
diffing, which destroyed all indentation. Move whitespace handling to
the server by threading a `-w` flag through the git diff pipeline.

- Add `GitDiffOptions` to review-core.ts, inject `-w` in all 7 diff
  type paths + untracked file diffs
- Thread options through git.ts → vcs.ts → review.ts / Pi server
- Read `hideWhitespace` from ~/.plannotator/config.json on startup so
  the initial diff already respects the persisted preference
- Accept `hideWhitespace` in `/api/diff/switch`, echo in responses
- Client toggles trigger a lightweight server refetch that preserves
  the active file (no panel reset)
- Handle edge case where current file disappears when `-w` removes
  whitespace-only diffs
- Remove broken client-side parseDiffFromFile/normalize hack
- Update API docs in AGENTS.md

Closes the indentation bug reported by @zeroZshadow on PR #631.

For provenance purposes, this commit was AI assisted.
2026-04-30 17:23:55 -07:00
Michael Ramos fdc4bc4656 feat(plan,annotate): include source line numbers in exported feedback (#623)
Each annotation in exported plan/annotate feedback now carries source
line numbers — single-line blocks show `(line N)`, multi-line blocks
show `(lines N–M)`. Diff-context and global comments stay lineless.

When the document was produced by Turndown/Jina (HTML file or URL),
the export carries a caveat that line numbers refer to the converted
markdown rather than the original source.

Key implementation details:
- extractFrontmatter() returns contentStartLine so block line numbers
  account for stripped YAML headers
- blockEndLine() computes end lines per block type, with code blocks,
  directives, and alerts accounting for stripped wrapper lines
- isConvertedSource() helper in url-to-markdown.ts centralizes the
  source-type check across all entry points
- sourceConverted threaded from all CLIs through annotate servers
  to the /api/plan payload; isConverted added to /api/doc responses
- Per-document conversion tracking in useLinkedDoc ensures the correct
  flag is used when viewing linked HTML docs

Supersedes #621.

For provenance purposes, this commit was AI assisted.
2026-04-27 23:13:52 -07:00
Michael Ramos bb404f8d14 feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620)
* feat(shared): add isSameProject, PR stack types, and PR list provider

Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree,
PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject()
for owner/repo validation on PR switching. Adds fetchPRStack() and
fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs).

Includes 9 new tests for isSameProject covering GitHub, GitLab, and
cross-platform scenarios.

For provenance purposes, this commit was AI assisted.

* feat(shared): add GitHub PR stack tree walking and PR list fetching

Implements fetchGhPRStack() which walks up/down the PR stack via
GraphQL, resolving numbers and titles for each node in the chain.
Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef
helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support
by removing hostnameArgs from fetchGhPRList (--repo already handles
GHE). Filters jq "null" string from defaultBranch detection.

For provenance purposes, this commit was AI assisted.

* feat(shared): fetch defaultBranch for GitLab MRs

Queries the project's default_branch via glab API so getPRStackInfo
can detect stacked MRs on GitLab. Best-effort — caught errors fall
back to undefined.

For provenance purposes, this commit was AI assisted.

* feat(shared): add PR stack detection and full-stack diff module

New pr-stack module with:
- getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch
- getPRDiffScopeOptions(): generates layer/full-stack scope options
- runPRFullStackDiff(): computes diff from default branch to HEAD
- resolvePRFullStackBaseRef(): resolves origin/main or local main
- checkoutPRHead(): fetches and checks out a PR head in a worktree
- buildMinimalStackTree(): builds UI tree from stack info

Includes 13 tests covering ref resolution, branch fallbacks, and
GitLab ref formats.

For provenance purposes, this commit was AI assisted.

* feat(shared): add worktree pool for per-PR agent isolation

Creates a session-scoped pool of git worktrees — each PR visited
during a stacked review gets its own isolated checkout. Agents run
in their PR's worktree undisturbed by PR switches. Handles
deduplication of concurrent ensure() calls for the same PR.

Includes 11 tests covering caching, cross-repo restrictions, GitLab
ref formats, and cleanup.

For provenance purposes, this commit was AI assisted.

* feat(shared): add diffScope/prUrl to agent jobs, branch diff type

Adds prUrl and diffScope optional fields to AgentJobInfo so agent
findings carry the PR and scope context they were launched under.
Exports new pr-stack and worktree-pool modules from package.json.
Adds 'branch' to DefaultDiffType union for branch diff as default.

For provenance purposes, this commit was AI assisted.

* feat(ui): add PR annotation fields, Popover, and SearchableSelect

Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and
diffScope fields for stacked PR attribution. Adds shared Popover
wrapper around radix-ui. Adds SearchableSelect for filterable
dropdown lists (used by PR selector).

For provenance purposes, this commit was AI assisted.

* feat(ui): add branch diff as default option, new Git settings tab

Adds 'Branch' as a fourth default diff type option in both the
first-run dialog and settings panel. Moves the default diff type
setting from the Display tab to a new Git tab in review mode.
Updates config store validators to accept 'branch'.

For provenance purposes, this commit was AI assisted.

* feat(server): add prUrl/diffScope plumbing to agent jobs and prompts

Threads prUrl and diffScope through the agent job lifecycle so
findings carry the PR and scope they were generated under. Adds
full-stack prompt branch to codex-review and tour-review — when
in full-stack mode, the diff is inlined in the prompt instead of
telling the agent to run git diff. Re-exports isSameProject and
new PR provider functions from server/pr.ts.

For provenance purposes, this commit was AI assisted.

* feat(server): add stacked PR support to Bun review server

Adds PR switching, layer/full-stack scope toggling, PR list caching,
worktree pool integration, and multi-PR platform posting to the Bun
review server. Key additions:

- /api/pr-diff-scope: switch between layer and full-stack diffs
- /api/pr-list: cached PR list for the current repo
- /api/pr-switch: in-place navigation between PRs in a stack
- /api/pr-action: targetPrUrl support for multi-PR posting
- /api/file-content: full-stack branch for hunk expansion
- prSwitchCache/prStackTreeCache for session-scoped caching
- diffScope tagging on agent job completion
- Scope guard: returns 400 on full-stack diff failure instead of
  overwriting the working diff with empty content

For provenance purposes, this commit was AI assisted.

* feat(ai): pass cwd to Claude agent SDK for worktree support

Forwards the working directory to the Claude agent provider so
agents run in the correct worktree when reviewing stacked PRs.

For provenance purposes, this commit was AI assisted.

* feat(pi): add stacked PR support to Pi server (Bun parity)

Mirrors all stacked PR features from the Bun server:
- PR switching, scope toggling, PR list, multi-PR posting
- prSwitchCache/prStackTreeCache with initial PR seeding
- diffScope/prUrl plumbing in agent jobs
- Worktree pool creation and lifecycle
- Full-stack file-content resolution matching Bun's guard structure
- targetPrUrl support on /api/pr-action

Hoists worktreePool declaration to outer scope in plannotator-browser
to fix TS18004 scoping error. Updates vendor.sh for new shared modules.

For provenance purposes, this commit was AI assisted.

* feat(hook): create worktree pool for PR review sessions

Creates a worktree pool when opening a PR review with --local,
seeding it with the initial PR's checkout. Integrates pool cleanup
into server shutdown. Passes the pool to startReviewServer for
agent isolation during PR switching.

For provenance purposes, this commit was AI assisted.

* feat(review-editor): add hooks for PR stack, context, and annotations

- useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope
  onto annotations, only when viewing a stacked PR
- usePRStack: handles scope selection and PR switching with loading state
- usePRContext: adds URL-change detection to prevent stale-fetch race
  when switching PRs (discards in-flight responses for previous PR)

For provenance purposes, this commit was AI assisted.

* feat(review-editor): add stacked PR UI components

- PRSelector: searchable dropdown for switching between PRs in a repo
- PRSwitchOverlay: loading animation during PR switch
- StackedPRLabel: stack tree popover with scope selector and PR navigation
- ReviewSubmissionDialog: multi-PR submission dialog with per-target
  status, orphaned findings section with copy-as-markdown, and
  partial failure retry

For provenance purposes, this commit was AI assisted.

* feat(review-editor): multi-PR export with heading hierarchy

Updates exportReviewFeedback for multi-PR sessions:
- Groups annotations by prUrl, then by file within each PR
- Uses proper heading hierarchy (## for files, ### for annotations
  in multi-PR mode)
- Detects single-PR mismatch (annotations from a different PR than
  the current view) and uses annotation-level PR context
- Adds diffScope labels per PR group when present

Includes 5 new tests: multi-PR headings, single-PR mismatch,
diffScope labels, and non-stacked annotation handling.

For provenance purposes, this commit was AI assisted.

* feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents

- ReviewSidebar: groups annotations by PR in multi-PR sessions,
  shows PR headers with annotation counts
- ReviewDiffPanel: filters annotations by prUrl and diffScope so
  only matching annotations appear in the diff gutter
- ReviewStateContext: adds prDiffScope to shared review state
- ReviewAgentJobDetailPanel: shows diffScope in job detail
- PRSummaryTab: shows stack info in PR summary
- index.css: PR switch shimmer and overlay animations

For provenance purposes, this commit was AI assisted.

* feat(review-editor): wire stacked PR into main review app

Integrates all stacked PR features into the review editor:
- PR stack state management (prStackInfo, prStackTree, prDiffScope)
- applyPRResponse: shared handler for PR switch and scope toggle,
  preserves active file index on scope changes
- Multi-PR platform posting via Promise.allSettled with parallel
  requests, partial failure retry, and per-target status tracking
- ReviewSubmissionDialog replaces inline dialog JSX
- useAnnotationFactory stamps PR context onto annotations
- keepalive on /api/feedback to survive tab closure
- Proper try/catch/finally on handlePlatformAction

For provenance purposes, this commit was AI assisted.

* docs: add stacked PR review documentation

Updates AGENTS.md, code-review command docs, and AI code review
guide with stacked PR review capabilities.

For provenance purposes, this commit was AI assisted.

* fix(server): stamp prNumber/prTitle/prRepo on agent findings

Agent annotations only had prUrl and diffScope, missing prNumber,
prTitle, and prRepo. When agent findings were the only annotations
for a PR target in the submission dialog, the target rendered as
#0 with no title. Now resolves full PR context from prSwitchCache
at job completion and stamps all five fields. Both Bun and Pi.

For provenance purposes, this commit was AI assisted.

* feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff"

Consolidates two confusing committed-diff options into one:
- Settings/first-run: "Committed" — "Everything you've committed on this branch"
- Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff")

Uses merge-base under the hood (matches GitHub PR behavior). Removes
the two-dot branch diff from the UI — it stays in the runtime DiffType
union for backwards compat. Old "branch" values in config/cookies are
silently upgraded to merge-base.

Git settings tab now uses radio cards with descriptions instead of
a cramped segmented control. First-run dialog descriptions rewritten
in plain language — no git commands.

For provenance purposes, this commit was AI assisted.

* fix(review-editor): rename client-side "PR Diff" labels to "Committed changes"

DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base
when the base picker is present. exportFeedback.ts also used "PR Diff"
in export labels. Both now say "Committed changes" to match the
server-side label and settings UI.

For provenance purposes, this commit was AI assisted.

* fix(server): discover stack UI for root PRs targeting the default branch

Root PRs (baseBranch === defaultBranch) were excluded from stack
detection because getPRStackInfo returned null. Now the server
always fetches the stack tree in PR mode. If the tree reveals
descendant PRs, prStackInfo is retroactively set with source
"tree-discovered", enabling the stack UI, scope selector, and
PR navigation from the root of a stack.

Both Bun and Pi servers updated. Adds "tree-discovered" to the
PRStackInfo source union.

For provenance purposes, this commit was AI assisted.

* fix(review-editor): derive diff scope from annotations, not UI state

The export function now reads diffScope from annotations instead of
the prReviewScope parameter. Fixes two issues:

1. Agent job "Copy All" showed the wrong scope when the user switched
   between layer/full-stack after launching the agent
2. Mixed-scope annotations produced a confusing "layer, full-stack"
   comma-joined label instead of grouping by scope

Extracts renderScopedGroups helper for scope-aware grouping — used
by both single-PR and multi-PR export paths. When annotations share
one scope, it appears in the header. When mixed, annotations are
grouped under ## Layer / ## Full-stack headings.

Includes 4 new tests: uniform scope derivation, mixed scope grouping,
single scope header, and prReviewScope override prevention.

For provenance purposes, this commit was AI assisted.

* fix(server): add tree-discovered stack fallback to pr-switch handler

The initial-load path upgrades prStackInfo for root PRs when the
stack tree reveals descendants, but the pr-switch handler was missing
this logic. The server now sends correct prStackInfo after switching
to a root-of-stack PR. Both Bun and Pi.

Also removes stale prReviewScope dependency from agent job panel's
copyAllText useMemo.

For provenance purposes, this commit was AI assisted.

* fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs

Extracts the tree-discovered stack fallback into resolveStackInfo()
in pr-stack.ts — eliminates 4 copies of the same logic across Bun
startup, Bun pr-switch, Pi startup, and Pi pr-switch.

Fixes StackedPRLabel showing on every PR: the check now counts
non-default-branch nodes (> 1) instead of all nodes (> 1). Without
this, every PR showed a "Stack (1 PR)" popover because the tree
always has at least [defaultBranch, currentPR].

For provenance purposes, this commit was AI assisted.

* fix(review-editor): don't re-open already-succeeded PR tabs on retry

On partial failure retry, openUrls was pre-seeded with URLs from
previously succeeded targets, causing those PR pages to re-open
in the browser alongside newly succeeded ones. Now starts empty —
only URLs from the current attempt are opened.

For provenance purposes, this commit was AI assisted.

* refactor(review-editor): extract PR session state into usePRSession hook

Consolidates 5 independent useState calls (prMetadata, prStackInfo,
prStackTree, prDiffScope, prDiffScopeOptions) into a single
usePRSession hook with atomic updatePRSession callback.

Replaces two identical 5-line setter blocks (initial load and
applyPRResponse) with single updatePRSession calls. All ~60 consumer
sites unchanged — same variable names via destructuring.

For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
Michael Ramos d102c5f709 feat(annotate): add --gate, --json, and --silent-approve flags (#570)
Adds an opt-in review gate flow to annotation mode with three composable flags:

- `--gate`: 3-way UX (Approve / Send Annotations / Close)
- `--json`: structured decision output (`{"decision":"approved|annotated|dismissed"}`)
- `--silent-approve`: suppresses plaintext approve marker for naive hooks

Includes shared arg parser, @-reference handling, updated templates across all
harnesses (Claude Code, Copilot, Gemini, OpenCode, Pi), and full documentation.

Closes #570

For provenance purposes, this commit was AI assisted.
2026-04-23 17:40:40 -07:00
Michael Ramos 68972aa6a6 feat(review): custom base branch for code review (#599) (#602)
Adds a searchable base-branch picker to the code review UI so reviewers
can compare against any branch, not just the auto-detected default.

Key changes:
- Base-branch picker (Radix Popover + search, local/remote groups)
- Diff-type picker (Radix DropdownMenu + info tooltips)
- Worktree picker (Radix Popover + search)
- getDefaultBranch prefers upstream ref (origin/main) for fresher diffs
- listBranches populates GitContext.availableBranches
- resolveBaseBranch trusts caller verbatim (no silent rewrites)
- --end-of-options hardens git argv against flag-injection via base refs
- Branch diff / PR Diff always available (removed hide-on-default guard)
- merge-base agent prompt runs git itself instead of inlining the patch
- Agent jobs snapshot diff context at launch for honest "Copy All"
- Feedback export includes diff mode + base header for agent context
- Round-trip base through /api/diff so refresh preserves the selection
- selectedBase / committedBase split prevents file-content race
- Optimistic picker reverts on switch failure
- DiffViewer remounts on mode switch to invalidate stale file content
- Worktree switch preserves active diff mode
- Pi parity: initialBase, currentBase, agent diffContext, vendor.sh
- Tooltip wide mode, TooltipProvider mounted, keyboard/touch fixes
- GPT-5.5 added to Codex model picker
- CLAUDE.md API table updated

Closes #599

For provenance purposes, this PR was AI assisted.
2026-04-23 16:49:25 -07:00
Michael Ramos ea758f9978 Add configurable paste service URL for self-hosting (#582)
* Wire PLANNOTATOR_PASTE_URL through opencode/pi servers and Landing demo link

OpenCode plugin only read PLANNOTATOR_SHARE_URL; add a getPasteApiUrl helper
and thread it into plan/annotate/archive server starts. Pi extension's
serverReview gains the same shareBaseUrl/pasteApiUrl env-var pair already
used by serverPlan/serverAnnotate. Landing.tsx now accepts a shareBaseUrl
prop for self-hosters' demo link. Paste-service CORS defaults grow a
comment clarifying that self-hosters must override ALLOWED_ORIGINS.

* Embed custom paste origin in short URL fragment

When PLANNOTATOR_PASTE_URL is set to a non-default paste service, the
generated short link now includes a base64url-encoded paste param in the
fragment (#key=...&paste=...). The share portal and importFromShareUrl
extract it on load so they can fetch from the right paste backend without
needing a server — fixing broken short links for self-hosters who use a
custom paste service but keep the hosted share portal.

Backward compatible: links without a paste param continue to use the
default or server-provided paste API URL as before.

For provenance purposes, this commit was AI assisted.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-17 22:21:49 -07:00
Michael Ramos b780739291 feat(annotate): support HTML files and URL annotation (#545)
* fix(annotate): sanitize dangerous link protocols in markdown renderer

Block javascript:, data:, and vbscript: URLs in InlineMarkdown link
rendering. Links with dangerous protocols render as plain text instead
of clickable anchors. Uses a blocklist approach so existing links with
custom protocols (obsidian://, vscode://, Windows C:\ paths) continue
to work.

For provenance purposes, this commit was AI assisted.

* feat(annotate): add HTML-to-markdown and URL-to-markdown utilities

- html-to-markdown.ts: Turndown wrapper with GFM table rule, strips
  script/style/noscript tags
- url-to-markdown.ts: Jina Reader (free, returns markdown) with
  fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for
  local/private URLs (localhost, 192.168.*, 10.*, etc.)
- config.ts: add jina setting and resolveUseJina() with priority chain
  --no-jina flag > PLANNOTATOR_JINA env > config.json > default true

For provenance purposes, this commit was AI assisted.

* feat(annotate): support HTML files and URLs in annotate command

Extend the annotate subcommand to accept .html/.htm local files
(converted via Turndown) and https:// URLs (fetched via Jina Reader
with fetch+Turndown fallback). URL content is fetched terminal-side
before opening the browser.

Add --no-jina global flag to disable Jina Reader per-invocation.
Add 10MB file size guard for local HTML files.

For provenance purposes, this commit was AI assisted.

* feat(annotate): HTML files in folder browser and on-demand conversion

- Widen file browser glob to include .html/.htm alongside markdown
- handleDoc converts HTML files via Turndown on demand when selected
- hasMarkdownFiles accepts optional extensions param for folder validation
- Add sourceInfo field to annotate server API response
- Add _site/, public/, out/, .docusaurus/, .jekyll-cache/,
  storybook-static/ to FILE_BROWSER_EXCLUDED

For provenance purposes, this commit was AI assisted.

* feat(annotate): source attribution badge for HTML/URL annotations

Show a subtle badge in DocBadges displaying the URL hostname or HTML
filename for converted content. Thread sourceInfo from API response
through App → Viewer → DocBadges.

Also update Pi extension to accept HTML-only folders in annotate mode.

For provenance purposes, this commit was AI assisted.

* test: update CLI help text assertion for HTML/URL annotate support

For provenance purposes, this commit was AI assisted.

* fix(annotate): address PR review findings

Security:
- Add project-root containment check for HTML files in /api/doc handler
  using exported isWithinProjectRoot() from resolve-file.ts
- Blocks path traversal via absolute paths or ../ escapes

isLocalUrl fixes:
- Add bracketed IPv6 loopback [::1] detection
- Replace hostname.startsWith('10.') with proper IPv4 regex to avoid
  matching public hostnames like 10.example.com

Revert Pi extension change:
- Pi server doesn't implement HTML file browsing or conversion yet
- Keep Pi folder validation markdown-only until both implementations
  are updated per CLAUDE.md guidelines

Cleanup:
- Remove dead el.children || el.childNodes fallback in table rule
- Extract hostnameOrFallback() helper to @plannotator/shared/project
  replacing duplicated try/catch IIFEs in DocBadges and index.ts

For provenance purposes, this commit was AI assisted.

* feat(annotate): Pi extension HTML annotation parity

Bring the Pi extension to full parity with the Bun server for HTML
annotation support:

- Vendor html-to-markdown and url-to-markdown via vendor.sh
- walkMarkdownFiles now scans .html/.htm alongside markdown
- handleDocRequest converts HTML files on-demand via Turndown with
  isWithinProjectRoot containment check
- serverAnnotate includes sourceInfo in /api/plan response
- index.ts supports URL detection (Jina Reader + fallback), HTML file
  detection with Turndown conversion, folder HTML validation, and 10MB
  file size guard
- openMarkdownAnnotation accepts and threads sourceInfo
- Add turndown as a Pi extension dependency

For provenance purposes, this commit was AI assisted.

* fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML

- Add extensions param to walkMarkdownFiles (default: HTML-inclusive)
- Obsidian callers pass /\.mdx?$/i to match Bun server behavior
- Add try/catch around HTML file reads in handleDocRequest

For provenance purposes, this commit was AI assisted.

* fix(annotate): address second review — base-block traversal, metadata IP, dead code

Security:
- Add isWithinProjectRoot check to the base-relative block for HTML
  files in both Bun and Pi /api/doc handlers. Previously HTML files
  served via the base query param bypassed the containment guard.
- Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl
  private IP ranges

Cleanup:
- Remove dead hostname === "[::1]" check (WHATWG URL parser strips
  brackets; hostname === "::1" already handles it)
- Remove dead parent?.childNodes fallback in table cell() function

For provenance purposes, this commit was AI assisted.

* refactor(annotate): replace custom table rules with turndown-plugin-gfm

Drop ~60 lines of hand-rolled GFM table conversion that had a bug
(tables without explicit <thead> produced invalid GFM). Use the
official turndown-plugin-gfm plugin (24KB) which correctly handles
all table patterns plus adds strikethrough and task list support.

For provenance purposes, this commit was AI assisted.

* fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown

Expand the backslash escape regex to cover all CommonMark-defined
escapable characters (. ) - # > + | { } &), not just the subset
the parser uses for formatting. Fixes literal backslashes appearing
in rendered output for Turndown-escaped content like "1\." → "1.".

For provenance purposes, this commit was AI assisted.

* fix(annotate): prevent SSRF via redirect to private/local URLs

Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown
and validate each redirect hop against isLocalUrl. Blocks attacks where
an external URL redirects to cloud metadata endpoints (169.254.169.254)
or other private IPs. Limits redirect chain to 10 hops.

For provenance purposes, this commit was AI assisted.

* chore: update lockfile for turndown-plugin-gfm in Pi extension

bun install needed to resolve turndown-plugin-gfm in the Pi extension
workspace after adding it to apps/pi-extension/package.json.

For provenance purposes, this commit was AI assisted.

* fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors

Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the
actively maintained Joplin fork (2025, v1.0.64, 16KB).

Fix TypeScript errors that broke CI:
- Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import
- Restructure fetchViaTurndown redirect loop to avoid uninitialized
  variable — first fetch before loop, loop only for redirects

For provenance purposes, this commit was AI assisted.

* fix(annotate): use proper declarations.d.ts instead of ts-expect-error

Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed
function signatures, remove the ts-expect-error suppression.

For provenance purposes, this commit was AI assisted.

* fix: explicitly include declarations.d.ts in shared tsconfig

CI's tsc wasn't finding the ambient module declaration with implicit
include. Add explicit include to ensure declarations.d.ts is always
picked up regardless of environment.

For provenance purposes, this commit was AI assisted.

* fix: use ts-expect-error for @joplin/turndown-plugin-gfm types

CI's tsc does not pick up ambient declarations.d.ts files despite
local tsc finding them — likely a module resolution discrepancy
between environments. Revert to @ts-expect-error which passes in
both CI and local typecheck.

For provenance purposes, this commit was AI assisted.

* fix(annotate): body size limit for URL fetches, redirect error, file: protocol

- Add 10MB body size limit to both Jina and fetch+Turndown URL paths,
  matching the local HTML file guard. Streams response body and aborts
  if limit exceeded.
- Distinguish "Too many redirects" from a genuine 3xx response after
  redirect loop exhaustion.
- Add file: to the dangerous protocol blocklist in sanitizeLinkUrl.

For provenance purposes, this commit was AI assisted.

* fix(annotate): HTML folder outside cwd, HTML linked doc navigation

- Remove containment check from base-relative block for HTML files in
  both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML
  files in annotated folders outside cwd are served correctly.
  Standalone block (no base) retains its cwd check as fallback.
- Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked
  documents. Clicking [Next](next.html) in a converted page now opens
  it via /api/doc with Turndown conversion instead of a new browser tab.

For provenance purposes, this commit was AI assisted.

* fix(annotate): full loopback range, drain redirect bodies, document env vars

- Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8
  range so all loopback addresses skip Jina Reader
- Cancel redirect response body before re-fetching to avoid leaking
  TCP connections back to the pool
- Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table

For provenance purposes, this commit was AI assisted.

* fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments

- Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves
  brackets for IPv6 (verified: Bun and Node both return "[::1]").
  Add comment explaining the empirical verification so future reviewers
  don't re-flag.
- Fix readBodyWithLimit null-body fallback to still enforce the 10MB
  limit via text length check instead of silently falling through.
- Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table
  (CLAUDE.md is a symlink to AGENTS.md).
- Add comments to base-relative blocks in both Bun and Pi handleDoc
  explaining the intentional lack of containment check (matches
  pre-existing markdown behavior, base is set server-side).

For provenance purposes, this commit was AI assisted.

* fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl

Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges:
- ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1])
- fe80: (link-local)
- fc00::/7 (unique-local, covers fc00:: through fdff::)

Closes the redirect-SSRF bypass where a public URL redirects to a
private address expressed as IPv4-mapped IPv6, e.g.
http://[::ffff:169.254.169.254]/latest/meta-data/

For provenance purposes, this commit was AI assisted.

* fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow

- Expand isLocalUrl comment with full empirical verification table
  showing actual hostname getter output for every IPv6 format in both
  Bun and Node — prevents false-positive review findings about brackets
- Add sourceInfo to /api/plan response type in App.tsx for type safety
- Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder
  input types

For provenance purposes, this commit was AI assisted.

* fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo

- Add ( to backslash escape regex alongside existing ) — Turndown
  emits \( in link-adjacent contexts
- Cancel response body before throwing on !res.ok in both fetchViaJina
  and fetchViaTurndown error paths (redirect loop already did this)
- Document sourceInfo field in AGENTS.md annotate server API table

For provenance purposes, this commit was AI assisted.

* fix(annotate): skip base injection for URL annotations, body cleanup

- Skip dirname(filePath) base injection when filePath is a URL in both
  Bun and Pi annotate servers. dirname on a URL string produces a
  nonsensical filesystem path, causing linked doc clicks to 404.
  URL annotations now let links open normally instead.
- Cancel response body before throwing on content-type mismatch and
  content-length overflow in fetchViaTurndown/readBodyWithLimit.
- Fix double parseInt in readBodyWithLimit content-length check.
- Correct AGENTS.md flow diagram: OpenCode not yet implemented for
  HTML/URL annotation.

For provenance purposes, this commit was AI assisted.

* feat(annotate): OpenCode HTML file and URL annotation support

Add URL detection (Jina Reader + fallback), HTML file detection with
Turndown conversion, 10MB file size guard, and sourceInfo threading
to OpenCode's handleAnnotateCommand. Uses the same shared utilities
as the Bun CLI and Pi extension.

OpenCode uses the Bun server directly (startAnnotateServer from
@plannotator/server/annotate), so no server-side changes needed —
only the command handler routing was missing.

Note: folder annotation mode is not added (OpenCode didn't have it
before this PR for markdown either — separate scope).

For provenance purposes, this commit was AI assisted.

* chore(annotate): update slash command description, align fetch log messages

- OpenCode plannotator-annotate.md description now mentions HTML/URL
- Align fetch progress messages across all three clients: all now show
  "(via Jina Reader)" or "(via fetch+Turndown)" consistently

For provenance purposes, this commit was AI assisted.

* fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup

- URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown.
  Content is already markdown. Removes text/plain from fetchViaTurndown
  content-type whitelist since .md URLs are now short-circuited.
- Wikilink regex widened to preserve .html/.htm targets instead of
  appending .md (e.g. [[page.html]] no longer becomes page.html.md)
- Remove redundant existsSync before statSync in OpenCode handler

For provenance purposes, this commit was AI assisted.

* test(annotate): add htmlToMarkdown conversion tests

Tests cover the core conversion utility that all three clients depend on:
- Basic HTML → markdown (headings, paragraphs, links, code blocks)
- Tables with and without <thead> (the GFM plugin bug that was caught)
- Script/style/noscript stripping
- Strikethrough (GFM)
- Empty HTML handling
- Dangerous links preserved (sanitization is in the renderer, not here)

For provenance purposes, this commit was AI assisted.

* fix(annotate): check content-type before treating .md URLs as raw markdown

URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md)
may return HTML instead of raw markdown. fetchRawText now checks the
response content-type — if the server returns HTML, returns null so
the caller falls through to Jina/Turndown for proper conversion.

For provenance purposes, this commit was AI assisted.

* fix(annotate): add SSRF redirect protection to fetchRawText

fetchRawText (for .md/.mdx URLs) was using default redirect: "follow"
with no isLocalUrl validation on redirect hops — a .md URL redirecting
to 169.254.169.254 would be followed and credentials returned as
"markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks,
matching fetchViaTurndown's SSRF protection.

For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
Michael Ramos 0287b96b63 feat(review): configurable default diff type (#531)
feat(review): configurable default diff type with first-run setup

Add `defaultDiffType` as a persistent user setting (cookie + config.json) with 'unstaged' as the default, matching `git diff` semantics. A first-run setup dialog prompts users to choose their preferred default on first review session. The setting is also available in Settings > Display.

Entry points (hook, opencode, pi-extension) read the config via `resolveDefaultDiffType()` instead of hardcoding. The setup dialog applies the chosen diff type to the active review immediately. P4 users are excluded from the Git-specific dialog.

Based on the community contribution in #521 by Hendrik Richert.

Co-authored-by: Hendrik Richert <hendrik.richert@swisscom.com>
2026-04-10 14:54:21 -07:00
Vladyslav Hrabovyi 3b1b3317ae feat(review,annotate): add Close button to exit sessions without feedback (#523)
Adds a Close button to review and annotation sessions so users can exit
cleanly without sending feedback or killing the agent. Works across all
agent origins and includes a warning dialog when annotations would be lost.

Fixes #522

Co-authored-by: gwynnnplaine <vladyslav.hrabovyii@gmail.com>
2026-04-09 19:22:01 -07:00
Michael Ramos 181d2a10d5 fix(pi): full PR review parity with Bun server (#503)
## Summary

Full Pi PR review parity with Bun server, plus shared fixes and UI improvements.

### Pi PR Review (new)
- Parse PR/MR URLs, authenticate, fetch metadata and diff
- Create local worktree (same-repo) or shallow clone (cross-repo) for agent file access
- Full server parity: all 27 feature areas audited and aligned

### Shared Fixes (Bun + Pi)
- parseRemoteUrl: GitLab subgroup support, SSH+port, HTTPS non-standard port
- Cross-repo clone: --hostname replaced with GH_HOST/GITLAB_HOST env vars
- Cross-repo clone: shallow fetch depth 50 → 200
- Git Add button disabled in PR review mode (client-side)
- DiffViewer: eliminate dark flash on file switch (sync theme init)

### UI
- Resolved/Outdated toggle filters in PR comments tab

For provenance purposes, this commit was AI assisted.
2026-04-06 18:06:38 -07:00
Stefan Kaufmann 6dabcc1dbb Add pi signal support - so other extensions can invoke the plannotator (#468)
* add pi signal support

* remove PLAN

* fix: pass cwd through to getGitContext in openCodeReview

getGitContext() was called without the custom cwd override, so the
initial diff was correct but live diff switching, file content, git-add,
and branch labels in the review UI would resolve against process.cwd()
instead of the caller-provided cwd.

For provenance purposes, this commit was AI assisted.

---------

Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-04-02 10:49:05 -07:00