Commit Graph

36 Commits

Author SHA1 Message Date
Michael Ramos c2950e709f fix: pre-release QA findings for 0.27.9 (#1405)
Fixes from the 0.27.9 pre-release review. Servers: an unreadable rendered-HTML root falls back to the startup snapshot on both runtimes with a once-per-process warning instead of hanging (Pi) or answering 500 (Bun); the version diff is recomputed against current bytes on reload and carried through the in-app Refresh instead of being dropped, with no history write on a GET. Client: a Refresh action on the compact touch shell; HtmlSurfaceControls renders Refresh independently of the eye; the dead HtmlSurfaceActions removed. Threading: one linear, cycle-safe reply resolution shared by the annotations panel, its sort, and the export (5,000-chain tests), PATCH ingest on both runtimes rejects self-references and cycles, nothing is ever dropped from feedback. WebMCP and viewer hygiene: bounded tombstone and request memories, per-instance minted ids, nudge id caps, waiter cleanup on unmount, a shared retry epoch for diagram blocks. Docs: HTML Refresh documented, the WebMCP design pointer fixed, marketing pages updated.

AI-assisted (Claude) under maintainer direction.
2026-08-27 15:23:28 -07:00
Michael Ramos 44611e5300 feat(ui): publish the HTML annotation seams hosts were hand-rolling (#1395)
Parity seams for hosts of @plannotator/ui, requested by Workspaces after the HTML annotation handoff: projectHostThreads and buildPersistedHtmlAnchor in @plannotator/core; HtmlViewer onUnanchoredChange completed over the annotations prop with a restore-keyed report so hosts can drop their mark-applied listeners; published useHtmlRefresh with a fetchSnapshot adapter; published HtmlSurfaceControls (eye, refresh, pen) with label overrides; AnnotationPanel unanchoredIds chip (wired for Plannotator too); HtmlViewer maxAdditionalTargets and scrollBehavior carried on the bridge; shortcuts and utils/inputMethod blessed as consumer exports. Plannotator's behavior is unchanged apart from the new Unanchored chip, verified by a real-browser A/B including the orphan and re-anchor cycle and by a combined cross-surface verification with #1394.

AI-assisted (Claude) under maintainer direction.
2026-08-27 07:35:22 -07:00
Michael Ramos 6903d7a3dd feat(webmcp): expose plan review and annotate as WebMCP tools for browser agents (#1393)
Phase 1 of WebMCP support: a zero-dependency, feature-detected engine in packages/ui/webmcp plus a read-and-comment tool catalog for plan review and annotate (read_document, add_comments, update_comment, remove_comments, reveal, nudge_user, list_documents). No decision tools; the human approves. Zero footprint in browsers without document.modelContext (DOM, network, console, timers, and cookies identical to main), idle until called where the API exists, and never registered inside the annotate iframes. Adds an optional inReplyTo field on annotations for threaded replies. Client-only; no server changes.

AI-assisted (Claude) under maintainer direction.
2026-08-26 14:39:37 -07:00
Michael Ramos 2ca55c8332 feat(annotate): live local app annotation through a loopback reverse proxy (#1352)
* feat(bridge): additive live-mode gate + LIVE_BRIDGE_BOOTSTRAP

Adds the config-gated live branch to BRIDGE_SCRIPT: frame gate, pinned
parent origin, token-stamped postToParent, origin+token checks on both
inbound handlers, pinpoint-only clamp, vim and resize off, pageUrl on
ready, and coalesced page-change reporting for SPA history navigation.
With no config present (srcdoc) every branch is inert and behavior is
unchanged; the existing html-viewer suites pass unmodified as the
regression proof. LIVE_BRIDGE_BOOTSTRAP installs the annotation CSS
from the JSON config prelude before the IIFE runs. New package export
exposes the string constants without the React barrel.

* feat(ui): live-session parent side for proxied app annotation

useHtmlAnnotation gains a live option (origin + token validated before
parseBridgeMessage; token + concrete targetOrigin on every outbound
post) and a validated page-change message with onPageChange. HtmlViewer
gains src/liveSession/currentPageUrl/onPageChange: src-mode iframe with
no sandbox and no srcdoc, ready pageUrl handling, per-page restore
filtering with explicit clear-marks + re-sync on navigation, and one
postToBridge choke point for its direct posts. Annotation.pageUrl is
additive; exportAnnotations groups by page (with global numbering kept)
only when a pageUrl is present, byte-identical otherwise. AnnotationPanel
shows the page label; AnnotationToolstrip can hide the input switch.
The editor app wires mode annotate-app: full-viewport live surface,
forced pinpoint, vim off, diff/share hidden, pageUrl stamping.

* feat(server): loopback reverse proxy for live app annotation

Whole-origin mirror of a local dev server on a dedicated 127.0.0.1
port: streaming bridge injection (after the head open tag, before a
bare </head>, or appended; exactly one per document; 8-byte holdback
plus a state machine for tags split across chunks), header hygiene
(upstream Host rewrite, X-Forwarded-*, identity Accept-Encoding on
document intent only, hop-by-hop strip), CSP drop-and-replace with
frame-ancestors listing the editor origins, X-Frame-Options removal,
target-origin Location rewrite, byte-identical passthrough for assets
and encoded HTML (no injection, once-per-session diagnostic), SSE
streaming, and WebSocket passthrough with a bounded pending queue for
HMR. Host header validation runs before any upstream contact; the bind
is the literal loopback constant and the advertised-URL override is
never applied. Tests boot a fake dev server and cover injection,
hygiene, fidelity, WS echo, and the security posture.

* feat(annotate): annotate-app server mode + CLI live probe with remote hard-off

startAnnotateServer gains mode annotate-app and a liveApp option: it
throws under PLANNOTATOR_REMOTE, generates the per-session token,
composes the proxy-served bridge body (JSON config prelude with both
editor origin forms, localhost first, plus bootstrap and bridge
supplied by the caller so packages/server never imports
@plannotator/ui), starts the loopback proxy after the annotate port is
known, serves the live /api/plan payload (no rawHtml, no version
fields, sharing off), and stops the proxy with the server. Version
history and durable submission records stay excluded via the explicit
mode gate.

The CLI resolution probes loopback http URLs (3s, accept text/html)
and defaults them to live mode when the probe returns HTML; --static
forces conversion, --app forces live and fails loudly on non-loopback,
https, unreachable, or non-HTML targets; both flags are mutually
exclusive transport-shape flags never echoed in the tolerant handoff.
A live resolution under PLANNOTATOR_REMOTE is a startup failure
suggesting --static. OpenCode and Pi parsers are untouched this phase.

* test(live-annotate): protocol, server, and probe suites + smoke script + docs

htmlLiveProtocol.test.tsx covers the parent trust boundary (origin and
token rejection before parseBridgeMessage, token + targetOrigin on
every outbound post, validated page-change and ready pageUrl, per-page
restore filtering with full-list numbering) and the bridge live gate,
executed as the composed config + bootstrap + bridge body inside a
dedicated harness iframe so the srcdoc suites keep running the same
script uncontaminated in this process. annotate.test.ts gains
annotate-app cases (live payload shape, composed bridge served by the
proxy, no-history version endpoints, proxy stopped with the server,
remote rejection); annotate-live-resolution.test.ts covers the probe
matrix. The two post helpers now drop unmatched-targetOrigin posts
silently, matching browser semantics where some DOM environments throw.
Adds the manual Vite/Next smoke script and the AGENTS.md live app
annotation section (phase gate, security posture, limitations).

* test(annotate-cli): cover the CLI layer of the live app remote hard-off

Spawns the real CLI entry (async, so the in-process fake app can answer
the live probe) with PLANNOTATOR_REMOTE=1 against a loopback HTML
server and asserts the startup-failure exit with the --static hint.
Completes per-layer coverage of the three-layer hard-off (CLI exit,
server throw, unconditional loopback proxy bind).

* fix(live-annotate): harden the loopback trust boundary end to end

- isLoopbackHostname (now canonical in live-proxy.ts, re-exported by the
  CLI resolution) requires localhost, ::1, or a LITERAL 127/8 IPv4
  address: DNS names like 127.0.0.1.evil.example no longer classify as
  loopback, so neither the default probe nor --app can start a live
  proxy against an off-box origin.
- The live-eligibility probe judges the FINAL response URL: a target
  that redirects off its loopback origin falls back to the static
  pipeline (or fails loudly under --app) instead of opening a live
  session whose iframe immediately leaves the proxy.
- WS upgrades with a browser Origin not naming the proxy itself are
  refused, so a hostile page's cross-site connect is never laundered
  into the origin-less shape dev servers trust as a non-browser client
  (Vite CVE-2025-24010 class).
- /__plannotator__/bridge.js refuses cross-site/same-site
  Sec-Fetch-Site fetches: the per-session token is no longer readable
  via an off-origin script include on modern browsers.
- X-Frame-Options is stripped only on HTML responses (where
  frame-ancestors replaces it); non-HTML responses keep the app's own
  framing protection.
- Redirect Locations are re-anchored by loopback-host + port
  equivalence instead of a string prefix: alternate loopback spellings
  are now caught and lookalike ports (5173 vs 51730) pass through
  untouched.
- --app on a non-URL target fails loudly instead of being silently
  swallowed.

* fix(live-annotate): session correctness for SPA restores, origins, and pathful targets

- A live find-and-mark that resolves nothing keeps its record, seeded
  with unresolved placeholder targets from the durable anchor/text
  params, so the mutation-driven reconcile re-acquires the pin once a
  lazy route or data-dependent tree renders (SPA navigation no longer
  permanently drops pins). Srcdoc restores keep the fail-closed drop.
- The bridge posts every outbound message once per listed editor
  origin; the browser delivers only the one matching the parent
  document, so an editor opened at 127.0.0.1 instead of localhost no
  longer silently loses ready and every subsequent message.
- The advertised appUrl is the proxy under its localhost spelling with
  the target URL's own path and query: the framed app stays same-site
  with the editor, shares the dev app's host-only localhost cookies
  and storage, and a pathful target opens its page instead of the app
  root. The proxy still binds the 127.0.0.1 literal.

* ci(live-annotate): run the live protocol DOM suite; document the hardened posture

htmlLiveProtocol.test.tsx is DOM-gated and was absent from the
workflow's DOM_TESTS file list, so none of its trust-boundary
assertions ran in CI. Add it, and update the live-app section of the
project docs: literal-loopback gate, probe redirect rule, WS Origin
check, bridge.js delivery gate, localhost appUrl advertisement, live
restore resilience, and the remote-mode behavior change (loopback URL
annotate under PLANNOTATOR_REMOTE now exits asking for --static
instead of silently converting).

* fix(live-annotate): absorb the v0.27 mainline into the live session surface

Post-rebase seam work after replaying the branch onto main (v0.27.4 era):

- Route the bridge's unanchored-transparency report through postToParent so
  live sessions deliver it token-stamped to the listed editor origins; the
  raw '*' post main introduced for srcdoc would be dropped by the live
  parent's message authentication exactly where restores fail most. New
  live-harness test pins the contract.
- Extend the live remote hard-off to --tailscale sessions (flag postdates
  the branch): CLI startup failure + startAnnotateServer throw keyed on
  tailnetPublished, matching how the annotate agent terminal treats tailnet
  publication. Covered in annotate.test.ts and documented in AGENTS.md.
- Keep main's compact-touch input controls and effective mode/input values
  on the HTML surface while preserving the live pinpoint-only clamps.
- Regenerate the pinned guide-viewer manifest (CSS hash moved with the new
  UI classes; JS unchanged).

* feat(live-annotate): Interact/Annotate mode toggle for live app and raw HTML sessions

A live app session used to be unusable: the pinpoint capture-phase click
handler owned every click, so buttons, checkboxes, inputs, and links never
fired. One boolean mode now governs the HTML/live viewer surface:

- Interact: the bridge is fully passive. Pinpoint capture, hover outline,
  drag-selection toolbar, [data-annotate] clicks, and committed-highlight
  click interception are all gated behind annotateModeActive, so clicks,
  forms, text selection, and SPA navigation reach the page natively.
  Committed markers and highlights stay VISIBLE, and marker buttons keep
  their clicks (a marker click still opens its comment).
- Annotate: classic behavior, unchanged. Live sessions annotate exclusively
  via pinpoint while armed.

Control: a single bubble icon button in the editor header (icon never
changes; armed = accent + visible border, idle = transparent border of the
same width, so the box is pixel-identical in both states), plus a subtle
inset accent ring floated over the viewer while armed (pointer-transparent,
no layout shift). Keyboard: Mod+Shift+A through the shortcut registry
(html-annotate scope; the bridge mirrors the chord inside the iframe and
forwards it over the authenticated postToParent path). Esc gains a final
ladder rung: draft closes first, then the hover outline clears, then Esc
exits Annotate back to Interact (bridge posts annotate-exit; a parent-side
listener covers Esc with editor focus). The parent owns the mode and pushes
it with the same re-post-on-ready pattern as set-input-method, so it
survives live page changes, HMR reloads, and bridge re-injection without
ever reloading the iframe.

Defaults: live app sessions START in Interact; static/raw HTML sessions
START in Annotate (today's behavior preserved, and the srcdoc bridge default
keeps behavior byte-identical when no set-annotate-mode ever arrives).
Session-only state, no persistence. Vim navigation is available only while
Annotate is armed.

Covered by new bridge-harness and parent-side DOM tests in
htmlLiveProtocol.test.tsx and htmlPinpointProtocol.test.tsx: Interact
pass-through, armed capture, the Esc ladder order, mode survival across
re-injection, marker clicks in Interact, and both defaults.

* feat(live-annotate): pinpoint-armed default, always-on drag comments, comment-only HTML surfaces

Simplifies the Interact/Annotate design after live review. The new
contract replaces the previous one where they conflict:

- BOTH surfaces (raw HTML and live app) now START ARMED with pinpoint;
  the live-session Interact default is gone. Esc keeps the ladder
  (close draft, clear hover, then exit to Interact) and the header
  toggle re-arms. The bridge also paints the pinpoint cursor at init
  instead of waiting for the parent's first round trip.
- The header toggle is a PEN icon: the old bubble sat next to the
  annotations-panel bubble and the two were indistinguishable. Same
  box geometry (armed = accent + visible border, idle = transparent
  border of identical width), aria-pressed, Mod+Shift+A, and the
  armed ring over the viewer are all unchanged.
- Text drag-selection commenting is ALWAYS live on HTML/live surfaces,
  in BOTH states: the selection pass is ungated from annotateModeActive
  and from the pinpoint input method. In armed pinpoint, click = pin an
  element and drag = select text, simultaneously; the >4px drag arming
  decides which one a gesture was, a completed drag's trailing click
  never re-pins (one-shot dragEndedClick), and a plain click is never
  swallowed (the pass only acts on a real selection and never
  preventDefaults). Esc in Interact still closes an open drag draft
  before yielding to the page.
- HTML/live surfaces are COMMENT-ONLY: useHtmlAnnotation clamps
  redline/quickLabel (both the host mode and a bridge-posted
  modeOverride, so a hostile page cannot force a DELETION), the
  selection toolbar drops Delete and quick labels behind a new
  commentOnly seam on AnnotationToolbar, and the quick-label picker
  portal is gone from HtmlViewer. Markdown surfaces keep the full
  toolbar, and persisted DELETION annotations still restore.
- The "Show tools"/"Hide tools" header button is removed. It hid the
  floating toolstrip (now gone from HTML surfaces entirely: with
  comment-only plus both input paths live there is nothing left to
  switch), the collapsed sidebar tab flags, and the viewer's floating
  action cluster (attachments + global comment + version-diff toggle),
  all of which are now always visible. htmlChrome persistence keeps
  only the sidebar/panel state; an old cookie's toolsHidden flag is
  read tolerantly and ignored, so a stale record cannot strand a user
  with hidden chrome and no way back.
- HTML surfaces pin the viewer input method to pinpoint (the drag/
  pinpoint switch is meaningless when both are live); the Alt input
  switch no-ops there. Vim stays armed-only, as built.

No server, proxy, or protocol-security changes; the armed flag stays
session-only.

Tests: the live-bridge harness is reworked around the armed default
(forged-DISARM posture, drag-selection passes in armed and Interact,
the trailing-click guard), the pinpoint suite covers the comment-only
toolbar and the redline/quickLabel clamp at the trust boundary, a new
AnnotationToolbar.commentOnly seam test guards both surfaces'
toolbars, App.htmlChrome.test.tsx replaces App.htmlHideTools.test.tsx
(no tools button, stale-cookie tolerance, pen armed default), and the
htmlChrome tests cover the narrowed persisted shape.

* feat(live-annotate): collapsible floating controls cluster

The simplification removed the Hide tools toggle, which left the floating
comment/attachments cluster permanently over the page. Restore a hide
affordance on the cluster itself: a collapse chevron shrinks it to a small
expand pill in the same corner, so the page is never obstructed without a
way back. Collapsed state persists with the rest of the HTML chrome cookie
(sidebar/panel), tolerantly read. Hosts that do not wire the toggle
(readOnly viewers, review-editor panels) are unchanged.

* feat(live-annotate): header Show/Hide tools replaces the collapse pill

The collapse pill was a half measure: it left its own artifact over the
page and the sidebar tongue tabs stayed. Revert it and restore the real
thing as a header control: an eye toggle immediately left of the pen that
removes ALL floating chrome over the page from the DOM (sidebar tongue
tabs + the comment/attachments cluster), leaving nothing behind. The
toggle lives in the header, so a hidden state always has a way back,
which also makes honoring a persisted (or pre-existing) toolsHidden
cookie safe again.
2026-08-19 10:44:21 -07:00
Michael Ramos 27791a6fba Mobile Phase 2B: Plan shell and navigation (#1303)
* feat(editor): add compact plan navigator

* feat(editor): simplify compact plan chrome

* fix(editor): close compact navigator after file selection

* feat(editor): add compact plan review surfaces

* fix(editor): hold navigator through cold file loads

* fix(editor): preserve desktop diff activation
2026-08-13 09:38:14 -07:00
Michael Ramos e181b824cc Mobile-safe plan and code comment composition (#1297)
* feat: harden mobile comment composition

* fix(ui): keep mobile app inside Safari viewport

* docs: record physical mobile triage

* fix(ui): extend plan canvas behind Safari controls

* fix(ui): let mobile plans drive Safari chrome

* fix(ui): release Safari top edge on mobile plans

* docs: triage mobile feedback and close phase 1b

* fix(ui): harden compact touch behavior
2026-08-13 08:58:55 -07:00
Michael Ramos ab8d2581eb feat(ui): onUnanchoredChange report + readOnly keeps the host footer slot (0.30.0) (#1263)
The bridge now names WHICH annotations have no live representation on
the page (every target dead, or the restore never resolved), reported
on change through a new validated message and the HtmlViewer
onUnanchoredChange prop, delivered in readOnly mode too. Fail-closed
anchors previously hid markers silently.

AnnotationPanel readOnly no longer suppresses the renderCardFooter
slot: its contents are host-owned and may be read affordances (replies,
links), so the host gates what belongs in it. Built-in delete/edit and
direct-edit discard stay hidden.
2026-08-10 22:46:55 -07:00
Michael Ramos 463f6ed57c fix(ui): fall back to legacy copy in insecure browser contexts (#1174)
* fix(ui): fall back to legacy copy in insecure browser contexts

navigator.clipboard only exists in secure contexts. Remote mode serves
plain HTTP on a non-localhost host, so every bare
navigator.clipboard.writeText call threw TypeError and copy buttons
silently broke.

Add copyTextToClipboard(text): Promise<boolean> to
packages/ui/utils/clipboard.ts: it tries the async Clipboard API
(guarded against synchronous throws), falls back to the existing
copy-event plus execCommand path, reports success as a boolean, and
never throws. copyTextWithFallback now returns whether the copy
happened and accepts an optional focusOwner; copyTextPreservingFocus
keeps its exported signature and behavior unchanged.

Route all bare call sites through the helper, preserving each site's
UX: Copied states only flip on success, error toasts and console
errors remain for the failure case, fire-and-forget sites stay
fire-and-forget. GoalSetupSurface gains the fallback and keeps its
error surface for the all-strategies-failed case.

Add DOM-gated unit tests for the helper and register them in CI.

Closes #1173

* fix(ui): address clipboard fallback review findings

Review follow-ups for the insecure-context clipboard fallback:

1. Tag the fallback textarea with data-clipboard-fallback and whitelist
   it in PopoutDialog's ANNOTATION_SELECTORS so the transient focus
   shift during a fallback copy no longer closes popout dialogs
   (TablePopout copy buttons, CodeFilePopout copy contents).

2. Widen AnnotationPanel's onQuickCopy prop to Promise<void | boolean>.
   A false resolution now suppresses the Copied flash; void resolution
   stays success so existing hosts keep today's behavior. The editor
   quick-copy site returns the helper's boolean.

3. In copyTextWithFallback, only flag the copy-event path as success
   when clipboardData was present and setData actually ran, and only
   when execCommand also reported success. A null clipboardData no
   longer calls preventDefault, so the textarea retry still runs.

4. Add tests pinning that the fallback runs synchronously when
   navigator.clipboard is absent (execCommand fires before the call
   returns, keeping it inside the user-gesture window), that a copy
   event without clipboardData is not treated as success, and that the
   fallback textarea carries the PopoutDialog focus-out marker and is
   removed after the copy resolves.

5. GoalSetupSurface surfaces the real writeText rejection message when
   the Clipboard API exists but fails and the fallback also fails; the
   generic unavailable message is reserved for the API-absent case.
2026-08-03 10:14:34 -07:00
Michael Ramos d53cbfb373 fix(annotate): enforce archive read-only surfaces (#1171)
* fix(annotate): enforce archive read-only surfaces

* fix(archive): close remaining read-only leaks
2026-07-31 17:23:44 -07:00
Michael Ramos e20fd97be7 Consumer enablement for @plannotator/ui (0.24.0) (#1017)
* feat(ui): AnnotationPanel renderCardFooter + readOnly host props

Per-card footer slot for host reply/resolve UI (clicks inside don't
select the card); readOnly hides delete/edit on all card kinds.
Both optional, both no-op by default — Plannotator unchanged.

* feat(ui): bless 6 exports into the strict-consumer surface

TableOfContents, ResizeHandle, useResizablePanel, useActiveSection,
useScrollViewport, utils/annotationHelpers — verified strict-clean and
backend-free (useResizablePanel persists via the storageBackend seam);
added to the gate and the HANDOFF supported-imports table.

* feat(ui): Viewer allowImages + readOnly host props

allowImages threads to both CommentPopover sites (popover already gated
its attach affordance; Viewer never exposed the knob). readOnly
suppresses every composer entry point — selection toolbar (highlighter
'enabled'), pinpoint, global comment, attachments, checkbox toggles —
while existing annotations still render and select.
Both default to today's behavior.

* fix(ui): lazy-import Viewer/CommentPopover in the consumer test (DOM-less bun test crashed on web-highlighter)

* feat(ui): strict-consumer gate gains verbatimModuleSyntax + noUnusedLocals/Parameters

Fixed the 24 violations the flags surfaced across the supported-import
graph: type-only imports (verbatimModuleSyntax) and dead imports/locals.
Consumers with stricter tsconfigs no longer have to relax them.

* feat(ui): opt-in content-verifying annotation restore

verifyRestoredContent on useAnnotationHighlighter: after a meta-based
fromStore restore, the painted text is checked against originalText
(whitespace-normalized). Mismatch -> highlight removed, text-search
fallback re-anchors; if that fails too, onRestoreMismatch(annotation,
restoredText) fires and nothing is painted. Default off — today's
trust-the-positions behavior. Workspaces hit this live after document
drift; correctness upgrade for every consumer.

* chore(ui): 0.24.0 — HANDOFF consumer-enablement notes + version bump
2026-07-07 19:09:52 -07:00
Michael Ramos 195328f7a6 Persist saved annotate file edits in drafts (#936)
* Persist saved annotate file edits in drafts

* Handle stale saved file edit context

* Test source edit conflict actions

* Return source metadata for single-file docs

* Fix saved file edit conflict races

* Handle deleted source files in annotate edits

* Tighten annotate missing-file recovery

* Reset edit state for missing file reopen

* Tighten source edit restore path handling

* Harden source edit recovery paths

* Harden source edit disk reconciliation

* Fix live file tree startup delay

* Document file tree watcher startup ordering

* Preserve source save through missing files and symlinks

* Harden missing source file recovery

* Tighten annotate source edit boundaries
2026-06-18 21:31:25 -07:00
Michael Ramos 40210fdfd2 Add live annotate file tree workspace status (#931)
* feat(annotate): add live file tree workspace status

* fix(annotate): guard dirty feedback and rename stats

* fix(annotate): tighten live file tree status

* fix(annotate): surface deleted file browser roots

* fix(annotate): normalize file tree status paths

* fix(annotate): avoid optional git locks for workspace status

* fix(annotate): tighten workspace status git metadata

* fix(annotate): refresh file tree after reconnect

* fix(pi): expose file browser stream route
2026-06-17 14:25:28 -07:00
Michael Ramos 4d5a73aff0 feat(editor): clearer edit controls — Edits label, Save emphasis, Save/Cancel (#928)
* feat(editor): clearer edit controls — Edits label, Save emphasis, Save/Cancel

Annotation panel: rename the pinned 'Direct edits' card label to 'Edits'
(it line-broke at narrow panel widths).

Save button (source-backed sessions): drive its state entirely from the
editableDocuments state machine instead of a parallel flag. Shows a dot +
emphasis only when there are unsaved disk changes (was inverted before,
lighting up when already saved), turns destructive on a failed save, and
no longer reflows — the dot slot is always reserved and the label width is
pinned to its widest value so Save/Saving/Saved swap without nudging
neighbors.

Edit exit control: a source-backed session with unsaved edits now shows a
two-step 'Cancel' (-> 'Discard?') that discards edits and exits, instead
of the ambiguous 'Done'. Plan mode and clean source sessions keep 'Done'
(commit edits + exit), so plan-mode keep behavior is unchanged.

* fix(editor): reset discard confirmation when switching files

In folder annotate mode the editor stays open across files, but the
'Cancel' -> 'Discard?' confirmation was a single app-level flag. Arming it
on one dirty file and switching to another dirty file carried the armed
state over, so the first click discarded the second file's edits with no
confirmation. Reset the confirmation whenever the active editable document
changes so each file's discard is independent.
2026-06-16 22:20:49 -07:00
Michael Ramos 9ed3ba8937 feat(editor): markdown edit mode — direct document editing with diff-to-agent feedback
Adds direct markdown editing, source-backed annotate saves, folder edit buffers, and review-hardening fixes.
2026-06-16 16:35:51 -07:00
Michael Ramos c23df4db43 UI 2.0 visual refresh + HTML-render annotate (strictly UI, off main) (#863)
Extracts the UI 2.0 visual refresh and the HTML-render annotate feature onto main, standalone (no daemon). Faithful copy of feat's UI/HTML logic with the standalone transport kept.
2026-06-08 17:03:41 -07:00
Michael Ramos a11bf802bd feat(ui): code file viewer with syntax highlighting and annotations (#634)
* feat(ui): extract reusable PopoutDialog, fix backdrop blur

The table popout lost its backdrop blur when we switched to modal={false}
to keep annotation toolbars interactive. Radix ignores Dialog.Overlay in
non-modal mode, so replace it with a plain div backdrop that works
regardless. Extract the dialog shell (backdrop, close button, portal,
annotation-aware dismiss) into a reusable PopoutDialog component for
upcoming use cases. Add a demo table to the dev plan content.

* Add read-only code file popout

* Add code file annotation support

* Fix code selection popover position

* fix(editor): restore global-attachment-only drafts

The save condition was broadened to persist drafts with only global
attachments, but the restore handler still skipped applying when both
annotation arrays were empty — silently dropping the attachments.

* fix(ui): import SelectedLineRange from @pierre/diffs base package

SelectedLineRange is not re-exported from @pierre/diffs/react —
import it from the base @pierre/diffs entry point instead.


* chore: add TODO for bot callback + code annotation limitation
2026-04-30 10:42:36 -07:00
Michael Ramos ba2e4d2a1d feat(ui): markdown reader parity — HTML blocks, GitHub alerts, GFM inline extras (#597)
* feat(ui): markdown reader parity — HTML blocks, GitHub alerts, GFM inline extras

Brings the in-app markdown reader to parity with GitHub's flavored rendering.
Additive across the parser + renderer; no behavior change for existing blocks.

Refactor:
- Extract InlineMarkdown (262 lines) out of Viewer.tsx into its own file
- Extract BlockRenderer + block-type components (CodeBlock, HtmlBlock, AlertBlock,
  Callout) into components/blocks/ — Viewer drops from 1279 to ~770 lines
- Each new block-level feature lands in BlockRenderer or a new blocks/*.tsx,
  not Viewer

Block-level features:
- Raw HTML blocks (<details>, <summary>, etc.) via balanced-tag parser branch,
  rendered through marked + DOMPurify for nested-markdown support; inner innerHTML
  set imperatively so React reconciliation doesn't collapse open <details>
- GitHub alerts (> [!NOTE] / [!TIP] / [!WARNING] / [!CAUTION] / [!IMPORTANT])
  with inline Octicons, title-case labels, GitHub's Primer colors (light + dark)
- Directive containers (:::kind ... :::) with arbitrary kinds for project-specific
  callouts (note, tip, warning, danger, info, success, question, etc.)
- Heading anchor ids — slugifyHeading() strips inline markdown, preserves unicode

Inline features (all in InlineMarkdown, all code-span-safe):
- Bare URL autolinks (https://...) with trailing-punctuation trimming
- @mentions and #issue-refs — render as clickable links when repo is GitHub,
  styled spans otherwise; threaded via repoInfo.display through BlockRenderer
- Emoji shortcodes (👋, 🚀, 29 curated codes) via transformPlainText()
- Smart punctuation (curly quotes, em/en dashes, ellipsis) applied only to
  plain-text fragments after code spans have been consumed

Safety:
- Render-time transforms live inside InlineMarkdown's plain-text push, which
  is only reached after code-span regex consumes code content. Backticks stay
  literal for shell/regex snippets.
- DOMPurify allowlist (no on* handlers, no style attrs, no scripts) gates every
  raw HTML block. Unsafe link protocols (javascript:/data:/vbscript:/file:)
  stripped by sanitizeLinkUrl.

Tests: +40 (149 total). New files:
- utils/slugify.test.ts (10) — unicode, markdown stripping, edge cases
- utils/inlineTransforms.test.ts (9) — emoji + smartypants
- utils/parser.test.ts — alert detection (5 cases), directives (5 cases), HTML
  block balancing (5 cases)

Fixtures for manual verification:
- tests/test-fixtures/11-html-blocks.md
- tests/test-fixtures/12-gfm-and-inline-extras.md (release-plan-shaped demo)

Known limitations (not blockers):
- Bare URL regex doesn't balance parens (https://en.wikipedia.org/wiki/Foo_(bar)
  drops the trailing ")")
- Duplicate heading text → duplicate anchor ids (browser picks first on hash nav)
- Directive body is inline-only (no nested headings/lists)

For provenance purposes, this commit was AI assisted.

* fix(ui): wire typecheck for packages/ui, address PR review findings

Root-cause fix for the missing-import bug caught in review: the UI package
had no tsconfig.json and no typecheck script, so missing references like
`getImageSrc` in the extracted InlineMarkdown slipped past vite/esbuild
(which only type-strip, they don't resolve imports).

Infrastructure:
- Added packages/ui/tsconfig.json with proper module resolution, JSX config,
  and bundler-style paths.
- Added globals.d.ts to accept side-effect CSS imports.
- Added @types/react, @types/react-dom, @types/bun, @types/dompurify as
  devDeps on packages/ui so React / Bun / DOMPurify types actually resolve.
- Wired `tsc --noEmit -p packages/ui/tsconfig.json` into the top-level
  `bun run typecheck` script.

With the typecheck running, 0 errors remain in this PR's scope. Four
pre-existing errors on main (plan-diff SVG type narrowing, sharing.ts
SharePayload shape) are unrelated and tracked separately.

Review fixes:
- InlineMarkdown: import getImageSrc from ImageThumbnail. Was calling the
  helper without importing it — markdown images with relative paths
  (`![alt](./foo.png)`) would throw ReferenceError at render. Regression
  caused by the InlineMarkdown extraction.
- useAnnotationHighlighter: findTextInDOM now retries with the rendered
  form (transformPlainText) when the raw originalText doesn't match.
  Annotations made before smart-punctuation / emoji shortcodes shipped
  (straight quotes, `👋` text) still re-bind after reload.
- sanitizeHtml: allow the `open` attribute so `<details open>` preserves
  its default-expanded state instead of always rendering collapsed.
- parser.test.ts: narrow a string->AlertKind assertion to satisfy strict
  typechecking.

Deferred (tracked as known limitation in PR description):
- HtmlBlock relative URL rewriting for nested <img src="./logo.png"> /
  <a href="note.md">. New-feature gap, not a regression.

For provenance purposes, this commit was AI assisted.

* fix(ui): HtmlBlock rewrites relative <img>/<a> refs to match markdown paths

Raw HTML blocks inject sanitized HTML verbatim, so nested <img src="./logo.png">
and <a href="notes.md"> resolved against the plannotator server URL instead of
the plan's directory — images 404'd, .md links navigated away instead of
opening in the linked-doc overlay. This is the path README.md content hits
(hero <img>, YouTube thumbnails, <details> sections with anchors).

Fix: after setting innerHTML, walk <img> and <a> elements and apply the same
rewriting markdown content uses:
- <img> relative src → getImageSrc(src, imageBaseDir), routing through
  /api/image?path=... with the plan's base directory.
- <a> relative href matching .md / .mdx / .html → click handler that calls
  onOpenLinkedDoc, same pattern as [label](./foo.md) markdown links.
- http(s):, data:, blob:, mailto:, tel:, and #anchor hrefs pass through
  untouched.

BlockRenderer now threads imageBaseDir + onOpenLinkedDoc into HtmlBlock.
React.memo equality extended to compare those props too, so legitimate
changes still re-run the rewrite pass without forcing re-renders on
every parent update.

Verified against the repo's own README.md — hero image, YouTube thumbnails,
and <details> sections all render correctly in annotate mode.

For provenance purposes, this commit was AI assisted.

* feat(ui): table conveniences — hover toolbar, popout dialog with sort/filter

Extracts table rendering into blocks/TableBlock and adds two companion
surfaces: a hover toolbar for quick copy, and a full-screen popout dialog
with TanStack-powered sort/filter/copy for power use. No pagination — plan
tables don't get that big.

Hover toolbar (blocks/TableToolbar.tsx):
- Floats above the table on mouse enter via React portal, positioned with
  getBoundingClientRect + scroll/resize listeners, entry/exit animations.
  Same positional pattern as AnnotationToolbar's top-right mode.
- Debounced hover state in Viewer (100ms leave → 150ms exit animation),
  mirroring hoveredCodeBlock's state machine.
- Three actions: Copy markdown (icon), CSV (short uppercase button,
  RFC 4180 escaping), Expand (opens popout).

Popout dialog (blocks/TablePopout.tsx):
- Radix Dialog, fullscreen-ish card with ~2rem backdrop visible for
  click-to-close. max-w-[min(calc(100vw-4rem),1500px)].
- Portaled into Viewer's containerRef so the annotation hook can walk
  into the popout's text nodes — selection-based annotations, text-search
  restoration, and shared blockId all work across the collapsed and
  popped-out views.
- TanStack Table for the grid: click column headers to sort (asc → desc →
  clear), global filter input, no pagination. Row count indicator shows
  "15 of 27" when filter reduces the set.
- Copy / CSV buttons in the header row: filter- and sort-aware. When
  visible rows < total, tooltips read "Copy 15 rows as markdown" /
  "Copy 15 rows as CSV". When no filter, copies whole table (normalized
  whitespace). Read is one-shot on click — no derived state to sync.
- Floating X close button (absolute top-right), no header bar.

Chrome stacking while popout is open (CSS-only, via :has()):
- body:has([data-popout="true"]) drops four element types behind the
  dialog: annotation sidebar, sticky header lane, app nav header, overlay
  scrollbars. :has() observes the dialog's presence directly — when the
  dialog unmounts, the selector stops matching and everything returns to
  natural stacking. No JS state, no useEffect cleanup.

Shared helpers in TableBlock.tsx (exported):
- parseTableContent — pipe-delimited markdown → { headers, rows }
- buildCsvFromRows / buildMarkdownTable — inverse, from parsed data
- buildCsv — thin wrapper for the hover toolbar's raw-block path

Dependencies added:
- @radix-ui/react-dialog ^1.1.15 (~6 KB gzipped)
- @tanstack/react-table ^8.21.3 (~14 KB gzipped)

Fixture:
- tests/test-fixtures/12-gfm-and-inline-extras.md — added a 27×11
  "Detailed feature backlog" table to exercise wide + deep tables,
  horizontal scroll in the popout, and the sort/filter flows.

For provenance purposes, this commit was AI assisted.

* fix(ui): table popout — annotation flow, chrome stacking, sidebar tabs

Tightens the popout so annotations work inside it and chrome doesn't
overlap the dialog.

Annotation flow inside popout:
- Radix Dialog modal={false} so the focus trap doesn't yank focus back
  from CommentPopover's textarea (CommentPopover portals to document.body,
  outside the dialog's DOM subtree).
- Dialog.Content onInteractOutside handler whitelists the annotation
  toolbar, CommentPopover, and FloatingQuickLabelPicker so clicking
  them doesn't dismiss the dialog. Backdrop click + Escape still close.
- aria-describedby={undefined} on Dialog.Content (Radix opt-out; the
  popout doesn't need a description).
- React.memo on TablePopout with a custom comparator (block id/content,
  open, container, imageBaseDir, githubRepo). Prevents upstream Viewer
  re-renders from re-running TanStack's flexRender on every cell, which
  conflicted with web-highlighter's live DOM mutations and caused a
  NotFoundError in React's reconciler.

Widget markers for :has()-based chrome stacking:
- [data-comment-popover="true"] on CommentPopover (both popover + dialog
  variants).
- [data-floating-picker="true"] on FloatingQuickLabelPicker.
- [data-sidebar-tabs="true"] on SidebarTabs (left-side TOC/Files/Versions
  flags that sit on top of the dialog otherwise).
- theme.css extended: sidebar tabs join the annotation sidebar, sticky
  header lane, app header, and overlay scrollbars in dropping to
  z-index -1 while body:has([data-popout="true"]) matches.

Known limitation (not addressed): annotations created inside the popout
show their <mark> only while the popout is open; when it closes, the
<mark> unmounts with the popout's DOM and does not reappear on the
collapsed table. The annotation itself persists in state (sidebar,
shared URLs, exports). Round-tripping visual marks between popout and
collapsed view requires either a second web-highlighter instance or a
switch to the CSS Custom Highlight API — out of scope here.

For provenance purposes, this commit was AI assisted.

* fix(ui): review findings — flags, alerts, forges, tabs, anchors, URL brackets

Six targeted fixes from the v0.19 PR review. Each is small and scoped;
the riskier items from the review (plan-diff block variants, HTML
relative non-doc links) are tracked as follow-ups.

Smart punctuation — CLI flags preserved:
- Narrowed the `--` → en-dash rule to only fire between digits
  (`pages 3--5` still converts; `bun --watch` stays literal).

GitHub alerts — list/code/heading bodies absorb correctly:
- Blockquote merge now always merges into a previous alert blockquote,
  regardless of whether the new line starts with a block marker. Without
  this, `> [!NOTE]\n> - item` split the list off into a plain italic
  quote and emptied the alert.
- AlertBlock got a mini block-level renderer for the body so `- item` /
  `* item` / `1. item` render as real <ul>/<ol>, not flattened prose.

Forge-aware mentions/issue refs:
- packages/shared/repo: new parseRemoteHost() extracts the host from
  the git remote URL; RepoInfo gains an optional `host` field.
- packages/server/repo: getRepoInfo populates host alongside display.
- Viewer only passes githubRepo to InlineMarkdown when the host is
  exactly "github.com". Non-GitHub repos render mentions/issue refs
  as styled text, no wrong github.com links.

HTML block external links:
- rewriteRelativeRefs now forces `target="_blank"` and
  `rel="noopener noreferrer"` on every external http(s) link inside
  raw HTML. Fixes two problems in one pass: external links no longer
  hijack the review tab, and pasted-HTML links can't tab-nab the
  plannotator tab via window.opener.

Heading anchor dedup:
- New buildHeadingSlugMap() walks all heading blocks and assigns
  `foo`, `foo-1`, `foo-2`, ... for repeats (GitHub convention).
  BlockRenderer receives the anchor id as a prop from Viewer via a
  memoized map rather than computing per-block; first occurrence
  keeps the bare slug so existing links stay stable.

URL autolink bracket balance:
- Trailing `)`/`]`/`}` in bare URLs are kept when they balance an
  earlier opener inside the URL. Wikipedia-style
  `https://en.wikipedia.org/wiki/Function_(mathematics)` now keeps its
  paren; `(see https://x.com)` still trims the orphan.

Tests: +8 (157 total).
- utils/slugify.test: buildHeadingSlugMap dedup behavior, non-heading
  skipping, empty-slug skipping.
- utils/inlineTransforms.test: CLI flags stay literal, `3--5` still
  converts.
- utils/parser.test: alerts with list body / code fence body, blank
  line ending an alert.

Fixture:
- tests/test-fixtures/13-known-issues.md — reproduces each of the
  review findings end-to-end; useful as a regression check going
  forward.

Deferred (tracked for follow-up):
- Plan diff view doesn't render html / directive / alertKind semantics
  (SimpleBlockRenderer has no cases for the new block variants).
- Relative non-doc links inside raw HTML (.pdf, .csv) don't get
  rewritten — only .md/.mdx/.html are routed through the linked-doc
  overlay today. Not a regression; narrow audience.

For provenance purposes, this commit was AI assisted.

* fix(ui): round-3 review — drop host gate, link paren balance, data/blob images

- Viewer: remove repoInfo.host === 'github.com' gate so @user/#123 links
  render for GitHub Enterprise and runtimes (Pi) that don't populate host.
- HtmlBlock: treat protocol-relative //host links as external and harden
  with target=_blank rel=noopener noreferrer.
- InlineMarkdown: data:/blob: image sources bypass /api/image rewrite.
- InlineMarkdown: replace [text](url) regex with a depth-tracking scanner
  so URLs with balanced parens (Wikipedia /Function_(mathematics)) and
  backslash-escapes no longer truncate. Empty text/url guard preserves
  prior fall-through behavior.
- InlineMarkdown: isLocalDoc accepts .md/.mdx/.html/.htm with optional
  #fragment; fragment stripped before onOpenLinkedDoc so guide.md#setup
  opens the linked doc instead of a broken anchor.

For provenance purposes, this commit was AI assisted.

* fix(ui): round-4 review — table pipe escape, callout lists, emoji h-splitter

- TableBlock: buildMarkdownTable now re-escapes literal | as \| in each
  cell. parseTableContent already unescapes on parse; without the mirror
  on serialize, the popout's copy-as-markdown produces extra columns for
  tables with pipes in regex, shell, or boolean content.
- AlertBlock + Callout: extract the shared paragraph-and-list body
  renderer into blocks/proseBody.tsx. Fixes directive callouts (:::note
  with a bulleted list) rendering as literal hyphens instead of a list.
  Paragraph lines join with '\n' so InlineMarkdown's hard-break handler
  still fires. Callout passes an empty text-color class so directive
  color tokens inherited from the container are preserved.
- InlineMarkdown: drop `h` from the plaintext chunk-break class; it was
  splitting emoji shortcodes like ❤️, 👍, 🤔 at the
  h, so the :word: pattern never reassembled and transformPlainText
  couldn't replace the shortcode. Bare URL detection moves inline via
  emitPlainTextWithBareUrls, which scans chunks for https?:// at word
  boundaries and emits anchors, passing surrounding text through
  transformPlainText so emoji + smart punctuation still apply to
  non-URL slices.
- InlineMarkdown: extract trimUrlTail (shared between the top-of-loop
  URL branch and the new inline scanner) — one balanced-paren trim
  implementation instead of two. +8 unit tests covering the trim cases
  (Wikipedia parens, unbalanced brackets, stacked punctuation).
- Fixture: section 9 in 13-known-issues.md demonstrates the table copy
  corruption for manual verification.

For provenance purposes, this commit was AI assisted.

* fix(ui): resolve pre-existing typecheck errors surfacing in CI

- PlanCleanDiffView: narrow heading Tag to 'h1'..'h6' so hover props
  resolve to HTMLHeadingElement instead of the SVGSymbolElement branch
  of keyof IntrinsicElements.
- VSCodeIcon: spread mask-type as a kebab-case attribute; React 19's
  typings no longer expose the camelCase maskType prop on SVG masks.
- useSharing / sharing: cast decompress() result to SharePayload — the
  shared compress module returns unknown by design; callers were
  implicitly any and TS 5.x now flags the assignment.

For provenance purposes, this commit was AI assisted.
2026-04-21 18:56:41 -07:00
Michael Ramos c342ffbed7 feat(plan): simplify share/copy + sticky header polish (#519)
* refactor(ui): simplify Quick Share/Copy to Share/Copy

Rename "Quick Copy"/"Quick Share" buttons in AnnotationPanel to plain
"Copy"/"Share" and route Share through the existing ExportModal so it
benefits from the short-link path for large payloads. The naive
clipboard.writeText fallback is gone.

For provenance purposes, this commit was AI assisted.

* feat(plan): coordinated sticky header label shrinking

Replace fixed pixel reserves in the sticky ghost header with measured
geometry: a ResizeObserver on the wrapper plus one on the Viewer's
action button cluster (tagged with data-sticky-actions) computes the
exact space available for the toolstrip + badges.

Both sides shrink in coordination so they stay horizontally aligned as
long as possible:

  plan area | right side       | ghost bar         | layout
  >= 800    | full labels      | active labels     | shared lane
  680..800  | short labels     | active labels     | shared lane
  500..680  | icons only       | active labels     | shared lane
  340..500  | icons only       | icon-only         | shared lane
  < 340     | icons only       | icon-only         | stacked

The label-mode bucket lives in App.tsx state so the tree re-renders at
most twice per drag instead of every pixel. Sticky lane measurements
snap to a 16px grid for the same reason. Switches the
IntersectionObserver scroll root from <main> to the OverlayScrollArea
viewport (via useScrollViewport) so the ghost bar actually appears at
the right scroll position. AttachmentsButton's "Images" label now also
collapses with the cluster.

For provenance purposes, this commit was AI assisted.

* fix(plan): float collapsed sidebar rail over the grid background

Absolutely position the SidebarTabs rail and reclaim its 30px gutter
with left padding on the OverlayScrollArea, so the bg-grid pattern
paints edge-to-edge under the flags instead of starting to their right.
The plan card lands in exactly the same place as before.

For provenance purposes, this commit was AI assisted.

* fix(plan): address PR review — mobile share, a11y, snap hoist

- AnnotationPanel mobile Share was opening ExportModal (z-50) underneath
  the panel (z-[60]) and its backdrop (z-[59]), creating a dead-end on
  mobile. Close the panel before opening the share modal.
- AttachmentsButton trigger had no accessible name when hideLabel was
  active and there were no images yet. Add aria-label + title.
- Hoist StickyHeaderLane's snap() to module scope so the effects (which
  use [] deps) can't close over a stale per-render instance. Currently
  harmless since snap is pure, but removes a footgun.

For provenance purposes, this commit was AI assisted.

* fix(plan): address PR review round 2

- StickyHeaderLane's [data-sticky-actions] ResizeObserver had [] deps
  and was attached at mount, but Viewer is keyed by linkedDocHook state
  and remounts on linked-doc toggle. The observer would stay bound to
  the now-detached old node and freeze actionsWidth, leaving the bar's
  geometry permanently wrong. Add a remountToken prop threaded from
  App.tsx so the effect re-queries against the fresh DOM.
- Restore the shareUrl gate on the AnnotationPanel Share action — only
  pass onShare when a URL has been generated, matching prior behavior.
- Hoist StickyHeaderLane's layout constants (LEFT_OFFSET, GAP,
  WIDE_BAR_WIDTH, MIN_BAR_WIDTH) to module scope alongside snap, for
  consistency.

For provenance purposes, this commit was AI assisted.

* fix(plan): address PR review round 3 — polish glitches

- snap() uses Math.floor instead of Math.round so the wrapper width
  undershoots and the actions width overshoots, both pushing toward a
  more cautious layout. Avoids a one-bucket overlap flash right at the
  300/460 thresholds during a slow drag.
- Reset actionsWidth to 0 at the top of the [remountToken] effect so
  the bar falls back to the safe unmeasured path for the one frame
  between Viewer remounting and the new observer's first callback.
- App.tsx switches to useLayoutEffect + a synchronous
  getBoundingClientRect to set the initial actionsLabelMode bucket
  before paint. Eliminates the one-frame flash of full labels on
  narrow viewports during first render.

For provenance purposes, this commit was AI assisted.
2026-04-07 23:19:39 -07:00
Michael Ramos 57495ec816 feat: Zed-style overlay scrollbars (#509)
* feat(ui): Zed-style overlay scrollbars for plan mode

Wide, translucent, full-length overlay scrollbars replacing the 6px
WebKit rail that users couldn't reliably grab. Click the track to
page-animate toward the click, drag the thumb, no layout shift, Firefox
parity.

Wraps plan-mode scroll containers (main viewer, annotation panel,
sidebar, settings, export modal) in a new <OverlayScrollArea> component
backed by overlayscrollbars-react. The library handles pointer capture,
click-to-jump, hover reveal, auto-hide, RTL, touch, momentum, and
cross-browser consistency. ClickScrollPlugin registered explicitly so
`clickScroll: true` actually pages (otherwise it silently no-ops).

Plumbing:

- New ScrollViewportContext + useScrollViewport() hook so descendants
  (TableOfContents, PinpointOverlay, Viewer sticky observer) can reach
  the real scrolling element instead of document.querySelector('main'),
  which no longer returns the scroll node after wrapping.
- New useOverlayViewport() hook — canonical ref+state+callback pattern
  bridging the library viewport into components that need both
  imperative access and effect re-runs when the viewport mounts.
- useActiveSection gains an optional scrollElement arg so its
  IntersectionObserver root re-attaches when the viewport becomes
  available (ref mutations don't retrigger effects).

Theme:

- New .os-theme-plannotator tokens sourced from existing theme CSS
  variables (translucent muted-foreground for handle, transparent track
  at rest). 10px at rest, 14px on hover. Color + width transitions
  only — deliberately does not reintroduce transform/opacity in global
  transitions, preserving the abc952f scroll-jank fix.
- Firefox `scrollbar-width: thin` + `scrollbar-color` fallback for
  unwrapped surfaces (micro-scrollers, future dockview).
- print.css hides .os-scrollbar during print.

ResizeHandle (#354 regression guard):

- `side="right"` touch area retuned from `-right-3 left-0` to
  `-right-3 left-3` to clear the 14px hover scrollbar. Load-bearing
  comment added explicitly warning against simplification because #354
  has already regressed twice.

Intentionally left native: max-h-24 inline scrollers
(EditorAnnotationCard, AgentsTab, ThemeTab), dropdown menus — a 14px
overlay scrollbar would dominate those UI elements.

Fixes #354
Follow-up to #359, #465 (both fixed #354, which kept regressing)
Preserves #253 bidirectional annotation scroll
Preserves #452 file-switch reset (plan mode portion)

For provenance purposes, this commit was AI assisted.

* feat(review): overlay scrollbars for file tree, sidebar, and PR panels

Wrap the trivial code-review scroll containers in <OverlayScrollArea>:
FileTree, ReviewSidebar content area, AITab chat history, PRCommentsTab
timeline, and the ReviewPRSummary / ReviewPRChecks dock panels.

None of these components read scrollTop / scrollHeight / scrollLeft
directly — all descendant queries use containerRef.current.querySelector
and all scroll-to-target calls use element.scrollIntoView, which walks
up to the nearest scrollable ancestor (now the library viewport). No
plumbing changes required.

AITab was originally scoped to Commit B but an audit of its scroll
effects (jump-to-question + auto-scroll-to-bottom) confirmed it only
uses descendant scrollIntoView, so it ships here.

DiffViewer and LiveLogViewer follow in a separate commit — they
programmatically read/write scrollTop and need explicit viewport
plumbing via useOverlayViewport.

For provenance purposes, this commit was AI assisted.

* feat(review): overlay scrollbars for diff viewer and live logs

Wrap DiffViewer's main scroll container and LiveLogViewer's log pane in
<OverlayScrollArea>, plumbing containerRef through useOverlayViewport
so imperative scroll reads/writes and IntersectionObserver roots land
on the real library viewport, not the OverlayScrollArea host.

DiffViewer:

- `previousScrollFilePathRef` guard added: the file-switch reset
  (#452) now only advances the tracking ref once the scroll actually
  executed, closing a race where a file switch landing before the
  library viewport attached would leave the ref stale while the
  scrollTo silently no-oped.
- `viewport` added to every effect dep that reads containerRef.current
  (file-switch reset, annotation scroll, search-highlight apply +
  swap, scroll-to-match) so they re-run when the viewport mounts.
  Without this they'd silently no-op on first paint.
- Split-view sync via @pierre/diffs unaffected — its ScrollSyncManager
  attaches scroll listeners to its own internal codeDeletions /
  codeAdditions elements inside the content, not the outer scroller.

LiveLogViewer:

- React onScroll replaced with a native addEventListener('scroll', ...)
  inside a useEffect keyed on `viewport` because React's onScroll
  doesn't bubble across the library's wrapper layers.
- Follow-tail heuristic (`scrollHeight - scrollTop - clientHeight < 40`)
  and the auto-scroll-to-bottom assignment both preserved verbatim —
  only the ref target changed from the raw div to the library viewport.

Preserves #452 file-switch reset
Preserves #253 bidirectional annotation scroll (diff side)

For provenance purposes, this commit was AI assisted.

* fix(ui): address PR #509 review — viewport delivery and resize handle

Two P1 bugs from the review, plus four correctness/cleanup items.

P1: OverlayScrollbars viewport was never delivered to consumers.

handleOsRef was reading osInstance() synchronously from the React ref
callback, but `defer: true` queues the library's initialization for a
later frame — at ref-callback time, the internal instance ref is still
null. With a stable useCallback the ref never re-fires, so
onViewportReady was never called with a real viewport. Every consumer
of useOverlayViewport/useScrollViewport stayed permanently null:
useActiveSection, TableOfContents.handleNavigate, Viewer sticky
detection, PinpointOverlay, DiffViewer file-switch reset, LiveLogViewer
follow-tail — all silently no-ops.

Fix: deliver the viewport via the library's own `events.initialized`
and `events.destroyed` callbacks, which fire exactly when elements are
ready and when they're torn down. `getViewport()` prefers the tracked
viewport ref over the imperative osInstance() path so late callers
still work.

P1: right-side ResizeHandle touch area was 0px wide.

Touch area is an absolute-positioned child of a w-0 parent, so actual
width = parent - left - right. With side='right' I'd set `left-3
-right-3`, which evaluates to `0 - 12 - (-12) = 0`. The annotation
panel resize handle in plan mode and both right handles in code review
had no draggable region. The visible 4px track has no event handlers,
so the only affordance was cursor-style feedback — drag did nothing.

Fix: revert to `left-0 -right-3` (12px wide, entirely right of the
boundary, no left encroachment into the adjacent scrollbar zone —
which was the original correct value before this branch). Rewrote the
comment to explain the geometry trap instead of protecting the value
that broke it.

Additional fixes:

- OverlayScrollArea: prefers-reduced-motion now reactive via
  useSyncExternalStore — OS toggle mid-session propagates to mounted
  instances instead of staying frozen at mount-time snapshot.
- OverlayScrollArea: `ref as never` replaced with a narrow cast to
  `React.RefCallback<OverlayScrollbarsComponentRef<'div'>>` so future
  signature changes get type feedback.
- PinpointOverlay: window resize listener moved above the scroll
  viewport guard so it attaches unconditionally. Scroll listener still
  requires the viewport (correct). Old code always registered resize
  on window; new code was accidentally skipping it when viewport was
  null.
- TableOfContents: `className || default` changed to `className ??
  default`. An explicit empty string from a caller (SidebarContainer
  passing className="" now that it wraps us in an OverlayScrollArea)
  should mean "no container styling", not "use the default". The old
  || operator treated "" as falsy and applied the default, leaving
  dead overflow-y-auto and unintended backdrop-blur on the nav.
- useOverlayViewport: removed redundant double cast and `?? null`
  no-op in the ref setter.

For provenance purposes, this commit was AI assisted.

* fix(ui): print clipping with overlay scrollbar wrappers

When <main> is wrapped in OverlayScrollArea, the library adds its own
attribute-selector CSS rules: `[data-overlayscrollbars~="host"]` gets
`overflow: hidden !important` and `[data-overlayscrollbars-viewport]`
gets `overflow-x/y: hidden` (or scroll) with fixed viewport heights.
These beat our existing `main { overflow: visible !important }` print
override on specificity — attribute selectors outrank tag selectors
even when both use `!important`. Result: long plans printed only the
currently-visible viewport instead of flowing across pages.

Fix: add a print-scoped override that targets the library's attribute
selectors directly, setting overflow:visible, height:auto,
max-height:none, and display:block to defeat both the overflow clip
and the flex layout the library applies to host/padding wrappers.

Verified by printing a multi-page plan in the dev server.

For provenance purposes, this commit was AI assisted.

* fix(ui): persistent overlay scrollbar, remove dead reduced-motion rule

Switch autoHide from 'leave' to 'never'. The previous behavior faded
the scrollbar 800ms after the pointer left the scroll host, which felt
broken in a common interaction pattern: click a TOC entry (pointer in
the sidebar) → trackpad-scroll (pointer still in sidebar) → 800ms idle
→ scrollbar disappears. User had to hover the right edge to bring it
back on every interaction.

Persistent visibility matches the pattern used by every editor-class
technical app (VS Code, Zed, JetBrains, Xcode, Sublime) where the
scrollbar is both a position indicator and a targeting surface for
click-to-jump. Overlay scrollbars cost zero layout space, so "always
visible" has no downside.

Also removes the dead `.os-theme-plannotator .os-scrollbar` selector
from the reduced-motion block. The library applies the theme class
directly to the .os-scrollbar element itself (verified in the library
runtime source, not just CSS), so a descendant selector with a space
matches nothing. The track and handle selectors in the same block
work correctly (they really are descendants) and are preserved.

The component's own prefers-reduced-motion hook and helpers are now
unused (autoHide is unconditionally 'never') and removed. Reduced
motion is still honored for the hover color + width transitions on
track/handle via the CSS @media (prefers-reduced-motion: reduce)
block in theme.css, which the browser evaluates independently.

For provenance purposes, this commit was AI assisted.

* docs(ui): update OverlayScrollArea jsdoc to match persistent-scrollbar behavior

The component header still described the old autoHide:'leave' behavior
and implied the reduced-motion branch was in the component itself.
Neither is true after cf137bf. Rewrite the jsdoc to describe the
current behavior: always visible, no fade, reduced-motion handled via
a CSS media query in theme.css rather than a React branch.

For provenance purposes, this commit was AI assisted.

* fix(ui): recompute scrollbar on content resize (pierre/diffs expand-lines)

When pierre/diffs expanded context lines on a file whose diff previously
fit inside the viewport, the scrollbar stayed hidden until the user
manually scrolled or dragged the split-ratio handle to force a layout
recalculation.

Root cause: OverlayScrollbars' internal content observer doesn't see
the mutation because pierre/diffs renders inside a shadow DOM, and
MutationObserver does not pierce shadow DOM by default. The library's
own host-level size observer doesn't help either — the host (our
<main> / flex-1 container) has a fixed layout size that doesn't
change when content grows.

Fix: track the OverlayScrollbars instance in state and attach a
ResizeObserver to the viewport's first element child in a useEffect.
When the content's layout box grows — which happens even when the
growth originates inside a shadow tree, because layout size
propagates from shadow content to the shadow host — the observer
fires and calls `instance.update(true)` to recompute scrollbar
visibility. The call is debounced through requestAnimationFrame so
the browser commits the new layout before OverlayScrollbars reads
dimensions.

Verified manually in the compiled binary against PR #509 itself:
opening a small file, clicking pierre's expand-lines control, now
reveals the scrollbar immediately. No regression observed in normal
scroll / click-to-jump / file-switch / annotation-click paths.

For provenance purposes, this commit was AI assisted.

* docs(ui): document ResizeObserver content-resize mechanism

Add the content-resize auto-recompute behavior to OverlayScrollArea's
jsdoc header so the "what does this component do" summary is complete.
The inline comment on the effect already explains the mechanism; this
just surfaces it at the top.

For provenance purposes, this commit was AI assisted.
2026-04-07 14:17:32 -07:00
Michael Ramos ede10fef9c feat(ui): cross-file annotation visibility and adaptive navigation (#444)
- Shared CountBadge component replacing heavy TOC accent circles
- Per-file annotation count badges in FileBrowser and VaultBrowser
- Folder aggregate counts from descendant files
- Summary header showing total annotations across files
- Dot indicators on Files/Vault sidebar tabs when annotations exist
- Adaptive back button text (file list / file / message / plan)
- Cross-file annotation indicator in right panel with flash highlight
- Fix directory prefix matching bug (startsWith without trailing slash)
- Move flash animation CSS to shared theme stylesheet

For provenance purposes, this commit was AI assisted.
2026-03-30 21:39:00 -07:00
Michael Ramos 4627f75426 feat: external annotations API with real-time SSE (#400)
Adds a general-purpose External Annotations API that allows external programs (linters, AI tools, security scanners) to push annotations into a live Plannotator session via HTTP, with real-time delivery over SSE.

## What's included

- **Shared core** (`packages/shared/external-annotation.ts`): types, in-memory store, input validation, SSE serialization
- **Server handlers**: Bun + Pi implementations with full CRUD (GET/POST/PATCH/DELETE) + SSE streaming
- **Client hook** (`useExternalAnnotations`): EventSource with polling fallback, optimistic updates
- **Editor integration**: two-array state model (local + external), content-aware dedup, ID-based routing
- **Persistence**: source field preserved through share URLs and crash-recovery drafts
- **Docs**: new Integrations category with API overview page, updated API reference

## API surface

All three servers (plan, review, annotate) expose:
- `GET /api/external-annotations/stream` - SSE stream
- `GET /api/external-annotations` - JSON snapshot (polling fallback)
- `POST /api/external-annotations` - Add annotations (single or batch)
- `PATCH /api/external-annotations?id=` - Update fields
- `DELETE /api/external-annotations` - Remove by id, source, or clear all

For provenance purposes, this commit was AI assisted.
2026-03-29 17:18:31 -07:00
Michael Ramos 93c0f035b3 feat: annotatable diff view with diff context in feedback
* refactor: extract useAnnotationHighlighter hook from Viewer

Move annotation plumbing (web-highlighter lifecycle, toolbar/popover
state, text-selection handlers, findTextInDOM, applyAnnotations) out
of Viewer.tsx into a dedicated hook. Pure refactor — zero behavior
change. Viewer consumes the hook and keeps its own code block, global
comment, and pinpoint-specific logic.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: block-level diff annotation with diffContext support

Add annotation support to plan diff view using block-level hover.
Hovering added/removed/modified sections shows the annotation toolbar.
No web-highlighter in diff mode — annotations live in React state only.

- diffContext field on Annotation type (added/removed/modified)
- PlanCleanDiffView: hover handlers, toolbar, comment/quicklabel flows
- Annotated blocks show persistent highlight ring via content matching
- View isolation: diff annotations filtered to diff view, normal to normal
- Share/draft restore filters diff annotations from Viewer DOM
- AnnotationPanel: neutral "diff" badge for diff annotations
- Export: [In diff content] label in feedback
- Toolstrip visible during diff mode for mode switching
- CLAUDE.md updated

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: scroll-to-selected and visible highlight ring for diff annotations

Add scroll-to-selected when clicking a diff annotation in the panel —
scrolls to the block and briefly glows (same focused effect as Viewer).
Replace invisible ring-1 ring-primary/20 with ring-2 ring-accent for
annotated blocks so they're visually distinct.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* cleanup: memoize annotation filters, fix timer leaks, use blockId for highlight rings

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: preserve normal annotations across diff toggle

Replace ternary rendering with display:none so the Viewer
stays mounted and web-highlighter DOM marks survive the toggle.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: store full block content in diff annotations instead of truncating to 500 chars

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 23:47:35 -07:00
Michael Ramos e1bd27aae4 feat: custom theme system with 18 built-in themes (#294)
* feat: custom theme system with 15 built-in themes

Consolidate CSS theming into a single source of truth (packages/ui/theme.css)
and introduce a multi-theme architecture where each theme defines both dark
and light mode variants. Users can pick a color palette (theme) and separately
toggle dark/light mode within it.

- Extract shared color tokens, Tailwind bridge, and base styles into packages/ui/theme.css
- Replace hardcoded oklch values with token references (oklch from var syntax)
- Fix 3 light-mode bugs in review-editor diff colors
- Create 15 built-in themes: Plannotator (default), Claude+, Soft Pop, Adwaita,
  Caffeine, Cyberdyne, Cyberfunk, Doom 64, Dracula, Gruvbox, PaulMillr,
  Quantum Rose, Solar Dusk, Terminal, Tinacious
- Expand ThemeProvider to manage colorTheme + mode independently
- Add Theme tab to Settings with mode toggle, search, and swatch grid
- Dark-only themes (Dracula, Terminal, etc.) suppress light class to prevent
  broken styling; light-only themes (Tinacious) force it
- Cookie persistence: plannotator-color-theme for palette, existing key for mode
- Include theme conversion script for FinSitter theme adaptation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: refine themes, add Catppuccin/Rosé Pine/Monokai Pro/Synthwave 84/Tokyo Night

Theme curation:
- Replace Cyberdyne with Synthwave '84 (from robb0wen/synthwave-vscode)
- Replace Cyberfunk with Catppuccin (Mocha dark + Latte light), Rosé Pine
  (dark + Dawn light), Monokai Pro (dark only), Tokyo Night (Storm + Day)
- Rewrite Gruvbox from canonical source (morhetz/gruvbox)
- Rewrite Adwaita from canonical VS Code theme (piousdeer/vscode-adwaita)
- Rewrite PaulMillr from Ghostty canonical palette

Theme fixes:
- Fix faded Send Feedback button on Solar Dusk, Quantum Rose, Caffeine
  (accent colors were too dark/invisible at 15% opacity)
- Fix Dracula/Terminal/PaulMillr/Tinacious light mode breakage — dark-only
  themes now suppress .light class via modeSupport in ThemeProvider
- Fix code block backgrounds — use --code-bg token instead of --muted
- Add faint green grid overlay for Terminal theme
- Alphabetize theme registry (Plannotator first)

Code review diff theming:
- Pass theme colors into @pierre/diffs shadow DOM via unsafeCSS prop
- Dynamic themeType based on resolved mode

18 built-in themes: Plannotator, Absolutely, Adwaita, Caffeine, Catppuccin,
Doom 64, Dracula, Gruvbox, Monokai Pro, PaulMillr, Quantum Rose, Rosé Pine,
Soft Pop, Solar Dusk, Synthwave '84, Terminal, Tinacious, Tokyo Night

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: increase settings modal height for theme grid visibility

Remove 340px cap on theme grid, bump content area from 70vh to 85vh
so all themes are visible without scrolling.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: memoize ThemeProvider context, deduplicate Mode type, clean up DiffViewer

From /simplify review:
- Export Mode type from ThemeProvider, import in ThemeTab (was duplicated)
- Add resolvedMode to context — consumers no longer re-query matchMedia
- Memoize context value with useMemo, setters with useCallback (prevents
  unnecessary re-renders of all useTheme consumers)
- Consolidate DiffViewer's two pierre state vars into single object
- Use resolvedMode from context in DiffViewer instead of classList check
- Format crammed single-line extended tokens in 4 theme CSS files

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: prevent FOUC, fix system mode stale read, restore marketing theme class

P1: Marketing site inline script now sets theme-{name} class on <html>
    before first paint (reads plannotator-color-theme cookie). Without this,
    CSS tokens under .theme-* selectors were never active.

P2: System mode effect now re-reads matchMedia.matches immediately when
    entering system mode, not just on future changes. Fixes stale resolvedMode
    when OS preference changed while pinned to explicit dark/light.

P3: ThemeProvider applies theme class synchronously during render (not in
    a passive useEffect) to prevent flash of unstyled content on hard refresh.
    Also extracted resolveThemeClasses to module scope to avoid useCallback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: add Quick Copy button, fix import icon, comment out agent badge

- Add Quick Copy button to annotation panel footer (splits horizontally
  with existing Quick Share). Copies annotations wrapped with the deny
  preamble so output is paste-ready for agent sessions.
- Export Modal annotations copy also wraps with deny preamble
- Extract wrapFeedbackForAgent() utility in parser.ts as single source
  of truth for the preamble text
- Fix desktop import icon to match mobile (arrow-into-document, not download)
- Comment out code review agent badge — unreliable across multiple harnesses

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-14 21:26:51 -07:00
Itay Grubman 5437a37da9 feat: add mobile compatibility (#260)
* feat: add mobile compatibility

- Add responsive hamburger menu with all header actions (MobileMenu)
- Annotation panel renders as full-screen overlay on mobile with backdrop and close button
- Panel starts closed on mobile (<768px)
- Touch support for resize handles, pinpoint annotations, and toolstrip buttons
- Mobile text selection creates annotations via highlighter.fromRange() bridge
- Card action buttons always visible on touch devices (hover:none media query)
- Settings modal uses horizontal tab bar on mobile
- CommentPopover width capped to viewport on small screens
- Replace mousedown with pointerdown for touch-compatible click-outside handling
- Add useIsMobile reactive hook for breakpoint detection
- Desktop layout (>=768px) unchanged

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: mobile layout polish — panel gap, button overlap, responsive labels

- AnnotationPanel: fix bottom gap on mobile overlay (inset-y-12 → top-12 bottom-0)
- Viewer: push in-plan action buttons below badges on mobile (mt-6), add
  clear-right before frontmatter, show short labels (Comment/Copy) on mobile
- App: reduce mobile horizontal padding to 8px (px-2)
- test-hook.sh: build review before hook to fix missing dist error

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add plan width display setting with compact/default/wide options

Adds a configurable plan width preference (compact 832px, default 1040px,
wide 1280px) with an abstract layout preview in Settings. Dynamic max-width
flows through to Viewer, PlanDiffViewer, and the toolstrip. Default is
compact to preserve existing behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-03-11 16:25:48 -07:00
Itay Grubman 2a461380b1 feat: bidirectional scroll navigation between annotations and highlights (#253)
* feat: bidirectional scroll navigation between annotations and highlights

When reviewing long plans with many annotations, it's hard to visually
connect which annotation card corresponds to which highlighted line.

- Click annotation card → scrolls content to the highlight + applies
  a bright cyan "focused" color for visibility
- Click highlighted text → scrolls the right panel to bring the
  corresponding annotation card into view
- Works with both web-highlighter and manually created (shared/imported)
  annotations
- Handles edge cases: global comments (no highlight), multi-node
  selections, already-visible elements

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: scroll to center and skip focus on annotation creation

- Change scrollIntoView block from 'nearest' to 'center' so targets
  appear prominently in the middle of the viewport
- Track just-created annotation IDs to skip scroll+focus effect when
  a new annotation is added (user is already looking at it)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 06:31:33 -07:00
Michael Ramos cb4de46636 feat: VS Code editor annotations + theme integration (#239)
* feat: add shared EditorAnnotation type

Single source of truth for the editor annotation interface,
imported by both @plannotator/server and @plannotator/ui.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: editor annotation server endpoints

In-memory store with POST/GET/DELETE endpoints for editor annotations.
The array lives in the handler closure and dies with the server session.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: editor annotation UI — polling hook, card, panel, and export

- useEditorAnnotations hook with auto-disable polling (500ms interval)
- EditorAnnotationCard with file path, code preview, and comment
- AnnotationPanel conditionally renders editor annotation section
- exportEditorAnnotations formats annotations for Claude feedback
- App.tsx wires hook, includes in output memo and send feedback gate

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: VS Code extension editor annotation command

Cmd+Shift+. or right-click to capture selected text as an annotation.
POSTs through the cookie proxy to the plannotator server. Adds amber
left-border decorations on annotated lines, cleared on panel close.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: inline comment threads, lightbulb menu, and stronger decorations

Replace showInputBox with VS Code CommentController for inline annotation
threads anchored to selected code. Add CodeActionProvider for lightbulb
discoverability. Stronger decoration styling with gutter icon.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: VS Code theme integration for webview

Bridge VS Code CSS variables to Plannotator's CSS variable system via
postMessage between wrapper page and proxied iframe. Automatically adopts
the active VS Code color theme (dark/light/custom) without touching any
UI components or CSS files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: gate editor annotation polling behind VS Code detection

Only poll /api/editor-annotations when running inside a VS Code webview
(window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have
zero network cost from the editor annotations feature. Also fixes poll
interval from 500ms to 2000ms.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: faster polling, prevent unnecessary re-renders, unify HTTP helper

- Poll interval 2s → 500ms for snappier annotation pickup
- Shallow equality check on annotation IDs prevents React re-renders
  when poll data is unchanged
- Merge postToProxy/deleteFromProxy into single requestProxy function

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: editor annotations support in code review

Wire existing editor annotation infrastructure into the review flow
so VS Code users can annotate files outside the diff during code review.

- Add editor annotation endpoints to review server (same 3-line pattern)
- Call useEditorAnnotations hook in review App.tsx
- Display editor annotations in ReviewPanel with "Editor" divider
- Include editor annotations in feedback export and gating logic

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
Michael Ramos bf4589e395 fix: guard Enter key handlers with isComposing for CJK IME support (#201)
CJK users press Enter to confirm IME character selection, which
was triggering form submission instead. Add !e.nativeEvent.isComposing
guard to all Enter-to-submit handlers in the plan editor UI.

Fixes #191

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 22:45:37 -08:00
Michael Ramos e46815d8ea 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
김영준E 044a50ea2c ✨ feat: add resizable side panels (#141)
Add drag-to-resize for the annotation panel, table of contents,
and file tree sidebar. Panel widths persist in cookie storage
across sessions and random-port hook invocations.

- Add useResizablePanel hook with left/right side support
- Extract ResizeHandle component with spread-friendly handleProps API
- Apply to AnnotationPanel, ReviewPanel, TableOfContents, FileTree
- Double-click handle to reset to default width
- Add min-w-0 on content areas for proper flex shrinking
2026-02-12 11:19:14 -08:00
Michael Ramos 131d1b9d0e feat: add config to disable URL sharing (#69)
Add deployment-level configuration to disable URL sharing for
security/privacy concerns.

Configuration methods:
- Claude Code: PLANNOTATOR_SHARE=disabled env var
- OpenCode: "share": "disabled" in opencode.json (primary), env var fallback

When disabled:
- Quick Share button hidden in annotation panel
- Share tab hidden in export modal (shows only Raw Diff)

Closes #69

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 13:12:37 -08:00
Gregson Murcia 4e18e3dccc feat: enable inline editing for annotations (#58) 2026-01-13 20:29:47 -08:00
Michael Ramos 046ca06fcb feat: improve dark mode contrast and add success/warning tokens (#54)
- Lift background from 13% to 15% lightness (softer than pure black)
- Soften foreground from 95% to 90% (reduces glare)
- Increase surface elevation separation (card 22%, popover 28%)
- Make muted-foreground more readable (65% → 72%)
- Make borders more visible (28% → 35%)
- Add --success and --warning design tokens
- Replace all hardcoded Tailwind colors (green-500, purple-500, yellow-500)
  with design tokens for consistent theming
- Boost annotation highlight opacity in dark mode for better readability

Closes #53

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-11 09:37:42 -08:00
Michael Ramos 386a9e6d4a Feat: Add image attachments with annotation drawing
- Add global (plan-level) and per-annotation image attachments
- Image upload via drag-drop, file picker, or clipboard paste (Cmd+V)
- ImageAnnotator component for drawing on images before saving
  - Freehand pen, arrow, and circle tools
  - Adjustable stroke size and color presets
  - Edge-to-edge circle drawing
- Server endpoints for image upload (/api/upload) and serving (/api/image)
- Images stored as paths in /tmp/plannotator/, included in export for Claude
- Preserve image paths in URL sharing for round-trip scenarios
- Uses perfect-freehand (~2KB) for smooth pen strokes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 17:06:43 -08:00
Michael Ramos 226f2ad25d Feat/ux improvements (#10)
* handle indents and checkboxes

* menu persistence when scrolling

* better ux on teh annotation comment box
2026-01-02 08:57:01 -08:00
Michael Ramos 22aae761e1 add global comments (#8)
* Add global comments annotation capability

- Add GLOBAL_COMMENT type to AnnotationType enum
- Add "Global comment" button next to "Copy plan" in Viewer header
- Implement inline input form for entering global comments
- Update AnnotationPanel to display global comments with purple styling
- Update exportDiff to include global comments in feedback output
- Update sharing utils to serialize/deserialize global comments with 'G' prefix

* Add fallback for unknown annotation types and update docs

- Add fallback config in AnnotationPanel for forward compatibility
  (prevents crash when portal encounters unknown annotation types)
- Update CLAUDE.md with GLOBAL_COMMENT enum value
- Update CLAUDE.md with 'G' ShareableAnnotation variant
2026-01-01 11:23:01 -08:00
Michael Ramos 34297b5c55 Restructure to Bun monorepo with apps and packages
- apps/hooks: Claude Code hook integration (ExitPlanMode)
- apps/portal: Standalone web portal (future)
- apps/marketing: Landing page (future)
- packages/ui: Shared React components and utilities

Key improvements:
- Cookie-based settings persistence (works across random ports)
- Bundled highlight.js with per-block language detection
- Inline markdown rendering (bold, italic, code, links)
- Fixed sprite z-index layering

Legacy code preserved in legacy/ for reference.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 21:24:05 -08:00