mirror of
https://github.com/backnotprop/plannotator.git
synced 2026-09-14 14:17:26 +08:00
codex-mobile-phase-1b-input
38 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
f8951cd3c6 |
feat(annotate): shift-click multi-element selection for raw-HTML pinpoint (#1254)
* feat(annotate): shift-click multi-element selection for raw-HTML pinpoint drafts One comment covering multiple targets: shift-clicking elements while a pinpoint draft composer is open toggles them in/out of the SAME draft. - bridge: pendingMultiTargets registry with per-target pinned outline boxes, DOM-identity + anchor-equality toggle dedup, primary promotion on removal, draft cancel on last removal, shift-hover preview, rAF pointer relay for the composer yield, remove-target/flash-target parent messages, capped at 16 additional targets at the source - pins: registerPin now allows several elements per annotation id (deduped by (id, element)/(id, anchor)); badges number by first-seen id so all targets of one annotation share one number; find-and-mark restores additionalAnchors as same-numbered pins (anchor-only, fail-closed) - parent hook: multi-target-added/removed/pointer messages validated and capped at the trust boundary (key<=64, label<=64 truncated, text via the 10k surrogate-safe cap, anchors via parseHtmlElementAnchor, array cap 16); draftTargets state, chip removal with deterministic promotion mirrored on both sides, composerFocusToken for focus return - types: additive Annotation.htmlAdditionalTargets (label/text/anchor per extra target; anchor optional so fail-closed targets still export) - CommentPopover (all seams optional, default off): horizontally scrollable target chips with remove buttons and hover-to-flash, refocusToken, captureStrayKeys first-keystroke guard, yieldState fade/click-through with 180ms transition and prefers-reduced-motion fallback - HtmlViewer: composer-yield state machine (composerYield.ts) fed by parent mousemoves plus bridge-relayed pointer positions, with 48px/96px hysteresis - export: multi-target comments append an 'Also applies to N more elements' block (label + excerpt per target); single-target output byte-identical - share URLs: additional targets are dropped exactly like htmlAnchor (the compact tuple format never carried anchors); drafts carry them verbatim * test(annotate): cover shift-click multi-select across bridge, DTO, composer, export, drafts, sharing - srcdoc.test.ts (bridge DOM): shift-click add + toggle-off with echoed removals and per-target pinned boxes; create-mark commits all targets under one id with one badge number (second annotation numbers 2); primary promotion and last-removal cancel; parent remove-target mirrors without echo; flash-target; 16-target cap at the source; find-and-mark restores additionalAnchors as same-numbered pins with stale anchors failing closed - htmlPinpointProtocol.test.tsx: multi-target-added/removed/pointer DTO validation (key/label/text/anchor caps, hostile payloads), selection targetKey/targetLabel validation; mounted-composer flows — primary chip, shift-adds into ONE submitted comment carrying htmlAnchor + 2 additional targets, single-target submit shape unchanged, promotion onto the comment, last-removal closes the composer, chip removal, 16-cap at the trust boundary, drag selections never arm multi-select - CommentPopover.multiTarget.test.tsx: chips render primary-first with remove/hover handlers, refocusToken focus return, captureStrayKeys stray keydown routing (and non-interference when focused), yieldState classes + reduced-motion-aware 180ms style; default composer renders none of it - composerYield.test.ts: distance + hysteresis state machine (48px over-exit, 80/96px near enter/exit) - parser.test.ts: multi-target export block (labels, excerpt clipping, fail-closed targets) and byte-identical single-target output - useAnnotationDraft.seam.test.tsx: multi-target annotations round-trip the draft transport verbatim (save body + restoreDraft) - sharing.multiTarget.test.ts: share tuples drop anchors AND additional targets while the comment itself still shares * fix(annotate): keep pinpoint drafts alive when the pinned element scrolls out of view Found by the real-browser signoff harness: reaching a second element to shift-click often scrolls the pinned primary out of the viewport BEFORE any additional target exists, and the scroll-out teardown then cleared the bridge's pin state mid-compose — the shift-click landed on a dead draft and started a new one instead of adding to it (and even a single-target pinpoint draft silently lost its visual pin on commit after scrolling). Pinpoint drafts (pendingPinViaPinpoint) now survive scroll-out; drag selections keep the existing close-on-scroll-out behavior unchanged. * fix(annotate): address adversarial review of multi-select (arm handshake, label sanitization, iframe shift relay, removal resync) D1 (blocker): the bridge accepted shift-toggles for ANY pinpoint draft while the parent only mirrors targets when the comment composer owns it — in quickLabel mode the user could pin elements the saved annotation would never carry. Multi-select is now ARMED EXPLICITLY: the parent posts arm-multi-select (keyed to the primary, so a stale arm can never arm a new draft) only from the composer flow, and the bridge refuses the toggle — shift-click behaves as a plain click — until armed. D2: target labels derive from page-controlled attributes (aria-label), so newlines could smuggle real markdown structure (fake headings) into agent-read feedback. parseTargetLabel now collapses all whitespace at the trust boundary, and the exporter collapses again (defense in depth for persisted pre-fix drafts). D3: the composer yield armed Shift only from parent-window keydown/mousemove, but window blur (focus entering the iframe) cleared it and modifier keydowns don't reach the parent from the sandbox — from the second shift-click on, the composer never yielded. The bridge pointer relay now carries the observed shiftKey (validated strict boolean) and arms/disarms yield directly. D4: a forged multi-target-removed desynced parent (promotes) from bridge (keeps original). applyTargetRemoval now ALWAYS echoes remove-target — idempotent for legit bridge-side removals, forcing convergence after forgery. D5: the 'Also applies to N more elements' block gains a leading blank line so markdown lazy continuation cannot fold it into the preceding blockquote. D6: the stray-key guard registers in capture phase (a bubbling global shortcut can no longer both fire and have its character appended), inserts at the textarea's remembered caret instead of end-of-text, and refocusToken now preserves the caret rather than jumping to the end. D7: the expanded dialog no longer carries the dead yield class/style — its data-comment-popover wrapper spans the viewport, making proximity meaningless; the dialog deliberately does not yield. Also reverts the incidental bun.lock version-catch-up churn. Tests: unarmed/stale-arm refusal, quickLabel non-arming and non-mirroring, newline-label collapse at both layers, bridge-shift-driven yield, forged removal echo + bridge-side idempotent resync, caret-preserving stray keys, blockquote separation. Signoff harness re-run green (14/14) on rules-ui-signoff.html including the arm handshake. * fix(annotate): reset multi-select arm on every new pinpoint draft (D1-R) The re-review caught that multiSelectArmed was never cleared when annotateElement started a fresh draft — only clearPendingPin reset it. So a comment-mode draft (armed) followed by a mode switch the parent doesn't mirror (quick label posts no arm) and a new pinpoint click left the stale arm live: the bridge accepted shift-clicks and pinned elements the saved annotation would never carry. Reset the flag at the top of annotateElement alongside clearMultiTargets. Regression test reproduces the exact sequence (armed draft -> new unarmed draft -> shift-click must not add a target); mutation-verified that removing only this reset fails it. * docs(annotate): correct the first-keystroke guard comment reasoning The comment claimed capture phase prevents a global shortcut from also firing; preventDefault does not stop the dispatcher (it ignores defaultPrevented by design). Restate the actual invariant: the guard is safe only because no bare printable single-key binding exists on this surface, and flag that as a constraint for future bindings. Comment only. |
||
|
|
7ad4d39ed9 |
feat(comments): reference agent skills with / or $ in plan review and annotate comments (#1229)
* feat(comments): reference agent skills with / or $ in plan and annotate comments
Typing / or $ at the start of a word in the document-UI comment composer
opens a picker of the user's global agent skills (~/.claude/skills,
~/.codex/skills, ~/.agents skills roots), served by a new GET /api/skills
on the plan and annotate servers in both runtimes (Bun + Pi mirror).
Multiple references per comment are supported; references live in the
comment text itself and are appended to exported feedback as a
'Skills referenced' block so the acting agent knows which skills to apply.
Human-invocation-only skills (disable-model-invocation: true frontmatter)
stay listed and selectable but render dimmed with a badge, warn in the
menu and composer, and are marked in the export so the agent is never
asked to invoke something it cannot.
Discovery reuses the review-skill loader (same roots, precedence, and
skip-and-log discipline), reads only an 8KB head per SKILL.md, caps the
catalog at 500 skills, takes no client input, and is never persisted;
any failure degrades to plain typing.
* fix(comments): harden skill references per review (trigger, IME, seam, fail-closed frontmatter)
Blockers:
- B1: a trigger now requires at least one query character. A bare / or $
no longer opens the catalog, so Enter stays a newline and Tab still
leaves the field ("This costs $" + Enter, "cd /" + Tab, bullets).
- B2: the menu ignores keys mid-IME-composition (nativeEvent.isComposing),
matching the 16 existing guards; Enter committing a Pinyin/Telex/Korean
candidate can no longer insert a skill.
- B3: the catalog request is a host seam (skillCatalogTransport via
configurePlannotatorUI), defaulting to the existing GET /api/skills.
- B4: resetSkillCatalogCache() invalidates outstanding requests
(generation counter), and a late-resolving stale request can no longer
overwrite a newer cached value or the export registry. The catalog
tests reset in beforeEach, so they hold in any file order.
Also:
- F1: skillReferences={false} is fully inert — the human-only notice memo
and the cache seed are gated on the prop.
- F4: frontmatter flag parsing no longer fails open: trailing YAML
comments are stripped, on/1 (and TRUE/yes etc.) read as true, the head
read is 64KB, and truncated unterminated frontmatter fails CLOSED on
disable-model-invocation.
- F5: extraction ignores markdown link destinations ([x](/name)), shell
redirects (cat /x > out), and /-triggered FHS root names (/run, /tmp);
menu insertion switches / to $ for those names so inserted references
always survive extraction.
- F6: the 500-skill cap slices after sorting, so which skills survive no
longer depends on readdir order.
- F3: /api/skills wiring guards for the Bun and Pi plan + annotate
servers (skills-endpoint.test.ts).
- Keyboard state machine tests against the real CommentPopover in
happy-dom (bare trigger, insertion, composition, Escape, highlight
bounding, opt-out inertness), added to the CI DOM step.
- The insertion path dismisses the trigger start so the menu close is
ordering-safe against React's select-plugin re-reading a stale caret.
* feat(comments): redesign the skill reference menu (bare triggers, no preselection, highlighted tokens)
Per maintainer direction, reversing the earlier bare-trigger opt-out
deliberately: typing a bare / or $ at the start of a word now opens the
full skill catalog immediately, and the safety story moves from the
trigger to the menu itself.
No preselection (the load-bearing rule): the menu opens with NO row
active, and while nothing is active every key behaves exactly as if the
menu were closed. "This costs $" + Enter is a newline; "cd /" + Tab
leaves the field (the proven regression that must never return). A row
activates only via ArrowDown/ArrowUp (Down from none lands on the first
row, Up on the last); only then do Enter/Tab insert. Pointer hover never
activates a row, because the menu floats exactly where the mouse rests
over the composer; a click inserts directly and never arms Enter.
Continuing to type re-filters and disarms any active row. Escape clears
the active row and dismisses when the user engaged (query typed or row
active); an unengaged bare-trigger menu passes Escape through so closing
the composer still costs one press.
Menu redesign to the reference look: icon, bold name, dimmed inline
description with ellipsis, right-aligned source column (Agents / Claude
/ Codex from the discovery roots), rounded generously padded rows, and a
subtle active-row background; human-only rows stay dimmed with their
badge and the warning now shows while such a row is ACTIVE.
Inserted references render highlighted in the composer via a mirrored
aria-hidden overlay behind a transparent-text textarea (identical font,
padding and wrapping metrics; scroll synced; tokens change color and
background only, drawn from the --primary theme token so every palette
works in light and dark). The caret keeps --foreground, selection uses a
translucent primary wash, and IME composition temporarily restores
native textarea text so composition underlines render normally.
skillReferences={false} still renders the plain pre-feature textarea.
Also, per review:
- extraction: dropped the over-broad shell-redirect exclusion (false
negatives on prose like "use /animate <- this one"; the motivating
case stays covered by the reserved-path rule)
- frontmatter: an unterminated frontmatter block now fails CLOSED on
disable-model-invocation even in complete (untruncated) files
- the reserved-path / to $ insertion switch stays: extraction still
reads /run as a path, and the new token highlight makes the switch
self-explanatory (an unhighlighted insert would look broken)
The composition guard, transport seam, catalog generation counter,
enabled gating, and export rules are unchanged and re-covered by the
rewritten DOM test matrix.
* fix(comments): give the skill reference menu adaptive, viewport-clamped placement
The menu rendered bottom-full with a fixed max-h-64: always upward, up to
256px, with no viewport awareness. With the comment popover near the top of
the viewport (annotating near the top of a document), typing a trigger ran
the menu off the top of the screen with its upper rows unreachable.
Placement now mirrors the popover's own computePosition idiom: measure the
space above and below the composer wrapper against window.innerHeight,
prefer above (the shipped direction; keeps the action row and human-only
notice visible), flip below when the list fits below but not above, and when
neither side fits pick the roomier side. The list's max height is clamped to
the available space (still capped at the former 256px), so the menu never
extends past a viewport edge. Recomputes on every commit (drag moves,
popover flips, filtering changing the item count, warning-footer toggles)
plus capture-phase scroll and resize listeners, matching the popover's
tracking. Visual design of the menu and rows is unchanged.
* feat(comments): inject human-only skill instructions into exported feedback
A human-only skill (disable-model-invocation: true) referenced in a review
comment used to export as a dead name the agent could do nothing with. A
human referencing a human-only skill IS the human invocation, so the export
now injects the skill's SKILL.md body verbatim (frontmatter stripped) inside
clearly delimited BEGIN/END SKILL INSTRUCTIONS markers, with the absolute
skill directory and the resolve-relative-paths pointer so references/,
scripts/, and assets/ stay actionable. Model-invocable skills keep exporting
as names the agent can invoke itself.
Transport is lazy: a new GET /api/skills/content?name= endpoint (Bun and Pi)
serves one discovered skill's body, capped at 20k chars with an explicit
truncation notice pointing at the file; the client fetches contents only for
the human-only skills actually referenced, keyed off comment state, and the
catalog now carries each skill's absolute dir so every failure path (deleted
skill, unreadable file, race with submit) degrades to naming the skill plus
its directory. Names are matched against discovery only and never used as
paths, so traversal cannot escape the skill roots. A per-export dedupe
injects each skill once even when several comments reference it, and
GLOBAL_COMMENT annotations run through the same block.
The referenced-skills header now says the reviewer is asking for the
invocation, and the human-only menu footer and composer notice explain that
the skill's instructions will be included with the feedback instead of
warning that the reference will not work.
* polish(comments): quiet, progressive human-only skill treatment
The human-only surfaces shipped with too much emphasis: a dimmed row plus
a bordered uppercase badge, an amber warning footer, and a persistent
amber notice in the composer after insertion. Human-only is a property of
a skill, not an error state, so the treatment is now quiet and
progressively disclosed:
- Menu rows render at full strength with a small muted 'human-only' pill
(bg-muted / muted-foreground tokens; no border, no dimming).
- The plain-language explanation (a model cannot invoke it, so its
instructions will be included with your feedback) appears as a muted
footer only while a human-only row is active (keyboard) or hovered
(pointer). Hover disclosure is purely visual state local to the menu;
it never touches activeIndex, so the no-preselection invariant and the
hover-never-arms-Enter rule are unchanged and re-asserted by a new test.
- When not disclosed, the same sentence stays in the DOM sr-only and
human-only rows point at it with aria-describedby, so the state reaches
assistive tech as text rather than as a purely visual badge (this does
not attempt the #1233 combobox semantics, and does not worsen them).
- After insertion, the highlighted token itself carries the quiet inline
marker (a dotted primary underline; text-decoration cannot move glyphs,
so overlay alignment is untouched) and the standing amber notice is
replaced by a native <details> disclosure: a single muted 'Includes
skill instructions' summary line that expands to the full accurate
sentence, operable by pointer, keyboard, and AT alike.
No amber remains; every color is a theme token (muted, muted-foreground,
border, primary, ring), so the treatment follows every palette in light
and dark. Copy is unchanged where it was accurate. Behavior is unchanged:
human-only skills stay selectable and injection still happens.
* fix(comments): harden human-only skill injection per adversarial review
Three findings on the injection path, each with tests that fail pre-fix:
1. Marker forgery: an injected SKILL.md body containing our own
`--- BEGIN/END SKILL INSTRUCTIONS ---` markers (or an
`[Instructions truncated:` notice) could close the block early — making
everything after it read as the reviewer's own words — forge a block for
a skill nobody referenced, or forge a truncation notice pointing at an
attacker-chosen path. Body lines matching the structural marker forms
(leading-whitespace and case variants included) are now visibly
neutralized before injection: kept verbatim but prefixed, never silently
deleted (neutralizeSkillMarkerLines).
2. Forged human invocation: POST /api/external-annotations is
unauthenticated on localhost, so any local process could submit a
comment referencing a human-only skill and cause its instructions to be
injected "at the reviewer's request". Annotations carrying a `source`
now still LIST their skill references but never cause verbatim
injection — human-only references fall back to naming the skill plus
its directory, with an honest reason. The content-prime effect skips
external texts for the same reason. A human referencing a human-only
skill IS the human invocation; a tool is not.
3. Unbounded read: readReferenceSkillContent read the whole SKILL.md
before slicing to the 20k cap, so an unauthenticated no-cors fetch loop
could balloon RSS by file size per request (measured +64.4MB for a 64MB
file). It now uses the same bounded readFileHead as the catalog,
reading only frontmatter allowance + 4 bytes per capped char + slack;
truncation detection is unchanged for any file whose frontmatter fits
the catalog bound, and frontmatter that overflows the read falls back
to null rather than serving raw YAML. Measured: 12 reads of a 64MB
SKILL.md now cost +5.1MB total.
Also: the fast-fail guard no longer rejects legitimately discovered names —
`name.includes("..")` 404'd a real `v1..2` skill dir forever (and `\` is
legal in POSIX names) while defending nothing, since the name is only ever
matched against discovery output and never joined into a path. It now
rejects exactly the names that can never be a readdir entry: empty, `.`,
`..`.
|
||
|
|
9389a8c543 |
feat(ui): render markdown reference links (#1168)
* feat(ui): render markdown reference links The simplified markdown parser only understood inline links `[text](url)`, so CommonMark reference links rendered as raw text: `[text][id]` and the `[id]: url` definition both showed literally (#923). Add `resolveReferenceLinks`, a pure pass run at the top of `parseMarkdownToBlocks` that rewrites full (`[text][id]`), collapsed (`[text][]`), and shortcut (`[text]`) references, plus their image forms, into inline `[text](url)` links, so the existing inline renderer draws them. Link reference definitions are collected first (first definition wins, labels matched case-insensitively with collapsed whitespace, `<url>` and quoted-title forms supported) and then blanked in place, so a definition never renders and every block keeps its original source line number. Resolution is code-aware: references and definitions inside fenced code blocks and inline code spans are left verbatim, a shortcut is skipped when an inline `(...)` destination follows it or when it is a task-list checkbox marker at the start of a list item, and an unknown reference stays literal so bracketed prose like `[TODO]` or `[0]` never becomes a false link. A definition-shaped line is only collected when it can start a block (after a blank line, a code fence, another definition, or the document start), so a `[word]: token` line that continues a paragraph is left as text rather than deleted (CommonMark: a definition cannot interrupt a paragraph). A document with no definitions is returned unchanged. * fix(ui): protect code/HTML/footnotes and quadratic risk in reference-link resolution Owner review round for reference-style link resolution (#923): - Fence detection now mirrors the block parser's own naive rule exactly (full .trim() + startsWith('```'), any indentation, backtick-only — no ~~~ support) instead of a looser 0-3-space approximation, so indented and list-nested fences the block parser treats as code can never be rewritten. Aligns tilde-fence behavior the same way: since the block parser has no ~~~ support, the resolver no longer protects ~~~ blocks either. - Raw HTML blocks (<details>, <pre>, etc.) are now protected using the same HTML_BLOCK_TAGS/HTML_BLOCK_OPEN_RE/VOID_HTML_TAGS the block parser itself uses, with the same three termination rules (blank-line, void single-line, balanced-depth). - GFM footnote definitions ([^label]: ...) are excluded from collection entirely, so they and their [^label] references are never rewritten into inline links. - A definition-shaped line is now only blanked when its label was actually consumed by a resolved reference outside a protected region. Unused definitions, and definitions referenced only from inside code/HTML, stay visible. This also fixes a plan-diff bug: a URL-only edit to a definition line used to blank to nothing on both sides of the diff (a real change rendering as empty); now the isolated diff chunk keeps the definition visible and diffs normally. - CRLF lines are now recognized (definition regex tolerates a trailing \r) and preserved (a blanked line keeps its own \r). - Bound the label/text capture groups (999 chars, CommonMark's own label limit) and the code-span alternative (5000 chars) so a long run of unmatched brackets/backticks can no longer cause quadratic backtracking within the 2MB annotate cap; added a defense-in-depth cap on the number of definitions tracked per document. - Added coverage for nested brackets, backslash-escaped brackets, parenthesized destinations, idempotence, and confirmed dangerous destinations still flow through the existing sanitizeLinkUrl path unchanged. Added a migration-caveat note to the existing annotation-anchor section of packages/ui/HANDOFF.md: documents using reference-style links render differently now, which can shift position-based anchors captured before a host upgrades past this change. * fix(ui): bound HTML-block extent scan to kill quadratic unclosed-opener case markProtectedLines and parseMarkdownToBlocks each independently scanned line-by-line from a multi-line HTML opener until its balanced open/close depth returned to zero, giving up only at end-of-document. That scan never advanced the outer index on failure, so a document with many consecutive unclosed openers (e.g. thousands of bare <div> lines with no </div> anywhere) made every one of them re-run the same O(N) tail scan — O(N^2) total, a real hazard well within the 2MB annotate cap. Extract the scan into one shared helper, findHtmlBlockEnd, used by both call sites so they can't drift apart: - closeExistsFromLine lazily builds (once per tag name, cached per document) a suffix array answering whether a closing tag exists at or after a given line, so an opener that can never close is rejected in O(1) instead of scanning to EOF. - MAX_HTML_BLOCK_SCAN_LINES bounds the residual case (a closing tag exists far away but depth never actually reaches zero before it) to a constant amount of work per start position — a documented, safe degradation: a block whose true close sits beyond the cap is treated as unclosed, identically to today's 'no close ever found' case. Added a failing-before-fix perf test (many unclosed <div> lines took ~2.3-3.4s and blew a 800ms bound; now ~12-15ms) for both parseMarkdownToBlocks and resolveReferenceLinks, plus a parity test proving a real <details>...</details> block stays intact and identically protected/parsed among thousands of decoy unclosed <div> lines. * fix(ui): remove HTML-block scan cap that truncated valid long blocks MAX_HTML_BLOCK_SCAN_LINES (2000) fixed the O(N^2) unclosed-opener case but as a side effect also truncated genuinely valid, longer HTML blocks: a <details> or raw <table> block whose closing tag sits beyond 2000 lines got cut off mid-block, with its remaining content and the real closing tag falling through as separate, incorrect blocks. closeExistsFromLine already rejects an opener that can never close in O(1) (no closing tag anywhere in the document) without scanning a single line — that already eliminates the pathological 'many failing scans' case on its own. A cap on top of that only ever hurt the opposite case: a scan that DOES succeed, which happens once per document and costs O(L) for an L-line block exactly like reading any other block's content once. So the cap bought nothing further and could silently corrupt valid parsing for any block longer than it, however generous its value. Removed it; the scan now runs unbounded to its real end once closeExistsFromLine confirms a close exists at all. findHtmlBlockEnd is still the single shared implementation used by both markProtectedLines and parseMarkdownToBlocks, so both stay in parity. Added regression tests: a >2000-line <details> and a >2000-line raw <table> block each stay one whole html block (previously truncated); a link definition inside a >2000-line <details> block stays protected and never wins over a real definition outside it; a valid long <details> block survives even preceded by thousands of unclosed <div> decoys. Re-verified the 40k-unclosed-opener perf/parity case (already handled by closeExistsFromLine alone) stays fast and unaffected. * fix(ui): replace HTML-block close scan with a linear prefix-sum index Removing the fixed line-count cap fixed truncation of valid long HTML blocks, but reopened a closely related O(N^2) case: N unclosed <div> openers followed by a single trailing </div> all still pass the 'does a close exist anywhere' pre-check, so every one of them independently scanned forward (mostly to end-of-document) before giving up. Measured before this fix: 5000 openers ~1.0s, 10000 ~4.1s, 40000 timed out past 69s. Replaced the scan entirely with a per-tag-name prefix-sum index (buildTagCloseIndex): the running open-minus-close count for a tag name, plus a classic 'next element at or below this one' index over that prefix sum (an O(N) monotonic-stack construction, each position pushed/popped at most once). Finding where (if anywhere) a block starting at a given line closes is exactly that classic query, so it is now an O(1) lookup with zero scanning per opener, whether the block never closes, closes after 3 lines, or closes 3000 lines away. Both markProtectedLines and parseMarkdownToBlocks still share the single findHtmlBlockEnd implementation, so they stay in parity. 40000 unclosed <div> openers + one trailing </div> now resolve in ~30-45ms (parser and resolver both), with block-boundary parity between them. Re-verified: no truncating cap reintroduced (>2000-line <details>/<table> blocks still stay whole), nested same-tag blocks still balance on true depth (not just tag presence), and independent tag types (e.g. a <table> nested inside a <details>) don't cross-talk between their separate per-tag indices. |
||
|
|
6297358994 |
fix(ui): parse YAML block scalars in frontmatter (#1101)
* fix(ui): parse YAML block scalars in frontmatter Folded (>) and literal (|) values were stored as the bare indicator (e.g. ">-") with their body dropped, so multi-line skill descriptions rendered empty in the plan/annotate viewer. * fix: strip trailing CR from block scalar body lines (CRLF sources) --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> |
||
|
|
f9a6c1e39d |
feat: annotate accepts YAML, JSON, TOML and other plain-text files (#1099)
* feat(annotate): accept common plain-text config formats (.yaml, .json, .toml, …) Annotate previously rejected every file that wasn't .md/.mdx/.txt (or .html/.htm), even though the pipeline reads files as UTF-8 text and renders anything. Widen the accepted set to unambiguously plain-text config/data formats: .yaml .yml .json .jsonc .json5 .toml .ini .cfg .conf .properties .csv .tsv .log .xml .env.example. They render exactly the way .txt renders today. - New single source of truth: packages/core/annotatable.ts (ANNOTATABLE_TEXT_REGEX / ANNOTATABLE_DOC_REGEX + predicates), re-exported through @plannotator/shared/resolve-file and vendored into the Pi extension. - .env stays excluded (commonly holds secrets; annotate history copies file contents into the data dir). Source-code extensions stay with code review. - Single-file accept + bare-filename fuzzy search widen in resolveMarkdownFile; folder discovery and the file-browser listing widen in all three runtimes (hook CLI, OpenCode, Pi). - /api/doc gains a `doc=1` param set by the file browser so extensions that overlap CODE_FILE_REGEX (.yaml/.json/.toml/.ini/.xml) render as annotatable documents there while code-file links inside documents keep the syntax-highlighted popout. - Error messages now list the wider set; docs updated (AGENTS.md, marketing annotate page). Closes #1029 Claude-Session: https://claude.ai/code/session_01YXkgsNucxDwAL4GdR4XYRk * fix(annotate): frontmatter, size caps, edit-guard, and skill docs from review Review fixes for #1099: - Frontmatter: `--- … ---` stripping is a markdown convention; for non-markdown annotatable sources (multi-document YAML, .txt starting with ---) the delimiters are real content. parseMarkdownToBlocks gains a { frontmatter } option and the editor keys it off the active document's path via shouldStripFrontmatter() (strip for .md/.mdx and pathless/converted sources; keep raw for other annotatable text). - Size caps: new shared MAX_ANNOTATABLE_FILE_BYTES (2MB — same limit the code-file popout always had) now guards the annotate CLI single-file read in all three runtimes and the /api/doc document branches in both servers. Also applies to .md/.txt (behavior change for pathological inputs; previously unbounded). - Editing guard: mid-edit file opens gate on isSourceSaveFilePath (.md/.mdx/.txt) instead of the wider annotatable set — config files are view-only, so switching to one mid-edit no longer silently downgrades "Done editing" to feedback-only edits. - Skill docs: plannotator-annotate SKILL.md (core + Kiro) now mention the plain-text config formats. Claude-Session: https://claude.ai/code/session_01YXkgsNucxDwAL4GdR4XYRk |
||
|
|
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 |
||
|
|
070d9a5f6d |
Make the document UI reusable as published building blocks (#957)
* docs(adr): revert failed document-ui cutover, add ADR 004 with corrected reuse plan The document-ui extraction/cutover (ADRs 002/003) was an AI-driven rewrite that broke the app; the code was reverted. Add ADR 004 as the source of truth: share @plannotator/ui as published building blocks for the Workspaces app, keep Plannotator's app unchanged, gate on human-verified parity. Banner the reverted ADRs and point AGENTS.md/CLAUDE.md at 004 so future agents don't rebuild the mess. * docs(adr): add verified document-ui extraction plan, supersede draft inventory 36-agent verification of the reuse inventory: confirmed the /api coupling but found the draft missed Viewer's transitive backend call, the cookie settings layer, 3 React contexts + identity singleton, SSE transports, and harder packaging blockers. Adds the verified per-subsystem extraction plan with a parity guardrail on every step; flags the draft inventory as superseded. * docs(adr): add document-ui extraction roadmap + parity checklist Phase 0-7 execution roadmap (safety net -> packaging -> foundation seams -> rendering -> navigation -> comments -> extras -> publish) and the reusable 'did it break?' parity checklist run after every step. Both enforce the law: move + decouple, never rewrite; Plannotator's experience cannot change. * build(ui): packaging unblock for external install (Phase 1) — no runtime change Phase 0: captured parity baseline (typecheck/test/build + shipped-bundle hashes). Phase 1 packaging fixes to packages/ui, metadata only: - add phantom dompurify ^3.3.3 dep (imported in sanitizeHtml/aiChatFormat, was undeclared) - align diff ^8.0.3 -> ^8.0.4 with root - add peerDependencies (react, react-dom, tailwindcss, tailwindcss-animate); keep as devDeps - add files allowlist (excludes tests); remove dead tsconfig @plannotator/shared alias Verified byte-identical: typecheck pass, 1620 tests pass/0 fail, all 3 builds OK, shipped plan+review bundle hashes unchanged from baseline. Remaining Phase 1 blocker (@plannotator/ai + @plannotator/shared workspace:* deps) deferred pending a publish-vs-inline decision; logged in worklog. * feat(ui): make image URL resolution host-overridable (Phase 2, seam 1) getImageSrc now delegates to a module-level resolver defaulting to the verbatim Plannotator /api/image logic; add setImageSrcResolver/resetImageSrcResolver so a host (Workspaces) can resolve images via its own backend. All 5 consumers and the signature unchanged. Verified: default URLs byte-identical, typecheck pass, 1620 tests pass/0 fail, builds OK. No Plannotator behavior change. * feat(ui): make settings storage backend host-overridable (Phase 2, seam 2) storage.ts cookie impl is now the default 'cookieBackend'; add setStorageBackend/ resetStorageBackend so a host (Workspaces) can persist settings via its own storage. getItem/setItem/removeItem delegate to the active backend; the ~24 consumers and literal plannotator-* keys are unchanged. Verified: swap works, typecheck pass, 1620 tests pass/0 fail, builds OK, theme persists across reload. * feat(ui): make MarkdownEditor theme mode host-supplyable (Phase 3) Add optional mode? prop; mode now mode ?? resolvedMode. Plannotator passes no mode (App.tsx:4261) so it keeps using ThemeProvider's resolvedMode unchanged. A host without ThemeProvider can supply mode directly. Verified: typecheck pass, 1620 tests/0 fail, builds OK, App.tsx untouched. * feat(ui): allow hosts to opt out of code-path validation (Phase 3) Viewer gains optional disableCodePathValidation? threaded to a new disabled? arg on useValidatedCodePaths; when set, the /api/doc/exists probe is skipped. Default undefined for Plannotator => validation stays on, /api/doc/exists fires exactly as today. Verified: typecheck pass, 1620 tests/0 fail, builds OK, App.tsx untouched. Also logs Phase 3 workflow outcome + remaining scroll/docfetch pieces. * feat(ui): make code-file hover preview fetch host-overridable (Phase 3) Add DocPreviewFetcher seam (default = verbatim /api/doc fetch) + setDocPreviewFetcher/resetDocPreviewFetcher; route handleMouseEnter through it, useCallback deps unchanged. No caller overrides it => Plannotator fetches /api/doc identically. typecheck pass, 1620 tests/0 fail, builds OK. * feat(ui): ship ScrollViewportProvider with the library (Phase 3 scroll) Add render-transparent ScrollViewportProvider (createElement, keeps .ts) so the scroll-viewport context travels with @plannotator/ui instead of living only in App.tsx. Rewire App.tsx provider tags (3-line delta); identical tree/value/ position, sidebar TOC still reads the MAIN viewport. Fix stale OverlayScrollbars doc-comment. typecheck pass, 1620 tests/0 fail, builds OK, eyeball: TOC tracks. * fix(ui): disabled code-path validation should keep links clickable (self-review) The Phase-3 disabled branch set ready=true with an empty map, which makes gateCodePath demote every code link to plain text. Leave ready=false so the no-validation fallback renders links optimistically. No Plannotator impact (never disables). Logs Phase 3 completion + reusability note. typecheck pass, 1620 tests/0 fail, builds OK. * feat(ui): make file-tree backend host-overridable (Phase 4) Lift useFileBrowser's three backend wires (load-dir fetch, obsidian-vault fetch, and the SSE live-watch effect moved VERBATIM) into an injectable FileTreeBackend with default + setFileTreeBackend/resetFileTreeBackend, same pattern as the image /storage seams. useFileBrowser() stays zero-arg; default fetch/SSE URLs identical. Sidebar confirmed noop (zero backend wires, already reused by review-editor). Verified: useFileBrowser.test.tsx passes 6/0 UNMODIFIED (DOM_TESTS=1), typecheck pass, 1620 tests/0 fail, builds OK, App.tsx untouched, manual eyeball (annotate adr/: tree loads, file-switch works, new file appears live via SSE). Plannotator byte-unchanged. Logs two pre-existing bugs found during testing (not regressions). * docs(adr): research + synthesis + spec for Phase 5 (comments/annotations/drafts) Five-probe code research of the comment system. Key finding: most comment UI is already portable (panel/popover/toolbar/highlighter prop-driven; review-editor already reuses the hooks). Phase 5 narrows to 3 seams — draft transport (+ the 3-party generation protocol), external-annotation transport (SSE->polling, move verbatim), and identity/authorship — plus 2 non-extraction items: renderer coupling (document as a contract) and replies/threading (defer as a new feature). * docs(adr): accept ADR 005 — make comments/annotations/drafts host-overridable (Phase 5) Three seams (identity, draft transport, external-annotation transport), each defaulting to today's behavior; renderer coupling documented as a contract; replies/threading deferred as a new feature. Locks in the recommended choices from the Phase 5 spec/synthesis. * feat(ui): make annotation identity host-overridable (Phase 5 seam 1) Add IdentityProvider + setIdentityProvider/resetIdentityProvider in identity.ts; getIdentity/isCurrentUser now delegate to a module-level provider defaulting to today's ConfigStore tater behavior. The ~9 author-stamp sites and 2 (me)-badge sites delegate with zero call-site edits. No caller overrides => Plannotator byte-unchanged. typecheck pass, 1620 tests/0 fail, builds OK. * feat(ui): make draft persistence transport host-overridable (Phase 5 seam 2) Add DraftTransport (load/save/remove) + getDraftTransport/setDraftTransport/ resetDraftTransport in useAnnotationDraft.ts, default = today's /api/draft fetches verbatim. useCodeAnnotationDraft reads getDraftTransport() live. The generation pre-increment, 500ms debounce, keepalive retry-gate, and pagehide/visibilitychange flush stay in the hooks; getDraftGeneration() still escapes to the host. save rejects-on-failure so the gated retry is preserved. No caller overrides => Plannotator byte-unchanged. shared/draft.test.ts 10/0, annotationDraftPersistence 13/0, typecheck pass, 1620 tests/0 fail, builds OK. * feat(ui): make external-annotation transport host-overridable (Phase 5 seam 3) Add ExternalAnnotationTransport<T> (subscribe/getSnapshot/CRUD) + setters in useExternalAnnotations.ts; default = today's SSE->polling wire moved verbatim into createDefaultTransport. The reducer (applyEvent), fallback-once gate, 500ms poll, versionRef scoping, optimistic-before-await, and [enabled] gate stay in the hook. A host (Workspaces) can implement the same event contract over Durable Objects. No override caller => Plannotator byte-unchanged. external-annotations test green, typecheck pass, 1620 tests/0 fail, builds OK. Logs Phase 5 completion. * docs(adr): research + synthesis + spec for Phase 6 (versions, settings, sharing, AI) Five-probe code research. Most of the four subsystems is already portable; the real work is 5 seams (version fetchers + vscode-diff, config write-back, obsidian detect, save-to-notes, AI transport) + 1 CSS move (block/raw diff classes from the app shell into the package's theme.css). Fragile do-not-touch: the AI SSE reader loop + epoch guards, and configStore debounce/deepMerge. Five Plannotator-only pieces (OpenInApp, HooksTab, useUpdateCheck, useAgents/useAgentJobs) stay home. * docs(adr): accept ADR 006 — make extras (versions/settings/sharing/AI) host-overridable (Phase 6) Five seams + one CSS move, each defaulting to today's behavior. AI reader loop + epoch guards and configStore debounce/deepMerge stay verbatim. Five Plannotator- only pieces stay home. Locks the recommended choices from the Phase 6 spec. * feat(ui): make version fetchers + vscode-diff host-overridable; move diff CSS into package (Phase 6 versions) usePlanDiff gains optional fetchers (default /api/plan/version(s), error asymmetry kept: selectBaseVersion alerts, fetchVersions silent). PlanDiffViewer gains optional onOpenVscodeDiff (default /api/plan/vscode-diff). Relocate .annotation-highlight* + .plan-diff-* block/raw CSS from editor/index.css into ui/theme.css (next to .plan-diff-word-*) so the diff/highlights are self-styling from the package. Verified: relocated CSS gone from index.css, present in shipped bundle (33x), diff renders identical; typecheck pass, 1620 tests/0 fail, builds OK, App.tsx untouched. * feat(ui): make config write-back + obsidian-detect host-overridable (Phase 6 settings) configStore.setServerSync(fn) injects only the terminal POST /api/config; the 300ms debounce, deepMerge batching, singleton, and eager cookie reads stay verbatim. Settings gains optional onDetectObsidianVaults (default /api/obsidian/vaults), with the [obsidian.enabled] effect dep + auto-select-first-vault verbatim. No override caller => Plannotator unchanged. typecheck pass, 1620 tests/0 fail, builds OK. * feat(ui): make save-to-notes host-overridable (Phase 6 sharing) ExportModal gains optional onSaveToNotes (default = verbatim POST /api/save-notes); showNotesTab = isApiMode && !!markdown kept byte-for-byte. Sharing utils already parameterized (noop). No override caller => Plannotator unchanged. typecheck pass, 1620 tests/0 fail, builds OK. * feat(ui): make Ask AI transport host-overridable (Phase 6 ai) useAIChat gains a module-level AITransport (session/query/abort/permission) + setAITransport/resetAITransport, default = the five /api/ai/* fetches verbatim. The SSE reader loop, epoch/createRequest guards, and the supersede-abort position inside createSession stay untouched. Capabilities + provider-resolution stay host-owned in App.tsx. No override caller => Plannotator unchanged. ai.test.ts 97/0, typecheck pass, 1620 tests/0 fail, builds OK. * docs(adr): log Phase 6 completion (4 seams + diff CSS move) * docs(adr): research + synthesis + spec for Phase 7 (carve @plannotator/core + publish) Carve a browser-safe @plannotator/core: move the ~15 pure shared modules in, extract types from the 3-4 node-bound ones (config/storage/workspace-status) so nothing duplicates, shim @plannotator/shared so Plannotator's 99 import sites stay unchanged, re-point @plannotator/ui to depend only on core, move wideMode.ts, then publish core+ui (source-only). shared + ai stay private. Open: registry, versions, CI job. Publish is the one outward-facing step — confirm before pushing. * docs(adr): fold configurePlannotatorUI() front door + precompiled CSS into Phase 7 spec Add the single typed configure() facade over the 9 global host-override setters (zero-risk, additive) and an optional precompiled CSS bundle (smooths the Tailwind-in-shared-lib wrinkle) to the Phase 7 publish scope. Both make the published surface nicer to consume; neither touches Plannotator. * docs(adr): lock Phase 7 publish decisions + carry over review fixes Decided: ship JS as source (single internal consumer on controlled stack, no build to maintain, no dist drift); precompiled CSS now REQUIRED (the @source glob is fragile under pnpm symlinks); core CI typecheck node-free; pin ui->core exact. Recorded the interrogation's carried-over Phase-5 code fixes (useExternalAnnotations split-transport + fallbackRef reset, per-seam override tests, configStore loadFromBackend) to do before publish. * docs(adr): ADR 007 — carve @plannotator/core, complete settings provider, publish Locks Phase 7 decisions: public npm; lockstep version at repo 0.21.0 (ui->core pinned exact); JS ships as source + required precompiled CSS; core CI node-free; ai stays unpublished-to-npm. Settings provider completed (loadFromBackend, prefetch +sync) is now IN SCOPE — Workspaces uses the same UI settings stored in its own backend. CI publish job wired but artifacts validated on-branch (pack + dry-run) before merge; first publish gated. Carries the 2 override-path bug fixes + per-seam override tests as pre-publish work. * fix(ui): make external-annotation transport reads consistent + reset fallback on re-enable Two override-path bugs found by the interrogation pass (both unreachable on Plannotator's path; harden the host-override path for a real consumer): 1. Split-transport: the effect captured the transport at mount for subscribe/poll while the CRUD callbacks read the module global live, so a host swapping the transport after mount would split reads and writes across two backends. Capture once in a ref and use it in all four spots. 2. fallbackRef/receivedSnapshotRef were not reset on effect re-run, so an enabled false->true toggle inherited a stale 'already fell back' flag and silently stopped updating. Reset both at the top of the effect. Plannotator unchanged: it never overrides the transport (same default singleton captured) and enabled never toggles (reset is a no-op). typecheck clean; full test suite shows zero delta (1605 pass / 45 pre-existing env failures, identical with and without this change). * docs(adr): align Phase 7 spec with ADR 007 (version 0.21.0 lockstep, CSS required, scope completeness) * feat(core): carve @plannotator/core — move pure modules, extract node-bound types, shim shared (Phase 7 step 1) * feat(ui): depend only on @plannotator/core — re-point all shared/ai imports (Phase 7 step 2) * refactor(ui): relocate wideMode helper to @plannotator/ui/utils (Phase 7 step 3) * feat(ui): add loadFromBackend settings rehydration + configurePlannotatorUI front door (Phase 7 step 4) * build(ui): precompiled styles.css CSS build + madge circular-dep check (Phase 7 step 5) * test(ui): per-seam override tests + configure routing test (Phase 7 step 6) Add one override test per seam (setX(fake)→drive→assert→resetX()) for all 9 seams + loadFromBackend, modeled after the existing seam test pattern. Fix configure.test.ts to defer mock.module() into beforeAll and restore with captured real function references in afterAll so sibling seam test files are not poisoned by spy replacements in the shared Bun worker module registry. * fix(ui): apply Phase 7 review findings — version lockstep + seam consistency - Bump @plannotator/ui to 0.21.0 (lockstep with @plannotator/core + repo, per ADR 007) [was the 1 critical review finding] - useAnnotationDraft: route persistNow/dismissDraft save+remove through getDraftTransport() so all paths read the transport consistently (matches the load path; makes the single-global invariant explicit) - configStore.loadFromBackend: document it must be called BEFORE init() or server values get overwritten - packages/core/tsconfig: add explicit types:[] so the node-free invariant is first-class (verified: planted node:fs still fails TS2882) * docs(adr): Phase 7 implementation plan (workflow-generated, durable artifact) * fix(ui): reconcile #948 with the draft-transport seam + lockstep 0.21.1 Rebased onto origin/main (picks up #948 draft-deletion fix, the 0.21.1 bump, and the #949/#950 editor fix). The rebase auto-merged #948's code-draft logic (hasHadAnnotationsRef, empty-state tombstone, clearTimeout in restore/dismiss) with the Phase-5 transport refactor cleanly — except the empty-state tombstone delete was left as a raw fetch('/api/draft', DELETE). Route it through getDraftTransport().remove() so a host backend tombstones its own stored draft on clear (the #948 guarantee, for hosts). Plannotator unchanged (default transport hits the same endpoint). Bump @plannotator/core + @plannotator/ui 0.21.0 -> 0.21.1 to match main's version (lockstep per ADR 007). Verified: typecheck clean, madge no-cycles, plain suite 1637 pass / 0 fail, #948 draft-clear test 3/0. (The 45 DOM_TESTS failures are the known server/network integration tests that need a real OS env — same set on main, not regressions.) * fix(ui): address review nits — host-path robustness + cleanups - PlanDiffViewer: wrap onOpenVscodeDiff in try/finally so a host opener that throws can't wedge the VS Code button in a permanent loading state (default unaffected) - useExternalAnnotations: (re-)capture the transport inside the effect on enable so a host that installs a transport before enabling annotations is honored, not the stale default — keeps the split-transport fix (effect + CRUD share one ref) - configure.ts: import ServerSyncFn from configStore instead of duplicating the type - repoint the 2 remaining @plannotator/shared test imports to @plannotator/core - AGENTS.md/CLAUDE.md: document the new packages/core package All host-path only — Plannotator behavior unchanged. typecheck clean, no cycles, full suite green. Skipped (not simple/over-engineering): usePlanDiff prop->module-level (design change), Obsidian late-bind, getSnapshot guard (inert), transport <any> (variance). * docs: collapse 29 ADR process docs into one packages/ui/README.md The branch had accumulated ~6,200 lines of ADR scaffolding (6 decisions, 7 specs, 10 research spikes/synthesis, 6 worklogs/roadmaps/plans) for this one effort. Replace all of it with a single concise README that ships with the published package: what @plannotator/ui + @plannotator/core are, why they exist (commercial reuse), how the host-override seams work (configurePlannotatorUI), how a consumer installs/builds, and the one rule (don't reimplement from scratch — add a seam). Repoint the CLAUDE.md banner at the README. No code references the deleted docs; main's pre-existing adr/ docs untouched. * docs(ui): add packages/ui/AGENTS.md guardrail + CLAUDE.md symlink Directory-scoped agent guidance for anyone editing @plannotator/ui: don't rewrite from scratch, add a seam (default = today's behavior, Plannotator byte-for-byte unchanged), core stays node-free, never delete working code until human parity. Points to README.md for the architecture. CLAUDE.md -> AGENTS.md symlink mirrors the repo root convention. * build: remove madge circular-dep check (unmaintained) madge is unmaintained (~3 years stale) and the check was never wired into CI, so it was a dormant script + devDependency on a load-bearing path. Drop it: remove the check:cycles script, the madge devDependency, and .madgerc. The no-cycle invariant still holds by construction — @plannotator/core imports nothing (zero @plannotator deps in its package.json), so any accidental core->shared/ui import fails at publish-time bun pm pack (and review). No automated tripwire, but no stale unmaintained tooling either. * fix(ui): address review — TDZ guard, html-viewer export, doc corrections - useExternalAnnotations: declare unsubscribe as let (not const) + guard calls, so a host transport that fires onError synchronously during subscribe falls back to polling instead of throwing a TDZ ReferenceError (Plannotator's EventSource fires async, never hit) - package.json: add explicit ./components/html-viewer export (dir has index.ts; the ./components/* -> *.tsx wildcard can't resolve it, so external installers would fail) - README: fix configurePlannotatorUI sample keys to the real option names (storageBackend/identityProvider/imageSrcResolver/externalAnnotationTransport) - AGENTS.md: point the Ask-AI mapping at packages/core/agents.ts (shared/agents.ts is a shim now) All publish/host-path/doc only — Plannotator unchanged. (#1 CSS-build font collision deferred to publish-prep — it needs the asset pipeline + files allowlist, not a one-liner.) * build(ui): don't bundle fonts in published styles.css — app loads fonts (review #1) Industry standard for a shared UI package: ship theme + component CSS, let the consuming app load fonts. Drop the @fontsource imports from styles-entry.css (the publish CSS entry); the theme still defines --font-sans/--font-mono, and the app provides those families. Fixes the asset-name collision (every emitted .woff2 was renamed styles.css) and shrinks the published stylesheet 555kB -> 185kB. README documents the two-line @fontsource install. Plannotator unaffected: its apps (editor/review-editor index.css) load fonts via their own entry CSS — styles-entry.css is consumed ONLY by the publish CSS build. * fix(ui): build styles.css on prepack, not prepublishOnly (review #4) prepublishOnly doesn't run for npm pack / bun pm pack / git / file: installs, so the package exported ./styles.css without shipping it. prepack runs on any pack, so the stylesheet is always present. Verified: bun pm pack now emits styles.css. * chore(ui): post-rebase reconciliation — version lockstep 0.21.3, awaitable AI abort seam Rebased onto main (0.21.3). Bump @plannotator/core + @plannotator/ui to 0.21.3 to stay in lockstep with the repo version. Resolve the useAIChat conflict: main added postServerAbort (an awaitable abort that prevents session-busy races) using a raw fetch. Route it through the AITransport seam by making AITransport.abort return Promise<unknown> instead of void, so the host override is honored AND main's await-the-abort behavior is preserved. Update the abort mocks in the seam/configure tests accordingly. * fix(ui): make postServerAbort never reject regardless of AI transport The await site in ask() relies on postServerAbort resolving so a superseding query can proceed. main's original guaranteed this with its own .catch on the fetch; routing through the AITransport seam delegated that guarantee to the transport. Restore it at the call site (Promise.resolve(...).catch) so a host override that rejects — or returns void at runtime — can't throw out of ask(). * fix(ui): address review — core import, abort sync-throw, snapshot guards - useAIProviderConfig: import Origin from @plannotator/core/agents (was the only ui file still importing @plannotator/shared); drop the masking shared/* path alias from ui/tsconfig.json so a stray shared import now fails typecheck. The hook is part of the published surface — a standalone install had no @plannotator/shared to resolve. - useAIChat.postServerAbort: defer the transport call into .then so a host abort that throws *synchronously* also can't reject (the .catch only caught async). - useExternalAnnotations: default getSnapshot returns null (skip) on a malformed 200 instead of coercing to []/0, so it can't clear annotations or reset the version cursor — restoring the pre-seam behavior. * feat(ui): add upload + identity-editable seams for host backends Two override points the Workspaces app needs that had no seam: - UploadTransport (utils/upload.ts): image attachments hardcoded POST /api/upload with no override. Add a setX/resetX/getX seam (default = today's /api/upload, verbatim) and route AttachmentsButton through it. Workspaces sends bytes to its R2 asset API and returns the content-addressed URL. - IdentityProvider.isEditable() (utils/identity.ts): the Settings rename/regenerate controls wrote to the cookie store, bypassing a host identity provider — so a host with server-owned identity could split one user across two author names. Add an optional isEditable() (default true) and hide the rename controls when a host returns false. Plannotator's cookie identity stays editable — unchanged. Both wired into configurePlannotatorUI(); seam tests added; configure routing test covers uploadTransport. HANDOFF.md updated with the Workspaces seam mapping from the repo research (asset layer, identity, realtime, no-AI-infra, the Me display-name backend follow-up). README publish command corrected to bun pm pack + npm publish. * refactor(ui): capture sessionId synchronously in postServerAbort Self-review: the deferred .then read sessionIdRef.current a microtask after the guard checked it. Capture the id synchronously so the abort always targets the session current at call time and there's no double-read. * fix(ui): address review — seed host store, browser-safe timer type, harden abort - configStore.loadFromBackend: seed the host StorageBackend with resolved defaults for keys it lacks. The constructor runs at module load (before a host installs its backend), so its default-seeding writes went to the cookie backend; without this a fresh host store was never populated and generated defaults (e.g. displayName) regenerated every reload. [P1, host path] - Viewer.tsx: replace NodeJS.Timeout with ReturnType<typeof setTimeout> (2 refs) so a browser-only consumer compiling the published source doesn't need @types/node. Matches the pattern already used in configStore. [P1, published path] - useAIChat: harden the create-session supersede abort the same way as postServerAbort, so a host transport that throws can't surface an unhandled rejection. No impact on Plannotator (default self-catches). [nit] - .gitignore: correct stale 'prepublishOnly' comment to 'prepack'. [nit] Plannotator behavior unchanged (it never calls loadFromBackend; the timer/abort changes are behavior-preserving). Strengthened configStore seam test to assert first-run seeding. typecheck clean, 1773 pass / 0 fail. * refactor(ui): single-source the never-reject abort via safeAbort helper Self-review: the hardened abort pattern (defer into .then + .catch so a host transport that throws can't reject) was duplicated across postServerAbort and the create-session supersede site — the exact drift the review flagged. Extract a module-level safeAbort(sessionId) so both call sites share one hardened implementation and can't diverge again. Behavior unchanged; reads aiTransport at call time so a late override is honored. * chore(ui): post-rebase version lockstep to 0.21.4 Rebased onto main (0.21.4, adds markdown math #878 + parser hardening). Bump @plannotator/core + @plannotator/ui to 0.21.4 to stay in lockstep with the repo. katex (main's math dep) merged into ui; typecheck clean, 1810 pass / 0 fail. * docs(ui): consumer-lens handoff hardening + ADR 005 - HANDOFF.md: add supported-imports allowlist vs unsupported (hardcoded /api/*) list; document the annotation anchor schema, reattachment order, and untested stale-anchor degradation; state that the markdown editor cannot take CM6/Yjs extensions yet and the plan of record; note AI avoidability re-verified post-rebase; fix stale 0.21.3 ref. - adr/decisions/005: record the publish-as-packages decision (packages over copy/vendor, core/ui split, seam-singleton pattern + SSR revisit condition, the law, lockstep publish model). * fix(ui): make shipped source strict-TS clean for consumers + seam type barrel Consumers compile the published TS source with their own compiler options, and strict mode failed with 35 errors inside the package: - settings.ts: satisfies SettingDef<unknown> is contravariantly illegal under strictFunctionTypes (33 errors) — use SettingDef<any> - useDismissOnOutsideAndEscape: RefObject<HTMLElement> rejects React 19's useRef<T>(null) refs — widen to HTMLElement | null - globals.d.ts: declare *.png / *.webp modules, referenced from each asset-importing component so any consumer program that includes one gets the ambient declarations Also unscatter the seam contract types: configure.ts re-exports every seam type next to configurePlannotatorUI, and ServerSyncFn is now exported from config/index.ts (it was unreachable through the exports map). Verified: standalone Vite consumer importing the full supported surface passes tsc --noEmit under full strict (was 35 errors). * fix(ui): keep KaTeX fonts out of published styles.css (back to ~187KB, was 1.6MB) Main's math PR imports katex/dist/katex.min.css in theme.css; the publish build (Vite lib mode) force-inlines all 60 KaTeX math fonts as data URIs, ballooning styles.css to 1.6MB (977KB gzip) and breaking the package's consumer-owns-fonts policy. Alias the katex stylesheet to an empty stub in vite.css.config.ts only — theme.css stays untouched (no rebase surface) and Plannotator's own apps, which import theme.css directly, still bundle KaTeX as before. Hosts that render math load katex.min.css themselves (bundler import, CDN tag, or self-hosted copy per HANDOFF.md), which also gets them lazy font loading. Verified: fresh build is 186.9KB / 30.8KB gzip with zero @font-face data URIs; consumer vite build CSS drops 1.66MB -> 200KB. * docs(ui): HANDOFF corrections from adversarial consumer review - Math rendering section: KaTeX css/fonts excluded from styles.css by design; three one-time host setup options (self-hosted recommended, CDN tag, bundler import) - styles.css size claim corrected (~187KB / ~31KB gzip) + strict-TS guarantee documented (verified against a standalone consumer) - AI-avoidability claim made precise: configure.ts statically imports useAIChat for its setter; unused AI code tree-shakes to zero (bundle- verified) — the runtime claim holds, the static wording was wrong - Loud warning on the loadSettingsFromBackend ordering footgun: configuring before hydration seeds generated defaults into the host backend and nothing re-runs hydration - DraftTransport.load() tombstone-generation contract spelled out - Seam-type barrel documented on the configure row; 'everything is importable' softened (some components/*.ts don't resolve via the *.tsx wildcard); stale diff stats refreshed * docs(ui): math setup pointer in README + pnpm caveat on the katex bundler-import option * fix(ui): lazy settings resolution — zero cookies on a configured host The configStore resolved all settings eagerly in its constructor, at module import — before a host's configurePlannotatorUI() could install its StorageBackend — writing 17 plannotator-* cookies (including a generated identity) onto the host origin. Resolution now runs lazily on first settings access (get/set/init/loadFromBackend): by then the host backend is live, so the initial reads AND default-seeding writes route through it. A configured host gets zero cookies, ever. Plannotator unchanged: same resolution, same cookie seeding, same values — on first settings read (same page load) instead of at import. New configStore.lazyInit.seam.test.ts proves the contract from a fresh module graph; full suite + consumer strict tsc green. * chore(ui): post-rebase version lockstep to 0.22.0 * fix(ui): round-2 review batch — dedupe asset declarations, CI seam tests, strict consumer gate, doc corrections - components/types.d.ts: drop the *.png/*.webp declarations that globals.d.ts now owns — both shipping was a duplicate-identifier error for any consumer with skipLibCheck: false - untrack packages/ui/styles.css (generated by prepack, gitignored; got scooped into the carve commit during the rebase by git add -A before the ignore entry existed in the replay) - CI: the DOM test step now runs ALL packages/ui tests, so the seam contract tests (AI/draft/external-annotations/file-tree/inline- markdown) actually execute in CI instead of skipping - new packages/ui/tsconfig.strict-consumer.json wired into root typecheck: type-checks the supported-import surface under full strict, so the consumer strict-TS guarantee can't silently rot - HANDOFF: rot-proofed the diff stat, strict guarantee now cites the CI gate, CDN katex pinned-version wording, theme-vs-styles.css caveats (theme still imports KaTeX + needs Tailwind), Viewer required props, Yjs plan-of-record updated to the atomic-editor fork - README: @source fallback wording (build entry isn't shipped) * test(ui): make the lazy-resolution seam test deterministic The test asserted lazy resolution on the module singleton and relied on its test file getting a fresh module graph — an isolation assumption that doesn't hold under all bun test orderings (CI failed with zero observed reads because another file had already resolved the store). Test the contract on a fresh instance instead: ConfigStore is exported as @internal ConfigStoreForTest, the spy backend is installed before construction, and the test asserts construction reads nothing while the first get() resolves and seeds through the live backend. Deterministic by construction. * test(ui): poll for the debounced reconnect refetch instead of a fixed sleep The reconnect-refresh assertion waited a fixed 150ms against the SSE watcher's 120ms debounce — a 30ms margin that slower CI runners lose, flaking 'refreshes after an SSE ready event from reconnect'. The watched logic is unchanged (verified byte-identical to main's inline version — the seam only relocated it into the default watchTrees and added the onChange indirection). Poll for calls.length===2 up to 1s so the pass/fail is hardware-independent. * test(ui): poll the committed tree state, not the fetch call count Prior fix polled calls.length===2, but the fetch call is counted one tick before its result commits to React state — so the poll exited early and the next assertion (dirs[0].tree === reconnectedTree) lost the race on slow CI (toEqual failure). Poll on the committed tree itself, which is exactly what the assertion checks: now the only way to fail is a genuine no-refresh, not a timing margin. * test(ui): give the reconnect-refetch poll a 10s ceiling + 20s test timeout A CI runner was measured at 6x normal speed (1676ms for a ~275ms test), blowing through the 1.5s poll ceiling before the 120ms debounce fired — same commit passed on a faster runner. Raise the poll to ~10s and set an explicit 20s test timeout (bun's 5s default would otherwise kill the poll). Root cause is load, not logic: this timing-sensitive test only started flaking when the CI DOM step was broadened to run the whole ui suite in one process. * ci: run the file-browser DOM test isolated; scope the DOM step to DOM files Root-causes the intermittent 'refreshes after an SSE ready event from reconnect' failure. The round-2 change ran the ENTIRE ui suite under DOM_TESTS=1 to catch the seam contracts; that load intermittently starved the test's 120ms real-timer debounce so the reconnect refetch never fired (observed failing after a full 10s poll — not a margin issue). The hook logic is byte-identical to main, and main runs this test in its own process (green for months). Fix at the CI layer, not the test: run useFileBrowser.test.tsx isolated (matching main), and run the seam contracts + remaining DOM-gated tests as an explicitly-scoped light batch. The test file is reverted to main verbatim (today's timing-poll experiments dropped). Follow-up issue to file: the underlying re-subscription race the load exposed. |
||
|
|
16db952000 |
fix(ui): stop unclosed math from pairing with a stray delimiter in a later code fence
The unclosed-$$/\[ guard scanned ahead to EOF for the closing delimiter, so an unterminated opener could match a $$ (or \]) that appears far below - e.g. inside a code fence - and swallow every heading/paragraph in between into one broken math block. The scan now stops at a blank line: real display math has no blank line before its close, so a blank both confirms "unclosed" and keeps the search from reaching distant delimiters. Adds a regression test and a manual LaTeX + media test fixture. |
||
|
|
cd934e6de2 |
fix(ui): stop stray math delimiters from mangling plan/PR text
Two math-parser regressions from #878, both the same "greedy delimiter" class
as the <video> fix in
|
||
|
|
ec551c83af |
fix(ui): stop unclosed <video>/<picture> from swallowing the document
An unclosed or self-closing <video>/<picture> ran the HTML-block scanner off the end of the document, funneling every following heading/table/code block into one opaque html block (gone from the TOC, unannotatable). The scanner now only extends the block when it actually finds the matching close tag; otherwise it keeps the block to the opening line. Also fixes multi-line <img> (was truncated to a bare "<img" fragment) and allowlists srcset/media/sizes so <picture>/<source> and responsive <img> render instead of rendering inert. Reachable via GitHub PR description/comment media (#981) and plannotator annotate on any .md file. |
||
|
|
d39bc871b7 |
feat(ui): render markdown math (#878)
* feat(ui): render markdown math * feat(ui): support more markdown math delimiters * feat(ui): renders spaced dollar-delimited TeX support * chore(deps): update katex * Update bun.lock chore(deps): update chore(deps): update chore(deps): update chore(deps): update chore(deps): update * feat(highlight): highlight math * feat(ui): support formule & text highlight together * fix(ui): make rendered math drag-selectable for annotation Drag-selecting an inline formula did nothing: the browser normalizes the selection focus to offset 0 of the following text node, so the strict anchor/focus check in selectionHasNonMathContent treated every inline drag as "mixed prose+math" and bailed without claiming the event. Control fell to web-highlighter, which excludes .katex/.math-annotatable, so no annotation was created and the selection just collapsed. Drop the anchor/focus check and rely on the existing clone-and-strip logic (leftover text => genuinely mixed), plus a guard for selections wholly inside one formula. Add a regression test that reproduces the real spilled-endpoint drag, which the prior empty-selection tests missed. Also paint a preview highlight the moment a formula's toolbar/popover opens (stripped on cancel, committed on submit) and show cursor: pointer on hover so formulas read as annotation targets. * chore(ui): reconcile lockfile and math styles after rebase onto main Rebase reconciliation, not new behavior: - Re-add katex to bun.lock. The lockfile conflicted on every replayed commit and was resolved to main's copy throughout; regenerate it here so package.json (katex) and the lockfile agree again. - Move the math annotation styles (.math-inline-annotation / .math-block-annotation) into packages/ui/theme.css. main relocated all annotation-highlight rules there to share them with the code-review description annotations; the PR had added the math variants to the old editor/index.css location. * test(ui): lazy-load highlighter hook so DOM-less bun test skips cleanly The math-annotation test statically imported useAnnotationHighlighter, which pulls in @plannotator/web-highlighter — a UMD bundle that reads `window` at module-eval time. Under the default `bun test` (no DOM), that threw a ReferenceError on import, failing CI before the skipIf(!hasDom) guards ever ran. Import the hook lazily, gated on hasDom, so the file loads and its tests skip cleanly in CI while DOM_TESTS=1 still exercises them. * fix(ui): stop display math from swallowing the document The `$$`/`\[` block parser only recognized the closing delimiter when it was the last non-space text on its line. A line like `$$E=mc^2$$.` (trailing period) or `$$E=mc^2$$ where E is energy.` therefore looked like an unterminated opener and consumed every following line until the next fence or EOF — silently hiding the rest of the plan. Detect the closing delimiter anywhere on the line and re-process any trailing text as its own line, so the equation renders and the following content is preserved instead of dropped. Same fix for the multi-line closing path and the `\[ ... \]` branch. Adds parser regression tests (these run in CI; no DOM). --------- Co-authored-by: ishowman <ishowman@users.noreply.github.com> Co-authored-by: Michael Ramos <mdramos8@gmail.com> |
||
|
|
e3de938914 |
feat(review): PR Overview panel + description/comment annotations + media (#981)
Combine the PR Summary/Comments/Checks tabs into one PR Overview panel, then make the description and comments annotatable and render their media. - PR Overview panel (one sidebar entry) + comment UI (avatars, filters, hide bots, live context, responsive stacking). - Annotate the PR description (select → comment) and PR comments (Annotate button), with Ask AI; notes show in the Annotations sidebar and ship to the agent. - Split/Unified diff toggle relocated into the dock tab strip. - Render images + video in descriptions and comments (raw HTML + markdown), capped to the card so nothing bleeds. - Review-flow fixes: copy-all feedback, prose-only feedback preamble, no image control on prose notes, GitHub review-body seeding; stronger review trailer. - Add Claude Sonnet 5 as the default Ask AI model. No server, endpoint, or Pi-runtime changes. |
||
|
|
be2c81fa3b |
annotate-last: pick which message to annotate (fixes #800) (#809)
* feat: message picker for annotate-last (#800) When running /plannotator-last after /rewind, the newest transcript entry is no longer the message the user intended to annotate, and there was no affordance to pick a different one. Adds a picker UI that surfaces the recent assistant messages so the user can choose which one to annotate: - A "Message N of M" button in the Viewer's sticky-top action bar (alongside Copy / Global comment / Attachments), so it stays accessible while scrolling. - A "Messages" tab in the left sidebar with the full list (newest-first, preview + timestamp, default ★), mirroring the existing Files / Versions / Archive tab pattern. Wired for Claude Code, Codex, and Droid (all share apps/hook/server). OpenCode, Pi, and Copilot still get the original single-message behavior — they don't emit recentMessages, so the picker affordances hide cleanly. Default selection (index 0) matches today's "last message" behavior, so users who don't interact with the picker see no change. * feat: extend annotate-last picker to Copilot and OpenCode The picker UI from #800 was wired for Claude / Codex / Droid only. Pull Copilot and OpenCode onto the same shape so users on those harnesses also get the recent-messages picker when annotating the last assistant message. - Copilot: replace getLastCopilotMessage with getRecentCopilotMessages, walking events.jsonl newest-first up to 25 assistant.message events. - OpenCode: rewrite the session walk to collect up to 25 messages (newest first) instead of bailing on the first hit; normalize the SDK time.created (ms epoch) to ISO to match the shared picker contract. - Both pass recentMessages to startAnnotateServer only when length > 1, matching the existing Claude/Codex/Droid behavior. Also trims a leftover narrating comment in MessagesBrowser and refreshes the stale Copilot session-parser header. Pi parity follows in the next commit (needs round-trip of the picker selection through /api/feedback so its post-submit anchoring quotes the right message). * feat(pi): wire annotate-last picker with feedback round-trip Extends the picker UI (#800) to Pi and fixes a Pi-specific anchoring bug the picker would otherwise introduce. Picker plumbing - assistant-message: getRecentAssistantMessages walks the active branch newest-first, returning { messageId, text, timestamp? } in the same shape the other harnesses produce. - Plumbed through plannotator-browser / plannotator-events so the Bun server's recentMessages option is populated when the branch has more than one assistant message. Anchoring fix - Pi quotes the targeted assistant message back to the agent because its UX is async — the conversation may have moved on by feedback time. With the picker, that target is no longer guaranteed to be the snapshot taken when the UI opened. The editor now sends the user's selectedMessageId with /api/feedback; Pi looks it up in the current branch via findAssistantMessageByEntryId and quotes that message instead. Falls back to the original snapshot if the entry is gone. - The round-trip field is optional and only meaningful in annotate-last mode; other harnesses (and other modes) ignore it. Timestamp safety - Pi's SDK currently types SessionEntryBase.timestamp as string, but the picker contract everywhere else is ISO. Treat the value as unknown and normalize string/number(ms)/Date to ISO; drop anything else, rather than blind-casting and risking silent drift if the SDK changes. * chore: strip issue-number references from comments Comments shouldn't rely on external references — issue numbers age out of context, link rot is a thing, and a reader shouldn't need to open GitHub to understand why a line exists. Strip the `(#800)` and `(#570)` parentheticals from comments and doc strings across the picker and review-gate code; the surrounding "why" content is preserved. * fix: prevent removeChild crash when switching annotate-last messages Switching the picked message remounted nothing, so React reconciled new content against DOM that web-highlighter had mutated with <mark> nodes, throwing removeChild. Drive the Viewer key (and StickyHeaderLane's remount token) off a shared viewerContentKey so a message switch fully remounts the Viewer and re-anchors the sticky-header observer. Also cap MessagesBrowser row previews via previewText() and drop the redundant 'block' class that was overriding line-clamp-2. * feat: persist annotate-last feedback across messages --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> |
||
|
|
fcf2ba4cf5 |
fix: indent loose list continuation content under parent bullet (#705)
Closes #704 |
||
|
|
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
|
||
|
|
fdc4bc4656 |
feat(plan,annotate): include source line numbers in exported feedback (#623)
Each annotation in exported plan/annotate feedback now carries source line numbers — single-line blocks show `(line N)`, multi-line blocks show `(lines N–M)`. Diff-context and global comments stay lineless. When the document was produced by Turndown/Jina (HTML file or URL), the export carries a caveat that line numbers refer to the converted markdown rather than the original source. Key implementation details: - extractFrontmatter() returns contentStartLine so block line numbers account for stripped YAML headers - blockEndLine() computes end lines per block type, with code blocks, directives, and alerts accounting for stripped wrapper lines - isConvertedSource() helper in url-to-markdown.ts centralizes the source-type check across all entry points - sourceConverted threaded from all CLIs through annotate servers to the /api/plan payload; isConverted added to /api/doc responses - Per-document conversion tracking in useLinkedDoc ensures the correct flag is used when viewing linked HTML docs Supersedes #621. For provenance purposes, this commit was AI assisted. |
||
|
|
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 (``) 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. |
||
|
|
b3fc1f724f |
fix(ui): render numerals for ordered list items (#520)
* feat(parser): detect ordered list markers and compute display indices
The block parser collapsed `*`, `-`, and `\d+.` markers into a single
`list-item` block type, discarding ordered/unordered status. Add
`ordered` + `orderedStart` to Block, capture the numeric marker in the
list regex, and introduce `computeListIndices()` — a pure helper that
walks a list group and assigns each ordered item a CommonMark-correct
display number (sequential renumbering, streak break/restart on
unordered items, deeper-level state truncation, top-level numbering
preserved across nested children).
21 new unit tests cover both the parser changes and the indexing
helper, including the tricky cases: `1./2./99.` renumbers as 1,2,3;
sub-bullets between ordered items keep the top-level streak alive;
nested ordered sublists number independently and reset between
siblings; numeric checkboxes set both `ordered` and `checked`.
For provenance purposes, this commit was AI assisted.
* feat(ui): render numerals for ordered list items
Branch the list-item marker span on `block.ordered`: render
`${index}.` (with `tabular-nums` and a 1.5rem min-width to keep
columns stable across single- and double-digit numerals) when the
source marker was numeric, otherwise fall through to the existing
`•`/`◦`/`▪` bullet symbols. Indices come from `computeListIndices()`
called once per list group; `groupBlocks` is unchanged so mixed
nested lists still share a single `data-pinpoint-group="list"`
hover wrapper and annotation anchoring is unaffected. Checkbox
items still take precedence over numerals.
Adds a real-world manual fixture (06-ordered-list-plan.md) whose
`## Verification` section exercises a 10-item ordered list, the
case that originally surfaced the bug.
For provenance purposes, this commit was AI assisted.
* fix(parser): merge consecutive blockquote lines into one block
Each `>` line was emitted as its own blockquote block, so the
renderer's `my-4` margin produced visible gaps between every line
of a multi-line quote (the parser had a literal TODO comment:
"Check if previous was blockquote, if so, merge? No, separate for
now"). Fix: append to the previous block when it's a blockquote
and the prior line wasn't blank, mirroring the list-continuation
pattern. A blank line still breaks the quote so two `>` runs
separated by a blank line stay distinct.
Adds 5 unit tests (merge, blank-line break, paragraph boundaries,
single-line) and a manual fixture (07-blockquotes.md) covering the
bug case, the blank-line-break case, sandwich-between-paragraphs,
and inline markdown across merged lines.
For provenance purposes, this commit was AI assisted.
* fix(ui): address code review — diff view, task lists, blockquote paragraphs
Three issues surfaced by PR review #520:
1. **Diff view flattened ordered lists to bullets.** PlanCleanDiffView's
SimpleBlockRenderer duplicated Viewer's list-item JSX with hardcoded
bullet symbols, so a denied+resubmitted plan with numbered steps
showed numerals in the main view but `•` in the diff view — exactly
the screen where "which step changed?" matters most. Fixed by
threading computeListIndices through MarkdownChunk and sharing the
marker rendering via a new ListMarker component used by both
renderers, which also removes the root-cause duplication.
2. **Ordered task lists dropped their numbers.** `1. [ ] step` set both
`ordered=true` and `checked=false` in the parser, but the renderer's
checkbox branch took precedence and the numeral was never shown.
GitHub renders `1. [ ]` as numeral + checkbox side by side; we now
match that by rendering both glyphs in ListMarker when an ordered
task list item appears.
3. **Multi-paragraph blockquotes collapsed.** After the blockquote-merge
fix in the previous commit, `> a\n>\n> b` produced content
`"a\n\nb"` but the renderer passed it straight to InlineMarkdown,
which renders `\n\n` as whitespace — so two quoted paragraphs
mashed into one line. Fixed by splitting blockquote content on
`/\n\n+/` in both Viewer and PlanCleanDiffView and emitting one
`<p>` child per paragraph.
Adds one unit test for the multi-paragraph blockquote content shape and
a manual fixture (08-ordered-edge-cases.md) covering ordered task lists,
multi-paragraph quotes, nested-bullet counter preservation, double-digit
alignment, and start-at-N numbering.
The fourth review comment — loose ordered lists with intervening non-list
blocks restarting numbering — is deferred. It requires parser-level
loose-list detection (CommonMark's indented-continuation rule) and the
bug only fires when users rely on lazy `1./1./1.` markers across a
break. Tracked as a follow-up.
For provenance purposes, this commit was AI assisted.
* fix(parser): don't merge blockquote lines containing block-level markers
Round-two review flagged a regression: `> 1. foo\n> 2. bar\n> 3. baz` was
merging into one blockquote whose content was `"1. foo\n2. bar\n3. baz"`.
The renderer split on `\n\n+` (paragraph breaks), found none, and emitted
a single `<p>` — so `\n` collapsed to whitespace in HTML and the user
saw `"1. foo 2. bar 3. baz"` as one run-on line. Worse than the pre-PR
behavior (which at least kept each line in its own box).
Pragmatic fix: don't merge a `>` line whose stripped content starts with
a block-level marker (`*`, `-`, `\d+.`, `#`, `` ``` ``, `>`). Those stay
as separate blockquote blocks so each marker line is visually distinct
(legible, matching pre-PR behavior for quoted lists). Wrapped prose
quotes — the original motivating case — still merge correctly because
prose lines don't start with markers.
Also check the PREVIOUS block's content for markers so a trailing prose
line after a `> 1. item` doesn't glue onto the list-item block.
7 new unit tests cover: quoted ordered list stays separate, quoted
unordered list stays separate, quoted heading stays separate, quoted
code fence stays separate, nested blockquote stays separate, wrapped
prose quote still merges (regression guard), and mixed prose+list where
prose merges and list lines stay separate.
Adds tests/test-fixtures/09-quoted-list-regression.md as a manual repro.
Known follow-ups (tracked separately, not in this PR):
- Consecutive separate blockquote blocks still get individual `my-4`
margins, so a quoted list shows as stacked boxes with gaps between
lines. The proper fix is recursive blockquote parsing (render the
content as its own Block[] tree with an actual nested list inside
the quote). Deferred — requires `children?: Block[]` on Block,
parser rework, and exportAnnotations traversal changes.
- Clean diff view renumbers ordered lists from the start of each diff
chunk when users rely on CommonMark's lazy `1./1./1.` markers. Same
power-user population as the earlier deferred loose-list case.
- Pure code-hygiene items from the second review (non-list-block
handling in computeListIndices, BULLET_BY_LEVEL modulo cycle,
<ListGroup> extraction, CLAUDE.md Block interface drift,
splitBlockquoteParagraphs helper) — batch into a follow-up cleanup.
For provenance purposes, this commit was AI assisted.
|
||
|
|
d850b78ba6 |
fix: handle markdown hard line breaks and list continuations (#483)
* fix: handle markdown hard line breaks and list continuation lines List items with indented continuation lines (no blank line separator) now merge into the preceding bullet instead of becoming orphan paragraphs. InlineMarkdown now converts two-trailing-space and backslash line breaks into <br> elements. Synced to the diff view's InlineMarkdown copy. Closes #482 For provenance purposes, this commit was AI assisted. * fix: allow bold/italic to span across hard line breaks Changed bold/italic regexes from .+? to [\s\S]+? so emphasis can match across newlines (per CommonMark spec). Moved hard break check after all ^-anchored inline patterns so bold/italic get first crack, then the recursive InlineMarkdown call inside <strong>/<em> handles the break. For provenance purposes, this commit was AI assisted. |
||
|
|
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. |
||
|
|
2ae4f2a292 |
fix(parser): indented fences, trailing text, table detection, and escaped pipes (#429)
Three fixes to parseMarkdownToBlocks and one to table cell rendering: 1. Indented closing fences — allow leading whitespace so ` ``` ` inside list items closes the code block instead of swallowing to EOF. 2. Trailing text after closing fence — drop end-of-line anchor so ` ``` some text` still closes the block. 3. False table detection — require lines start with `|` instead of matching any line with 2+ pipe characters. 4. Escaped pipes in table cells — split on unescaped `|` only, so `\|` renders as a literal pipe instead of creating extra columns. Closes #427 For provenance purposes, this commit was AI assisted. |
||
|
|
7ed85dfe0b |
fix(parser): support nested markdown code fences (#355)
* fix(parser): support nested markdown code fences Count backticks in the opening fence and only close on a line with at least that many backticks. Previously any ``` line would prematurely close a 4- or 5-backtick fence, corrupting blocks that embed markdown examples. Follows CommonMark §4.5. Adds parser.test.ts with 6 tests covering the fix and baseline triple-backtick behaviour. Also adds devbox.json to pin bun for running tests. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore(devbox): wire up test script to bun test Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(parser): pass raw line to closingFence regex; add edge-case tests The regex already anchors trailing whitespace with \s*$ so calling .trim() before testing was redundant. Passing the raw line is also more correct — it lets the regex reject a closing fence indented more than three spaces (CommonMark §4.5 semantics), not that the rest of the parser handles indented blocks today, but the intent is clearer. Also adds three previously untested edge cases: - Unclosed fence at EOF (extends to end of document per spec) - Fence opener as the last line (zero-content block, no crash) - toHaveLength(1) guard on the language-tag preservation test Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Overcomit * Overcomit --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> |
||
|
|
6b775ea1ed |
feat: /plannotator-last — annotate the last agent message (#325)
* feat: add /plannotator-last command to annotate last assistant message
Adds a new slash command that extracts the last rendered assistant message
from Claude Code's session log and opens it in the annotation UI.
Session log parser (apps/hook/server/session-log.ts):
- Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl
- Finds the last assistant message.id with text content blocks
- Skips noise entries (progress, system, file-history-snapshot, queue-operation)
- Filters system-generated user messages by prefix to avoid false turn boundaries
- Walks backward through empty turns when back-to-back user messages exist
- No anchoring — reads from end of log since <command-message> isn't written
until after the binary completes
New files:
- apps/hook/commands/plannotator-last.md — slash command definition
- apps/hook/server/session-log.ts — Claude-Code-specific log parser
- apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks,
tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases
Modified:
- apps/hook/server/index.ts — annotate-last subcommand
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove 3 redundant real-world scenario tests
These duplicated coverage already provided by focused unit tests:
- "full conversation" → covered by "grabs last message.id in multi-tool turn"
- "stop hook interrupted" → covered by "skips progress and system noise"
- "long tool-only sequence" → covered by "skips tool-only assistant entries"
Kept the thinking block test (unique coverage). 27 tests remain.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add /plannotator-last command to Pi extension
Uses Pi's session manager API to find the last assistant message —
walks backward through ctx.sessionManager.getEntries(), finds the
last entry with role "assistant" and text content, opens it in the
annotation UI. Reuses existing isAssistantMessage(), getTextContent(),
startAnnotateServer(), and runBrowserReview() from the extension.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add /plannotator-last to OpenCode plugin + extract command handlers
Adds annotate-last command that fetches session messages via
client.session.messages(), finds the last assistant message with text
parts, and opens it in the annotation UI.
Refactors command handling: extracts review, annotate, and annotate-last
handlers from the inline event hook into commands.ts module. Reduces
index.ts by ~120 lines and makes adding future commands cleaner.
New files:
- apps/opencode-plugin/commands.ts — extracted command handlers
- apps/opencode-plugin/commands/plannotator-last.md — command metadata
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: context-aware UI labels for annotate-last mode
Adds "annotate-last" mode to the annotate server, passed through to the
UI via /api/plan response. The editor uses this to show "Copy message"
instead of "Copy plan", and "annotations on the message" in the
completion overlay.
- packages/server/annotate.ts: new `mode` option on AnnotateServerOptions
- packages/editor/App.tsx: annotateSource state derived from mode
- packages/ui/components/Viewer.tsx: copyLabel prop for button text
- All three harnesses pass mode: "annotate-last" in their callers
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add Codex support to annotate-last command
Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every
spawned process). Uses the thread ID to find the rollout file in
~/.codex/sessions/, parses the Codex rollout JSONL format to extract
the last assistant message.
Also adds `plannotator last` alias for shorter usage in Codex bang
commands (!plannotator last).
New files:
- apps/hook/server/codex-session.ts — Codex rollout parser
- apps/hook/server/codex-session.test.ts — 9 tests
Modified:
- apps/hook/server/index.ts — Codex detection + `last` alias
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: context-aware feedback title + top spacing for paragraph-first content
- exportAnnotations now accepts a title param: "Message Feedback" for
annotate-last, "File Feedback" for file annotation, "Plan Feedback"
for plan review (default)
- Adds top spacer when content starts with a paragraph (not a heading)
and has no frontmatter, fixing tight spacing in annotate-last mode
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add sandbox scripts for Pi and Codex testing
- sandbox-pi.sh: builds extension, creates temp project, installs via
`pi install`, launches Pi with sample files
- sandbox-codex.sh: compiles binary, creates temp project, launches
Codex. Test with `!plannotator last`
Both follow the same pattern as sandbox-opencode.sh.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: add hook build step to opencode sandbox script
The opencode build copies HTML from hook/dist/ — without building hook
first, the sandbox could use stale HTML. Pi and Codex sandboxes already
had this step.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove command body from plannotator-last to prevent agent response
The .md body was being sent to the agent as a prompt, causing it to
respond with "Opening annotation UI..." before the event handler could
fetch messages. That response became the "last message" instead of the
actual one. Empty body = agent stays silent, event handler intercepts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: use command.execute.before hook for OpenCode annotate-last
Moves plannotator-last from the passive event hook to the
command.execute.before hook. This intercepts the command before the
agent sees it, clears output.parts so the agent stays silent, fetches
session messages, opens the annotation UI, then sends feedback via
client.session.prompt() — same pattern as review/annotate.
Previously the agent would respond to the command body before the
event handler could fetch messages, polluting the session history.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: add Codex to origin type and agent name mapping
Origin "codex" was falling through to the default "Coding Agent" label.
Added "codex" to the origin union type across annotate server, editor,
and removed the `as any` cast in the hook.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remote share link, plan-specific prose, and codex type unions
- Add writeRemoteShareLink to annotate-last onReady callback so remote
sessions get a reachable URL
- Add subject parameter to exportAnnotations so feedback says "message"
or "file" instead of "plan" when appropriate
- Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner,
and App.tsx fetch handler
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: use RenderedMessage type instead of inline structural type
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
||
|
|
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> |
||
|
|
908ea9cf32 |
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> |
||
|
|
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> |
||
|
|
9a23c249b2 |
feat: add quick label selection mode for one-click annotations (#272)
* feat: add quick annotation labels for one-click preset feedback Add preset label chips (Needs tests, Security concern, Break this up, etc.) that allow instant annotation without typing. Includes ⚡ toolbar button, Alt+1..8 keyboard shortcuts, label customization in Settings, and label summary in export output. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: add quick label selection mode for one-click annotations * feat: redesign quick label picker UX and add label tips - Redesign FloatingQuickLabelPicker as a vertical context-menu style list with cursor-anchored positioning (appears at mouseup point, not selection center) - Unify label dropdown: toolbar and quick-label mode now share the same FloatingQuickLabelPicker component (removed duplicate InlineQuickLabelDropdown) - Fix above/below flip positioning (follow CommentPopover pattern with conditional translateY) - Add label tips: optional instruction text on QuickLabel that gets injected into agent feedback as a blockquote below the label - Add tip editor in Settings with three visual states (empty/editing/filled) - Add "Missing overview" default label with a tip for requesting narrative context - Extend keyboard shortcuts from Alt+1-8 to Alt+1-9 - Suppress input method toggle (Alt) when label picker is open - Reorder default labels: Clarify this, Needs tests, Consider edge cases, Missing overview, Security concern, Break this up, Wrong order, Discuss first, Nice approach Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: curate default labels, add cyan/amber colors, bare digit shortcuts Finalize the 10 default quick labels based on user feedback data: clarify, overview, verify, example, patterns, alternatives, regression, out-of-scope, tests, nice-approach. Each label gets a unique color (added cyan and amber to the palette). Bare digit keys (1-0) now apply labels when the picker is open, Alt+N still works everywhere. Tip editor cursor starts at beginning for readability. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: prevent duplicate annotation when digit key fires both toolbar and picker handlers When the quick label picker is open from the toolbar's zap button, let FloatingQuickLabelPicker own all keyboard input instead of both components handling the same keypress. 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> |
||
|
|
c0076621ac |
feat: add quick annotation labels for one-click preset feedback (#268)
Add preset label chips (Needs tests, Security concern, Break this up, etc.) that allow instant annotation without typing. Includes ⚡ toolbar button, Alt+1..8 keyboard shortcuts, label customization in Settings, and label summary in export output. Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Michael Ramos <mdramos8@gmail.com> |
||
|
|
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> |
||
|
|
93e9420cb4 |
feat: open linked .md files in read-only tabs with TOC navigation (#184)
* feat: open linked .md files in read-only tabs with TOC navigation When a plan references local .md files via markdown links, they now open in a new browser tab using the full Plannotator viewer in read-only mode. Changes: - server: add /api/doc?path= endpoint with 4-strategy path resolution (absolute, relative to project root, bare filename search). Returns 400 with match list on ambiguous filenames, 404 when not found, 403 on path traversal. Only resolves files within process.cwd(). - Viewer: detect local .md links in InlineMarkdown and route them to /?doc=<path>&readonly=true with a new-tab icon. Add isReadOnly prop that guards the web-highlighter init (prevents phantom highlights) and suppresses annotation toolbars. - App: parse ?doc= URL param on load and fetch from /api/doc instead of /api/plan. Set isReadOnly mode which shows a read-only banner, hides approve/deny/feedback buttons, ModeSwitcher, Settings, AnnotationPanel, and annotation panel toggle. Shows an error view (not a silent fallback) when the document cannot be found or is ambiguous. Opens the sidebar to the TOC tab automatically. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat: upgrade linked docs to same-view annotatable navigation with aggregated feedback Replace the new-tab read-only approach with same-view navigation: clicking a .md link swaps the plan content in-place, preserving all annotations via a docCache. Users can annotate linked docs and all feedback (plan + linked docs) is aggregated into the deny/approve payload sent to Claude. Key changes: - New useLinkedDoc hook for state swapping, caching, and highlight restoration - React key on Viewer forces clean unmount/remount (fixes web-highlighter DOM crash) - exportLinkedDocAnnotations() aggregates linked doc feedback with filepath context - UI: 2px primary border, "Linked File" badge, "Copy file" button, TOC filepath indicator with back-to-plan button - Fix Tailwind v4 cascade: move * { border-color } to @layer base so utility classes like border-primary actually override it - Compact TOC spacing (padding, gaps, line-height) without affecting Version Browser - Exclude node_modules/.git from /api/doc bare filename glob Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: harden /api/doc endpoint and align linked doc annotation output Restrict /api/doc to .md/.mdx files only, fix heading hierarchy and sorting in exportLinkedDocAnnotations, and update CLAUDE.md docs. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: complete linked doc annotations in getDocAnnotations and fix useMemo deps - getDocAnnotations() now includes the active linked doc's live annotations alongside the cache, removing the implicit requirement to call back() before reading - Remove unstable linkedDocHook object from annotationsOutput useMemo dependency array (was defeating memoization every render) - Guard Cmd+Enter shortcut against linkedDocHook.isActive to prevent accidental approve/deny while viewing a linked doc Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: include linked doc annotations in approve feedback gate The handleApprove gate only checked plan-level annotations, silently dropping linked-doc-only feedback on "approve with notes" (OpenCode). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: add getDocAnnotations to annotationsOutput useMemo deps Ensures memo recomputes when navigating to/from linked docs, preventing stale annotation output. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: Michael Ramos <mdramos8@gmail.com> |
||
|
|
444934a654 |
refactor: rename diff → annotations in plan review context (#173)
* refactor: rename misleading "diff" terminology to "annotations" in plan review context The plan review flow used "diff" naming (exportDiff, diffOutput, .diff.md, "Raw Diff", "Download .diff") for what is actually user annotations/feedback on a plan. This was confusing since the code review flow legitimately uses "diff" for actual git diffs. Renames all plan-review-context "diff" references to "annotations" across code, UI labels, file extensions, and docs. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: update stale exportDiff references in ANNOTATE.md Missed during the diff→annotations rename. Updates two references to exportDiff() → exportAnnotations() in the annotate flow docs. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: rename remaining "Download Diff" label and tab type in App.tsx The quick-save dropdown button still showed "Download Diff" and the initialExportTab state type still used 'diff' instead of 'annotations'. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
0926837d15 |
Render YAML frontmatter as styled metadata card (#45)
Fixes #43 - YAML frontmatter was rendering as ugly text because the parser treated it as regular markdown content. Changes: - Added extractFrontmatter() to parser that parses YAML key-value pairs - Added FrontmatterCard component that renders frontmatter nicely - Supports string values and arrays (rendered as tags) - Card appears at top of plan with muted background Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
226f2ad25d |
Feat/ux improvements (#10)
* handle indents and checkboxes * menu persistence when scrolling * better ux on teh annotation comment box |
||
|
|
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 |
||
|
|
889569a562 |
Add markdown table parsing and rendering
- Add 'table' type to Block union - Detect and collect table lines in parser - Render tables with proper HTML structure and styling 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> |
||
|
|
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> |