Files
backnotprop__plannotator/apps/opencode-plugin/commands.ts
T

457 lines
15 KiB
TypeScript
Raw Normal View History

feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
/**
* Command Handlers for OpenCode Plugin
*
* Handles /plannotator-review, /plannotator-annotate, /plannotator-last,
* and /plannotator-archive slash commands. Extracted from the event hook
* for modularity.
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
*/
import {
startPlannotatorServer,
handleServerReady,
} from "@plannotator/server";
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
import {
startReviewServer,
handleReviewServerReady,
} from "@plannotator/server/review";
import {
startAnnotateServer,
handleAnnotateServerReady,
} from "@plannotator/server/annotate";
import { type DiffType, prepareLocalReviewDiff } from "@plannotator/server/vcs";
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 { parsePRUrl, checkPRAuth, fetchPR, getCliName, getMRLabel, getMRNumberLabel, getDisplayRepo } from "@plannotator/server/pr";
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
import { loadConfig, resolveDefaultDiffType, resolveUseJina } from "@plannotator/shared/config";
import {
getReviewApprovedPrompt,
getReviewDeniedSuffix,
getAnnotateFileFeedbackPrompt,
} from "@plannotator/shared/prompts";
import { resolveMarkdownFile, resolveUserPath, hasMarkdownFiles } from "@plannotator/shared/resolve-file";
import { FILE_BROWSER_EXCLUDED } from "@plannotator/shared/reference-common";
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
import { htmlToMarkdown } from "@plannotator/shared/html-to-markdown";
import { parseAnnotateArgs } from "@plannotator/shared/annotate-args";
import { parseReviewArgs } from "@plannotator/shared/review-args";
import { urlToMarkdown, isConvertedSource } from "@plannotator/shared/url-to-markdown";
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
import { statSync } from "fs";
import path from "path";
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
/** Shared dependencies injected by the plugin */
export interface CommandDeps {
client: any;
htmlContent: string;
reviewHtmlContent: string;
getSharingEnabled: () => Promise<boolean>;
getShareBaseUrl: () => string | undefined;
getPasteApiUrl: () => string | undefined;
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
directory?: string;
}
export async function handleReviewCommand(
event: any,
deps: CommandDeps
) {
const { client, reviewHtmlContent, getSharingEnabled, getShareBaseUrl, directory } = deps;
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
// @ts-ignore - Event properties contain arguments
const reviewArgs = parseReviewArgs(event.properties?.arguments || "");
const urlArg = reviewArgs.prUrl;
const isPRMode = urlArg !== undefined;
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -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
let rawPatch: string;
let gitRef: string;
let diffError: string | undefined;
let userDiffType: DiffType | undefined;
let gitContext: Awaited<ReturnType<typeof prepareLocalReviewDiff>>["gitContext"] | undefined;
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
let prMetadata: Awaited<ReturnType<typeof fetchPR>>["metadata"] | undefined;
if (isPRMode) {
const prRef = parsePRUrl(urlArg);
if (!prRef) {
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
client.app.log({ level: "error", message: `Invalid PR/MR URL: ${urlArg}` });
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;
}
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
client.app.log({ level: "info", message: `Fetching ${getMRLabel(prRef)} ${getMRNumberLabel(prRef)} from ${getDisplayRepo(prRef)}...` });
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
try {
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
await checkPRAuth(prRef);
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
} catch (err) {
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 cliName = getCliName(prRef);
client.app.log({ level: "error", message: err instanceof Error ? err.message : `${cliName} auth check failed` });
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;
}
try {
const pr = await fetchPR(prRef);
rawPatch = pr.rawPatch;
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
gitRef = `${getMRLabel(prRef)} ${getMRNumberLabel(prRef)}`;
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
prMetadata = pr.metadata;
} catch (err) {
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
client.app.log({ level: "error", message: err instanceof Error ? err.message : `Failed to fetch ${getMRLabel(prRef)} ${getMRNumberLabel(prRef)}` });
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;
}
} else {
client.app.log({ level: "info", message: "Opening code review UI..." });
const config = loadConfig();
const diffResult = await prepareLocalReviewDiff({
cwd: directory,
vcsType: reviewArgs.vcsType,
configuredDiffType: resolveDefaultDiffType(config),
hideWhitespace: config.diffOptions?.hideWhitespace ?? false,
});
gitContext = diffResult.gitContext;
userDiffType = diffResult.diffType;
rawPatch = diffResult.rawPatch;
gitRef = diffResult.gitRef;
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
diffError = diffResult.error;
}
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
const server = await startReviewServer({
rawPatch,
gitRef,
error: diffError,
origin: "opencode",
diffType: isPRMode ? undefined : userDiffType,
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
gitContext,
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
prMetadata,
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
sharingEnabled: await getSharingEnabled(),
shareBaseUrl: getShareBaseUrl(),
htmlContent: reviewHtmlContent,
opencodeClient: client,
onReady: (url, isRemote, port) => {
handleReviewServerReady(url, isRemote, port);
if (isRemote) {
client.app.log({ level: "info", message: `[Plannotator] Open in browser: ${url}` });
}
},
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
});
const result = await server.waitForDecision();
await Bun.sleep(1500);
server.stop();
if (result.exit) {
return;
}
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
if (result.feedback) {
// @ts-ignore - Event properties contain sessionID
const sessionId = event.properties?.sessionID;
if (sessionId) {
const shouldSwitchAgent = result.agentSwitch && result.agentSwitch !== "disabled";
const targetAgent = result.agentSwitch || "build";
const message = result.approved
? getReviewApprovedPrompt("opencode")
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
: isPRMode
? result.feedback
: `${result.feedback}${getReviewDeniedSuffix("opencode")}`;
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
try {
await client.session.prompt({
path: { id: sessionId },
body: {
...(shouldSwitchAgent && { agent: targetAgent }),
parts: [{ type: "text", text: message }],
},
});
} catch {
// Session may not be available
}
}
}
}
export async function handleAnnotateCommand(
event: any,
deps: CommandDeps
) {
const { client, htmlContent, getSharingEnabled, getShareBaseUrl, getPasteApiUrl, directory } = deps;
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
// @ts-ignore - Event properties contain arguments
const rawArgs = event.properties?.arguments || event.arguments || "";
annotate-last: pick which message to annotate (fixes #800) (#809) * feat: message picker for annotate-last (#800) When running /plannotator-last after /rewind, the newest transcript entry is no longer the message the user intended to annotate, and there was no affordance to pick a different one. Adds a picker UI that surfaces the recent assistant messages so the user can choose which one to annotate: - A "Message N of M" button in the Viewer's sticky-top action bar (alongside Copy / Global comment / Attachments), so it stays accessible while scrolling. - A "Messages" tab in the left sidebar with the full list (newest-first, preview + timestamp, default ★), mirroring the existing Files / Versions / Archive tab pattern. Wired for Claude Code, Codex, and Droid (all share apps/hook/server). OpenCode, Pi, and Copilot still get the original single-message behavior — they don't emit recentMessages, so the picker affordances hide cleanly. Default selection (index 0) matches today's "last message" behavior, so users who don't interact with the picker see no change. * feat: extend annotate-last picker to Copilot and OpenCode The picker UI from #800 was wired for Claude / Codex / Droid only. Pull Copilot and OpenCode onto the same shape so users on those harnesses also get the recent-messages picker when annotating the last assistant message. - Copilot: replace getLastCopilotMessage with getRecentCopilotMessages, walking events.jsonl newest-first up to 25 assistant.message events. - OpenCode: rewrite the session walk to collect up to 25 messages (newest first) instead of bailing on the first hit; normalize the SDK time.created (ms epoch) to ISO to match the shared picker contract. - Both pass recentMessages to startAnnotateServer only when length > 1, matching the existing Claude/Codex/Droid behavior. Also trims a leftover narrating comment in MessagesBrowser and refreshes the stale Copilot session-parser header. Pi parity follows in the next commit (needs round-trip of the picker selection through /api/feedback so its post-submit anchoring quotes the right message). * feat(pi): wire annotate-last picker with feedback round-trip Extends the picker UI (#800) to Pi and fixes a Pi-specific anchoring bug the picker would otherwise introduce. Picker plumbing - assistant-message: getRecentAssistantMessages walks the active branch newest-first, returning { messageId, text, timestamp? } in the same shape the other harnesses produce. - Plumbed through plannotator-browser / plannotator-events so the Bun server's recentMessages option is populated when the branch has more than one assistant message. Anchoring fix - Pi quotes the targeted assistant message back to the agent because its UX is async — the conversation may have moved on by feedback time. With the picker, that target is no longer guaranteed to be the snapshot taken when the UI opened. The editor now sends the user's selectedMessageId with /api/feedback; Pi looks it up in the current branch via findAssistantMessageByEntryId and quotes that message instead. Falls back to the original snapshot if the entry is gone. - The round-trip field is optional and only meaningful in annotate-last mode; other harnesses (and other modes) ignore it. Timestamp safety - Pi's SDK currently types SessionEntryBase.timestamp as string, but the picker contract everywhere else is ISO. Treat the value as unknown and normalize string/number(ms)/Date to ISO; drop anything else, rather than blind-casting and risking silent drift if the SDK changes. * chore: strip issue-number references from comments Comments shouldn't rely on external references — issue numbers age out of context, link rot is a thing, and a reader shouldn't need to open GitHub to understand why a line exists. Strip the `(#800)` and `(#570)` parentheticals from comments and doc strings across the picker and review-gate code; the surrounding "why" content is preserved. * fix: prevent removeChild crash when switching annotate-last messages Switching the picked message remounted nothing, so React reconciled new content against DOM that web-highlighter had mutated with <mark> nodes, throwing removeChild. Drive the Viewer key (and StickyHeaderLane's remount token) off a shared viewerContentKey so a message switch fully remounts the Viewer and re-anchors the sticky-header observer. Also cap MessagesBrowser row previews via previewText() and drop the redundant 'block' class that was overriding line-clamp-2. * feat: persist annotate-last feedback across messages --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-03 13:01:36 -07:00
// Split --gate / --json out of the args; rest is the file path.
// --json is accepted silently (OpenCode writes to session, not stdout).
// parseAnnotateArgs strips leading @ on filePath (reference-mode convention).
// `rawFilePath` preserves it for the scoped-package markdown fallback.
const { filePath, rawFilePath, gate, renderHtml: renderHtmlFlag } = parseAnnotateArgs(rawArgs);
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
if (!filePath) {
client.app.log({ level: "error", message: "Usage: /plannotator-annotate <file.md | file.html | https://... | folder/> [--gate] [--json]" });
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
return;
}
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
let markdown: string;
let rawHtml: string | undefined;
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
let absolutePath: string;
let folderPath: string | undefined;
let annotateMode: "annotate" | "annotate-folder" = "annotate";
let isFolder = false;
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
let sourceInfo: string | undefined;
let sourceConverted = false;
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
// --- URL annotation ---
const isUrl = /^https?:\/\//i.test(filePath);
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
if (isUrl) {
const useJina = resolveUseJina(false, loadConfig());
client.app.log({ level: "info", message: `Fetching: ${filePath}${useJina ? " (via Jina Reader)" : " (via fetch+Turndown)"}...` });
try {
const result = await urlToMarkdown(filePath, { useJina });
markdown = result.markdown;
sourceConverted = isConvertedSource(result.source);
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
} catch (err) {
client.app.log({ level: "error", message: `Failed to fetch URL: ${err instanceof Error ? err.message : String(err)}` });
return;
}
absolutePath = filePath;
sourceInfo = filePath;
} else {
const projectRoot = directory || process.cwd();
Add ~ support for user-entered file paths (#572) * refactor(path): centralize user path resolution * fix(annotate): resolve user paths in file entrypoints * fix(pi-extension): restore resolve import and add typecheck to CI The refactor removed `resolve` from `node:path` imports, but `resolvePlanPath()` and the planning-mode write/edit guards still call `resolve(...)`. That breaks plan submission and plan-file restriction at runtime for Pi users. Also wires pi-extension's tsconfig into the root `typecheck` script so CI catches this class of missing-symbol regression in the future. Required adding @mariozechner/pi-* packages as explicit devDependencies so tsc can resolve them (they were previously only reachable transitively via the peer dep, which Bun keeps in its `.bun/` store unhoisted). For provenance purposes, this commit was AI assisted. * fix(path): reject whitespace-only user paths and run vendor before typecheck resolveUserPath() trims input, so whitespace-only customPath/vaultPath resolved to process.cwd(). Plans silently wrote into the repo root and Obsidian notes landed in <cwd>/plannotator/ instead of erroring. Guard at both call sites (getPlanDir, saveToObsidian — Bun + Pi copies). Also prepend vendor.sh to the root typecheck script so fresh-clone `bun run typecheck` works without a separate vendoring step. For provenance purposes, this commit was AI assisted. * fix(path): short-circuit resolveUserPath on empty input Trimming in normalizeUserPathInput meant whitespace-only input resolved to cwd/baseDir. Callers like the annotate CLI and reference API endpoints would then list the project root instead of erroring. Return "" early so downstream existsSync/resolveMarkdownFile checks fail naturally. For provenance purposes, this commit was AI assisted. --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-04-20 02:54:15 +03:00
const resolvedArg = resolveUserPath(filePath, projectRoot);
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
try {
isFolder = statSync(resolvedArg).isDirectory();
} catch {
// Not a directory, fall through to file resolution.
}
if (isFolder) {
if (!hasMarkdownFiles(resolvedArg, FILE_BROWSER_EXCLUDED, /\.(mdx?|html?)$/i)) {
client.app.log({ level: "error", message: `No markdown or HTML files found in ${resolvedArg}` });
return;
}
folderPath = resolvedArg;
absolutePath = resolvedArg;
markdown = "";
annotateMode = "annotate-folder";
client.app.log({ level: "info", message: `Opening annotation UI for folder ${resolvedArg}...` });
} else if (/\.html?$/i.test(resolvedArg)) {
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
let fileSize: number;
try {
fileSize = statSync(resolvedArg).size;
} catch {
client.app.log({ level: "error", message: `File not found: ${filePath}` });
return;
}
if (fileSize > 10 * 1024 * 1024) {
client.app.log({ level: "error", message: `File too large (${Math.round(fileSize / 1024 / 1024)}MB, max 10MB)` });
return;
}
const html = await Bun.file(resolvedArg).text();
if (renderHtmlFlag) {
rawHtml = html;
markdown = "";
} else {
markdown = htmlToMarkdown(html);
sourceConverted = true;
}
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
absolutePath = resolvedArg;
sourceInfo = path.basename(resolvedArg);
client.app.log({ level: "info", message: `${renderHtmlFlag ? "Raw HTML" : "Converted"}: ${absolutePath}` });
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
} else {
// Markdown file annotation
client.app.log({ level: "info", message: `Opening annotation UI for ${filePath}...` });
// Strip-first with literal-@ fallback (scoped-package-style names).
let resolved = await resolveMarkdownFile(filePath, projectRoot);
if (resolved.kind === "not_found" && rawFilePath !== filePath) {
resolved = await resolveMarkdownFile(rawFilePath, projectRoot);
}
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
if (resolved.kind === "ambiguous") {
client.app.log({
level: "error",
message: `Ambiguous filename "${resolved.input}" — found ${resolved.matches.length} matches:\n${resolved.matches.map((m) => ` ${m}`).join("\n")}`,
});
return;
}
if (resolved.kind === "not_found") {
client.app.log({ level: "error", message: `File not found: ${resolved.input}` });
return;
}
absolutePath = resolved.path;
client.app.log({ level: "info", message: `Resolved: ${absolutePath}` });
markdown = await Bun.file(absolutePath).text();
}
}
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
const server = await startAnnotateServer({
markdown,
filePath: absolutePath,
origin: "opencode",
mode: annotateMode,
folderPath,
feat(annotate): support HTML files and URL annotation (#545) * fix(annotate): sanitize dangerous link protocols in markdown renderer Block javascript:, data:, and vbscript: URLs in InlineMarkdown link rendering. Links with dangerous protocols render as plain text instead of clickable anchors. Uses a blocklist approach so existing links with custom protocols (obsidian://, vscode://, Windows C:\ paths) continue to work. For provenance purposes, this commit was AI assisted. * feat(annotate): add HTML-to-markdown and URL-to-markdown utilities - html-to-markdown.ts: Turndown wrapper with GFM table rule, strips script/style/noscript tags - url-to-markdown.ts: Jina Reader (free, returns markdown) with fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for local/private URLs (localhost, 192.168.*, 10.*, etc.) - config.ts: add jina setting and resolveUseJina() with priority chain --no-jina flag > PLANNOTATOR_JINA env > config.json > default true For provenance purposes, this commit was AI assisted. * feat(annotate): support HTML files and URLs in annotate command Extend the annotate subcommand to accept .html/.htm local files (converted via Turndown) and https:// URLs (fetched via Jina Reader with fetch+Turndown fallback). URL content is fetched terminal-side before opening the browser. Add --no-jina global flag to disable Jina Reader per-invocation. Add 10MB file size guard for local HTML files. For provenance purposes, this commit was AI assisted. * feat(annotate): HTML files in folder browser and on-demand conversion - Widen file browser glob to include .html/.htm alongside markdown - handleDoc converts HTML files via Turndown on demand when selected - hasMarkdownFiles accepts optional extensions param for folder validation - Add sourceInfo field to annotate server API response - Add _site/, public/, out/, .docusaurus/, .jekyll-cache/, storybook-static/ to FILE_BROWSER_EXCLUDED For provenance purposes, this commit was AI assisted. * feat(annotate): source attribution badge for HTML/URL annotations Show a subtle badge in DocBadges displaying the URL hostname or HTML filename for converted content. Thread sourceInfo from API response through App → Viewer → DocBadges. Also update Pi extension to accept HTML-only folders in annotate mode. For provenance purposes, this commit was AI assisted. * test: update CLI help text assertion for HTML/URL annotate support For provenance purposes, this commit was AI assisted. * fix(annotate): address PR review findings Security: - Add project-root containment check for HTML files in /api/doc handler using exported isWithinProjectRoot() from resolve-file.ts - Blocks path traversal via absolute paths or ../ escapes isLocalUrl fixes: - Add bracketed IPv6 loopback [::1] detection - Replace hostname.startsWith('10.') with proper IPv4 regex to avoid matching public hostnames like 10.example.com Revert Pi extension change: - Pi server doesn't implement HTML file browsing or conversion yet - Keep Pi folder validation markdown-only until both implementations are updated per CLAUDE.md guidelines Cleanup: - Remove dead el.children || el.childNodes fallback in table rule - Extract hostnameOrFallback() helper to @plannotator/shared/project replacing duplicated try/catch IIFEs in DocBadges and index.ts For provenance purposes, this commit was AI assisted. * feat(annotate): Pi extension HTML annotation parity Bring the Pi extension to full parity with the Bun server for HTML annotation support: - Vendor html-to-markdown and url-to-markdown via vendor.sh - walkMarkdownFiles now scans .html/.htm alongside markdown - handleDocRequest converts HTML files on-demand via Turndown with isWithinProjectRoot containment check - serverAnnotate includes sourceInfo in /api/plan response - index.ts supports URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, folder HTML validation, and 10MB file size guard - openMarkdownAnnotation accepts and threads sourceInfo - Add turndown as a Pi extension dependency For provenance purposes, this commit was AI assisted. * fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML - Add extensions param to walkMarkdownFiles (default: HTML-inclusive) - Obsidian callers pass /\.mdx?$/i to match Bun server behavior - Add try/catch around HTML file reads in handleDocRequest For provenance purposes, this commit was AI assisted. * fix(annotate): address second review — base-block traversal, metadata IP, dead code Security: - Add isWithinProjectRoot check to the base-relative block for HTML files in both Bun and Pi /api/doc handlers. Previously HTML files served via the base query param bypassed the containment guard. - Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl private IP ranges Cleanup: - Remove dead hostname === "[::1]" check (WHATWG URL parser strips brackets; hostname === "::1" already handles it) - Remove dead parent?.childNodes fallback in table cell() function For provenance purposes, this commit was AI assisted. * refactor(annotate): replace custom table rules with turndown-plugin-gfm Drop ~60 lines of hand-rolled GFM table conversion that had a bug (tables without explicit <thead> produced invalid GFM). Use the official turndown-plugin-gfm plugin (24KB) which correctly handles all table patterns plus adds strikethrough and task list support. For provenance purposes, this commit was AI assisted. * fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown Expand the backslash escape regex to cover all CommonMark-defined escapable characters (. ) - # > + | { } &), not just the subset the parser uses for formatting. Fixes literal backslashes appearing in rendered output for Turndown-escaped content like "1\." → "1.". For provenance purposes, this commit was AI assisted. * fix(annotate): prevent SSRF via redirect to private/local URLs Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown and validate each redirect hop against isLocalUrl. Blocks attacks where an external URL redirects to cloud metadata endpoints (169.254.169.254) or other private IPs. Limits redirect chain to 10 hops. For provenance purposes, this commit was AI assisted. * chore: update lockfile for turndown-plugin-gfm in Pi extension bun install needed to resolve turndown-plugin-gfm in the Pi extension workspace after adding it to apps/pi-extension/package.json. For provenance purposes, this commit was AI assisted. * fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the actively maintained Joplin fork (2025, v1.0.64, 16KB). Fix TypeScript errors that broke CI: - Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import - Restructure fetchViaTurndown redirect loop to avoid uninitialized variable — first fetch before loop, loop only for redirects For provenance purposes, this commit was AI assisted. * fix(annotate): use proper declarations.d.ts instead of ts-expect-error Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed function signatures, remove the ts-expect-error suppression. For provenance purposes, this commit was AI assisted. * fix: explicitly include declarations.d.ts in shared tsconfig CI's tsc wasn't finding the ambient module declaration with implicit include. Add explicit include to ensure declarations.d.ts is always picked up regardless of environment. For provenance purposes, this commit was AI assisted. * fix: use ts-expect-error for @joplin/turndown-plugin-gfm types CI's tsc does not pick up ambient declarations.d.ts files despite local tsc finding them — likely a module resolution discrepancy between environments. Revert to @ts-expect-error which passes in both CI and local typecheck. For provenance purposes, this commit was AI assisted. * fix(annotate): body size limit for URL fetches, redirect error, file: protocol - Add 10MB body size limit to both Jina and fetch+Turndown URL paths, matching the local HTML file guard. Streams response body and aborts if limit exceeded. - Distinguish "Too many redirects" from a genuine 3xx response after redirect loop exhaustion. - Add file: to the dangerous protocol blocklist in sanitizeLinkUrl. For provenance purposes, this commit was AI assisted. * fix(annotate): HTML folder outside cwd, HTML linked doc navigation - Remove containment check from base-relative block for HTML files in both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML files in annotated folders outside cwd are served correctly. Standalone block (no base) retains its cwd check as fallback. - Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked documents. Clicking [Next](next.html) in a converted page now opens it via /api/doc with Turndown conversion instead of a new browser tab. For provenance purposes, this commit was AI assisted. * fix(annotate): full loopback range, drain redirect bodies, document env vars - Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8 range so all loopback addresses skip Jina Reader - Cancel redirect response body before re-fetching to avoid leaking TCP connections back to the pool - Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table For provenance purposes, this commit was AI assisted. * fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments - Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves brackets for IPv6 (verified: Bun and Node both return "[::1]"). Add comment explaining the empirical verification so future reviewers don't re-flag. - Fix readBodyWithLimit null-body fallback to still enforce the 10MB limit via text length check instead of silently falling through. - Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table (CLAUDE.md is a symlink to AGENTS.md). - Add comments to base-relative blocks in both Bun and Pi handleDoc explaining the intentional lack of containment check (matches pre-existing markdown behavior, base is set server-side). For provenance purposes, this commit was AI assisted. * fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges: - ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1]) - fe80: (link-local) - fc00::/7 (unique-local, covers fc00:: through fdff::) Closes the redirect-SSRF bypass where a public URL redirects to a private address expressed as IPv4-mapped IPv6, e.g. http://[::ffff:169.254.169.254]/latest/meta-data/ For provenance purposes, this commit was AI assisted. * fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow - Expand isLocalUrl comment with full empirical verification table showing actual hostname getter output for every IPv6 format in both Bun and Node — prevents false-positive review findings about brackets - Add sourceInfo to /api/plan response type in App.tsx for type safety - Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder input types For provenance purposes, this commit was AI assisted. * fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo - Add ( to backslash escape regex alongside existing ) — Turndown emits \( in link-adjacent contexts - Cancel response body before throwing on !res.ok in both fetchViaJina and fetchViaTurndown error paths (redirect loop already did this) - Document sourceInfo field in AGENTS.md annotate server API table For provenance purposes, this commit was AI assisted. * fix(annotate): skip base injection for URL annotations, body cleanup - Skip dirname(filePath) base injection when filePath is a URL in both Bun and Pi annotate servers. dirname on a URL string produces a nonsensical filesystem path, causing linked doc clicks to 404. URL annotations now let links open normally instead. - Cancel response body before throwing on content-type mismatch and content-length overflow in fetchViaTurndown/readBodyWithLimit. - Fix double parseInt in readBodyWithLimit content-length check. - Correct AGENTS.md flow diagram: OpenCode not yet implemented for HTML/URL annotation. For provenance purposes, this commit was AI assisted. * feat(annotate): OpenCode HTML file and URL annotation support Add URL detection (Jina Reader + fallback), HTML file detection with Turndown conversion, 10MB file size guard, and sourceInfo threading to OpenCode's handleAnnotateCommand. Uses the same shared utilities as the Bun CLI and Pi extension. OpenCode uses the Bun server directly (startAnnotateServer from @plannotator/server/annotate), so no server-side changes needed — only the command handler routing was missing. Note: folder annotation mode is not added (OpenCode didn't have it before this PR for markdown either — separate scope). For provenance purposes, this commit was AI assisted. * chore(annotate): update slash command description, align fetch log messages - OpenCode plannotator-annotate.md description now mentions HTML/URL - Align fetch progress messages across all three clients: all now show "(via Jina Reader)" or "(via fetch+Turndown)" consistently For provenance purposes, this commit was AI assisted. * fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup - URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown. Content is already markdown. Removes text/plain from fetchViaTurndown content-type whitelist since .md URLs are now short-circuited. - Wikilink regex widened to preserve .html/.htm targets instead of appending .md (e.g. [[page.html]] no longer becomes page.html.md) - Remove redundant existsSync before statSync in OpenCode handler For provenance purposes, this commit was AI assisted. * test(annotate): add htmlToMarkdown conversion tests Tests cover the core conversion utility that all three clients depend on: - Basic HTML → markdown (headings, paragraphs, links, code blocks) - Tables with and without <thead> (the GFM plugin bug that was caught) - Script/style/noscript stripping - Strikethrough (GFM) - Empty HTML handling - Dangerous links preserved (sanitization is in the renderer, not here) For provenance purposes, this commit was AI assisted. * fix(annotate): check content-type before treating .md URLs as raw markdown URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md) may return HTML instead of raw markdown. fetchRawText now checks the response content-type — if the server returns HTML, returns null so the caller falls through to Jina/Turndown for proper conversion. For provenance purposes, this commit was AI assisted. * fix(annotate): add SSRF redirect protection to fetchRawText fetchRawText (for .md/.mdx URLs) was using default redirect: "follow" with no isLocalUrl validation on redirect hops — a .md URL redirecting to 169.254.169.254 would be followed and credentials returned as "markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks, matching fetchViaTurndown's SSRF protection. For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
sourceInfo,
sourceConverted,
rawHtml,
renderHtml: renderHtmlFlag,
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
sharingEnabled: await getSharingEnabled(),
shareBaseUrl: getShareBaseUrl(),
pasteApiUrl: getPasteApiUrl(),
gate,
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
htmlContent,
onReady: (url, isRemote, port) => {
handleAnnotateServerReady(url, isRemote, port);
if (isRemote) {
client.app.log({ level: "info", message: `[Plannotator] Open in browser: ${url}` });
}
},
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
});
const result = await server.waitForDecision();
await Bun.sleep(1500);
server.stop();
// Both exit and approve are "no-op for the agent" — skip session injection.
if (result.exit || result.approved) {
return;
}
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
if (result.feedback) {
// @ts-ignore - Event properties contain sessionID
const sessionId = event.properties?.sessionID;
if (sessionId) {
try {
await client.session.prompt({
path: { id: sessionId },
body: {
parts: [{
type: "text",
text: getAnnotateFileFeedbackPrompt("opencode", undefined, {
fileHeader: isFolder ? "Folder" : "File",
filePath: absolutePath,
feedback: result.feedback,
}),
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
}],
},
});
} catch {
// Session may not be available
}
}
}
}
/**
* Handle /plannotator-last command.
* Called from command.execute.before — returns the feedback string
* so the caller can set it as output.parts for the agent to see.
*/
export async function handleAnnotateLastCommand(
event: any,
deps: CommandDeps
): Promise<string | null> {
const { client, htmlContent, getSharingEnabled, getShareBaseUrl, getPasteApiUrl } = deps;
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
// @ts-ignore - Event properties contain arguments
const rawArgs = event.properties?.arguments || event.arguments || "";
annotate-last: pick which message to annotate (fixes #800) (#809) * feat: message picker for annotate-last (#800) When running /plannotator-last after /rewind, the newest transcript entry is no longer the message the user intended to annotate, and there was no affordance to pick a different one. Adds a picker UI that surfaces the recent assistant messages so the user can choose which one to annotate: - A "Message N of M" button in the Viewer's sticky-top action bar (alongside Copy / Global comment / Attachments), so it stays accessible while scrolling. - A "Messages" tab in the left sidebar with the full list (newest-first, preview + timestamp, default ★), mirroring the existing Files / Versions / Archive tab pattern. Wired for Claude Code, Codex, and Droid (all share apps/hook/server). OpenCode, Pi, and Copilot still get the original single-message behavior — they don't emit recentMessages, so the picker affordances hide cleanly. Default selection (index 0) matches today's "last message" behavior, so users who don't interact with the picker see no change. * feat: extend annotate-last picker to Copilot and OpenCode The picker UI from #800 was wired for Claude / Codex / Droid only. Pull Copilot and OpenCode onto the same shape so users on those harnesses also get the recent-messages picker when annotating the last assistant message. - Copilot: replace getLastCopilotMessage with getRecentCopilotMessages, walking events.jsonl newest-first up to 25 assistant.message events. - OpenCode: rewrite the session walk to collect up to 25 messages (newest first) instead of bailing on the first hit; normalize the SDK time.created (ms epoch) to ISO to match the shared picker contract. - Both pass recentMessages to startAnnotateServer only when length > 1, matching the existing Claude/Codex/Droid behavior. Also trims a leftover narrating comment in MessagesBrowser and refreshes the stale Copilot session-parser header. Pi parity follows in the next commit (needs round-trip of the picker selection through /api/feedback so its post-submit anchoring quotes the right message). * feat(pi): wire annotate-last picker with feedback round-trip Extends the picker UI (#800) to Pi and fixes a Pi-specific anchoring bug the picker would otherwise introduce. Picker plumbing - assistant-message: getRecentAssistantMessages walks the active branch newest-first, returning { messageId, text, timestamp? } in the same shape the other harnesses produce. - Plumbed through plannotator-browser / plannotator-events so the Bun server's recentMessages option is populated when the branch has more than one assistant message. Anchoring fix - Pi quotes the targeted assistant message back to the agent because its UX is async — the conversation may have moved on by feedback time. With the picker, that target is no longer guaranteed to be the snapshot taken when the UI opened. The editor now sends the user's selectedMessageId with /api/feedback; Pi looks it up in the current branch via findAssistantMessageByEntryId and quotes that message instead. Falls back to the original snapshot if the entry is gone. - The round-trip field is optional and only meaningful in annotate-last mode; other harnesses (and other modes) ignore it. Timestamp safety - Pi's SDK currently types SessionEntryBase.timestamp as string, but the picker contract everywhere else is ISO. Treat the value as unknown and normalize string/number(ms)/Date to ISO; drop anything else, rather than blind-casting and risking silent drift if the SDK changes. * chore: strip issue-number references from comments Comments shouldn't rely on external references — issue numbers age out of context, link rot is a thing, and a reader shouldn't need to open GitHub to understand why a line exists. Strip the `(#800)` and `(#570)` parentheticals from comments and doc strings across the picker and review-gate code; the surrounding "why" content is preserved. * fix: prevent removeChild crash when switching annotate-last messages Switching the picked message remounted nothing, so React reconciled new content against DOM that web-highlighter had mutated with <mark> nodes, throwing removeChild. Drive the Viewer key (and StickyHeaderLane's remount token) off a shared viewerContentKey so a message switch fully remounts the Viewer and re-anchors the sticky-header observer. Also cap MessagesBrowser row previews via previewText() and drop the redundant 'block' class that was overriding line-clamp-2. * feat: persist annotate-last feedback across messages --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-03 13:01:36 -07:00
// Support --gate on /plannotator-last (Stop-hook review-gate pattern).
const { gate } = parseAnnotateArgs(rawArgs);
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
// @ts-ignore - Event properties contain sessionID
const sessionId = event.properties?.sessionID;
if (!sessionId) {
client.app.log({ level: "error", message: "No active session." });
return null;
}
// Fetch messages from session
const messagesResponse = await client.session.messages({
path: { id: sessionId },
});
const messages = messagesResponse.data;
annotate-last: pick which message to annotate (fixes #800) (#809) * feat: message picker for annotate-last (#800) When running /plannotator-last after /rewind, the newest transcript entry is no longer the message the user intended to annotate, and there was no affordance to pick a different one. Adds a picker UI that surfaces the recent assistant messages so the user can choose which one to annotate: - A "Message N of M" button in the Viewer's sticky-top action bar (alongside Copy / Global comment / Attachments), so it stays accessible while scrolling. - A "Messages" tab in the left sidebar with the full list (newest-first, preview + timestamp, default ★), mirroring the existing Files / Versions / Archive tab pattern. Wired for Claude Code, Codex, and Droid (all share apps/hook/server). OpenCode, Pi, and Copilot still get the original single-message behavior — they don't emit recentMessages, so the picker affordances hide cleanly. Default selection (index 0) matches today's "last message" behavior, so users who don't interact with the picker see no change. * feat: extend annotate-last picker to Copilot and OpenCode The picker UI from #800 was wired for Claude / Codex / Droid only. Pull Copilot and OpenCode onto the same shape so users on those harnesses also get the recent-messages picker when annotating the last assistant message. - Copilot: replace getLastCopilotMessage with getRecentCopilotMessages, walking events.jsonl newest-first up to 25 assistant.message events. - OpenCode: rewrite the session walk to collect up to 25 messages (newest first) instead of bailing on the first hit; normalize the SDK time.created (ms epoch) to ISO to match the shared picker contract. - Both pass recentMessages to startAnnotateServer only when length > 1, matching the existing Claude/Codex/Droid behavior. Also trims a leftover narrating comment in MessagesBrowser and refreshes the stale Copilot session-parser header. Pi parity follows in the next commit (needs round-trip of the picker selection through /api/feedback so its post-submit anchoring quotes the right message). * feat(pi): wire annotate-last picker with feedback round-trip Extends the picker UI (#800) to Pi and fixes a Pi-specific anchoring bug the picker would otherwise introduce. Picker plumbing - assistant-message: getRecentAssistantMessages walks the active branch newest-first, returning { messageId, text, timestamp? } in the same shape the other harnesses produce. - Plumbed through plannotator-browser / plannotator-events so the Bun server's recentMessages option is populated when the branch has more than one assistant message. Anchoring fix - Pi quotes the targeted assistant message back to the agent because its UX is async — the conversation may have moved on by feedback time. With the picker, that target is no longer guaranteed to be the snapshot taken when the UI opened. The editor now sends the user's selectedMessageId with /api/feedback; Pi looks it up in the current branch via findAssistantMessageByEntryId and quotes that message instead. Falls back to the original snapshot if the entry is gone. - The round-trip field is optional and only meaningful in annotate-last mode; other harnesses (and other modes) ignore it. Timestamp safety - Pi's SDK currently types SessionEntryBase.timestamp as string, but the picker contract everywhere else is ISO. Treat the value as unknown and normalize string/number(ms)/Date to ISO; drop anything else, rather than blind-casting and risking silent drift if the SDK changes. * chore: strip issue-number references from comments Comments shouldn't rely on external references — issue numbers age out of context, link rot is a thing, and a reader shouldn't need to open GitHub to understand why a line exists. Strip the `(#800)` and `(#570)` parentheticals from comments and doc strings across the picker and review-gate code; the surrounding "why" content is preserved. * fix: prevent removeChild crash when switching annotate-last messages Switching the picked message remounted nothing, so React reconciled new content against DOM that web-highlighter had mutated with <mark> nodes, throwing removeChild. Drive the Viewer key (and StickyHeaderLane's remount token) off a shared viewerContentKey so a message switch fully remounts the Viewer and re-anchors the sticky-header observer. Also cap MessagesBrowser row previews via previewText() and drop the redundant 'block' class that was overriding line-clamp-2. * feat: persist annotate-last feedback across messages --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-03 13:01:36 -07:00
const RECENT_LIMIT = 25;
const recentMessages: { messageId: string; text: string; timestamp?: string }[] = [];
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
if (messages) {
annotate-last: pick which message to annotate (fixes #800) (#809) * feat: message picker for annotate-last (#800) When running /plannotator-last after /rewind, the newest transcript entry is no longer the message the user intended to annotate, and there was no affordance to pick a different one. Adds a picker UI that surfaces the recent assistant messages so the user can choose which one to annotate: - A "Message N of M" button in the Viewer's sticky-top action bar (alongside Copy / Global comment / Attachments), so it stays accessible while scrolling. - A "Messages" tab in the left sidebar with the full list (newest-first, preview + timestamp, default ★), mirroring the existing Files / Versions / Archive tab pattern. Wired for Claude Code, Codex, and Droid (all share apps/hook/server). OpenCode, Pi, and Copilot still get the original single-message behavior — they don't emit recentMessages, so the picker affordances hide cleanly. Default selection (index 0) matches today's "last message" behavior, so users who don't interact with the picker see no change. * feat: extend annotate-last picker to Copilot and OpenCode The picker UI from #800 was wired for Claude / Codex / Droid only. Pull Copilot and OpenCode onto the same shape so users on those harnesses also get the recent-messages picker when annotating the last assistant message. - Copilot: replace getLastCopilotMessage with getRecentCopilotMessages, walking events.jsonl newest-first up to 25 assistant.message events. - OpenCode: rewrite the session walk to collect up to 25 messages (newest first) instead of bailing on the first hit; normalize the SDK time.created (ms epoch) to ISO to match the shared picker contract. - Both pass recentMessages to startAnnotateServer only when length > 1, matching the existing Claude/Codex/Droid behavior. Also trims a leftover narrating comment in MessagesBrowser and refreshes the stale Copilot session-parser header. Pi parity follows in the next commit (needs round-trip of the picker selection through /api/feedback so its post-submit anchoring quotes the right message). * feat(pi): wire annotate-last picker with feedback round-trip Extends the picker UI (#800) to Pi and fixes a Pi-specific anchoring bug the picker would otherwise introduce. Picker plumbing - assistant-message: getRecentAssistantMessages walks the active branch newest-first, returning { messageId, text, timestamp? } in the same shape the other harnesses produce. - Plumbed through plannotator-browser / plannotator-events so the Bun server's recentMessages option is populated when the branch has more than one assistant message. Anchoring fix - Pi quotes the targeted assistant message back to the agent because its UX is async — the conversation may have moved on by feedback time. With the picker, that target is no longer guaranteed to be the snapshot taken when the UI opened. The editor now sends the user's selectedMessageId with /api/feedback; Pi looks it up in the current branch via findAssistantMessageByEntryId and quotes that message instead. Falls back to the original snapshot if the entry is gone. - The round-trip field is optional and only meaningful in annotate-last mode; other harnesses (and other modes) ignore it. Timestamp safety - Pi's SDK currently types SessionEntryBase.timestamp as string, but the picker contract everywhere else is ISO. Treat the value as unknown and normalize string/number(ms)/Date to ISO; drop anything else, rather than blind-casting and risking silent drift if the SDK changes. * chore: strip issue-number references from comments Comments shouldn't rely on external references — issue numbers age out of context, link rot is a thing, and a reader shouldn't need to open GitHub to understand why a line exists. Strip the `(#800)` and `(#570)` parentheticals from comments and doc strings across the picker and review-gate code; the surrounding "why" content is preserved. * fix: prevent removeChild crash when switching annotate-last messages Switching the picked message remounted nothing, so React reconciled new content against DOM that web-highlighter had mutated with <mark> nodes, throwing removeChild. Drive the Viewer key (and StickyHeaderLane's remount token) off a shared viewerContentKey so a message switch fully remounts the Viewer and re-anchors the sticky-header observer. Also cap MessagesBrowser row previews via previewText() and drop the redundant 'block' class that was overriding line-clamp-2. * feat: persist annotate-last feedback across messages --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-03 13:01:36 -07:00
for (let i = messages.length - 1; i >= 0 && recentMessages.length < RECENT_LIMIT; i--) {
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
const msg = messages[i];
annotate-last: pick which message to annotate (fixes #800) (#809) * feat: message picker for annotate-last (#800) When running /plannotator-last after /rewind, the newest transcript entry is no longer the message the user intended to annotate, and there was no affordance to pick a different one. Adds a picker UI that surfaces the recent assistant messages so the user can choose which one to annotate: - A "Message N of M" button in the Viewer's sticky-top action bar (alongside Copy / Global comment / Attachments), so it stays accessible while scrolling. - A "Messages" tab in the left sidebar with the full list (newest-first, preview + timestamp, default ★), mirroring the existing Files / Versions / Archive tab pattern. Wired for Claude Code, Codex, and Droid (all share apps/hook/server). OpenCode, Pi, and Copilot still get the original single-message behavior — they don't emit recentMessages, so the picker affordances hide cleanly. Default selection (index 0) matches today's "last message" behavior, so users who don't interact with the picker see no change. * feat: extend annotate-last picker to Copilot and OpenCode The picker UI from #800 was wired for Claude / Codex / Droid only. Pull Copilot and OpenCode onto the same shape so users on those harnesses also get the recent-messages picker when annotating the last assistant message. - Copilot: replace getLastCopilotMessage with getRecentCopilotMessages, walking events.jsonl newest-first up to 25 assistant.message events. - OpenCode: rewrite the session walk to collect up to 25 messages (newest first) instead of bailing on the first hit; normalize the SDK time.created (ms epoch) to ISO to match the shared picker contract. - Both pass recentMessages to startAnnotateServer only when length > 1, matching the existing Claude/Codex/Droid behavior. Also trims a leftover narrating comment in MessagesBrowser and refreshes the stale Copilot session-parser header. Pi parity follows in the next commit (needs round-trip of the picker selection through /api/feedback so its post-submit anchoring quotes the right message). * feat(pi): wire annotate-last picker with feedback round-trip Extends the picker UI (#800) to Pi and fixes a Pi-specific anchoring bug the picker would otherwise introduce. Picker plumbing - assistant-message: getRecentAssistantMessages walks the active branch newest-first, returning { messageId, text, timestamp? } in the same shape the other harnesses produce. - Plumbed through plannotator-browser / plannotator-events so the Bun server's recentMessages option is populated when the branch has more than one assistant message. Anchoring fix - Pi quotes the targeted assistant message back to the agent because its UX is async — the conversation may have moved on by feedback time. With the picker, that target is no longer guaranteed to be the snapshot taken when the UI opened. The editor now sends the user's selectedMessageId with /api/feedback; Pi looks it up in the current branch via findAssistantMessageByEntryId and quotes that message instead. Falls back to the original snapshot if the entry is gone. - The round-trip field is optional and only meaningful in annotate-last mode; other harnesses (and other modes) ignore it. Timestamp safety - Pi's SDK currently types SessionEntryBase.timestamp as string, but the picker contract everywhere else is ISO. Treat the value as unknown and normalize string/number(ms)/Date to ISO; drop anything else, rather than blind-casting and risking silent drift if the SDK changes. * chore: strip issue-number references from comments Comments shouldn't rely on external references — issue numbers age out of context, link rot is a thing, and a reader shouldn't need to open GitHub to understand why a line exists. Strip the `(#800)` and `(#570)` parentheticals from comments and doc strings across the picker and review-gate code; the surrounding "why" content is preserved. * fix: prevent removeChild crash when switching annotate-last messages Switching the picked message remounted nothing, so React reconciled new content against DOM that web-highlighter had mutated with <mark> nodes, throwing removeChild. Drive the Viewer key (and StickyHeaderLane's remount token) off a shared viewerContentKey so a message switch fully remounts the Viewer and re-anchors the sticky-header observer. Also cap MessagesBrowser row previews via previewText() and drop the redundant 'block' class that was overriding line-clamp-2. * feat: persist annotate-last feedback across messages --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-03 13:01:36 -07:00
if (msg.info.role !== "assistant") continue;
const textParts = msg.parts
.filter((p: any) => p.type === "text" && p.text?.trim())
.map((p: any) => p.text);
if (textParts.length === 0) continue;
recentMessages.push({
messageId: msg.info.id ?? `opencode-${i}`,
text: textParts.join("\n"),
timestamp: msg.info.time?.created ? new Date(msg.info.time.created).toISOString() : undefined,
});
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
}
}
annotate-last: pick which message to annotate (fixes #800) (#809) * feat: message picker for annotate-last (#800) When running /plannotator-last after /rewind, the newest transcript entry is no longer the message the user intended to annotate, and there was no affordance to pick a different one. Adds a picker UI that surfaces the recent assistant messages so the user can choose which one to annotate: - A "Message N of M" button in the Viewer's sticky-top action bar (alongside Copy / Global comment / Attachments), so it stays accessible while scrolling. - A "Messages" tab in the left sidebar with the full list (newest-first, preview + timestamp, default ★), mirroring the existing Files / Versions / Archive tab pattern. Wired for Claude Code, Codex, and Droid (all share apps/hook/server). OpenCode, Pi, and Copilot still get the original single-message behavior — they don't emit recentMessages, so the picker affordances hide cleanly. Default selection (index 0) matches today's "last message" behavior, so users who don't interact with the picker see no change. * feat: extend annotate-last picker to Copilot and OpenCode The picker UI from #800 was wired for Claude / Codex / Droid only. Pull Copilot and OpenCode onto the same shape so users on those harnesses also get the recent-messages picker when annotating the last assistant message. - Copilot: replace getLastCopilotMessage with getRecentCopilotMessages, walking events.jsonl newest-first up to 25 assistant.message events. - OpenCode: rewrite the session walk to collect up to 25 messages (newest first) instead of bailing on the first hit; normalize the SDK time.created (ms epoch) to ISO to match the shared picker contract. - Both pass recentMessages to startAnnotateServer only when length > 1, matching the existing Claude/Codex/Droid behavior. Also trims a leftover narrating comment in MessagesBrowser and refreshes the stale Copilot session-parser header. Pi parity follows in the next commit (needs round-trip of the picker selection through /api/feedback so its post-submit anchoring quotes the right message). * feat(pi): wire annotate-last picker with feedback round-trip Extends the picker UI (#800) to Pi and fixes a Pi-specific anchoring bug the picker would otherwise introduce. Picker plumbing - assistant-message: getRecentAssistantMessages walks the active branch newest-first, returning { messageId, text, timestamp? } in the same shape the other harnesses produce. - Plumbed through plannotator-browser / plannotator-events so the Bun server's recentMessages option is populated when the branch has more than one assistant message. Anchoring fix - Pi quotes the targeted assistant message back to the agent because its UX is async — the conversation may have moved on by feedback time. With the picker, that target is no longer guaranteed to be the snapshot taken when the UI opened. The editor now sends the user's selectedMessageId with /api/feedback; Pi looks it up in the current branch via findAssistantMessageByEntryId and quotes that message instead. Falls back to the original snapshot if the entry is gone. - The round-trip field is optional and only meaningful in annotate-last mode; other harnesses (and other modes) ignore it. Timestamp safety - Pi's SDK currently types SessionEntryBase.timestamp as string, but the picker contract everywhere else is ISO. Treat the value as unknown and normalize string/number(ms)/Date to ISO; drop anything else, rather than blind-casting and risking silent drift if the SDK changes. * chore: strip issue-number references from comments Comments shouldn't rely on external references — issue numbers age out of context, link rot is a thing, and a reader shouldn't need to open GitHub to understand why a line exists. Strip the `(#800)` and `(#570)` parentheticals from comments and doc strings across the picker and review-gate code; the surrounding "why" content is preserved. * fix: prevent removeChild crash when switching annotate-last messages Switching the picked message remounted nothing, so React reconciled new content against DOM that web-highlighter had mutated with <mark> nodes, throwing removeChild. Drive the Viewer key (and StickyHeaderLane's remount token) off a shared viewerContentKey so a message switch fully remounts the Viewer and re-anchors the sticky-header observer. Also cap MessagesBrowser row previews via previewText() and drop the redundant 'block' class that was overriding line-clamp-2. * feat: persist annotate-last feedback across messages --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-03 13:01:36 -07:00
const lastText = recentMessages[0]?.text ?? null;
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
if (!lastText) {
client.app.log({ level: "error", message: "No assistant message found in session." });
return null;
}
client.app.log({ level: "info", message: "Opening annotation UI for last message..." });
annotate-last: pick which message to annotate (fixes #800) (#809) * feat: message picker for annotate-last (#800) When running /plannotator-last after /rewind, the newest transcript entry is no longer the message the user intended to annotate, and there was no affordance to pick a different one. Adds a picker UI that surfaces the recent assistant messages so the user can choose which one to annotate: - A "Message N of M" button in the Viewer's sticky-top action bar (alongside Copy / Global comment / Attachments), so it stays accessible while scrolling. - A "Messages" tab in the left sidebar with the full list (newest-first, preview + timestamp, default ★), mirroring the existing Files / Versions / Archive tab pattern. Wired for Claude Code, Codex, and Droid (all share apps/hook/server). OpenCode, Pi, and Copilot still get the original single-message behavior — they don't emit recentMessages, so the picker affordances hide cleanly. Default selection (index 0) matches today's "last message" behavior, so users who don't interact with the picker see no change. * feat: extend annotate-last picker to Copilot and OpenCode The picker UI from #800 was wired for Claude / Codex / Droid only. Pull Copilot and OpenCode onto the same shape so users on those harnesses also get the recent-messages picker when annotating the last assistant message. - Copilot: replace getLastCopilotMessage with getRecentCopilotMessages, walking events.jsonl newest-first up to 25 assistant.message events. - OpenCode: rewrite the session walk to collect up to 25 messages (newest first) instead of bailing on the first hit; normalize the SDK time.created (ms epoch) to ISO to match the shared picker contract. - Both pass recentMessages to startAnnotateServer only when length > 1, matching the existing Claude/Codex/Droid behavior. Also trims a leftover narrating comment in MessagesBrowser and refreshes the stale Copilot session-parser header. Pi parity follows in the next commit (needs round-trip of the picker selection through /api/feedback so its post-submit anchoring quotes the right message). * feat(pi): wire annotate-last picker with feedback round-trip Extends the picker UI (#800) to Pi and fixes a Pi-specific anchoring bug the picker would otherwise introduce. Picker plumbing - assistant-message: getRecentAssistantMessages walks the active branch newest-first, returning { messageId, text, timestamp? } in the same shape the other harnesses produce. - Plumbed through plannotator-browser / plannotator-events so the Bun server's recentMessages option is populated when the branch has more than one assistant message. Anchoring fix - Pi quotes the targeted assistant message back to the agent because its UX is async — the conversation may have moved on by feedback time. With the picker, that target is no longer guaranteed to be the snapshot taken when the UI opened. The editor now sends the user's selectedMessageId with /api/feedback; Pi looks it up in the current branch via findAssistantMessageByEntryId and quotes that message instead. Falls back to the original snapshot if the entry is gone. - The round-trip field is optional and only meaningful in annotate-last mode; other harnesses (and other modes) ignore it. Timestamp safety - Pi's SDK currently types SessionEntryBase.timestamp as string, but the picker contract everywhere else is ISO. Treat the value as unknown and normalize string/number(ms)/Date to ISO; drop anything else, rather than blind-casting and risking silent drift if the SDK changes. * chore: strip issue-number references from comments Comments shouldn't rely on external references — issue numbers age out of context, link rot is a thing, and a reader shouldn't need to open GitHub to understand why a line exists. Strip the `(#800)` and `(#570)` parentheticals from comments and doc strings across the picker and review-gate code; the surrounding "why" content is preserved. * fix: prevent removeChild crash when switching annotate-last messages Switching the picked message remounted nothing, so React reconciled new content against DOM that web-highlighter had mutated with <mark> nodes, throwing removeChild. Drive the Viewer key (and StickyHeaderLane's remount token) off a shared viewerContentKey so a message switch fully remounts the Viewer and re-anchors the sticky-header observer. Also cap MessagesBrowser row previews via previewText() and drop the redundant 'block' class that was overriding line-clamp-2. * feat: persist annotate-last feedback across messages --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-03 13:01:36 -07:00
const pickerMessages = recentMessages.length > 1 ? recentMessages : undefined;
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
const server = await startAnnotateServer({
markdown: lastText,
filePath: "last-message",
origin: "opencode",
mode: "annotate-last",
annotate-last: pick which message to annotate (fixes #800) (#809) * feat: message picker for annotate-last (#800) When running /plannotator-last after /rewind, the newest transcript entry is no longer the message the user intended to annotate, and there was no affordance to pick a different one. Adds a picker UI that surfaces the recent assistant messages so the user can choose which one to annotate: - A "Message N of M" button in the Viewer's sticky-top action bar (alongside Copy / Global comment / Attachments), so it stays accessible while scrolling. - A "Messages" tab in the left sidebar with the full list (newest-first, preview + timestamp, default ★), mirroring the existing Files / Versions / Archive tab pattern. Wired for Claude Code, Codex, and Droid (all share apps/hook/server). OpenCode, Pi, and Copilot still get the original single-message behavior — they don't emit recentMessages, so the picker affordances hide cleanly. Default selection (index 0) matches today's "last message" behavior, so users who don't interact with the picker see no change. * feat: extend annotate-last picker to Copilot and OpenCode The picker UI from #800 was wired for Claude / Codex / Droid only. Pull Copilot and OpenCode onto the same shape so users on those harnesses also get the recent-messages picker when annotating the last assistant message. - Copilot: replace getLastCopilotMessage with getRecentCopilotMessages, walking events.jsonl newest-first up to 25 assistant.message events. - OpenCode: rewrite the session walk to collect up to 25 messages (newest first) instead of bailing on the first hit; normalize the SDK time.created (ms epoch) to ISO to match the shared picker contract. - Both pass recentMessages to startAnnotateServer only when length > 1, matching the existing Claude/Codex/Droid behavior. Also trims a leftover narrating comment in MessagesBrowser and refreshes the stale Copilot session-parser header. Pi parity follows in the next commit (needs round-trip of the picker selection through /api/feedback so its post-submit anchoring quotes the right message). * feat(pi): wire annotate-last picker with feedback round-trip Extends the picker UI (#800) to Pi and fixes a Pi-specific anchoring bug the picker would otherwise introduce. Picker plumbing - assistant-message: getRecentAssistantMessages walks the active branch newest-first, returning { messageId, text, timestamp? } in the same shape the other harnesses produce. - Plumbed through plannotator-browser / plannotator-events so the Bun server's recentMessages option is populated when the branch has more than one assistant message. Anchoring fix - Pi quotes the targeted assistant message back to the agent because its UX is async — the conversation may have moved on by feedback time. With the picker, that target is no longer guaranteed to be the snapshot taken when the UI opened. The editor now sends the user's selectedMessageId with /api/feedback; Pi looks it up in the current branch via findAssistantMessageByEntryId and quotes that message instead. Falls back to the original snapshot if the entry is gone. - The round-trip field is optional and only meaningful in annotate-last mode; other harnesses (and other modes) ignore it. Timestamp safety - Pi's SDK currently types SessionEntryBase.timestamp as string, but the picker contract everywhere else is ISO. Treat the value as unknown and normalize string/number(ms)/Date to ISO; drop anything else, rather than blind-casting and risking silent drift if the SDK changes. * chore: strip issue-number references from comments Comments shouldn't rely on external references — issue numbers age out of context, link rot is a thing, and a reader shouldn't need to open GitHub to understand why a line exists. Strip the `(#800)` and `(#570)` parentheticals from comments and doc strings across the picker and review-gate code; the surrounding "why" content is preserved. * fix: prevent removeChild crash when switching annotate-last messages Switching the picked message remounted nothing, so React reconciled new content against DOM that web-highlighter had mutated with <mark> nodes, throwing removeChild. Drive the Viewer key (and StickyHeaderLane's remount token) off a shared viewerContentKey so a message switch fully remounts the Viewer and re-anchors the sticky-header observer. Also cap MessagesBrowser row previews via previewText() and drop the redundant 'block' class that was overriding line-clamp-2. * feat: persist annotate-last feedback across messages --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-03 13:01:36 -07:00
recentMessages: pickerMessages,
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
sharingEnabled: await getSharingEnabled(),
shareBaseUrl: getShareBaseUrl(),
pasteApiUrl: getPasteApiUrl(),
gate,
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
htmlContent,
onReady: (url, isRemote, port) => {
handleAnnotateServerReady(url, isRemote, port);
if (isRemote) {
client.app.log({ level: "info", message: `[Plannotator] Open in browser: ${url}` });
}
},
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
});
const result = await server.waitForDecision();
await Bun.sleep(1500);
server.stop();
// Both exit and approve signal "don't inject feedback" — return null.
if (result.exit || result.approved) {
return null;
}
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type 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-17 23:49:34 -07:00
return result.feedback || null;
}
export async function handleArchiveCommand(
event: any,
deps: CommandDeps
) {
const { client, htmlContent, getSharingEnabled, getShareBaseUrl, getPasteApiUrl } = deps;
client.app.log({ level: "info", message: "Opening plan archive..." });
const server = await startPlannotatorServer({
plan: "",
origin: "opencode",
mode: "archive",
sharingEnabled: await getSharingEnabled(),
shareBaseUrl: getShareBaseUrl(),
pasteApiUrl: getPasteApiUrl(),
htmlContent,
onReady: (url, isRemote, port) => {
handleServerReady(url, isRemote, port);
if (isRemote) {
client.app.log({ level: "info", message: `[Plannotator] Open in browser: ${url}` });
}
},
});
if (server.waitForDone) {
await server.waitForDone();
}
await Bun.sleep(1500);
server.stop();
}