Files
backnotprop__plannotator/apps/hook/server/index.ts
T

382 lines
11 KiB
TypeScript
Raw Normal View History

/**
* Plannotator CLI for Claude Code
*
* Supports four modes:
*
* 1. Plan Review (default, no args):
* - Spawned by ExitPlanMode hook
* - Reads hook event from stdin, extracts plan content
* - Serves UI, returns approve/deny decision to stdout
*
* 2. Code Review (`plannotator review`):
* - Triggered by /review slash command
* - Runs git diff, opens review UI
* - Outputs feedback to stdout (captured by slash command)
*
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
* 3. Annotate (`plannotator annotate <file.md>`):
* - Triggered by /plannotator-annotate slash command
* - Opens any markdown file in the annotation UI
* - Outputs structured feedback to stdout
*
* 4. Sessions (`plannotator sessions`):
* - Lists active Plannotator server sessions
* - `--open [N]` reopens a session in the browser
* - `--clean` removes stale session files
*
* Global flags:
* --browser <name> - Override which browser to open (e.g. "Google Chrome")
*
* Environment variables:
Fix/devcontainer & plan auto switching (opencode) (#31) * Refactor: shared server package with PLANNOTATOR_REMOTE env var - Create packages/server/ with shared server implementation - Add PLANNOTATOR_REMOTE=1 env var for devcontainer/SSH mode - Deprecate SSH_CONNECTION detection (still works with warning) - Both Claude Code and OpenCode now use identical server logic - OpenCode gains Obsidian/Bear integrations and remote detection - Update documentation with environment variables section Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove PLANNOTATOR_ORIGIN env var, fix onReady callback timing - Remove PLANNOTATOR_ORIGIN hack from Claude Code hook (hardcode "claude-code") - Fix onReady callback to pass port directly (was referencing undefined server) - Create tests/manual/test-server.ts for testing either origin - Update test-hook-2.sh to use new test server with opencode origin 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer test setup, reduce logging verbosity - Add tests/devcontainer/ with devcontainer.json for testing remote mode - Add tests/opencode-local/ for local OpenCode testing - Update package.json build script for proper bundling - Remove verbose multi-line error messages, keep useful errors - Clean up unused deprecationWarned variable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer support and documentation - Add PLANNOTATOR_REMOTE env var for container/remote detection - Remove console logging (silent operation) - Add devcontainer.md with full setup instructions - Add devcontainer section to OpenCode plugin README - Add port-only test setup to reproduce common misconfiguration - Update test devcontainers to forward port 4096 for opencode web - Bump version to 0.4.1 Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update CLAUDE.md: legacy SSH detection, not deprecated Removed incorrect mention of deprecation warning - SSH_TTY/SSH_CONNECTION detection is silent by design. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix OpenCode agent switching after plan approval After approving a plan, the conversation context stayed in "plan" mode even though the TUI showed "build". This caused edits to fail because the plan agent has edit permissions denied. The fix uses session.prompt() to inject a message with agent: "build", which triggers a new agentic loop with proper build agent permissions. Fixes #29 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:25:19 -08:00
* PLANNOTATOR_REMOTE - Set to "1" or "true" for remote mode (preferred)
* PLANNOTATOR_PORT - Fixed port to use (default: random locally, 19432 for remote)
*/
Fix/devcontainer & plan auto switching (opencode) (#31) * Refactor: shared server package with PLANNOTATOR_REMOTE env var - Create packages/server/ with shared server implementation - Add PLANNOTATOR_REMOTE=1 env var for devcontainer/SSH mode - Deprecate SSH_CONNECTION detection (still works with warning) - Both Claude Code and OpenCode now use identical server logic - OpenCode gains Obsidian/Bear integrations and remote detection - Update documentation with environment variables section Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove PLANNOTATOR_ORIGIN env var, fix onReady callback timing - Remove PLANNOTATOR_ORIGIN hack from Claude Code hook (hardcode "claude-code") - Fix onReady callback to pass port directly (was referencing undefined server) - Create tests/manual/test-server.ts for testing either origin - Update test-hook-2.sh to use new test server with opencode origin 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer test setup, reduce logging verbosity - Add tests/devcontainer/ with devcontainer.json for testing remote mode - Add tests/opencode-local/ for local OpenCode testing - Update package.json build script for proper bundling - Remove verbose multi-line error messages, keep useful errors - Clean up unused deprecationWarned variable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer support and documentation - Add PLANNOTATOR_REMOTE env var for container/remote detection - Remove console logging (silent operation) - Add devcontainer.md with full setup instructions - Add devcontainer section to OpenCode plugin README - Add port-only test setup to reproduce common misconfiguration - Update test devcontainers to forward port 4096 for opencode web - Bump version to 0.4.1 Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update CLAUDE.md: legacy SSH detection, not deprecated Removed incorrect mention of deprecation warning - SSH_TTY/SSH_CONNECTION detection is silent by design. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix OpenCode agent switching after plan approval After approving a plan, the conversation context stayed in "plan" mode even though the TUI showed "build". This caused edits to fail because the plan agent has edit permissions denied. The fix uses session.prompt() to inject a message with agent: "build", which triggers a new agentic loop with proper build agent permissions. Fixes #29 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:25:19 -08:00
import {
startPlannotatorServer,
handleServerReady,
} from "@plannotator/server";
import {
startReviewServer,
handleReviewServerReady,
} from "@plannotator/server/review";
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
import {
startAnnotateServer,
handleAnnotateServerReady,
} from "@plannotator/server/annotate";
import { getGitContext, runGitDiff } from "@plannotator/server/git";
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
import { writeRemoteShareLink } from "@plannotator/server/share-url";
import { resolveMarkdownFile } from "@plannotator/server/resolve-file";
import { registerSession, unregisterSession, listSessions } from "@plannotator/server/sessions";
import { openBrowser } from "@plannotator/server/browser";
import { detectProjectName } from "@plannotator/server/project";
refactor: shared feedback templates + preserve plan title on deny (#296) (#298) * refactor: shared feedback templates across all integrations The deny/feedback prompts sent to LLM agents were duplicated as inline string templates in hook, opencode-plugin, and pi-extension — each with different tone and framing. The hook's directive style (from #224) was the most effective at getting agents to address feedback. This extracts all feedback text into @plannotator/shared/feedback-templates and has every integration import from the single source of truth. Closes #215 follow-up (propagates fix to OpenCode and Pi). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: rewrite feedback template tests around contracts not implementation Tests now verify: cross-integration consistency, verbatim feedback preservation, empty input handling, and that approved messages don't contain directive language. Wording can change freely without breaking tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: instruct agent to preserve plan title on resubmission (#296) Version history slugs are derived from the plan's first # heading. When the agent renames the heading after a deny, the version chain breaks and the user loses diffs. The deny template now tells the agent not to change the title unless explicitly asked. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * style: improve plan deny preamble readability Break the dense single-paragraph preamble into structured sections: verdict, directive, and rules list. Easier for agents to parse. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add missing @plannotator/shared workspace dependency Hook and OpenCode plugin imported from @plannotator/shared/feedback-templates without declaring it as a dependency. Worked locally but failed in CI. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * revert: remove code review and annotate from shared templates Scope-crept into code review/annotate feedback which introduced a double heading regression and dropped integration-specific strings. Reverts those paths to their original inline strings; shared module now only covers plan deny feedback. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore Pi plan file hint and vendor template for source installs Add optional planFilePath to planDenyFeedback so Pi can tell the agent to read the plan file before editing. Check in a vendored copy of the template so Pi source installs work without running build:pi first. 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-15 19:38:22 -07:00
import { planDenyFeedback } from "@plannotator/shared/feedback-templates";
import path from "path";
// Embed the built HTML at compile time
Fix/devcontainer & plan auto switching (opencode) (#31) * Refactor: shared server package with PLANNOTATOR_REMOTE env var - Create packages/server/ with shared server implementation - Add PLANNOTATOR_REMOTE=1 env var for devcontainer/SSH mode - Deprecate SSH_CONNECTION detection (still works with warning) - Both Claude Code and OpenCode now use identical server logic - OpenCode gains Obsidian/Bear integrations and remote detection - Update documentation with environment variables section Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove PLANNOTATOR_ORIGIN env var, fix onReady callback timing - Remove PLANNOTATOR_ORIGIN hack from Claude Code hook (hardcode "claude-code") - Fix onReady callback to pass port directly (was referencing undefined server) - Create tests/manual/test-server.ts for testing either origin - Update test-hook-2.sh to use new test server with opencode origin 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer test setup, reduce logging verbosity - Add tests/devcontainer/ with devcontainer.json for testing remote mode - Add tests/opencode-local/ for local OpenCode testing - Update package.json build script for proper bundling - Remove verbose multi-line error messages, keep useful errors - Clean up unused deprecationWarned variable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer support and documentation - Add PLANNOTATOR_REMOTE env var for container/remote detection - Remove console logging (silent operation) - Add devcontainer.md with full setup instructions - Add devcontainer section to OpenCode plugin README - Add port-only test setup to reproduce common misconfiguration - Update test devcontainers to forward port 4096 for opencode web - Bump version to 0.4.1 Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update CLAUDE.md: legacy SSH detection, not deprecated Removed incorrect mention of deprecation warning - SSH_TTY/SSH_CONNECTION detection is silent by design. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix OpenCode agent switching after plan approval After approving a plan, the conversation context stayed in "plan" mode even though the TUI showed "build". This caused edits to fail because the plan agent has edit permissions denied. The fix uses session.prompt() to inject a message with agent: "build", which triggers a new agentic loop with proper build agent permissions. Fixes #29 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:25:19 -08:00
// @ts-ignore - Bun import attribute for text
import planHtml from "../dist/index.html" with { type: "text" };
const planHtmlContent = planHtml as unknown as string;
// @ts-ignore - Bun import attribute for text
import reviewHtml from "../dist/review.html" with { type: "text" };
const reviewHtmlContent = reviewHtml as unknown as string;
// Check for subcommand
const args = process.argv.slice(2);
// Global flag: --browser <name>
const browserIdx = args.indexOf("--browser");
if (browserIdx !== -1 && args[browserIdx + 1]) {
process.env.PLANNOTATOR_BROWSER = args[browserIdx + 1];
args.splice(browserIdx, 2);
}
// Ensure session cleanup on exit
process.on("exit", () => unregisterSession());
// Check if URL sharing is enabled (default: true)
const sharingEnabled = process.env.PLANNOTATOR_SHARE !== "disabled";
// Custom share portal URL for self-hosting
const shareBaseUrl = process.env.PLANNOTATOR_SHARE_URL || undefined;
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
// Paste service URL for short URL sharing
const pasteApiUrl = process.env.PLANNOTATOR_PASTE_URL || undefined;
if (args[0] === "sessions") {
// ============================================
// SESSION DISCOVERY MODE
// ============================================
if (args.includes("--clean")) {
// Force cleanup: list sessions (which auto-removes stale entries)
const sessions = listSessions();
console.error(`Cleaned up stale sessions. ${sessions.length} active session(s) remain.`);
process.exit(0);
}
const sessions = listSessions();
if (sessions.length === 0) {
console.error("No active Plannotator sessions.");
process.exit(0);
}
const openIdx = args.indexOf("--open");
if (openIdx !== -1) {
// Open a session in the browser
const nArg = args[openIdx + 1];
const n = nArg ? parseInt(nArg, 10) : 1;
const session = sessions[n - 1];
if (!session) {
console.error(`Session #${n} not found. ${sessions.length} active session(s).`);
process.exit(1);
}
await openBrowser(session.url);
console.error(`Opened ${session.mode} session in browser: ${session.url}`);
process.exit(0);
}
// List sessions as a table
console.error("Active Plannotator sessions:\n");
for (let i = 0; i < sessions.length; i++) {
const s = sessions[i];
const age = Math.round((Date.now() - new Date(s.startedAt).getTime()) / 60000);
const ageStr = age < 60 ? `${age}m` : `${Math.floor(age / 60)}h ${age % 60}m`;
console.error(` #${i + 1} ${s.mode.padEnd(9)} ${s.project.padEnd(20)} ${s.url.padEnd(28)} ${ageStr} ago`);
}
console.error(`\nReopen with: plannotator sessions --open [N]`);
process.exit(0);
} else if (args[0] === "review") {
// ============================================
// CODE REVIEW MODE
// ============================================
// Get git context (branches, available diff options)
const gitContext = await getGitContext();
// Run git diff HEAD (uncommitted changes - default)
const { patch: rawPatch, label: gitRef, error: diffError } = await runGitDiff(
"uncommitted",
gitContext.defaultBranch
Fix/devcontainer & plan auto switching (opencode) (#31) * Refactor: shared server package with PLANNOTATOR_REMOTE env var - Create packages/server/ with shared server implementation - Add PLANNOTATOR_REMOTE=1 env var for devcontainer/SSH mode - Deprecate SSH_CONNECTION detection (still works with warning) - Both Claude Code and OpenCode now use identical server logic - OpenCode gains Obsidian/Bear integrations and remote detection - Update documentation with environment variables section Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove PLANNOTATOR_ORIGIN env var, fix onReady callback timing - Remove PLANNOTATOR_ORIGIN hack from Claude Code hook (hardcode "claude-code") - Fix onReady callback to pass port directly (was referencing undefined server) - Create tests/manual/test-server.ts for testing either origin - Update test-hook-2.sh to use new test server with opencode origin 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer test setup, reduce logging verbosity - Add tests/devcontainer/ with devcontainer.json for testing remote mode - Add tests/opencode-local/ for local OpenCode testing - Update package.json build script for proper bundling - Remove verbose multi-line error messages, keep useful errors - Clean up unused deprecationWarned variable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer support and documentation - Add PLANNOTATOR_REMOTE env var for container/remote detection - Remove console logging (silent operation) - Add devcontainer.md with full setup instructions - Add devcontainer section to OpenCode plugin README - Add port-only test setup to reproduce common misconfiguration - Update test devcontainers to forward port 4096 for opencode web - Bump version to 0.4.1 Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update CLAUDE.md: legacy SSH detection, not deprecated Removed incorrect mention of deprecation warning - SSH_TTY/SSH_CONNECTION detection is silent by design. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix OpenCode agent switching after plan approval After approving a plan, the conversation context stayed in "plan" mode even though the TUI showed "build". This caused edits to fail because the plan agent has edit permissions denied. The fix uses session.prompt() to inject a message with agent: "build", which triggers a new agentic loop with proper build agent permissions. Fixes #29 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:25:19 -08:00
);
const reviewProject = (await detectProjectName()) ?? "_unknown";
// Start review server (even if empty - user can switch diff types)
const server = await startReviewServer({
rawPatch,
gitRef,
error: diffError,
origin: "claude-code",
diffType: "uncommitted",
gitContext,
sharingEnabled,
shareBaseUrl,
htmlContent: reviewHtmlContent,
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
onReady: async (url, isRemote, port) => {
handleReviewServerReady(url, isRemote, port);
if (isRemote && sharingEnabled && rawPatch) {
await writeRemoteShareLink(rawPatch, shareBaseUrl, "review changes", "diff only").catch(() => {});
}
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "review",
project: reviewProject,
startedAt: new Date().toISOString(),
label: `review-${reviewProject}`,
});
// Wait for user feedback
const result = await server.waitForDecision();
// Give browser time to receive response and update UI
await Bun.sleep(1500);
// Cleanup
server.stop();
// Output feedback (captured by slash command)
if (result.approved) {
console.log("Code review completed — no changes requested.");
} else {
console.log(result.feedback);
console.log("\nThe reviewer has identified issues above. You must address all of them.");
}
process.exit(0);
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
} else if (args[0] === "annotate") {
// ============================================
// ANNOTATE MODE
// ============================================
let filePath = args[1];
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
if (!filePath) {
console.error("Usage: plannotator annotate <file.md>");
process.exit(1);
}
// Strip @ prefix if present (Claude Code file reference syntax)
if (filePath.startsWith("@")) {
filePath = filePath.slice(1);
}
// Use PLANNOTATOR_CWD if set (original working directory before script cd'd)
const projectRoot = process.env.PLANNOTATOR_CWD || process.cwd();
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Project root: ${projectRoot}`);
console.error(`[DEBUG] File path arg: ${filePath}`);
}
// Smart file resolution: exact path, case-insensitive relative, or bare filename search
const resolved = await resolveMarkdownFile(filePath, projectRoot);
if (resolved.kind === "ambiguous") {
console.error(`Ambiguous filename "${resolved.input}" — found ${resolved.matches.length} matches:`);
for (const match of resolved.matches) {
console.error(` ${match}`);
}
process.exit(1);
}
if (resolved.kind === "not_found") {
console.error(`File not found: ${resolved.input}`);
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
process.exit(1);
}
const absolutePath = resolved.path;
console.error(`Resolved: ${absolutePath}`);
const markdown = await Bun.file(absolutePath).text();
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
const annotateProject = (await detectProjectName()) ?? "_unknown";
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
// Start the annotate server (reuses plan editor HTML)
const server = await startAnnotateServer({
markdown,
filePath: absolutePath,
origin: "claude-code",
sharingEnabled,
shareBaseUrl,
htmlContent: planHtmlContent,
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
onReady: async (url, isRemote, port) => {
handleAnnotateServerReady(url, isRemote, port);
if (isRemote && sharingEnabled) {
await writeRemoteShareLink(markdown, shareBaseUrl, "annotate", "document only").catch(() => {});
}
},
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "annotate",
project: annotateProject,
startedAt: new Date().toISOString(),
label: `annotate-${path.basename(absolutePath)}`,
});
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
// Wait for user feedback
const result = await server.waitForDecision();
// Give browser time to receive response and update UI
await Bun.sleep(1500);
// Cleanup
server.stop();
// Output feedback (captured by slash command)
console.log(result.feedback || "No feedback provided.");
process.exit(0);
} else {
// ============================================
// PLAN REVIEW MODE (default)
// ============================================
// Read hook event from stdin
const eventJson = await Bun.stdin.text();
let planContent = "";
let permissionMode = "default";
try {
const event = JSON.parse(eventJson);
planContent = event.tool_input?.plan || "";
permissionMode = event.permission_mode || "default";
} catch {
console.error("Failed to parse hook event from stdin");
process.exit(1);
}
if (!planContent) {
console.error("No plan content in hook event");
process.exit(1);
}
const planProject = (await detectProjectName()) ?? "_unknown";
// Start the plan review server
const server = await startPlannotatorServer({
plan: planContent,
origin: "claude-code",
permissionMode,
sharingEnabled,
shareBaseUrl,
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
pasteApiUrl,
htmlContent: planHtmlContent,
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
onReady: async (url, isRemote, port) => {
handleServerReady(url, isRemote, port);
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
if (isRemote && sharingEnabled) {
await writeRemoteShareLink(planContent, shareBaseUrl, "review the plan", "plan only").catch(() => {});
}
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "plan",
project: planProject,
startedAt: new Date().toISOString(),
label: `plan-${planProject}`,
});
// Wait for user decision (blocks until approve/deny)
const result = await server.waitForDecision();
// Give browser time to receive response and update UI
await Bun.sleep(1500);
// Cleanup
server.stop();
// Output JSON for PermissionRequest hook decision control
if (result.approved) {
// Build updatedPermissions to preserve the current permission mode
const updatedPermissions = [];
if (result.permissionMode) {
updatedPermissions.push({
type: "setMode",
mode: result.permissionMode,
destination: "session",
});
}
console.log(
JSON.stringify({
hookSpecificOutput: {
hookEventName: "PermissionRequest",
decision: {
behavior: "allow",
...(updatedPermissions.length > 0 && { updatedPermissions }),
},
Fix/devcontainer & plan auto switching (opencode) (#31) * Refactor: shared server package with PLANNOTATOR_REMOTE env var - Create packages/server/ with shared server implementation - Add PLANNOTATOR_REMOTE=1 env var for devcontainer/SSH mode - Deprecate SSH_CONNECTION detection (still works with warning) - Both Claude Code and OpenCode now use identical server logic - OpenCode gains Obsidian/Bear integrations and remote detection - Update documentation with environment variables section Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove PLANNOTATOR_ORIGIN env var, fix onReady callback timing - Remove PLANNOTATOR_ORIGIN hack from Claude Code hook (hardcode "claude-code") - Fix onReady callback to pass port directly (was referencing undefined server) - Create tests/manual/test-server.ts for testing either origin - Update test-hook-2.sh to use new test server with opencode origin 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer test setup, reduce logging verbosity - Add tests/devcontainer/ with devcontainer.json for testing remote mode - Add tests/opencode-local/ for local OpenCode testing - Update package.json build script for proper bundling - Remove verbose multi-line error messages, keep useful errors - Clean up unused deprecationWarned variable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer support and documentation - Add PLANNOTATOR_REMOTE env var for container/remote detection - Remove console logging (silent operation) - Add devcontainer.md with full setup instructions - Add devcontainer section to OpenCode plugin README - Add port-only test setup to reproduce common misconfiguration - Update test devcontainers to forward port 4096 for opencode web - Bump version to 0.4.1 Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update CLAUDE.md: legacy SSH detection, not deprecated Removed incorrect mention of deprecation warning - SSH_TTY/SSH_CONNECTION detection is silent by design. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix OpenCode agent switching after plan approval After approving a plan, the conversation context stayed in "plan" mode even though the TUI showed "build". This caused edits to fail because the plan agent has edit permissions denied. The fix uses session.prompt() to inject a message with agent: "build", which triggers a new agentic loop with proper build agent permissions. Fixes #29 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:25:19 -08:00
},
})
);
} else {
console.log(
JSON.stringify({
hookSpecificOutput: {
hookEventName: "PermissionRequest",
decision: {
behavior: "deny",
refactor: shared feedback templates + preserve plan title on deny (#296) (#298) * refactor: shared feedback templates across all integrations The deny/feedback prompts sent to LLM agents were duplicated as inline string templates in hook, opencode-plugin, and pi-extension — each with different tone and framing. The hook's directive style (from #224) was the most effective at getting agents to address feedback. This extracts all feedback text into @plannotator/shared/feedback-templates and has every integration import from the single source of truth. Closes #215 follow-up (propagates fix to OpenCode and Pi). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: rewrite feedback template tests around contracts not implementation Tests now verify: cross-integration consistency, verbatim feedback preservation, empty input handling, and that approved messages don't contain directive language. Wording can change freely without breaking tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: instruct agent to preserve plan title on resubmission (#296) Version history slugs are derived from the plan's first # heading. When the agent renames the heading after a deny, the version chain breaks and the user loses diffs. The deny template now tells the agent not to change the title unless explicitly asked. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * style: improve plan deny preamble readability Break the dense single-paragraph preamble into structured sections: verdict, directive, and rules list. Easier for agents to parse. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add missing @plannotator/shared workspace dependency Hook and OpenCode plugin imported from @plannotator/shared/feedback-templates without declaring it as a dependency. Worked locally but failed in CI. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * revert: remove code review and annotate from shared templates Scope-crept into code review/annotate feedback which introduced a double heading regression and dropped integration-specific strings. Reverts those paths to their original inline strings; shared module now only covers plan deny feedback. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore Pi plan file hint and vendor template for source installs Add optional planFilePath to planDenyFeedback so Pi can tell the agent to read the plan file before editing. Check in a vendored copy of the template so Pi source installs work without running build:pi first. 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-15 19:38:22 -07:00
message: planDenyFeedback(result.feedback || "", "ExitPlanMode"),
},
},
})
);
}
process.exit(0);
}