Repository navigation
Render markdown in comment bodies, and stop three ways of losing text - #19
Conversation
Renders comment bodies, replies, and notes as markdown in the marker popover and the Hub panel. types.ts has described the body as "freeform inline markdown" since the format was written and assistants emit markdown by default, so the flagship workflow reliably produced comments displayed as raw source. One entry point owns it, markdown-render.ts, so no surface can drift. Fixes #6 Two items on this work's checklist turned out to be live data-loss bugs in 1.13.0 rather than the precautions they were written as, confirmed by running the parser before changing anything: - Any trailing body line starting with `[` was deleted. The forward-compat rule matched every bracket-leading line, so a body ending in `[label](url)`, `[ref]: url`, `[^1]: note` or `[[Wikilink]]` lost that line on the next parse. data-format.md had always specified a narrower rule, so the code was out of conformance with its own contract. Narrowed to the two shapes the format defines. The principle is now written down: when a trailing line is ambiguous, keep it in the body, because deleted prose is unrecoverable and an unparsed structured line is merely visible. - `-->` in a body corrupted the note. serialize() wrote it raw, so the marker ended early and the remainder appeared as stray text in the document. Now escaped as `--\>` and restored on read, with the escape marker itself escaped so the mapping is reversible at every depth. Imports go through serialize() too, since a `%%...%%` comment can hold `-->` legally, and the exported AI skill documents the escape (SKILL_SCHEMA_VERSION 4). Fixes #12 Panel actions serialized the comment captured when the card was rendered, so a reply landing between render and button press was silently overwritten. replaceMarker now takes a transition applied to the freshly re-read comment rather than a finished `next`, which fixes all seven verbs at once and costs no extra read. A marker that can no longer be identified aborts instead of writing at stale offsets, sharing the identify-or-refuse predicate that rejectAddressed worked out in PR A. Because the write can now be refused, appendReply reports whether it landed and both composers keep the user's text and stay open when it did not. Also here, because rendering exposed them: - The popover has had no max-width since PR A. CodeMirror puts `cm-tooltip` on the element the source returns, so the frame-stripping rule and .annoteca-hover-preview land on the same node and the two-class selector wins. Harmless for text that wraps; a rendered table or code fence has no such limit. - The Hub did not refresh when a display setting changed, leaving cards in their previous state until an unrelated event happened to redraw them. - scripts/check-settings-parity.mjs now fails the build when a setting is missing from either of the two settings render paths. Both are live at minAppVersion 1.8.7 and nothing enforced it; the dev vault runs 1.13.x, so testing by hand only ever exercised the declarative one. Verified in Obsidian 1.13.4 over CDP as hand-verification, not coverage: rendering in both surfaces, the wikilink resolving to a.internal-link, the popover capped at 420px with a code fence scrolling inside it, the setting toggling both ways with the panel open, a popover in a non-active split pane resolving links against its own file rather than the active one, and the reply flow end to end. 313 tests, with the parser, snapshot, abort, and lifetime guards each mutation-checked.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughSummary by CodeRabbit
WalkthroughThe PR adds Markdown rendering for comment surfaces, safe marker terminator escaping, settings parity validation, lifecycle cleanup, asynchronous reply handling, and fresh-marker checks for comment actions. ChangesComment rendering and settings
Marker safety and lifecycle writes
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant Popover
participant MarkdownRenderer
participant CommentService
User->>Popover: open comment surface
Popover->>MarkdownRenderer: render body with source path
MarkdownRenderer-->>Popover: complete rendered content
User->>CommentService: submit reply or lifecycle action
CommentService->>CommentService: resolve current marker
CommentService-->>Popover: success or refusal status
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This PR adds markdown rendering for comment free-text (bodies/replies/notes) across the hover popover and Hub panel via a single rendering entry point, while also hardening the marker format and lifecycle writes to prevent multiple classes of silent text loss/corruption.
Changes:
- Introduces
markdown-render.tsand updates popover/Hub UI renderers to render comment text as markdown (with scoped CSS to contain headings/tables/code blocks). - Fixes marker parsing/serialization to avoid dropping bracket-leading body lines and to escape/unescape
-->across all free-text fields. - Refactors comment lifecycle writes to re-read current marker state before applying transitions (avoiding stale-snapshot overwrites), and adds settings parity enforcement via a lint script.
Reviewed changes
Copilot reviewed 24 out of 24 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| views.ts | Refresh Hub on settings changes; dispose per-render markdown lifetime to avoid leaks. |
| ui-helpers.ts | Route reply-row bodies through the shared markdown renderer (optional host). |
| types.ts | Adds renderMarkdownBodies setting to the shared settings interface. |
| styles.css | Adds scoped markdown styling and restores hover popover max-width specificity. |
| skill-export.ts | Bumps skill schema version and documents --> escaping rule. |
| settings.ts | Adds renderMarkdownBodies default + setting row in both render paths. |
| scripts/check-settings-parity.mjs | New lint-time guard ensuring settings appear in both render paths. |
| README.md | Documents markdown rendering behavior and its scope/setting. |
| parser.ts | Narrows forward-compat trailing-line detection; adds reversible --> escaping. |
| package.json | Adds settings parity check to the lint script. |
| markdown-render.ts | New single entry point for markdown rendering + lifetime helpers. |
| main.ts | Plumbs settings validation for renderMarkdownBodies; reply APIs now return “written” status. |
| imports.ts | Uses serialize() when importing comments so --> is escaped consistently. |
| hub-thread-tab.ts | Renders expanded bodies/notes/replies as markdown; cycles render lifetime; makes reply submit single-flight. |
| decorations.ts | Renders popover text as markdown with correct sourcePath; repositions tooltips after async render; adds single-flight reply submit. |
| comment-service.ts | Refactors lifecycle verbs to apply transitions to freshly re-read comments; adds abort-on-vanished marker behavior. |
| CHANGELOG.md | Documents the new feature and the three text-loss/corruption fixes under Unreleased. |
| .github/copilot-instructions.md | Updates repo guidance to reflect new markdown-render and escaping/parity rules. |
| tests/stub-context.ts | Updates decoration context stub for new required fields / async submitReply. |
| tests/parser.test.ts | Adds coverage for bracket-leading body lines and --> escaping reversibility/legacy behavior. |
| tests/markdown-render.test.ts | Adds jsdom-based tests for render gating, callback behavior, and lifetime cycling. |
| tests/imports.test.ts | Adds tests ensuring --> survives imports without corrupting prose. |
| tests/comment-service.test.ts | Adds tests for stale-snapshot safety, id-less fingerprinting, and vanished-marker aborts. |
| mocks/obsidian.ts | Extends Obsidian mock with Component/MarkdownRenderer/editorInfoField to support new modules/tests. |
| void this.plugin | ||
| .appendReply(c, { author, date: nowISO(), body }) | ||
| .then(() => { | ||
| .then((wrote) => { |
| el.classList.add('annoteca-md'); | ||
| void MarkdownRenderer.render( | ||
| host.app, | ||
| markdown, | ||
| el, | ||
| host.sourcePath, | ||
| host.component, | ||
| ).then(() => { | ||
| // The surface can be gone by now: a hover tooltip dismisses on mouse-out | ||
| // and a panel re-render empties its container, either of which can happen | ||
| // while the render is still in flight. | ||
| if (!el.isConnected) return; | ||
| host.onRendered?.(); | ||
| }); |
| async appendReply(comment: Comment, reply: Reply): Promise<boolean> { | ||
| const path = this.plugin.app.workspace.getActiveFile()?.path; | ||
| if (!path) return; | ||
| const updated: Comment = { | ||
| ...comment, | ||
| replies: [...comment.replies, reply], | ||
| }; | ||
| await this.replaceMarker(path, comment, updated); | ||
| if (!path) return false; | ||
| const outcome = await this.replaceMarker(path, comment, (current) => ({ |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
comment-service.ts (1)
164-169: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winThe
deleteOnResolveshortcut bypasses the fresh-state check that every other lifecycle verb now performs. BothresolveCommentandacceptAddressedtest the caller's snapshot, then delegate toresolveAndRemoveCommentwhendeleteOnResolveis enabled.resolveAndRemoveCommentre-resolves the marker offsets throughfreshComment, but it never re-checks the state the action was aimed at. The non-destructive branches do re-check, through theapplytransition inreplaceMarker, and decline. The destructive branch is the one that skips the check.
comment-service.ts#L164-L169: read the current marker before delegating, and decline with "This edit is no longer awaiting review." when the fresh comment has noaddressedstate. Without this, Accept deletes the marker, its body, and its whole thread after another writer already revised or rejected the pending edit.comment-service.ts#L41-L49: apply the same fresh-state read before delegating. The stakes are lower here, because removal is the configured outcome of resolving, but the asymmetry with the "Already resolved." path at line 60 is the same defect.__tests__/comment-service.test.ts#L295-L451: add two cases built withmakeHarnessWith(doc, true)sodeleteOnResolveis enabled. Assert that Accept refuses when the addressed state disappeared underneath the snapshot, and that Resolve refuses when a resolution landed in the meantime. The suite currently exercises only thedeleteOnResolve === falsebranch, which is why this gap is not caught.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@comment-service.ts` around lines 164 - 169, Update comment-service.ts lines 164-169 in acceptAddressed and lines 41-49 in resolveComment to read the current marker state before calling resolveAndRemoveComment; decline with "This edit is no longer awaiting review." when the fresh comment is no longer addressed, preserving the existing resolved-state behavior. In __tests__/comment-service.test.ts lines 295-451, add deleteOnResolve-enabled cases verifying Accept declines after the addressed state disappears and Resolve declines after resolution occurs concurrently.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@CHANGELOG.md`:
- Line 11: Update the changelog entry so the inline code span containing “- ”
uses an extra backtick delimiter to preserve its trailing space without
triggering MD038, and capitalize both prose occurrences of “markdown” as
“Markdown” on the affected lines.
In `@markdown-render.ts`:
- Around line 58-70: Add a rejection handler to the promise chain created by
MarkdownRenderer.render so failures are handled visibly rather than becoming
unhandled rejections. Update the catch path near host.onRendered?.() to provide
an appropriate visible fallback or failure signal, while preserving the existing
isConnected guard and successful-render behavior.
In `@styles.css`:
- Around line 2223-2226: Replace the deprecated word-break: break-word
declaration in both .annoteca-md code and .annoteca-md a with overflow-wrap:
anywhere, preserving arbitrary-word breaking behavior in both selectors.
---
Outside diff comments:
In `@comment-service.ts`:
- Around line 164-169: Update comment-service.ts lines 164-169 in
acceptAddressed and lines 41-49 in resolveComment to read the current marker
state before calling resolveAndRemoveComment; decline with "This edit is no
longer awaiting review." when the fresh comment is no longer addressed,
preserving the existing resolved-state behavior. In
__tests__/comment-service.test.ts lines 295-451, add deleteOnResolve-enabled
cases verifying Accept declines after the addressed state disappears and Resolve
declines after resolution occurs concurrently.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 11755d76-d8af-47c2-902a-217d69a9410e
📒 Files selected for processing (24)
.github/copilot-instructions.mdCHANGELOG.mdREADME.md__mocks__/obsidian.ts__tests__/comment-service.test.ts__tests__/imports.test.ts__tests__/markdown-render.test.ts__tests__/parser.test.ts__tests__/stub-context.tscomment-service.tsdecorations.tshub-thread-tab.tsimports.tsmain.tsmarkdown-render.tspackage.jsonparser.tsscripts/check-settings-parity.mjssettings.tsskill-export.tsstyles.csstypes.tsui-helpers.tsviews.ts
Addresses the CodeRabbit review on #19, plus two defects the commit gate and Codex found in the same area. The major one: `deleteOnResolve` bypassed the fresh-state check every other lifecycle verb now performs. `resolveComment` and `acceptAddressed` tested the caller's snapshot and then delegated to `resolveAndRemoveComment`, which re-resolved the marker's OFFSETS but never re-checked the STATE the action was aimed at. That is the destructive branch, so with the setting on, Accept deleted the marker, its body, and its whole thread even when another writer had already revised or rejected the pending edit. It now takes an optional freshness guard and declines. The explicit "Resolve and remove" action passes no guard and still acts on whatever is there, which is what its own confirmation is for. Reply drafts, which took two passes to get right: - Both composers cancelled the debounced draft save on submit, so a save queued by the last keystroke could land after clearDraft and bring the sent text back on next open. - Cancelling alone then created a worse bug: submitting inside the 300ms debounce meant the newest text had never been stored at all, so a refused or failed write left it only in a textarea that the next panel re-render rebuilds from the draft. Both now FLUSH the save before submitting and clear it only on success, which is correct in both directions. - The Hub's reply button had neither the single-flight guard nor the rejection handler the popover composer got, so a double press could post twice and a rejected write left it disabled with the text trapped behind it. Smaller review points: - `MarkdownRenderer.render` had no rejection handler. A throw inside another plugin's post-processor became an unhandled rejection and left an empty box where the comment was; it now falls back to the source text. - `word-break: break-word` is deprecated, replaced with `overflow-wrap`. - CHANGELOG: reworded to drop an inline code span with a trailing space (MD038). Left "markdown" lowercase, matching the file's existing usage. 316 tests. The destructive guard is mutation-checked: removing it fails both new cases.
|
@coderabbitai review The previous review landed on |
|
✅ Action performedReview finished.
|
`appendReply` resolved its target from `workspace.getActiveFile()`, but replies come from surfaces that are not tied to whatever is focused. A Hub card in a folder or vault scope belongs to another note entirely, and a popover can be open in a non-active split pane. `renderExpandedSection` already had the card's path and dropped it on the way to `renderReplyInput`. Before the stale-snapshot work in this branch, that wrote at the cached offsets inside the ACTIVE file, so replying from such a card corrupted a different document. The identify-or-refuse guard turned that into a visible refusal instead, which is better but still a broken reply button. The path is now passed explicitly the whole way down: the Hub passes its card's path, and the popover passes the file its own editor holds, via the same `sourcePathFor` rule already used to resolve links in a rendered body. Found by Copilot on #19. It is not a merge gate here, but the finding was correct and a push was happening anyway. The test harness was the reason this had no coverage: it returned the same file for any path asked of it, so it could not tell "wrote to the file it was given" from "wrote to whatever was focused". It now resolves only its own path and reports a different file as active. Both new tests fail if the target is taken from the active file again. 318 tests.
|
@coderabbitai full review Full rather than incremental: the two commits since your review ( All four findings from your review are addressed:
Also fixed here, from Copilot's review: 318 tests. |
|
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
__tests__/markdown-render.test.ts (1)
62-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a test for the render-rejection fallback.
beforeEachonly mocksMarkdownRenderer.renderwithmockResolvedValue. No test in this file drives the.catch()fallback inrenderCommentMarkdown(the plain-text fallback added inmarkdown-render.tsfor a rejecting render). That fallback was added to fix a previously flagged unhandled-rejection issue; a regression test locks the fix in.✅ Proposed test for the rejection fallback
+ it('falls back to plain text and still fires onRendered when the render rejects', async () => { + renderSpy.mockRejectedValueOnce(new Error('boom')); + const el = div(); + const onRendered = jest.fn(); + renderCommentMarkdown(el, '**bold**', makeHost({ onRendered })); + + await flush(); + await flush(); + expect(el.classList.contains('annoteca-md')).toBe(false); + expect(el.textContent).toBe('**bold**'); + expect(onRendered).toHaveBeenCalledTimes(1); + });Also applies to: 94-107
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@__tests__/markdown-render.test.ts` around lines 62 - 75, Add a test in the markdown rendering test suite that makes the MarkdownRenderer.render spy reject, invokes renderCommentMarkdown, and asserts the rendered output uses the plain-text fallback without an unhandled rejection. Keep the existing successful-render setup intact and restore the spy through the existing beforeEach/afterEach lifecycle.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@hub-thread-tab.ts`:
- Around line 750-762: Update the appendReply success handler in the reply
submission flow to show a Notice with the existing “Could not save the reply.
Try again.” message when wrote is false, before releasing and returning;
preserve the draft and existing release behavior.
---
Nitpick comments:
In `@__tests__/markdown-render.test.ts`:
- Around line 62-75: Add a test in the markdown rendering test suite that makes
the MarkdownRenderer.render spy reject, invokes renderCommentMarkdown, and
asserts the rendered output uses the plain-text fallback without an unhandled
rejection. Keep the existing successful-render setup intact and restore the spy
through the existing beforeEach/afterEach lifecycle.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 45045ae2-7c47-4f7e-915c-2d1a40e223bc
📒 Files selected for processing (24)
.github/copilot-instructions.mdCHANGELOG.mdREADME.md__mocks__/obsidian.ts__tests__/comment-service.test.ts__tests__/imports.test.ts__tests__/markdown-render.test.ts__tests__/parser.test.ts__tests__/stub-context.tscomment-service.tsdecorations.tshub-thread-tab.tsimports.tsmain.tsmarkdown-render.tspackage.jsonparser.tsscripts/check-settings-parity.mjssettings.tsskill-export.tsstyles.csstypes.tsui-helpers.tsviews.ts
| void this.plugin | ||
| .appendReply(c, { author, date: nowISO(), body }) | ||
| .then(() => { | ||
| .appendReply(path, c, { author, date: nowISO(), body }) | ||
| .then((wrote) => { | ||
| // Keep what the user typed when the write was refused. The | ||
| // draft is the only copy of it at that point. | ||
| if (!wrote) { | ||
| release(); | ||
| return; | ||
| } | ||
| textarea.value = ''; | ||
| if (c.id) this.plugin.clearDraft(c.id); | ||
| release(); | ||
| }) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Give feedback when the reply write is refused.
When appendReply resolves wrote === false, the handler calls release() and returns. The textarea keeps the draft, but nothing tells the user why the reply was not sent. Compare this to the rejected-promise branch, which shows new Notice('Could not save the reply. Try again.').
Add a Notice on the refusal branch so a stale-marker refusal is as visible as an I/O failure.
💬 Proposed fix to notify on refusal
.then((wrote) => {
// Keep what the user typed when the write was refused. The
// draft is the only copy of it at that point.
if (!wrote) {
release();
+ new Notice(
+ 'Could not add the reply: the comment changed. Refresh and try again.',
+ );
return;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| void this.plugin | |
| .appendReply(c, { author, date: nowISO(), body }) | |
| .then(() => { | |
| .appendReply(path, c, { author, date: nowISO(), body }) | |
| .then((wrote) => { | |
| // Keep what the user typed when the write was refused. The | |
| // draft is the only copy of it at that point. | |
| if (!wrote) { | |
| release(); | |
| return; | |
| } | |
| textarea.value = ''; | |
| if (c.id) this.plugin.clearDraft(c.id); | |
| release(); | |
| }) | |
| void this.plugin | |
| .appendReply(path, c, { author, date: nowISO(), body }) | |
| .then((wrote) => { | |
| // Keep what the user typed when the write was refused. The | |
| // draft is the only copy of it at that point. | |
| if (!wrote) { | |
| release(); | |
| new Notice( | |
| 'Could not add the reply: the comment changed. Refresh and try again.', | |
| ); | |
| return; | |
| } | |
| textarea.value = ''; | |
| if (c.id) this.plugin.clearDraft(c.id); | |
| release(); | |
| }) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@hub-thread-tab.ts` around lines 750 - 762, Update the appendReply success
handler in the reply submission flow to show a Notice with the existing “Could
not save the reply. Try again.” message when wrote is false, before releasing
and returning; preserve the draft and existing release behavior.
CodeRabbit's second review flagged that the Hub reply handler goes quiet when `appendReply` resolves false. Following that into the service found the cause, and it was wider than the reported symptom: `replaceMarker` returns 'missing' from two places, and only one of them notified. The other, `!(file instanceof TFile)`, returned silently, and so did the same guard in deleteComment, resolveAndRemoveComment and rejectAddressed. That path is reachable. Folder and vault scopes render Hub cards for notes the user is not looking at, and one can be renamed or deleted between the render and the button press. Every one of those buttons simply did nothing. All five write paths now report through one `noticeFileGone`, which names the path so the message says which note went missing. `deleteAllResolvedInFile` returns `number | null` instead of 0 for the same case. The confirmation modal sits between the resolved-count check and the write, so the note can go away in between, and returning 0 made the caller announce "Deleted 0 resolved comments" — which reads as "there were none" rather than "the file is gone". Also from that review: a test for the markdown render-rejection fallback, which was added earlier without one. The Notice text is deliberately not asserted. jest.spyOn cannot call through to an ES class constructor, and the ways around it are a type assertion on the mock or a recording member on the Obsidian stub that the real obsidian.d.ts does not have, which would compile under Jest and fail `npm run build`. The tests assert the return contracts the callers depend on instead, and each fails if its guard is removed. 325 tests.
|
Both points from the last review are in The reply handler going quiet. Correct, and following it into the service found the cause was wider than the symptom. I did not add a second Notice in the Hub handler as suggested, because the refusal case it was aimed at already fires Related, found while there: The render-rejection test. Added, plus one for the case where the element leaves the document before the rejection settles. 325 tests. Each new guard is mutation-checked: removing |
`[reply ...]`, `[anchor=]`, `[addressed ...]` and `[resolved ...]` are single-line grammars: parseInnerContent splits the inner content on `\n` and walks it backward, breaking on the first line that matches no known shape. A newline in any of those fields produced a continuation line that stopped the walk immediately, so the reply, the `[id=]`, and every other trailing line were absorbed into the body as visible text. The comment lost its thread and its identity, which breaks starring, drafts, Copy ID, and the freshComment re-lookup this branch relies on. Reproduced against the parser at a73c100: a reply body of "first line" + newline + "second line" re-parses to id undefined, replies [], and a body holding the marker's own metadata lines. Pre-existing, but this branch makes it the invited usage. The Hub reply box is a rows=3 textarea with no keydown handler, so Enter has always inserted a newline, and rendering replies as markdown makes writing a list the obvious thing to try. The parser header also claimed the format was "closed under arbitrary user text" after the `-->` escape, and that was not true while this held. escapeInline() is escapeTerminator() plus collapsing a run of line breaks to one space, applied to those four fields only. The body and the annoteca-original fence keep escapeTerminator() alone: both are multi-line by contract, the body because bodyMultiline re-emits it and the fence because it is delimited rather than parsed line by line. Seven tests, mutation-checked: removing the collapse fails six. The exported skill teaches the same rule, since an assistant writing a marker directly never goes through serialize(). SKILL_SCHEMA_VERSION is already 4 on this branch and 3 in 1.13.0, so no further bump is needed. Also: the Hub reply box stopped redisplaying a reply it had just sent. applySplices fires index-changed synchronously, and the panel rebuilds the card while appendReply is still unresolved, so the unconditional saveDraft added earlier on this branch was read straight back into the rebuilt textarea and the .then() cleared a detached one. The visible composer kept the text with its button re-enabled, and pressing Reply again posted a duplicate. The draft is now cleared before the write and restored only on the refusal and throw branches, which repaint when the composer was detached so the restored text is on screen rather than only in storage. Debounced saves are tracked on the renderer and cancelled in dispose(), because an orphan from a detached composer would otherwise fire after a later submit cleared the draft and resurrect the sent reply.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@hub-thread-tab.ts`:
- Around line 67-69: Update draftSaveTimers and the associated draft-save flow
in hub-thread-tab.ts to track pending timers by comment ID rather than timer ID
alone. Before clearDraft(c.id), cancel every pending timer associated with that
comment, and ensure cancelSave() is used for the current timer so it removes
itself from the tracking collection; preserve cancellation across
repaint-detached composers.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fa38207e-20e8-40b8-8e20-c64bba531265
📒 Files selected for processing (10)
CHANGELOG.md__tests__/comment-service.test.ts__tests__/markdown-render.test.ts__tests__/parser.test.tscomment-service.tshub-thread-tab.tsmain.tsparser.tsskill-export.tstypes.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- types.ts
- skill-export.ts
- tests/comment-service.test.ts
- main.ts
- comment-service.ts
CodeRabbit, on 7ce5c42: a debounced save left behind by a composer that a repaint detached could not be cancelled by the composer that replaced it, because the submit path only cancelled the timer held in its own closure. An orphan firing after clearDraft writes the old text back, and the sent reply reappears as a draft on the next render. draftSaveTimers becomes Map<commentId, Set<timer>>. Submitting cancels every timer for that comment before clearing the draft, so a timer from a previous render of the same card dies with it. dispose() still cancels everything, and a timer that fires normally removes itself. The reachability argument says the orphan cannot survive today: renderReplyInput has one caller, inside render(), whose only call site is views.ts:468, which is always preceded by dispose() at views.ts:459, and dispose() cancels every pending timer. Implemented as reported anyway. The guarantee then holds locally, in the submit path, instead of depending on a call graph three files away that a future refresh path could quietly break.
|
@coderabbitai full review Full rather than incremental: Your finding is implemented as written, not argued around. Associate pending draft timers with the comment ID ( For the record, the reachability argument said the orphan could not survive today: Two other defects were fixed in
|
|
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (4)
comment-service.ts (2)
25-31: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider exporting
WriteOutcome.
resolveAndRemoveCommentandreplaceMarkerare public and returnWriteOutcome, but the type is module-private. External callers cannot name the type when they store or forward the outcome. Also, if the build ever emits declarations, TypeScript reports TS4053 for a public method that returns a private name.♻️ Proposed change
-type WriteOutcome = 'written' | 'declined' | 'missing'; +export type WriteOutcome = 'written' | 'declined' | 'missing';🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@comment-service.ts` around lines 25 - 31, Export the WriteOutcome type so external callers can name the return type of the public resolveAndRemoveComment and replaceMarker methods, while preserving its existing three outcome values.
526-533: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueWiden the vanished-marker wording.
noticeVanishedfires when the marker was deleted as well as when it moved. The current text says only "has moved", which misstates the deletion case. A wording that covers both keeps the recovery instruction valid.♻️ Proposed change
new Notice( - 'This comment has moved since it was loaded. Reopen the note and try again.', + 'This comment changed or was removed since it was loaded. Reopen the note and try again.', );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@comment-service.ts` around lines 526 - 533, Update noticeVanished so its Notice message covers both cases where the marker was moved or deleted, while retaining the existing instruction to reopen the note and retry.__tests__/comment-service.test.ts (2)
444-454: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueIsolate the fingerprint field this test targets.
The replacement changes the body text and its length, so
marker.endshifts too. The test therefore passes if either the body check or the offset check refuses, and it cannot detect a regression that drops the body comparison fromfreshComment. A same-length replacement keeps the offsets stable and pins the body check alone.♻️ Proposed change
- h.content = h.content.replace('which products?', 'rewritten elsewhere'); + // Same byte length, so marker.start/end are unchanged and only the body + // comparison in freshComment can refuse this. + h.content = h.content.replace('which products?', 'which suppliers??');🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@__tests__/comment-service.test.ts` around lines 444 - 454, Update the test “refuses an id-less marker whose body changed underneath” to replace the original body text with different text of exactly the same length, keeping marker offsets unchanged. Preserve the assertions that the content and resolution remain unchanged so the test isolates the body comparison performed by freshComment.
656-670: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRecord
Noticeconstruction in the Obsidian mock.
__mocks__/obsidian.tsdefinesNoticeasclass Notice { constructor(_message?: string) { /* no-op */ } }, so these tests need not assert onlywrote/return values. Add a test-safe recorder to the mock, then assert the missing-file and vanished-marker messages, or accept non-assertion with an explicit reason.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@__tests__/comment-service.test.ts` around lines 656 - 670, Update the Obsidian Notice mock and the appendReply-related tests to record constructed messages, then assert the expected notices for missing files and vanished markers. Replace the current return-value-only rationale in the test near appendReply with assertions that verify the recorded Notice text while preserving the existing wrote=false behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@comment-service.ts`:
- Around line 111-119: Update reopenComment to show a notice when replaceMarker
does not write because the comment was already reopened, while preserving the
existing “Reopened.” notice for the written outcome. Use the existing notice
wording conventions for declined transitions.
In `@decorations.ts`:
- Around line 707-717: Update all path-sensitive DecorationContext callbacks in
decorations.ts to accept and pass sourcePathFor(ctx, view), not only reply
submission. Thread this editor path through main.ts into the corresponding popup
lifecycle handlers and “Open in side panel” operation, ensuring those handlers
use the supplied path instead of workspace.getActiveFile().
In `@hub-thread-tab.ts`:
- Around line 80-90: Update the reply draft debounce flow around
renderReplyInput, draftSaveTimers, and dispose() to retain each timer’s pending
draft text and persist that text before cancelling timers during disposal, so
refreshes preserve unsaved input. Keep cancelSavesFor()’s existing discard
behavior for submissions before clearDraft(), and add coverage for typing,
refreshing within 300 ms, and restoring the draft in the rebuilt composer.
In `@parser.ts`:
- Around line 464-468: Update the annoteca-original serialization block around
c.addressed.original to choose a backtick fence longer than any fence-like run
in the escaped content, use it for both opening and closing delimiters, and
preserve escapeTerminator. Update ORIGINAL_FENCE_RE to accept variable-length
fences and require the closing fence to match the opening length so fenced
content is captured intact.
In `@README.md`:
- Line 21: Update the README settings overview by adding the formatted-rendering
toggle under the Indicators entry, using the setting’s existing name and
describing that it disables markdown rendering for comments. Keep the
surrounding settings descriptions unchanged.
In `@scripts/check-settings-parity.mjs`:
- Around line 62-72: Replace the `NO_PLAIN_ROW` set with a key-to-reason map or
record, preserving all existing exempt keys and adding a clear justification for
each. Update the parity-check logic to use the map’s keys for exemption checks
while retaining the current behavior.
In `@settings.ts`:
- Around line 225-232: Update the setting rows for renderMarkdownBodies in
settings.ts at lines 225-232 and 574-579 to use the official “Markdown” casing
in both the setting name and description; apply the same casing consistently in
the imperative row.
---
Nitpick comments:
In `@__tests__/comment-service.test.ts`:
- Around line 444-454: Update the test “refuses an id-less marker whose body
changed underneath” to replace the original body text with different text of
exactly the same length, keeping marker offsets unchanged. Preserve the
assertions that the content and resolution remain unchanged so the test isolates
the body comparison performed by freshComment.
- Around line 656-670: Update the Obsidian Notice mock and the
appendReply-related tests to record constructed messages, then assert the
expected notices for missing files and vanished markers. Replace the current
return-value-only rationale in the test near appendReply with assertions that
verify the recorded Notice text while preserving the existing wrote=false
behavior.
In `@comment-service.ts`:
- Around line 25-31: Export the WriteOutcome type so external callers can name
the return type of the public resolveAndRemoveComment and replaceMarker methods,
while preserving its existing three outcome values.
- Around line 526-533: Update noticeVanished so its Notice message covers both
cases where the marker was moved or deleted, while retaining the existing
instruction to reopen the note and retry.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f1e6fe74-0a69-499f-bacd-4620197a5195
📒 Files selected for processing (24)
.github/copilot-instructions.mdCHANGELOG.mdREADME.md__mocks__/obsidian.ts__tests__/comment-service.test.ts__tests__/imports.test.ts__tests__/markdown-render.test.ts__tests__/parser.test.ts__tests__/stub-context.tscomment-service.tsdecorations.tshub-thread-tab.tsimports.tsmain.tsmarkdown-render.tspackage.jsonparser.tsscripts/check-settings-parity.mjssettings.tsskill-export.tsstyles.csstypes.tsui-helpers.tsviews.ts
CodeRabbit on e73b128, plus two Codex rounds on the fixes themselves. **A refresh was eating text typed in the last 300ms.** This is a regression introduced by the orphan-timer fix earlier on this branch, and it is the same trap the roadmap already recorded: cancelling a debounced draft save without running it loses the text a different way. dispose() runs before EVERY panel refresh (views.ts:459), so cancelling there discarded whatever had been typed since the last save and the rebuilt composer came back empty. The two ways a pending save can end are opposite, and conflating them loses text in one direction or the other. Submitting DISCARDS it, because the text was sent and a timer firing afterwards writes it back over the cleared draft. Disposing FLUSHES it, because the composer is still attached and the user is mid-sentence. Each pending save now carries a flush closure that reads the live textarea, so a flush stores the newest text rather than the value captured when it was armed. **A code block inside the replaced prose destroyed the comment.** The annoteca-original fence held the verbatim pre-edit text between bare ``` lines, and that text is arbitrary prose lifted out of the user's document, so it can contain a fence of its own. The first such line closed the block early; the leftovers then stopped the backward walk and collapsed the trailing block into the body, losing the original, the addressed state and the id. The fence is now always one backtick longer than the longest line-leading run in its content, and ORIGINAL_FENCE_RE takes a variable-length delimiter with a backreference so the close must match the open. Existing three-backtick markers still parse, and only content that cannot round-trip today gets a wider fence. Mutation-checked. **Widening the fence widened a pre-existing hole, so that is closed too.** The regex scanned the whole inner content, so any block tagged annoteca-original was lifted out and, with no addressed note to hang it on, deleted. A comment that documents the format by showing a fence is a normal thing to write, and the exported skill describes the fence, so assistants write them too. The code now enforces the adjacency its own comment already claimed: only a fence directly after the [addressed ...] line is an original. Mutation-checked. Also from the same review: reopenComment narrates its 'declined' outcome, which was the last lifecycle verb that silently did nothing; WriteOutcome is exported, since public methods return it; the vanished-marker notice says "moved or been deleted", which is what the id lookup actually cannot distinguish; NO_PLAIN_ROW is a Map carrying a reason per key, per copilot-instructions.md:174; and "Markdown" takes its official casing in both settings rows, the README and this release's CHANGELOG entries, per copilot-instructions.md:153. That last one reverses an earlier dismissal on this branch which claimed the repo convention was lowercase; the repo's written guideline says the opposite. Codex asked twice to bump SKILL_SCHEMA_VERSION so existing v4 exports would be flagged stale. Skipped, on the evidence: every released tag ships version 3 (1.10.1 through 1.13.0), and 4 exists only on this unreleased branch, so no export in the wild carries it. The fence rule is added to v4 before v4 ships. Deferred deliberately, now issue #22: the five popover lifecycle actions still resolve their path from getActiveFile() rather than the popover's own editor. The freshComment guard makes that a refusal rather than corruption, and the fix threads a path through five handlers, so it is its own change.
Fixes a data-loss regression introduced by 3a06b6f, the commit immediately before this one, and found after it was pushed. CI was green and mergeStateStatus read CLEAN on that commit; neither meant anything. **What broke.** 3a06b6f closed a real hole (any block tagged annoteca-original was lifted out of any comment, so a body documenting the format had those lines deleted) by requiring the fence to sit on the line immediately after [addressed ...]. The strip was doing TWO jobs and the guard only asked about one: it attributes the fenced text to the addressed note, AND it removes the block so the backward line-walk is not stopped by it. Guarding job 1 silently killed job 2. A fence one blank line lower stayed in the content, the walk is line-oriented and a fence line matches nothing, so it ended there and the entire trailing block collapsed into the body. No id, no addressed state, no original. Accept/Revise/Reject stop rendering and Reject can no longer revert the prose even though the original text is still sitting in the file, and findMalformedMarkers does not flag any of it because the marker is well formed. serialize() always writes the fence adjacently, so the plugin never produced this itself. Hand-written and assistant-written markers do, and assistant-written markers are the premise of the feature. A blank line before a fenced block is ordinary Markdown; a [reply ...] or [resolved ...] line can land in between; data-format.md only ever said "inside the [addressed ...] note". **The rule now.** Position, not adjacency: a fence is the original if it appears anywhere after the last [addressed ...] line that is not itself inside a fence. Last, because that is the one the walk keeps (it runs backward and takes the first it meets), and because the trailing block is a SUFFIX, so a real [addressed ...] always sits below a quoted one. Not inside a fence, because the block holds prose lifted verbatim out of the document and can therefore hold a line shaped like [addressed ...] exactly as it can hold a code fence or a `-->`. serialize() writes one when the replaced passage had one. Counting it put the anchor inside the block, which starts before it, so the real fence looked like a body fence and was left behind to stop the walk: the same failure through the back door. Codex caught this on the first version of the fix. **The strip is no longer trusted blind.** After lifting, the walk's own verdict is checked: no addressed note means the [addressed ...] line the fence was attributed to was body text, so the strip was wrong and the untouched content is walked instead. The walk is what classifies body vs trailing block, so asking it keeps a second, drifting copy of that rule out of the parser. **Evidence, since fourteen prior review passes read this diff and missed the bug it introduced.** Three parser builds (a73c100, 3a06b6f, this) were bundled and run against the same inputs: - 200k-case differential fuzz: every difference from a73c100 is either the regression class this fixes (6.4%) or an intended 3a06b6f fix. Zero parse -> serialize -> parse instabilities. - 300k-case scan for cases where this parses with less structure or drops text the other two kept: the only text ever dropped is a duplicate second fence. - 200k serialize -> parse round trips with adversarial originals ([addressed ...] lines, nested fences, `-->`, annoteca-original tags): 0% loss here and at 3a06b6f, 12.9% at a73c100. - Six mutations of the fix, one per decision it makes, each caught by the test written for it. None survived. **Deliberate, both pinned by tests.** A second fence after the addressed note is dropped rather than left in place to stop the walk, which is the trade the walk already makes for a duplicate [addressed ...] or [resolved ...] line. And a body whose LAST lines quote the format is absorbed, because it is byte-identical to a real addressed note; every released version has done this, every character survives the next rewrite, and the alternative is the adjacency rule that destroys real markers. The comment says not to "fix" it back. The CHANGELOG line 3a06b6f added stated the adjacency rule as the contract, so it is corrected here rather than appended to; the whole [Unreleased] section is one unshipped PR.
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (6)
comment-service.ts (2)
501-516: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win
freshCommentcan match the wrong marker when ids repeat.
parsed.find((c) => c.id === comment.id)returns the first match. Marker ids come from file text, so a copy-paste of a marker inside one note produces two markers with the same id. The write then lands on the first one, which may not be the marker the card points at.The id-less branch is stricter than the id branch here. If duplicate ids are considered possible, treat a multi-match as unidentifiable and refuse.
♻️ Proposed change
if (comment.id !== undefined) { - return parsed.find((c) => c.id === comment.id); + const matches = parsed.filter((c) => c.id === comment.id); + return matches.length === 1 ? matches[0] : undefined; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@comment-service.ts` around lines 501 - 516, Update freshComment so the id-based lookup collects all markers with the matching id and returns a comment only when exactly one match exists; return undefined for duplicate or missing ids, while preserving the existing stricter matching behavior for id-less comments.
180-196: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win
applyAddressedoverwrites a concurrent addressed state.The transition sets
addressedunconditionally on the live marker. If another writer marked the same comment as addressed after the caller's snapshot, this write replaces that author, date, note, andoriginal. The storedoriginalis the only revert source forrejectAddressed, so the earlier revert text is lost.Every sibling transition inspects
currentbefore it acts. Consider declining whencurrent.addressedalready exists.♻️ Proposed change
- const outcome = await this.replaceMarker(path, comment, (current) => ({ - ...current, - addressed, - })); - if (outcome === 'written') new Notice('Marked as addressed.'); + const outcome = await this.replaceMarker(path, comment, (current) => + current.addressed ? undefined : { ...current, addressed }, + ); + if (outcome === 'written') new Notice('Marked as addressed.'); + else if (outcome === 'declined') + new Notice('This comment is already awaiting review.');🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@comment-service.ts` around lines 180 - 196, Update applyAddressed to inspect the live marker’s current addressed state inside the replaceMarker callback and avoid overwriting it when current.addressed already exists. Preserve the existing addressed data, including original, for concurrent transitions; only create and store the new addressed record when the marker is not already addressed, while retaining the existing success notice behavior for an actual write.decorations.ts (1)
1236-1291: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueCancel the in-flight submit path when the composer is destroyed.
submitresolves after an asynchronous write. The composer tooltip can be closed in the meantime, for example with Escape or Cancel. On success the callback dispatchessetReplyComposerEffect.of(null)again, which is harmless. On refusal or rejection,release()writes tosendandtextareaelements that are already detached, andNoticereports a failure for a composer the user has dismissed.Consider tracking a
closedflag or checkingtextarea.isConnectedbeforerelease()so a dismissed composer stays dismissed.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@decorations.ts` around lines 1236 - 1291, The submit function's asynchronous path can complete after the composer is destroyed, causing release() to modify detached DOM elements and displaying notices for a dismissed composer. Add a check before calling release() in both the .then() and .catch() branches of the submitReply promise chain to verify the composer is still connected to the DOM. Use textarea.isConnected to guard the release logic, ensuring that once the composer is closed, the pending state cleanup and element modifications are skipped while preserving the harmless setReplyComposerEffect.of(null) dispatch on successful submission.scripts/check-settings-parity.mjs (2)
89-90: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winMatch actual settings rows in the parity check.
namedIn()treats any quoted key inside a method region as evidence that a row exists. A key in a comment, description, or unrelated call can therefore make the check pass while the corresponding row is missing. Extract declarativecontrol.keyvalues and imperativeadd*Rowarguments, or parse the source structurally.As per coding guidelines, every setting must have a row in both
getSettingDefinitions()andrenderImperativeSettings(); the check should identify actual row declarations.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@scripts/check-settings-parity.mjs` around lines 89 - 90, Update namedIn in the settings parity check to detect only actual row declarations: extract declarative control.key values and imperative add*Row arguments, or use structural parsing, instead of matching arbitrary quoted keys in method text. Ensure the parity check validates that every setting has a row in both getSettingDefinitions() and renderImperativeSettings().Source: Coding guidelines
1-4: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAlign the minimum supported Obsidian version with the manifest.
scripts/check-settings-parity.mjssays the imperative path supportsminAppVersion 1.8.7, whileREADME.mdstates the plugin requires Obsidian1.13.0. Use one supported version consistently, or clarify why the manifest lower bound differs from the README requirement.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@scripts/check-settings-parity.mjs` around lines 1 - 4, Align the supported Obsidian version referenced by check-settings-parity.mjs with the requirement documented in README.md. Update the imperative-path minimum version or the README requirement so both state the same supported version, unless the manifest intentionally uses a lower bound; in that case, document the reason for the difference..github/copilot-instructions.md (1)
115-116: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDocument the inline-field newline collapsing.
parser.tsnow also normalizes line breaks in single-line fields throughescapeInline([anchor=...], reply bodies, addressed and resolution notes). The format rules here describe the-->escaping but not that collapsing. A contributor reading this section will not learn that a newline in one of those fields becomes a space on write.skill-export.tsalready states the rule for assistants; state it here too.📝 Suggested addition
- The `-->` sequence cannot appear literally in any free-text field, because it closes the HTML comment wrapper. `parser.ts` escapes it as `--\>` on write and restores it on read, for the body, `[anchor=...]`, reply bodies, the addressed and resolved notes, and the `annoteca-original` fence. Anything that writes a marker must go through `serialize()`; do not hand-build one. +- Every bracketed trailing line is a single-line grammar. `serialize()` collapses a run of line breaks to one space in `[anchor=...]`, reply bodies, and the addressed and resolved notes, because a raw newline there emits a continuation line that ends the parser's backward walk and absorbs `[id=...]` into the body. The body and the `annoteca-original` fence are multi-line by contract and are not collapsed.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/copilot-instructions.md around lines 115 - 116, Add documentation to the format rules in .github/copilot-instructions.md stating that single-line fields are normalized through escapeInline: newlines in [anchor=...] values, reply bodies, addressed notes, and resolution notes become spaces when written, consistent with skill-export.ts.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@main.ts`:
- Around line 278-286: The renderMarkdownBodies boolean validation in
loadSettings() around the typeof check is not applied in restoreSettings() which
directly spreads parsed JSON at lines 1695-1700, allowing string values like
"false" to remain truthy. Extract the normalization logic that validates
renderMarkdownBodies is a boolean and falls back to
DEFAULT_SETTINGS.renderMarkdownBodies into a shared normalizer function, then
call this function in both the loadSettings path and the restoreSettings spread
operation to ensure consistent validation.
In `@parser.ts`:
- Around line 600-609: Update serialize() to validate c.category with the
existing accepted-category validator before constructing the annoteca marker.
When validation fails, return the invalid category value unchanged so the
comment remains visible while preventing generation of a non-parsable marker;
reuse the validator from categories.ts or an appropriate non-Obsidian helper.
In `@styles.css`:
- Around line 2152-2154: Update the .annoteca-md rule to add overflow-wrap:
anywhere so long unbroken plain Markdown text wraps within the popover, while
preserving the existing pre code override for fenced-code scrolling.
---
Nitpick comments:
In @.github/copilot-instructions.md:
- Around line 115-116: Add documentation to the format rules in
.github/copilot-instructions.md stating that single-line fields are normalized
through escapeInline: newlines in [anchor=...] values, reply bodies, addressed
notes, and resolution notes become spaces when written, consistent with
skill-export.ts.
In `@comment-service.ts`:
- Around line 501-516: Update freshComment so the id-based lookup collects all
markers with the matching id and returns a comment only when exactly one match
exists; return undefined for duplicate or missing ids, while preserving the
existing stricter matching behavior for id-less comments.
- Around line 180-196: Update applyAddressed to inspect the live marker’s
current addressed state inside the replaceMarker callback and avoid overwriting
it when current.addressed already exists. Preserve the existing addressed data,
including original, for concurrent transitions; only create and store the new
addressed record when the marker is not already addressed, while retaining the
existing success notice behavior for an actual write.
In `@decorations.ts`:
- Around line 1236-1291: The submit function's asynchronous path can complete
after the composer is destroyed, causing release() to modify detached DOM
elements and displaying notices for a dismissed composer. Add a check before
calling release() in both the .then() and .catch() branches of the submitReply
promise chain to verify the composer is still connected to the DOM. Use
textarea.isConnected to guard the release logic, ensuring that once the composer
is closed, the pending state cleanup and element modifications are skipped while
preserving the harmless setReplyComposerEffect.of(null) dispatch on successful
submission.
In `@scripts/check-settings-parity.mjs`:
- Around line 89-90: Update namedIn in the settings parity check to detect only
actual row declarations: extract declarative control.key values and imperative
add*Row arguments, or use structural parsing, instead of matching arbitrary
quoted keys in method text. Ensure the parity check validates that every setting
has a row in both getSettingDefinitions() and renderImperativeSettings().
- Around line 1-4: Align the supported Obsidian version referenced by
check-settings-parity.mjs with the requirement documented in README.md. Update
the imperative-path minimum version or the README requirement so both state the
same supported version, unless the manifest intentionally uses a lower bound; in
that case, document the reason for the difference.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 5a210e00-14d4-4313-a26a-7b89619737d0
📒 Files selected for processing (24)
.github/copilot-instructions.mdCHANGELOG.mdREADME.md__mocks__/obsidian.ts__tests__/comment-service.test.ts__tests__/imports.test.ts__tests__/markdown-render.test.ts__tests__/parser.test.ts__tests__/stub-context.tscomment-service.tsdecorations.tshub-thread-tab.tsimports.tsmain.tsmarkdown-render.tspackage.jsonparser.tsscripts/check-settings-parity.mjssettings.tsskill-export.tsstyles.csstypes.tsui-helpers.tsviews.ts
| return `<!-- annoteca/${c.category}: ${body} -->`; | ||
| } | ||
|
|
||
| const lines: string[] = []; | ||
| lines.push(`<!-- annoteca/${c.category}: ${c.body}`); | ||
| lines.push(`<!-- annoteca/${c.category}: ${body}`); | ||
| if (c.id !== undefined) lines.push(`[id=${c.id}]`); | ||
| if (c.date !== undefined) lines.push(`[date=${c.date}]`); | ||
| if (c.author !== undefined) lines.push(`[author=${c.author}]`); | ||
| if (c.anchor !== undefined) lines.push(`[anchor=${c.anchor.text}]`); | ||
| if (c.anchor !== undefined) | ||
| lines.push(`[anchor=${escapeInline(c.anchor.text)}]`); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find every serialize() call site and the origin of its category argument.
rg -n -C4 --type=ts '\bserialize\s*\(' -g '!__tests__/**'
# Check what categories.ts exposes for validation.
rg -n -C3 --type=ts 'export (function|const) .*[Vv]alid' categories.tsRepository: ckelsoe/obsidian-annoteca
Length of output: 163
🏁 Script executed:
#!/bin/bash
set -u
echo "Tracked TS files with parser/categories/imports and test exclusion"
git ls-files '*.ts' | sed -n '1,200p'
echo
echo "Locate relevant files"
fd -a '^(parser|categories|imports|globals|skill-export)\.ts$|__tests__' . | sort | sed -n '1,200p'
echo
echo "search serialize occurrences"
rg -n -C4 '\bserialize\s*\(' . --glob '*.ts' --iglob '!**/__tests__/**' || true
echo
echo "search category validator occurrences"
rg -n -C3 'valid[ate|ation]|/^\[a-z\]|MARKER|category' parser.ts categories.ts imports.ts 2>/dev/null || trueRepository: ckelsoe/obsidian-annoteca
Length of output: 15807
🏁 Script executed:
#!/bin/bash
set -u
echo "parser.ts relevant sections"
sed -n '1,80p' parser.ts
sed -n '560,630p' parser.ts
echo
echo "categories.ts relevant sections"
sed -n '1,120p' categories.ts
sed -n '118,165p' categories.ts
sed -n '320,380p' categories.ts
echo
echo "imports.ts relevant sections"
sed -n '1,90p' imports.ts
echo
echo "comment-service.ts relevant sections around serialize calls"
sed -n '285,445p' comment-service.ts
echo
echo "composer.ts relevant sections around serialize calls"
sed -n '230,335p' composer.ts
echo
echo "views.ts relevant sections around serializeReplyAppended"
sed -n '300,350p' views.ts
echo
echo "import relationships for serialize"
rg -n "from ['\"].*parser|serialize\\(" imports.ts comment-service.ts views.ts composer.ts parser.ts categories.ts --glob '*.ts'Repository: ckelsoe/obsidian-annoteca
Length of output: 26502
Reject invalid category names in serialize().
serialize() interpolates c.category into the marker without parsing-level validation, while parsed categories must match annoteca/[a-z][a-z0-9-]*. If an invalid value reaches it, the comment becomes non-parsable text without a user-facing diagnostic. Return the invalid category unchanged for now, so existing comments still display.
♻️ Sketch
export function serialize(c: SerializeInput): string {
+ if (!/^[a-z](-?[a-z0-9])*$/.test(c.category)) return c.category;
// Every free-text field is escaped on the way out and unescaped on the waycategories.ts already has the accepted-name validator; reuse it from a non-Obsidian helper if possible.
♻️ Sketch
const valid = c.category === undefined || /^[a-z](-?[a-z0-9])*$/.test(c.category);
if (!valid)
console.warn(`invalid category: ${c.category}`);
const serialized = serialize({
...current,
id: next.id,
- category: valid ? next.category : c.category,
+ category: valid ? next.category : c.category,
body: next.body,
date: next.date,
author: next.author,
});🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@parser.ts` around lines 600 - 609, Update serialize() to validate c.category
with the existing accepted-category validator before constructing the annoteca
marker. When validation fails, return the invalid category value unchanged so
the comment remains visible while preventing generation of a non-parsable
marker; reuse the validator from categories.ts or an appropriate non-Obsidian
helper.
Six fixed, three declined with reasons. Two Codex rounds on the fixes; the second came back clean. **A second writer's revision was being overwritten.** applyAddressed set `addressed` unconditionally on the live marker, the only lifecycle transition that did not inspect `current` first. If an assistant, another pane, or a sync addressed the same comment after the caller's snapshot, that write replaced the author, date, note AND the annoteca-original fence, and the fence is the only revert source rejectAddressed has, so the earlier prose was gone for good. It declines now and says the comment is already awaiting review. **A duplicated marker id wrote to whichever twin came first.** Ids live in file text, so copy-pasting a marker inside a note produces two carrying one id, and freshComment's `find` returned the first whether or not it was the marker the card pointed at. The id-less branch was already strict; the id branch matches it now. Codex caught the follow-on: returning `undefined` routed the duplicate through noticeVanished, which says the comment "moved or been deleted" and to reopen the note. That is false, reopening cannot fix it, and it leaves every action dead with no way to understand why. The lookup returns a discriminated result and the duplicate gets its own message naming the id. The first test written for this asserted only that SOME notice fired, which is exactly the assertion that would have let the wrong wording through; it now pins both messages and that a genuinely missing marker still reports as missing. **A restored backup bypassed the type check on data.json.** loadSettings normalizes renderMarkdownBodies because a stored string "false" is truthy and every read of that setting is a truthiness test; restoreSettings spread parsed JSON straight in, so a backup could reintroduce the exact value the load path exists to reject. The merge moved to a pure mergeRestoredSettings() in settings.ts for a reason found by mutation, not by preference: with it inline in the plugin method, DELETING the normalizing entirely left the suite green, because nothing in this repo reaches main.ts at runtime. A normalizer no test can reach is one that can quietly stop running. The normalizer also takes its fallback as a parameter, because absent and wrong-type are different questions: a backup that does not mention a setting must leave the current value alone, the way every other key in that spread does, rather than resetting it to the shipped default. **Long unbroken text painted outside the popover.** `.annoteca-md a` and `.annoteca-md code` already broke anywhere, but a bare token in a paragraph, heading, or quote is neither, and #19 is what put rendered markdown on that surface. The `pre code` override still keeps fenced code scrolling. **A dismissed reply composer still talked.** The write is awaited and the composer can be torn down across it (Escape, Cancel, tooltip teardown), after which release() wrote to a detached Send button and textarea and the catch branch raised a Notice about a composer the user had already closed. Guarded on textarea.isConnected, which catches every teardown path rather than only the ones running through that closure. **Prose drift.** copilot-instructions.md documented the `-->` escape but not escapeInline's newline collapsing, which this branch introduced, and not the fence-attribution rule. Both are added, the second phrased as "adjacency must not be reintroduced", since reintroducing it is what caused the regression e248c3d fixed. **__mocks__/obsidian.ts gains a noticeLog.** The reason recorded for not having one did not hold: it is a module-level export reached through a relative import, so it types against the mock file rather than obsidian.d.ts, and the mock stays a subset of the real API. Without it the abort BEHAVIOUR was pinned while the user-facing message, which is the entire point of several of these paths, had no coverage at all. Nine mutations, one per decision, each caught by the test written for it. **Declined, with reasons, all reported on the PR:** - serialize() category validation. Pre-existing, untouched by #19 and by e248c3d, and the suggested fix is dangerous: serialize()'s return value is written into the document, so returning the bare category string on an invalid value replaces the whole marker with that string. The real fix is validating at the settings boundary, which is the same class as the data.json finding above and belongs with it. - check-settings-parity.mjs matching any quoted key. Correct, pre-existing dev tooling, and structural parsing is its own change. - manifest minAppVersion 1.8.7 vs README "requires 1.13.0". A real inconsistency that Obsidian acts on when deciding who gets the plugin, but which one is wrong is a product decision about the supported range. Known gap, stated rather than papered over: the one-line call site in restoreSettings is still uncovered, because no test in this repo imports main.ts at runtime. The merge it calls is fully covered.
|
Pushed Fixed
Two follow-ons from Codex, on top of the above:
Declined
Known gapThe one-line call site in |
Promotes [Unreleased] to [1.14.0] and bumps the version. MINOR, not PATCH, because the section carries three new user-facing capabilities (markdown rendering in comment bodies, "Clear orphaned stars", the automatic broken-marker notice); not MAJOR, because nothing removes a user-facing surface. Requiring Obsidian 1.13 is a supported baseline rather than a break, decided 2026-08-07. version-bump.mjs writes versions.json from the manifest's CURRENT minAppVersion, so 1.14.0 -> 1.13.0 lands without a hand edit, and the existing "1.13.0": "1.8.7" line stays as correct history: the 1.13.0 tag genuinely shipped 1.8.7, and #25 raised it afterwards. Promoting the heading is not cosmetic. release.yml extracts the release body with awk on ^## \[<tag>\] and silently falls back to a generated commit list when that finds nothing. Replayed the workflow's exact awk against the file: 0 bytes before this change, 26890 after. Two factual errors in the notes, which ship into the release body verbatim, are fixed: - The notes told users to run "Check for problems", which does not exist. grep over the sources finds no such string; the command is "Validate marker format" (main.ts:820). - #31's known cost was shipped and undocumented. parser.ts:610-624 states it and __tests__/parser.test.ts:2142 pins it: a marker written before the <!-- escape whose body quotes an opener now comes back under the QUOTED category, body truncated, carrying the outer id. Nothing is deleted, and it is reported on read, so it is a Changed entry rather than a Fixed one. The entry also says the repair is to escape the inner opener by hand, because the report classifies this as an unclosed opener and so advises adding a --> that is not the fix. Four accuracy fixes in the same pass: "Import all" was a code comment, not a UI label (the label is "Convert every comment to the canonical format", main.ts:909); the Hub redraw shipped in #19 was undocumented; three bullets each repeated the re-export instruction for one schema bump, now one; and two near-duplicate "quotes the comment format" bullets are merged. Subsections reordered to Keep a Changelog's Added, Changed, Fixed. No logic surface in this diff, so the Codex pre-commit pass is skipped deliberately: CHANGELOG prose plus version metadata only.
Renders comment bodies, replies, and notes as markdown in the marker popover and the Hub panel (#6), and fixes three separate ways the plugin could lose or corrupt user text.
Fixes #6
Fixes #12
Scope note. This is deliberately three stories in one diff. I raised the concern that bundling data-loss fixes with a feature makes a muddy CHANGELOG and couples a revert of the feature to a revert of the fixes; Charles decided to fold them together, including #12. Recording it here so the CHANGELOG's shape is a decision on the record rather than drift.
The feature
types.tshas described the body as "freeform inline markdown" since the format was written, and AI assistants emit markdown by default, so the flagship workflow reliably produced comments displayed as raw source: literal asterisks, backticks, and-bullets.markdown-render.ts, so no surface can drift from another.annoteca-originaleverywhere, which is the verbatim prose Reject restores and so must be shown as what would be written back, not as what it renders to.Two implementation problems the plan called out, and how they went:
create()returns, so the popover was sized around an empty box. Solved with CodeMirror's ownrepositionTooltips(view), called from the host'sonRenderedhook once the render settles and only while the element is still connected.MarkdownLifetimeper popover, unloaded in the tooltip'sdestroy; the Hub cycles one per render pass and disposes it on tab switch and on close. A hover creates and destroys a tooltip on every dwell, so leaking one per hover would have been the fastest leak in the plugin.Three ways of losing text
The first two were on the checklist as precautions. Both were already happening in 1.13.0, confirmed by running the parser before changing anything.
Trailing bracket-leading lines were deleted from bodies. The forward-compat rule matched any
[...]-leading last line, so a body ending in[label](url),[ref]: url,[^1]: note, or[[Wikilink]]silently lost it.data-format.mdhad always specified a narrower rule ("a recognized keyword"), so the implementation was out of conformance with its own contract. Narrowed to the two shapes the format actually defines. The governing principle is now written down: when a trailing line is ambiguous, keep it in the body, because deleted prose is unrecoverable and an unparsed structured line is merely visible.-->in a body corrupted the document.serialize()wrote it raw, so<!-- annoteca/note: arrow --> here -->re-parsed as the bodyarrowand lefthere -->behind as visible text. Now escaped as--\>and restored on read, with the escape marker itself escaped so the mapping is reversible at every depth. Imports go throughserialize()too, since a%%...%%comment can legally contain-->, and the exported AI skill documents the escape (SKILL_SCHEMA_VERSION4, so existing exports are flagged stale).Known limitation, accepted deliberately and documented in
data-format.md: a marker written before this encoding whose text legitimately contained--\>cannot be told apart from an encoded terminator, and reads back one backslash shorter. Encoding and decoding are inverses, so parse + serialize is a fixed point: opening a vault never rewrites an affected file and repeated edits do not walk the text further. Pinned by tests. The alternative is a format version sentinel, which is a breaking change requiring migration machinery, and that is a poor trade against a bug that loses whole lines today.#12, panel actions on a stale snapshot. Every action serialized the
Commentcaptured when the card was drawn, so a reply landing between render and button press was silently overwritten.replaceMarkernow takes a transition applied to the freshly re-read comment rather than a finishednext. That fixes all seven verbs at once instead of patching each, and costs no extra read because the content fetch was already there for the offsets. A marker that can no longer be identified now aborts rather than writing at stale offsets, sharing the identify-or-refuse predicaterejectAddressedworked out across four rounds in PR A. Because the write can now be refused,appendReplyreports whether it landed, and both composers keep the user's text and stay open when it did not.Also here, because rendering exposed them
max-widthsince PR A. CodeMirror putscm-tooltipon the element the tooltip source returns, not on a wrapper, so the frame-stripping rule and.annoteca-hover-previewland on the same node and the two-class selector wins. Invisible while bodies were plain text, which wraps at any width; a rendered table or fenced block has no such limit. Measured over CDP: 467px before, capped at 420px after, with the code fence scrolling inside its own box.refreshDecorationsEverywhere(); this is the panel half.scripts/check-settings-parity.mjsnow fails the build when a setting is missing from either settings render path. Both are live atminAppVersion1.8.7 and nothing enforced it, and the dev vault runs 1.13.x so testing by hand only ever exercised the declarative one. It lives inscripts/rather than as a Jest test because the check has to read source text, whichobsidianmd/no-nodejs-modulesrightly forbids in plugin code.Verification
316 tests, up from 285. The parser rules, the stale-snapshot fix, the vanished-marker aborts, and the render lifetimes were each mutation-checked: the guard was broken, the failure count recorded, and the guard restored.
Driven in Obsidian 1.13.4 over CDP. This is hand-verification, not regression coverage: rendering in both surfaces, a
[[wikilink]]resolving toa.internal-link, the popover capped at 420px with a code fence scrolling inside it, the setting toggling both ways with the panel open, a popover in a non-active split pane resolving links against its own file rather than the active one (the old code resolvedalpha/Target.mdwhere the new one resolvesbeta/Target.md), and the reply flow end to end.Review round 2 (after CodeRabbit's first pass)
All four of CodeRabbit's findings were legitimate and are fixed in
c70d49e:deleteOnResolvebypassed the fresh-state check every other lifecycle verb now performs.resolveCommentandacceptAddressedtested the caller's snapshot and delegated toresolveAndRemoveComment, which re-resolved the marker's OFFSETS but never re-checked the STATE. That is the destructive branch, so with the setting on, Accept deleted the marker, its body, and its whole thread even when another writer had already revised or rejected the pending edit. It now takes an optional freshness guard and declines; the explicit "Resolve and remove" action passes no guard and still acts on whatever is there, which is what its own confirmation is for. Mutation-checked.MarkdownRenderer.renderhad no rejection handler, so a throw inside another plugin's post-processor became an unhandled rejection and left an empty box where the comment was. It now falls back to the source text.word-break: break-wordis deprecated; replaced withoverflow-wrap.Two more found in the same area by the commit gate and Codex, fixed in the same commit: the Hub's reply button had neither the single-flight guard nor the rejection handler the popover composer got, and both composers cancelled the debounced draft save on submit, which fixed a resurrection bug but created a worse one where text typed inside the 300ms debounce was never stored at all. Both now flush the draft before submitting and clear it only on success.
On the review count
Codex ran eight rounds; seven found something real, including two P1s. The pattern worth keeping: rounds 3 and 4 were both "this rule holds where you applied it and not where you did not", and round 5 was the sharper version, that making a write refusable obliges you to walk every caller that assumed it could not fail. The commit gate then caught the same async-lifecycle gap in the Hub's reply button that I had already fixed in the popover.
That churn was avoidable and most of it was self-inflicted: rounds 5, 6, 7 all descend from round 3's change, because making a write refusable obliges you to walk every caller that assumed it could not fail, and I fixed them reactively one round at a time instead of sweeping once. Before this push I ran that sweep explicitly across every defect class from this PR (marker writers bypassing
serialize(), promise chains without acatch, settings read at render time, component lifetimes, callers assuming success) and it came back clean.Not done here
renderMarkdownBodiesis validated as a boolean on load, but the other ten booleans inDEFAULT_SETTINGSare still spread fromdata.jsonunchecked. Pre-existing, out of scope for this diff, reported rather than fixed.