2026-01-12 19:36:09 -08:00
|
|
|
/**
|
|
|
|
|
* Code Review Server
|
|
|
|
|
*
|
|
|
|
|
* Provides a server implementation for code review with git diff rendering.
|
|
|
|
|
* Follows the same patterns as the plan server.
|
|
|
|
|
*
|
|
|
|
|
* Environment variables:
|
|
|
|
|
* PLANNOTATOR_REMOTE - Set to "1" or "true" for remote/devcontainer mode
|
|
|
|
|
* PLANNOTATOR_PORT - Fixed port to use (default: random locally, 19432 for remote)
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import { isRemoteSession, getServerPort } from "./remote";
|
2026-03-28 16:37:56 -07:00
|
|
|
import type { Origin } from "@plannotator/shared/agents";
|
2026-03-09 07:31:17 -07:00
|
|
|
import { type DiffType, type GitContext, runGitDiff, getFileContentsForDiff, gitAddFile, gitResetFile, parseWorktreeDiffType, validateFilePath } from "./git";
|
2026-01-28 10:29:52 -08:00
|
|
|
import { getRepoInfo } from "./repo";
|
2026-03-16 15:45:00 +01:00
|
|
|
import { handleImage, handleUpload, handleAgents, handleServerReady, handleDraftSave, handleDraftLoad, handleDraftDelete, handleFavicon, type OpencodeClient } from "./shared-handlers";
|
2026-03-04 10:12:58 -08:00
|
|
|
import { contentHash, deleteDraft } from "./draft";
|
feat: VS Code editor annotations + theme integration (#239)
* feat: add shared EditorAnnotation type
Single source of truth for the editor annotation interface,
imported by both @plannotator/server and @plannotator/ui.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation server endpoints
In-memory store with POST/GET/DELETE endpoints for editor annotations.
The array lives in the handler closure and dies with the server session.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation UI — polling hook, card, panel, and export
- useEditorAnnotations hook with auto-disable polling (500ms interval)
- EditorAnnotationCard with file path, code preview, and comment
- AnnotationPanel conditionally renders editor annotation section
- exportEditorAnnotations formats annotations for Claude feedback
- App.tsx wires hook, includes in output memo and send feedback gate
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code extension editor annotation command
Cmd+Shift+. or right-click to capture selected text as an annotation.
POSTs through the cookie proxy to the plannotator server. Adds amber
left-border decorations on annotated lines, cleared on panel close.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: inline comment threads, lightbulb menu, and stronger decorations
Replace showInputBox with VS Code CommentController for inline annotation
threads anchored to selected code. Add CodeActionProvider for lightbulb
discoverability. Stronger decoration styling with gutter icon.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code theme integration for webview
Bridge VS Code CSS variables to Plannotator's CSS variable system via
postMessage between wrapper page and proxied iframe. Automatically adopts
the active VS Code color theme (dark/light/custom) without touching any
UI components or CSS files.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: gate editor annotation polling behind VS Code detection
Only poll /api/editor-annotations when running inside a VS Code webview
(window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have
zero network cost from the editor annotations feature. Also fixes poll
interval from 500ms to 2000ms.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: faster polling, prevent unnecessary re-renders, unify HTTP helper
- Poll interval 2s → 500ms for snappier annotation pickup
- Shallow equality check on annotation IDs prevents React re-renders
when poll data is unchanged
- Merge postToProxy/deleteFromProxy into single requestProxy function
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotations support in code review
Wire existing editor annotation infrastructure into the review flow
so VS Code users can annotate files outside the diff during code review.
- Add editor annotation endpoints to review server (same 3-line pattern)
- Call useEditorAnnotations hook in review App.tsx
- Display editor annotations in ReviewPanel with "Editor" divider
- Include editor annotations in feedback export and gating logic
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
|
|
|
import { createEditorAnnotationHandler } from "./editor-annotations";
|
feat: external annotations API with real-time SSE (#400)
Adds a general-purpose External Annotations API that allows external programs (linters, AI tools, security scanners) to push annotations into a live Plannotator session via HTTP, with real-time delivery over SSE.
## What's included
- **Shared core** (`packages/shared/external-annotation.ts`): types, in-memory store, input validation, SSE serialization
- **Server handlers**: Bun + Pi implementations with full CRUD (GET/POST/PATCH/DELETE) + SSE streaming
- **Client hook** (`useExternalAnnotations`): EventSource with polling fallback, optimistic updates
- **Editor integration**: two-array state model (local + external), content-aware dedup, ID-based routing
- **Persistence**: source field preserved through share URLs and crash-recovery drafts
- **Docs**: new Integrations category with API overview page, updated API reference
## API surface
All three servers (plan, review, annotate) expose:
- `GET /api/external-annotations/stream` - SSE stream
- `GET /api/external-annotations` - JSON snapshot (polling fallback)
- `POST /api/external-annotations` - Add annotations (single or batch)
- `PATCH /api/external-annotations?id=` - Update fields
- `DELETE /api/external-annotations` - Remove by id, source, or clear all
For provenance purposes, this commit was AI assisted.
2026-03-29 17:18:31 -07:00
|
|
|
import { createExternalAnnotationHandler } from "./external-annotations";
|
2026-03-26 11:54:22 -07:00
|
|
|
import { saveConfig, detectGitUser, getServerConfig } from "./config";
|
2026-03-25 21:33:33 +01:00
|
|
|
import { type PRMetadata, type PRReviewFileComment, fetchPRFileContent, fetchPRContext, submitPRReview, fetchPRViewedFiles, markPRFilesViewed, getPRUser, prRefFromMetadata, getDisplayRepo, getMRLabel, getMRNumberLabel } from "./pr";
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
import { createAIEndpoints, ProviderRegistry, SessionManager, createProvider, type AIEndpoints, type PiSDKConfig } from "@plannotator/ai";
|
2026-03-25 15:06:29 -03:00
|
|
|
import { isWSL } from "./browser";
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
// Re-export utilities
|
|
|
|
|
export { isRemoteSession, getServerPort } from "./remote";
|
|
|
|
|
export { openBrowser } from "./browser";
|
2026-03-08 16:15:14 -07:00
|
|
|
export { type DiffType, type DiffOption, type GitContext, type WorktreeInfo } from "./git";
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
export { type PRMetadata } from "./pr";
|
2026-03-03 23:17:16 -08:00
|
|
|
export { handleServerReady as handleReviewServerReady } from "./shared-handlers";
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
// --- Types ---
|
|
|
|
|
|
|
|
|
|
export interface ReviewServerOptions {
|
|
|
|
|
/** Raw git diff patch string */
|
|
|
|
|
rawPatch: string;
|
|
|
|
|
/** Git ref used for the diff (e.g., "HEAD", "main..HEAD", "--staged") */
|
|
|
|
|
gitRef: string;
|
2026-03-02 15:26:07 +09:00
|
|
|
/** Error message if git diff failed */
|
|
|
|
|
error?: string;
|
2026-01-12 19:36:09 -08:00
|
|
|
/** HTML content to serve for the UI */
|
|
|
|
|
htmlContent: string;
|
|
|
|
|
/** Origin identifier for UI customization */
|
2026-03-28 16:37:56 -07:00
|
|
|
origin?: Origin;
|
2026-01-12 19:36:09 -08:00
|
|
|
/** Current diff type being displayed */
|
|
|
|
|
diffType?: DiffType;
|
|
|
|
|
/** Git context with branch info and available diff options */
|
|
|
|
|
gitContext?: GitContext;
|
2026-01-14 13:12:37 -08:00
|
|
|
/** Whether URL sharing is enabled (default: true) */
|
|
|
|
|
sharingEnabled?: boolean;
|
2026-02-12 15:07:43 -08:00
|
|
|
/** Custom base URL for share links (default: https://share.plannotator.ai) */
|
|
|
|
|
shareBaseUrl?: string;
|
2026-01-12 19:36:09 -08:00
|
|
|
/** Called when server starts with the URL, remote status, and port */
|
|
|
|
|
onReady?: (url: string, isRemote: boolean, port: number) => void;
|
2026-01-19 11:07:22 -08:00
|
|
|
/** OpenCode client for querying available agents (OpenCode only) */
|
2026-03-03 23:17:16 -08:00
|
|
|
opencodeClient?: OpencodeClient;
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
/** PR metadata when reviewing a pull request (PR mode) */
|
|
|
|
|
prMetadata?: PRMetadata;
|
2026-01-12 19:36:09 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface ReviewServerResult {
|
|
|
|
|
/** The port the server is running on */
|
|
|
|
|
port: number;
|
|
|
|
|
/** The full URL to access the server */
|
|
|
|
|
url: string;
|
|
|
|
|
/** Whether running in remote mode */
|
|
|
|
|
isRemote: boolean;
|
2026-03-14 17:58:57 -07:00
|
|
|
/** Wait for user review decision */
|
2026-01-12 19:36:09 -08:00
|
|
|
waitForDecision: () => Promise<{
|
2026-03-14 17:58:57 -07:00
|
|
|
approved: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: string;
|
|
|
|
|
annotations: unknown[];
|
|
|
|
|
agentSwitch?: string;
|
|
|
|
|
}>;
|
|
|
|
|
/** Stop the server */
|
|
|
|
|
stop: () => void;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- Server Implementation ---
|
|
|
|
|
|
|
|
|
|
const MAX_RETRIES = 5;
|
|
|
|
|
const RETRY_DELAY_MS = 500;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Start the Code Review server
|
|
|
|
|
*
|
|
|
|
|
* Handles:
|
|
|
|
|
* - Remote detection and port configuration
|
|
|
|
|
* - API routes (/api/diff, /api/feedback)
|
|
|
|
|
* - Port conflict retries
|
|
|
|
|
*/
|
|
|
|
|
export async function startReviewServer(
|
|
|
|
|
options: ReviewServerOptions
|
|
|
|
|
): Promise<ReviewServerResult> {
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
const { htmlContent, origin, gitContext, sharingEnabled = true, shareBaseUrl, onReady, prMetadata } = options;
|
2026-01-12 19:36:09 -08:00
|
|
|
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
const isPRMode = !!prMetadata;
|
2026-03-04 10:12:58 -08:00
|
|
|
const draftKey = contentHash(options.rawPatch);
|
feat: VS Code editor annotations + theme integration (#239)
* feat: add shared EditorAnnotation type
Single source of truth for the editor annotation interface,
imported by both @plannotator/server and @plannotator/ui.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation server endpoints
In-memory store with POST/GET/DELETE endpoints for editor annotations.
The array lives in the handler closure and dies with the server session.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation UI — polling hook, card, panel, and export
- useEditorAnnotations hook with auto-disable polling (500ms interval)
- EditorAnnotationCard with file path, code preview, and comment
- AnnotationPanel conditionally renders editor annotation section
- exportEditorAnnotations formats annotations for Claude feedback
- App.tsx wires hook, includes in output memo and send feedback gate
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code extension editor annotation command
Cmd+Shift+. or right-click to capture selected text as an annotation.
POSTs through the cookie proxy to the plannotator server. Adds amber
left-border decorations on annotated lines, cleared on panel close.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: inline comment threads, lightbulb menu, and stronger decorations
Replace showInputBox with VS Code CommentController for inline annotation
threads anchored to selected code. Add CodeActionProvider for lightbulb
discoverability. Stronger decoration styling with gutter icon.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code theme integration for webview
Bridge VS Code CSS variables to Plannotator's CSS variable system via
postMessage between wrapper page and proxied iframe. Automatically adopts
the active VS Code color theme (dark/light/custom) without touching any
UI components or CSS files.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: gate editor annotation polling behind VS Code detection
Only poll /api/editor-annotations when running inside a VS Code webview
(window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have
zero network cost from the editor annotations feature. Also fixes poll
interval from 500ms to 2000ms.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: faster polling, prevent unnecessary re-renders, unify HTTP helper
- Poll interval 2s → 500ms for snappier annotation pickup
- Shallow equality check on annotation IDs prevents React re-renders
when poll data is unchanged
- Merge postToProxy/deleteFromProxy into single requestProxy function
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotations support in code review
Wire existing editor annotation infrastructure into the review flow
so VS Code users can annotate files outside the diff during code review.
- Add editor annotation endpoints to review server (same 3-line pattern)
- Call useEditorAnnotations hook in review App.tsx
- Display editor annotations in ReviewPanel with "Editor" divider
- Include editor annotations in feedback export and gating logic
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
|
|
|
const editorAnnotations = createEditorAnnotationHandler();
|
feat: external annotations API with real-time SSE (#400)
Adds a general-purpose External Annotations API that allows external programs (linters, AI tools, security scanners) to push annotations into a live Plannotator session via HTTP, with real-time delivery over SSE.
## What's included
- **Shared core** (`packages/shared/external-annotation.ts`): types, in-memory store, input validation, SSE serialization
- **Server handlers**: Bun + Pi implementations with full CRUD (GET/POST/PATCH/DELETE) + SSE streaming
- **Client hook** (`useExternalAnnotations`): EventSource with polling fallback, optimistic updates
- **Editor integration**: two-array state model (local + external), content-aware dedup, ID-based routing
- **Persistence**: source field preserved through share URLs and crash-recovery drafts
- **Docs**: new Integrations category with API overview page, updated API reference
## API surface
All three servers (plan, review, annotate) expose:
- `GET /api/external-annotations/stream` - SSE stream
- `GET /api/external-annotations` - JSON snapshot (polling fallback)
- `POST /api/external-annotations` - Add annotations (single or batch)
- `PATCH /api/external-annotations?id=` - Update fields
- `DELETE /api/external-annotations` - Remove by id, source, or clear all
For provenance purposes, this commit was AI assisted.
2026-03-29 17:18:31 -07:00
|
|
|
const externalAnnotations = createExternalAnnotationHandler("review");
|
2026-03-04 10:12:58 -08:00
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// Mutable state for diff switching
|
|
|
|
|
let currentPatch = options.rawPatch;
|
|
|
|
|
let currentGitRef = options.gitRef;
|
|
|
|
|
let currentDiffType: DiffType = options.diffType || "uncommitted";
|
2026-03-02 15:26:07 +09:00
|
|
|
let currentError = options.error;
|
2026-01-12 19:36:09 -08:00
|
|
|
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
// AI provider setup (graceful — AI features degrade if SDK unavailable)
|
|
|
|
|
const aiRegistry = new ProviderRegistry();
|
|
|
|
|
const aiSessionManager = new SessionManager();
|
|
|
|
|
let aiEndpoints: AIEndpoints | null = null;
|
|
|
|
|
|
|
|
|
|
// Try Claude Agent SDK
|
|
|
|
|
try {
|
|
|
|
|
await import("@plannotator/ai/providers/claude-agent-sdk");
|
|
|
|
|
const claudePath = Bun.which("claude");
|
|
|
|
|
const provider = await createProvider({
|
|
|
|
|
type: "claude-agent-sdk",
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
...(claudePath && { claudeExecutablePath: claudePath }),
|
|
|
|
|
});
|
|
|
|
|
aiRegistry.register(provider);
|
|
|
|
|
} catch {
|
|
|
|
|
// Claude SDK not available
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Try Codex SDK
|
|
|
|
|
try {
|
|
|
|
|
await import("@plannotator/ai/providers/codex-sdk");
|
|
|
|
|
// Eagerly verify the SDK is importable so we don't advertise a broken provider.
|
|
|
|
|
await import("@openai/codex-sdk");
|
|
|
|
|
const codexPath = Bun.which("codex");
|
|
|
|
|
const provider = await createProvider({
|
|
|
|
|
type: "codex-sdk",
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
...(codexPath && { codexExecutablePath: codexPath }),
|
|
|
|
|
});
|
|
|
|
|
aiRegistry.register(provider);
|
|
|
|
|
} catch {
|
|
|
|
|
// Codex SDK not available
|
|
|
|
|
}
|
|
|
|
|
|
feat(ai): Pi provider via RPC subprocess (#377)
* refactor(ai): extract BaseSession and buildEffectivePrompt
Pull shared session lifecycle (~80 lines duplicated across Claude and
Codex providers) into BaseSession: query guard, abort, ID resolution,
generation counter. Extract first-query prompt prepending into
buildEffectivePrompt() in context.ts.
Both providers now extend BaseSession. Behavior-preserving — all 54
existing tests pass unchanged.
For provenance purposes, this commit was AI assisted.
* feat(ai): add Pi provider via RPC subprocess
Spawns `pi --mode rpc` and communicates via JSONL over stdio. No Pi SDK
bundled — user must have the pi CLI installed. Provider auto-discovers
available models at startup via get_available_models.
Includes: PiProcess (JSONL client), PiSDKProvider, PiSDKSession extending
BaseSession, mapPiEvent for streaming, Pi icon in provider UI, and 12
new tests (9 event mapping + 3 buildEffectivePrompt).
For provenance purposes, this commit was AI assisted.
* fix(ai): harden Pi provider error paths
- Surface startup errors when Pi process dies (bad config, missing API keys)
instead of hanging the chat indefinitely
- Map tool-call errors as non-terminal tool_result instead of AIErrorMessage,
so Pi can continue reasoning after a failed tool call
- Fix subprocess leak in fetchModels() by moving proc.kill() to finally block
For provenance purposes, this commit was AI assisted.
* fix(ai): detect Pi prompt rejections and process crashes
- Use sendAndWait for prompt command so RPC-level rejections (expired
credentials, invalid session) surface as errors instead of hanging
- Emit process_exited instead of synthetic agent_end when Pi subprocess
dies, so crashes show as errors instead of silent empty successes
For provenance purposes, this commit was AI assisted.
* docs(ai): add Pi to AI features guide, code review docs, and installation
For provenance purposes, this commit was AI assisted.
* style(ai): apply biome formatting to new files
For provenance purposes, this commit was AI assisted.
2026-03-23 15:50:30 -07:00
|
|
|
// Try Pi
|
|
|
|
|
try {
|
|
|
|
|
const { PiSDKProvider } = await import("@plannotator/ai/providers/pi-sdk");
|
|
|
|
|
const piPath = Bun.which("pi");
|
|
|
|
|
if (piPath) {
|
|
|
|
|
const provider = await createProvider({
|
|
|
|
|
type: "pi-sdk",
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
piExecutablePath: piPath,
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
} as PiSDKConfig);
|
feat(ai): Pi provider via RPC subprocess (#377)
* refactor(ai): extract BaseSession and buildEffectivePrompt
Pull shared session lifecycle (~80 lines duplicated across Claude and
Codex providers) into BaseSession: query guard, abort, ID resolution,
generation counter. Extract first-query prompt prepending into
buildEffectivePrompt() in context.ts.
Both providers now extend BaseSession. Behavior-preserving — all 54
existing tests pass unchanged.
For provenance purposes, this commit was AI assisted.
* feat(ai): add Pi provider via RPC subprocess
Spawns `pi --mode rpc` and communicates via JSONL over stdio. No Pi SDK
bundled — user must have the pi CLI installed. Provider auto-discovers
available models at startup via get_available_models.
Includes: PiProcess (JSONL client), PiSDKProvider, PiSDKSession extending
BaseSession, mapPiEvent for streaming, Pi icon in provider UI, and 12
new tests (9 event mapping + 3 buildEffectivePrompt).
For provenance purposes, this commit was AI assisted.
* fix(ai): harden Pi provider error paths
- Surface startup errors when Pi process dies (bad config, missing API keys)
instead of hanging the chat indefinitely
- Map tool-call errors as non-terminal tool_result instead of AIErrorMessage,
so Pi can continue reasoning after a failed tool call
- Fix subprocess leak in fetchModels() by moving proc.kill() to finally block
For provenance purposes, this commit was AI assisted.
* fix(ai): detect Pi prompt rejections and process crashes
- Use sendAndWait for prompt command so RPC-level rejections (expired
credentials, invalid session) surface as errors instead of hanging
- Emit process_exited instead of synthetic agent_end when Pi subprocess
dies, so crashes show as errors instead of silent empty successes
For provenance purposes, this commit was AI assisted.
* docs(ai): add Pi to AI features guide, code review docs, and installation
For provenance purposes, this commit was AI assisted.
* style(ai): apply biome formatting to new files
For provenance purposes, this commit was AI assisted.
2026-03-23 15:50:30 -07:00
|
|
|
if (provider instanceof PiSDKProvider) {
|
|
|
|
|
await provider.fetchModels();
|
|
|
|
|
}
|
|
|
|
|
aiRegistry.register(provider);
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// Pi not available
|
|
|
|
|
}
|
|
|
|
|
|
feat(ai): OpenCode provider via HTTP + SSE (#379)
* feat(ai): add OpenCode provider via HTTP + SSE
Bundle @opencode-ai/sdk to spawn `opencode serve` and communicate via
HTTP REST + SSE. Richest provider: fork, resume, streaming, tools, and
runtime permission approvals all work natively.
- OpenCodeProvider: lazy server spawn, shared HTTP client, dynamic model
discovery via GET /provider
- OpenCodeSession: SSE event drain loop, system prompt via API field,
permission reply (once/reject), abort via HTTP
- mapOpenCodeEvent: SSE → AIMessage mapping (text deltas, tool lifecycle,
permissions, session status, errors)
- 11 new event mapping tests (78 total, 157 expect calls)
For provenance purposes, this commit was AI assisted.
* docs(ai): add OpenCode to AI features guide and code review docs
For provenance purposes, this commit was AI assisted.
* fix(ai): prevent double server spawn in OpenCode ensureServer()
Use a promise-mutex pattern so concurrent callers (e.g. fetchModels +
createSession) share a single server spawn instead of racing to create two.
Also remove empty finally block from SSE drain loop.
For provenance purposes, this commit was AI assisted.
* fix(ai): await SSE subscribe in OpenCode provider
The SDK's event.subscribe() is async — must be awaited before
destructuring the stream.
For provenance purposes, this commit was AI assisted.
* fix(ui): scrollable model dropdown with search filter
Cap dropdown height at min(320px, 50vh) so it doesn't overflow the
viewport when providers expose many models (e.g. OpenCode with 20+).
Add a search/filter input when there are more than 8 models.
For provenance purposes, this commit was AI assisted.
* fix(ai): close SSE stream, rename to opencode-sdk, move dep to root
- Close SSE stream in finally block to prevent connection leak on
abort/early return
- Rename provider from opencode to opencode-sdk for consistency with
claude-agent-sdk, codex-sdk, pi-sdk
- Move @opencode-ai/sdk dependency to root package.json alongside the
other SDK dependencies
For provenance purposes, this commit was AI assisted.
* feat(ui): add first-run AI setup dialog for provider selection
Show a one-time modal on first review when AI providers are available.
Users pick a default provider and model from a 2-column grid, with a
brief feature intro and auth disclaimer. Persists via cookie, can be
changed later in Settings.
For provenance purposes, this commit was AI assisted.
* fix(ai): clear startPromise on failure so OpenCode provider can retry
If doStart() fails (port conflict, timeout, binary crash), the cached
rejected promise prevented all future ensureServer() calls from
retrying. Now cleared on failure and on dispose().
Also updates stale "future" comment in types.ts.
For provenance purposes, this commit was AI assisted.
2026-03-23 17:37:56 -07:00
|
|
|
// Try OpenCode
|
|
|
|
|
try {
|
|
|
|
|
const { OpenCodeProvider } = await import("@plannotator/ai/providers/opencode-sdk");
|
|
|
|
|
const opencodePath = Bun.which("opencode");
|
|
|
|
|
if (opencodePath) {
|
|
|
|
|
const provider = await createProvider({
|
|
|
|
|
type: "opencode-sdk",
|
|
|
|
|
cwd: process.cwd(),
|
|
|
|
|
});
|
|
|
|
|
if (provider instanceof OpenCodeProvider) {
|
|
|
|
|
await provider.fetchModels();
|
|
|
|
|
}
|
|
|
|
|
aiRegistry.register(provider);
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// OpenCode not available
|
|
|
|
|
}
|
|
|
|
|
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
// Create endpoints if any provider registered
|
|
|
|
|
if (aiRegistry.size > 0) {
|
|
|
|
|
aiEndpoints = createAIEndpoints({
|
|
|
|
|
registry: aiRegistry,
|
|
|
|
|
sessionManager: aiSessionManager,
|
|
|
|
|
getCwd: () => {
|
|
|
|
|
if (currentDiffType.startsWith("worktree:")) {
|
|
|
|
|
const parsed = parseWorktreeDiffType(currentDiffType);
|
|
|
|
|
if (parsed) return parsed.path;
|
|
|
|
|
}
|
|
|
|
|
return gitContext?.cwd ?? process.cwd();
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
const isRemote = isRemoteSession();
|
|
|
|
|
const configuredPort = getServerPort();
|
2026-03-25 15:06:29 -03:00
|
|
|
const wslFlag = await isWSL();
|
2026-03-26 11:54:22 -07:00
|
|
|
const gitUser = detectGitUser();
|
2026-01-12 19:36:09 -08:00
|
|
|
|
2026-01-28 10:29:52 -08:00
|
|
|
// Detect repo info (cached for this session)
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
// In PR mode, derive from metadata instead of local git
|
|
|
|
|
const repoInfo = isPRMode
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
? { display: getDisplayRepo(prMetadata), branch: `${getMRLabel(prMetadata)} ${getMRNumberLabel(prMetadata)}` }
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
: await getRepoInfo();
|
2026-01-28 10:29:52 -08:00
|
|
|
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
// Fetch current platform user (for own-PR/MR detection)
|
|
|
|
|
const prRef = isPRMode ? prRefFromMetadata(prMetadata) : null;
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
const platformUser = prRef ? await getPRUser(prRef) : null;
|
2026-03-21 00:48:26 +01:00
|
|
|
|
2026-03-25 21:33:33 +01:00
|
|
|
// Fetch GitHub viewed file state (non-blocking — errors are silently ignored)
|
|
|
|
|
let initialViewedFiles: string[] = [];
|
|
|
|
|
if (isPRMode && prRef) {
|
|
|
|
|
console.log("[plannotator] Fetching PR viewed files for", prRef);
|
|
|
|
|
try {
|
|
|
|
|
const viewedMap = await fetchPRViewedFiles(prRef);
|
|
|
|
|
console.log("[plannotator] PR viewed files map:", viewedMap);
|
|
|
|
|
initialViewedFiles = Object.entries(viewedMap)
|
|
|
|
|
.filter(([, isViewed]) => isViewed)
|
|
|
|
|
.map(([path]) => path);
|
|
|
|
|
console.log("[plannotator] Initial viewed files:", initialViewedFiles);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
// Non-fatal: viewed state is best-effort
|
|
|
|
|
console.warn("[plannotator] Could not fetch PR viewed files:", err instanceof Error ? err.message : err);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// Decision promise
|
|
|
|
|
let resolveDecision: (result: {
|
2026-03-14 17:58:57 -07:00
|
|
|
approved: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: string;
|
|
|
|
|
annotations: unknown[];
|
|
|
|
|
agentSwitch?: string;
|
|
|
|
|
}) => void;
|
|
|
|
|
const decisionPromise = new Promise<{
|
2026-03-14 17:58:57 -07:00
|
|
|
approved: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: string;
|
|
|
|
|
annotations: unknown[];
|
|
|
|
|
agentSwitch?: string;
|
|
|
|
|
}>((resolve) => {
|
|
|
|
|
resolveDecision = resolve;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Start server with retry logic
|
|
|
|
|
let server: ReturnType<typeof Bun.serve> | null = null;
|
|
|
|
|
|
|
|
|
|
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
|
|
|
|
try {
|
|
|
|
|
server = Bun.serve({
|
|
|
|
|
port: configuredPort,
|
|
|
|
|
|
|
|
|
|
async fetch(req) {
|
|
|
|
|
const url = new URL(req.url);
|
|
|
|
|
|
|
|
|
|
// API: Get diff content
|
|
|
|
|
if (url.pathname === "/api/diff" && req.method === "GET") {
|
|
|
|
|
return Response.json({
|
|
|
|
|
rawPatch: currentPatch,
|
|
|
|
|
gitRef: currentGitRef,
|
|
|
|
|
origin,
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
diffType: isPRMode ? undefined : currentDiffType,
|
|
|
|
|
gitContext: isPRMode ? undefined : gitContext,
|
2026-01-14 13:12:37 -08:00
|
|
|
sharingEnabled,
|
2026-02-12 15:07:43 -08:00
|
|
|
shareBaseUrl,
|
2026-01-28 10:29:52 -08:00
|
|
|
repoInfo,
|
2026-03-25 15:06:29 -03:00
|
|
|
isWSL: wslFlag,
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
...(isPRMode && { prMetadata, platformUser }),
|
2026-03-25 21:33:33 +01:00
|
|
|
...(isPRMode && initialViewedFiles.length > 0 && { viewedFiles: initialViewedFiles }),
|
2026-03-02 15:26:07 +09:00
|
|
|
...(currentError && { error: currentError }),
|
2026-03-26 11:54:22 -07:00
|
|
|
serverConfig: getServerConfig(gitUser),
|
2026-01-12 19:36:09 -08:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
// API: Switch diff type (disabled in PR mode)
|
2026-01-12 19:36:09 -08:00
|
|
|
if (url.pathname === "/api/diff/switch" && req.method === "POST") {
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
if (isPRMode) {
|
|
|
|
|
return Response.json(
|
|
|
|
|
{ error: "Not available for PR reviews" },
|
|
|
|
|
{ status: 400 },
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-01-12 19:36:09 -08:00
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as { diffType: DiffType };
|
2026-03-07 10:06:55 -08:00
|
|
|
let newDiffType = body.diffType;
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
if (!newDiffType) {
|
|
|
|
|
return Response.json(
|
|
|
|
|
{ error: "Missing diffType" },
|
|
|
|
|
{ status: 400 }
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const defaultBranch = gitContext?.defaultBranch || "main";
|
2026-03-17 20:29:09 -04:00
|
|
|
const defaultCwd = gitContext?.cwd;
|
2026-03-07 10:06:55 -08:00
|
|
|
|
|
|
|
|
// Run the new diff
|
2026-03-17 20:29:09 -04:00
|
|
|
const result = await runGitDiff(newDiffType, defaultBranch, defaultCwd);
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
// Update state
|
|
|
|
|
currentPatch = result.patch;
|
|
|
|
|
currentGitRef = result.label;
|
|
|
|
|
currentDiffType = newDiffType;
|
2026-03-02 15:26:07 +09:00
|
|
|
currentError = result.error;
|
2026-01-12 19:36:09 -08:00
|
|
|
|
2026-03-08 16:15:14 -07:00
|
|
|
return Response.json({
|
2026-01-12 19:36:09 -08:00
|
|
|
rawPatch: currentPatch,
|
|
|
|
|
gitRef: currentGitRef,
|
|
|
|
|
diffType: currentDiffType,
|
2026-03-02 15:26:07 +09:00
|
|
|
...(currentError && { error: currentError }),
|
2026-03-08 16:15:14 -07:00
|
|
|
});
|
2026-01-12 19:36:09 -08:00
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to switch diff";
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
feat(review): PR context panel — summary, comments, and checks (#350)
* feat(review): add PR context panel with summary, comments, and checks tabs
When reviewing a GitHub PR, the ReviewPanel now shows icon tabs for
Summary (PR body, labels, linked issues), Comments (chronological
thread of comments + reviews), and Checks (CI status, merge readiness).
Tabs only appear in PR mode; local review is unchanged.
Data fetched lazily via new /api/pr-context endpoint on first tab click.
Uses DOMPurify for safe HTML rendering of GitHub markdown content.
Inline markdown renderer extended with link and bare URL support.
Closes #348
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): reset fetch guard on error and detect inline HTML in PR bodies
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 23:14:21 -07:00
|
|
|
// API: Fetch PR context (comments, checks, merge status) — PR mode only
|
|
|
|
|
if (url.pathname === "/api/pr-context" && req.method === "GET") {
|
|
|
|
|
if (!isPRMode) {
|
|
|
|
|
return Response.json(
|
|
|
|
|
{ error: "Not in PR mode" },
|
|
|
|
|
{ status: 400 },
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
try {
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
const context = await fetchPRContext(prRef!);
|
feat(review): PR context panel — summary, comments, and checks (#350)
* feat(review): add PR context panel with summary, comments, and checks tabs
When reviewing a GitHub PR, the ReviewPanel now shows icon tabs for
Summary (PR body, labels, linked issues), Comments (chronological
thread of comments + reviews), and Checks (CI status, merge readiness).
Tabs only appear in PR mode; local review is unchanged.
Data fetched lazily via new /api/pr-context endpoint on first tab click.
Uses DOMPurify for safe HTML rendering of GitHub markdown content.
Inline markdown renderer extended with link and bare URL support.
Closes #348
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): reset fetch guard on error and detect inline HTML in PR bodies
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 23:14:21 -07:00
|
|
|
return Response.json(context);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to fetch PR context";
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-08 14:00:43 -07:00
|
|
|
// API: Get file content for expandable diff context
|
|
|
|
|
if (url.pathname === "/api/file-content" && req.method === "GET") {
|
|
|
|
|
const filePath = url.searchParams.get("path");
|
|
|
|
|
if (!filePath) {
|
|
|
|
|
return Response.json({ error: "Missing path" }, { status: 400 });
|
|
|
|
|
}
|
2026-03-09 07:31:17 -07:00
|
|
|
try { validateFilePath(filePath); } catch {
|
2026-03-08 14:00:43 -07:00
|
|
|
return Response.json({ error: "Invalid path" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
const oldPath = url.searchParams.get("oldPath") || undefined;
|
2026-03-09 07:31:17 -07:00
|
|
|
if (oldPath) {
|
|
|
|
|
try { validateFilePath(oldPath); } catch {
|
|
|
|
|
return Response.json({ error: "Invalid path" }, { status: 400 });
|
|
|
|
|
}
|
2026-03-08 14:00:43 -07:00
|
|
|
}
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
|
|
|
|
|
if (isPRMode) {
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
// Fetch file content from platform API using base/head SHAs
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
const [oldContent, newContent] = await Promise.all([
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
fetchPRFileContent(prRef!, prMetadata.baseSha, oldPath || filePath),
|
|
|
|
|
fetchPRFileContent(prRef!, prMetadata.headSha, filePath),
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
]);
|
|
|
|
|
return Response.json({ oldContent, newContent });
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-08 14:00:43 -07:00
|
|
|
const defaultBranch = gitContext?.defaultBranch || "main";
|
2026-03-17 20:29:09 -04:00
|
|
|
const defaultCwd = gitContext?.cwd;
|
2026-03-08 14:00:43 -07:00
|
|
|
const result = await getFileContentsForDiff(
|
|
|
|
|
currentDiffType,
|
|
|
|
|
defaultBranch,
|
|
|
|
|
filePath,
|
|
|
|
|
oldPath,
|
2026-03-17 20:29:09 -04:00
|
|
|
defaultCwd,
|
2026-03-08 14:00:43 -07:00
|
|
|
);
|
|
|
|
|
return Response.json(result);
|
|
|
|
|
}
|
|
|
|
|
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
// API: Git add / reset (stage / unstage) a file (disabled in PR mode)
|
2026-03-09 07:31:17 -07:00
|
|
|
if (url.pathname === "/api/git-add" && req.method === "POST") {
|
feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider
Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.
`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): add PR mode to review server
When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR review flow for Claude Code and OpenCode
Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.
Updates slash command definitions to pass $ARGUMENTS through.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): PR metadata display in review UI
Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(review): contextualized PR feedback for agent
In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(review): extract exportReviewFeedback + add tests
Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): strengthen PR/local boundary tests
Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test(review): remove redundant empty-annotations test
Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps
- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(install): add $ARGUMENTS to review command for PR URL support
Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add PR review support to docs and READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
|
|
|
if (isPRMode) {
|
|
|
|
|
return Response.json(
|
|
|
|
|
{ error: "Not available for PR reviews" },
|
|
|
|
|
{ status: 400 },
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-03-09 07:31:17 -07:00
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as { filePath: string; undo?: boolean };
|
|
|
|
|
if (!body.filePath) {
|
|
|
|
|
return Response.json({ error: "Missing filePath" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Determine cwd for worktree support
|
|
|
|
|
let cwd: string | undefined;
|
|
|
|
|
if (currentDiffType.startsWith("worktree:")) {
|
|
|
|
|
const parsed = parseWorktreeDiffType(currentDiffType);
|
|
|
|
|
if (parsed) cwd = parsed.path;
|
|
|
|
|
}
|
2026-03-17 20:29:09 -04:00
|
|
|
if (!cwd) {
|
|
|
|
|
cwd = gitContext?.cwd;
|
|
|
|
|
}
|
2026-03-09 07:31:17 -07:00
|
|
|
|
|
|
|
|
if (body.undo) {
|
|
|
|
|
await gitResetFile(body.filePath, cwd);
|
|
|
|
|
} else {
|
|
|
|
|
await gitAddFile(body.filePath, cwd);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message = err instanceof Error ? err.message : "Failed to git add";
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-26 11:54:22 -07:00
|
|
|
// API: Update user config (write-back to ~/.plannotator/config.json)
|
|
|
|
|
if (url.pathname === "/api/config" && req.method === "POST") {
|
|
|
|
|
try {
|
feat(review): diff display options with ConfigStore integration (#428)
* feat(config): add DiffOptions to PlannotatorConfig with deep-merge support
Extends the server-side config system to support diff display options
namespaced under `diffOptions` in ~/.plannotator/config.json. The
saveConfig deep-merge ensures partial writes (e.g. changing only
overflow) don't clobber sibling keys.
For provenance purposes, this commit was AI assisted.
* feat(server): accept diffOptions in POST /api/config handlers
All six server handlers (plan, review, annotate x Bun + Pi) now
whitelist diffOptions alongside displayName, forwarding it to
saveConfig for deep-merged disk persistence.
For provenance purposes, this commit was AI assisted.
* feat(config): register diff display settings with deep-merge write batching
Adds 6 diff option settings to the ConfigStore registry (diffStyle,
diffOverflow, diffIndicators, diffLineDiffType, diffShowLineNumbers,
diffShowBackground), all synced to disk under the diffOptions namespace.
Fixes write batching for nested server keys — replaces Object.assign
with deepMerge so rapid changes to multiple diff options within the
300ms debounce window don't clobber each other. Includes legacy cookie
migration for the old review-diff-style key.
For provenance purposes, this commit was AI assisted.
* feat(review): wire diff display options through to @pierre/diffs
Migrates diffStyle from raw cookie storage to ConfigStore. Reads all 6
diff options via useConfigValue and forwards them to FileDiff: overflow,
diffIndicators, lineDiffType, disableLineNumbers, disableBackground.
Adds a Scroll/Wrap toolbar toggle alongside the existing Split/Unified
toggle. Disables the custom resizable split dragger in wrap mode since
Pierre manages its own grid layout. Fixes the unsafeCSS grid override
to only target scroll mode, preventing per-character wrapping in split
view.
For provenance purposes, this commit was AI assisted.
* feat(review): add Display tab to review-mode Settings dialog
Adds a Display tab when Settings is in review mode, exposing all 6 diff
options: Diff Style, Line Overflow, Change Indicators, Inline Diff
Granularity, Show Line Numbers, and Show Diff Background. Changes take
effect immediately and persist via ConfigStore (cookie + disk).
Extracts reusable SegmentedControl and ToggleSwitch helpers for the
review display controls.
For provenance purposes, this commit was AI assisted.
* chore: update bun.lock
For provenance purposes, this commit was AI assisted.
* fix(review): reapply search highlights after display option changes
Add new diff display props to the search highlight and scroll-to-match
effect dependency arrays so highlights are restored after Pierre re-renders.
For provenance purposes, this commit was AI assisted.
2026-03-29 13:20:22 -07:00
|
|
|
const body = (await req.json()) as { displayName?: string; diffOptions?: Record<string, unknown> };
|
|
|
|
|
const toSave: Record<string, unknown> = {};
|
|
|
|
|
if (body.displayName !== undefined) toSave.displayName = body.displayName;
|
|
|
|
|
if (body.diffOptions !== undefined) toSave.diffOptions = body.diffOptions;
|
|
|
|
|
if (Object.keys(toSave).length > 0) saveConfig(toSave as Parameters<typeof saveConfig>[0]);
|
2026-03-26 11:54:22 -07:00
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
} catch {
|
|
|
|
|
return Response.json({ error: "Invalid request" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// API: Serve images (local paths or temp uploads)
|
|
|
|
|
if (url.pathname === "/api/image") {
|
2026-03-03 23:17:16 -08:00
|
|
|
return handleImage(req);
|
2026-01-12 19:36:09 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// API: Upload image -> save to temp -> return path
|
|
|
|
|
if (url.pathname === "/api/upload" && req.method === "POST") {
|
2026-03-03 23:17:16 -08:00
|
|
|
return handleUpload(req);
|
2026-01-12 19:36:09 -08:00
|
|
|
}
|
|
|
|
|
|
2026-01-19 11:07:22 -08:00
|
|
|
// API: Get available agents (OpenCode only)
|
|
|
|
|
if (url.pathname === "/api/agents") {
|
2026-03-03 23:17:16 -08:00
|
|
|
return handleAgents(options.opencodeClient);
|
2026-01-19 11:07:22 -08:00
|
|
|
}
|
|
|
|
|
|
2026-03-04 10:12:58 -08:00
|
|
|
// API: Annotation draft persistence
|
|
|
|
|
if (url.pathname === "/api/draft") {
|
|
|
|
|
if (req.method === "POST") return handleDraftSave(req, draftKey);
|
|
|
|
|
if (req.method === "DELETE") return handleDraftDelete(draftKey);
|
|
|
|
|
return handleDraftLoad(draftKey);
|
|
|
|
|
}
|
|
|
|
|
|
feat: VS Code editor annotations + theme integration (#239)
* feat: add shared EditorAnnotation type
Single source of truth for the editor annotation interface,
imported by both @plannotator/server and @plannotator/ui.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation server endpoints
In-memory store with POST/GET/DELETE endpoints for editor annotations.
The array lives in the handler closure and dies with the server session.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotation UI — polling hook, card, panel, and export
- useEditorAnnotations hook with auto-disable polling (500ms interval)
- EditorAnnotationCard with file path, code preview, and comment
- AnnotationPanel conditionally renders editor annotation section
- exportEditorAnnotations formats annotations for Claude feedback
- App.tsx wires hook, includes in output memo and send feedback gate
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code extension editor annotation command
Cmd+Shift+. or right-click to capture selected text as an annotation.
POSTs through the cookie proxy to the plannotator server. Adds amber
left-border decorations on annotated lines, cleared on panel close.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: inline comment threads, lightbulb menu, and stronger decorations
Replace showInputBox with VS Code CommentController for inline annotation
threads anchored to selected code. Add CodeActionProvider for lightbulb
discoverability. Stronger decoration styling with gutter icon.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: VS Code theme integration for webview
Bridge VS Code CSS variables to Plannotator's CSS variable system via
postMessage between wrapper page and proxied iframe. Automatically adopts
the active VS Code color theme (dark/light/custom) without touching any
UI components or CSS files.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: gate editor annotation polling behind VS Code detection
Only poll /api/editor-annotations when running inside a VS Code webview
(window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have
zero network cost from the editor annotations feature. Also fixes poll
interval from 500ms to 2000ms.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: faster polling, prevent unnecessary re-renders, unify HTTP helper
- Poll interval 2s → 500ms for snappier annotation pickup
- Shallow equality check on annotation IDs prevents React re-renders
when poll data is unchanged
- Merge postToProxy/deleteFromProxy into single requestProxy function
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: editor annotations support in code review
Wire existing editor annotation infrastructure into the review flow
so VS Code users can annotate files outside the diff during code review.
- Add editor annotation endpoints to review server (same 3-line pattern)
- Call useEditorAnnotations hook in review App.tsx
- Display editor annotations in ReviewPanel with "Editor" divider
- Include editor annotations in feedback export and gating logic
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
|
|
|
// API: Editor annotations (VS Code extension)
|
|
|
|
|
const editorResponse = await editorAnnotations.handle(req, url);
|
|
|
|
|
if (editorResponse) return editorResponse;
|
|
|
|
|
|
feat: external annotations API with real-time SSE (#400)
Adds a general-purpose External Annotations API that allows external programs (linters, AI tools, security scanners) to push annotations into a live Plannotator session via HTTP, with real-time delivery over SSE.
## What's included
- **Shared core** (`packages/shared/external-annotation.ts`): types, in-memory store, input validation, SSE serialization
- **Server handlers**: Bun + Pi implementations with full CRUD (GET/POST/PATCH/DELETE) + SSE streaming
- **Client hook** (`useExternalAnnotations`): EventSource with polling fallback, optimistic updates
- **Editor integration**: two-array state model (local + external), content-aware dedup, ID-based routing
- **Persistence**: source field preserved through share URLs and crash-recovery drafts
- **Docs**: new Integrations category with API overview page, updated API reference
## API surface
All three servers (plan, review, annotate) expose:
- `GET /api/external-annotations/stream` - SSE stream
- `GET /api/external-annotations` - JSON snapshot (polling fallback)
- `POST /api/external-annotations` - Add annotations (single or batch)
- `PATCH /api/external-annotations?id=` - Update fields
- `DELETE /api/external-annotations` - Remove by id, source, or clear all
For provenance purposes, this commit was AI assisted.
2026-03-29 17:18:31 -07:00
|
|
|
// API: External annotations (SSE-based, for any external tool)
|
|
|
|
|
const externalResponse = await externalAnnotations.handle(req, url);
|
|
|
|
|
if (externalResponse) return externalResponse;
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// API: Submit review feedback
|
|
|
|
|
if (url.pathname === "/api/feedback" && req.method === "POST") {
|
|
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as {
|
2026-03-14 17:58:57 -07:00
|
|
|
approved?: boolean;
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: string;
|
|
|
|
|
annotations: unknown[];
|
|
|
|
|
agentSwitch?: string;
|
|
|
|
|
};
|
|
|
|
|
|
2026-03-04 10:12:58 -08:00
|
|
|
deleteDraft(draftKey);
|
2026-01-12 19:36:09 -08:00
|
|
|
resolveDecision({
|
2026-03-14 17:58:57 -07:00
|
|
|
approved: body.approved ?? false,
|
2026-01-12 19:36:09 -08:00
|
|
|
feedback: body.feedback || "",
|
|
|
|
|
annotations: body.annotations || [],
|
|
|
|
|
agentSwitch: body.agentSwitch,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to process feedback";
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-21 00:48:26 +01:00
|
|
|
// API: Submit PR review directly to GitHub (PR mode only)
|
|
|
|
|
if (url.pathname === "/api/pr-action" && req.method === "POST") {
|
|
|
|
|
if (!isPRMode || !prMetadata) {
|
|
|
|
|
return Response.json({ error: "Not in PR mode" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as {
|
|
|
|
|
action: "approve" | "comment";
|
|
|
|
|
body: string;
|
|
|
|
|
fileComments: PRReviewFileComment[];
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await submitPRReview(
|
feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support
Add full GitLab MR review parity with existing GitHub PR review:
- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses
Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).
For provenance purposes, this commit was AI assisted.
* fix: correct GitLab enum mappings and add shared file path encoding
- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab
For provenance purposes, this commit was AI assisted.
* fix: align panel headers and refine file tree selection style
- Use shared --panel-header-h CSS variable for consistent header heights
across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
background for better readability and semantic color preservation
For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
|
|
|
prRef!,
|
2026-03-21 00:48:26 +01:00
|
|
|
prMetadata.headSha,
|
|
|
|
|
body.action,
|
|
|
|
|
body.body,
|
|
|
|
|
body.fileComments,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return Response.json({ ok: true, prUrl: prMetadata.url });
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to submit PR review";
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-25 21:33:33 +01:00
|
|
|
// API: Mark/unmark PR files as viewed on GitHub (PR mode, GitHub only)
|
|
|
|
|
if (url.pathname === "/api/pr-viewed" && req.method === "POST") {
|
|
|
|
|
if (!isPRMode || !prMetadata) {
|
|
|
|
|
console.log("[plannotator] /api/pr-viewed: not in PR mode");
|
|
|
|
|
return Response.json({ error: "Not in PR mode" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
if (prMetadata.platform !== "github") {
|
|
|
|
|
console.log("[plannotator] /api/pr-viewed: platform is", prMetadata.platform, "(not github)");
|
|
|
|
|
return Response.json({ error: "Viewed sync only supported for GitHub" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
const prNodeId = prMetadata.prNodeId;
|
|
|
|
|
if (!prNodeId) {
|
|
|
|
|
console.log("[plannotator] /api/pr-viewed: prNodeId missing from metadata:", prMetadata);
|
|
|
|
|
return Response.json({ error: "PR node ID not available" }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
const body = (await req.json()) as {
|
|
|
|
|
filePaths: string[];
|
|
|
|
|
viewed: boolean;
|
|
|
|
|
};
|
|
|
|
|
console.log("[plannotator] /api/pr-viewed: marking", body.filePaths, "as viewed=", body.viewed, "prNodeId=", prNodeId);
|
|
|
|
|
await markPRFilesViewed(prRef!, prNodeId, body.filePaths, body.viewed);
|
|
|
|
|
console.log("[plannotator] /api/pr-viewed: success");
|
|
|
|
|
return Response.json({ ok: true });
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const message =
|
|
|
|
|
err instanceof Error ? err.message : "Failed to update viewed state";
|
|
|
|
|
console.error("[plannotator] /api/pr-viewed error:", message);
|
|
|
|
|
return Response.json({ error: message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
// AI endpoints
|
|
|
|
|
if (aiEndpoints && url.pathname.startsWith("/api/ai/")) {
|
|
|
|
|
const handler = aiEndpoints[url.pathname as keyof AIEndpoints];
|
|
|
|
|
if (handler) return handler(req);
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
return Response.json({ error: "Not found" }, { status: 404 });
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
}
|
|
|
|
|
|
2026-03-16 15:45:00 +01:00
|
|
|
// Favicon
|
|
|
|
|
if (url.pathname === "/favicon.svg") return handleFavicon();
|
|
|
|
|
|
2026-01-12 19:36:09 -08:00
|
|
|
// Serve embedded HTML for all other routes (SPA)
|
|
|
|
|
return new Response(htmlContent, {
|
|
|
|
|
headers: { "Content-Type": "text/html" },
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
break; // Success, exit retry loop
|
|
|
|
|
} catch (err: unknown) {
|
|
|
|
|
const isAddressInUse =
|
|
|
|
|
err instanceof Error && err.message.includes("EADDRINUSE");
|
|
|
|
|
|
|
|
|
|
if (isAddressInUse && attempt < MAX_RETRIES) {
|
|
|
|
|
await Bun.sleep(RETRY_DELAY_MS);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (isAddressInUse) {
|
|
|
|
|
const hint = isRemote ? " (set PLANNOTATOR_PORT to use different port)" : "";
|
|
|
|
|
throw new Error(`Port ${configuredPort} in use after ${MAX_RETRIES} retries${hint}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw err;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!server) {
|
|
|
|
|
throw new Error("Failed to start server");
|
|
|
|
|
}
|
|
|
|
|
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
const port = server.port!;
|
|
|
|
|
const serverUrl = `http://localhost:${port}`;
|
2026-01-12 19:36:09 -08:00
|
|
|
|
|
|
|
|
// Notify caller that server is ready
|
|
|
|
|
if (onReady) {
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
onReady(serverUrl, isRemote, port);
|
2026-01-12 19:36:09 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
port,
|
2026-01-12 19:36:09 -08:00
|
|
|
url: serverUrl,
|
|
|
|
|
isRemote,
|
|
|
|
|
waitForDecision: () => decisionPromise,
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
stop: () => {
|
|
|
|
|
aiSessionManager.disposeAll();
|
|
|
|
|
aiRegistry.disposeAll();
|
|
|
|
|
server.stop();
|
|
|
|
|
},
|
2026-01-12 19:36:09 -08:00
|
|
|
};
|
|
|
|
|
}
|