Skip to content

Stop Save landing on the wrong comment and in the wrong note - #32

Merged
ckelsoe merged 1 commit into
mainfrom
fix/wrong-target-writes
Aug 7, 2026
Merged

ckelsoe merged 1 commit into
mainfrom
fix/wrong-target-writes

Conversation

@ckelsoe

@ckelsoe ckelsoe commented Aug 7, 2026

Copy link
Copy Markdown
Owner

Closes three defects from the 2026-08-05 ledger (M11, M7, M5). All three are a write that goes somewhere the user did not ask for. Every claim below was executed, not read off the code.

M11: Save wrote into whichever file the tab had moved on to

The composer writes through the Editor it captured when the form opened. Obsidian hands the same Editor object to whatever file a tab shows next, and the default composer is the side panel, whose whole point is that the editor stays usable behind the form. So a wikilink click, a file-explorer click, or "Make a copy" while the form was open sent Save into the new note, with no notice, while onSubmitted reindexed the note that was never touched.

The premise was verified live on Obsidian 1.13.4 during the audit: same Editor object across a same-leaf file switch, and the stale reference's getValue() returns the new buffer.

  • submit now compares view.file?.path to the captured path immediately before writing, and refuses rather than redirecting. Redirecting would write into a document the user cannot see; refusing keeps the form open with the text they typed, which is what every other refusal here already does.
  • ComposerRequest carries the view, and the field is required rather than optional, so a call site cannot forget it. That is not theoretical: making it required is what surfaced all seven construction sites.
  • The openers take the path from that view instead of getActiveFile(). It is the only path a write-time check can ever agree with.

The CREATE branch had no file guard at all and lands in the same wrong document through the same replaceRange. Only the edit path had any check, and that one ran when the form opened. Both are covered now.

M7: editing an id-less comment landed on a different comment

convert comments emits markers with no id, no date and no author, so a run of them differs only in body, and two of equal body length have equal extent. Offset + category + extent is therefore not an identity.

Reproduced against the shipped importer's output rather than a hand-built string: three converted comments, delete one line above while the form is open, and Save destroyed cut this aside. while the edit never reached the comment it was meant for. No notice, form closed as though it had worked.

Identity is now the marker's exact source text as captured when the form opened, plus the category and body of the snapshot that was clicked. Both are needed, and this is the subtle part: the fingerprint is read out of the document using the snapshot's offsets, so on its own it agrees with itself whenever the snapshot was already stale (a Hub card drawn before an edit and clicked after it, index refresh still in flight).

Residue, stated rather than hidden: two byte-identical markers stay indistinguishable. That costs the edit's placement between two markers that are the same character for character, and never any content, because every field the rewrite carries forward is identical.

M5: a collaborator colour set for a name with a space never applied

authorStyles[].tag was stored exactly as found, while every marker write sanitizes at serialize(). So a colour configured for Bob Smith was filed under a name no note ever contained, the picker offered both spellings, and the colour silently never appeared. Markers stayed valid; this is UI-level, not data loss.

  • The tag goes through the same repair as authorTag, one entry below it in the same validator table.
  • The repair is split (authorTokenOrEmpty / sanitizeAuthorToken) so the settings ingress can decline a row with nothing usable in it instead of inventing a user collaborator that could then displace a real one. The write funnel still must produce some token, so it keeps the fallback. One implementation of the grammar, two answers to "what if nothing is left".
  • Repaired collisions collapse, keeping a colour a later row offers rather than dropping a setting the user chose.
  • A restored list that arrives non-empty and loses every row falls back to the live styles instead of wiping them. Only visible on the restore path, where an accepted value replaces the live one.
  • setControlValue gets the same repair. It is a second, per-session ingress that bypasses normalizeSettings entirely and depended on Obsidian honouring the control's validate callback.

Verification

  • 730 tests green (up from 721), plus lint, prettier, submission check, tsc and build.
  • Every new test mutation-checked, and each mutation confirmed to apply. Each one kills only its own test; the M11 set has a control that stays green, so the refusals are not just a composer that refuses everything.
  • Codex review over the working diff, twice. Four findings, all real, all fixed, each pinned by a test that fails without the fix. Two of them were regressions introduced by the first round of fixing, which is why the second pass was worth running.
  • Sibling hunt: parseAt has exactly one production caller (the one fixed here). The two other direct editor writes, both in comment-service.ts, resolve the view by path at write time via getOpenMarkdownView(path), so they are not exposed to M11.

Not verified live. Obsidian was not running on the CDP port during this session, so none of this has been exercised in the app against this build. The M11 premise it rests on was verified live in the audit; the fix itself has regression coverage only.

Three confirmed defects from the 2026-08-05 ledger, all of them a write
that goes somewhere the user did not ask for.

M11: the composer wrote through the Editor it captured when the form
opened, and Obsidian hands the same Editor to whatever file a tab shows
next. The panel composer exists so the editor stays usable behind the
form, so a wikilink click, a file-explorer click or Make a copy sent Save
into the new note, silently, while onSubmitted reindexed the untouched
one. Verified live on 1.13.4 during the audit: same Editor object, and
its getValue() returns the new buffer. Submit now asks the view which
file it is showing and refuses otherwise. ComposerRequest carries the
view and the field is required, so a call site cannot forget it; the
openers take the path from that view rather than from getActiveFile(),
which is the only path the check can agree with. The CREATE branch is
covered too: it was never guarded at all, and lands in the same wrong
document through the same replaceRange.

M7: an id-less marker was identified by offset, category and extent.
convert comments emits markers with no id, no date and no author, so a
run of them differs only in body and two of equal body length have equal
extent. Deleting one line above slid the next marker onto the remembered
offset and Save destroyed a comment the user never opened, with no
notice. Identity is now the marker's exact source text as it stood when
the form opened, which no field list can drift out of step with, plus the
category and body of the card that was clicked. Both are needed: the
fingerprint is read using the snapshot's offsets, so on its own it agrees
with itself when the snapshot was already stale. Byte-identical markers
remain indistinguishable, which costs the edit's placement and no
content.

M5: authorStyles[].tag was stored exactly as found while every marker
write sanitizes at serialize(), so a colour configured for 'Bob Smith'
never matched the 'Bob-Smith' in the file and the picker offered both.
The tag now goes through the same repair as authorTag, split so a row
with nothing usable left is declined rather than becoming an invented
'user' collaborator that could displace a real one. Repaired collisions
collapse, keeping a colour a later row offers. A restored list that
arrives non-empty and loses every row falls back to the live styles
instead of wiping them. setControlValue gets the same repair: it is a
second, per-session ingress that bypasses normalizeSettings entirely.

Every new test mutation-checked. Codex review over the working diff,
twice; four findings, all fixed and each pinned by a test that fails
without the fix.

Not verified live: Obsidian was not running on the CDP port this
session, so none of this has been exercised in the app against this
build. The M11 premise it rests on was verified live in the audit.
Copilot AI lite review requested due to automatic review settings August 7, 2026 03:44
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Prevented comments from being saved to the wrong note when switching tabs or views.
    • Improved identification of comments without IDs, including protection against stale or ambiguous matches.
    • Preserved the correct document context when creating or editing comments from split panes and panels.
    • Normalized collaborator names consistently so configured colors apply correctly.
  • Settings

    • Improved author-tag validation, cleanup, collision handling, and fallback behavior.
    • Preserved valid colors when author tags are repaired or deduplicated.
  • Documentation

    • Added changelog entries describing these fixes.

Walkthrough

The composer now carries its originating Markdown view, validates the displayed file before writing, and matches id-less markers using captured source text and metadata. Author-style settings now normalize, repair, deduplicate, and validate author tags consistently.

Changes

Composer write safety

Layer / File(s) Summary
View-aware composer targeting
composer.ts, main.ts, .github/copilot-instructions.md, CHANGELOG.md
Composer actions retain the originating view. Writes stop when the view displays another file or no file. Id-less markers require matching source text, category, body, and extent.
Composer regression coverage
__tests__/composer.test.ts
Tests cover stale marker snapshots, ambiguous markers, imported markers, switched tabs, missing files, and valid saves.

Author-style normalization

Layer / File(s) Summary
Author token and style validation
parser.ts, settings.ts
Author tokens are normalized through shared repair logic. Invalid rows are removed, collisions are merged, and colors are preserved according to validation rules.
Author settings regression coverage
__tests__/settings-normalize.test.ts
Tests cover token repair, invalid tags, collision handling, restore fallback, empty lists, and direct authorTag updates.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MarkdownView
  participant Composer
  participant MarkdownFile
  MarkdownView->>Composer: provide originating file and marker snapshot
  Composer->>MarkdownView: validate current displayed file
  Composer->>MarkdownFile: resolve marker and write comment
Loading

Possibly related PRs

Suggested reviewers: copilot, copilot-pull-request-reviewer

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the two main write-target defects addressed by the pull request.
Description check ✅ Passed The description directly explains all three fixes, their rationale, testing, and verification limits.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
main.ts (1)

1019-1033: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider deriving the edit path from the view, as the other three openers do.

openModalAtCursor, openModalForSelection, and openScratchpadModal all read path from view.file?.path. openEditModal takes path from the caller instead. All three current callers pass a path equal to view.file?.path, so there is no defect today. A future caller that passes a different path would open the form and then refuse at Save with wrongFileMessage, which reads as a broken form rather than a guarded one.

Deriving the path inside openEditModal removes that class and matches the rule in .github/copilot-instructions.md line 235 that the path must come from the view.

♻️ Proposed refactor
 	private openEditModal(
 		editor: Editor,
 		view: MarkdownFileInfo,
-		path: string,
 		comment: Comment,
 	): void {
+		const path = view.file?.path;
+		if (!path) return;
 		const from = editor.offsetToPos(comment.marker.start);
 		const to = editor.offsetToPos(comment.marker.end);
 		this.openComposer({
 			editor,
 			view,
 			filePath: path,
 			editing: { comment, from, to },
 		});
 	}

Callers at lines 486-491, 570-571, and 1469 drop their path argument.

🤖 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 `@main.ts` around lines 1019 - 1033, Update openEditModal to derive the file
path from view.file?.path instead of accepting a caller-supplied path, matching
the other modal openers and preserving the view-derived path contract. Remove
the now-unused path argument from all openEditModal callers.
🤖 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.

Nitpick comments:
In `@main.ts`:
- Around line 1019-1033: Update openEditModal to derive the file path from
view.file?.path instead of accepting a caller-supplied path, matching the other
modal openers and preserving the view-derived path contract. Remove the
now-unused path argument from all openEditModal callers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f77da78a-ba2e-49d5-b920-deece6a321ee

📥 Commits

Reviewing files that changed from the base of the PR and between 462e5dd and 6019fc5.

📒 Files selected for processing (8)
  • .github/copilot-instructions.md
  • CHANGELOG.md
  • __tests__/composer.test.ts
  • __tests__/settings-normalize.test.ts
  • composer.ts
  • main.ts
  • parser.ts
  • settings.ts

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses three “write goes somewhere else” defects by (1) preventing saves from writing into a different note when the originating editor tab switches files, (2) tightening identity checks for id-less markers so edits can’t land on a different comment after drift, and (3) normalizing collaborator author-style tags using the same tokenization rules as marker writes so configured colors reliably apply.

Changes:

  • Require passing the originating MarkdownFileInfo view into the composer request and refuse Save if that view no longer points at the original file path.
  • For id-less markers, capture the exact marker source text at form open and require it (plus snapshot category/body) to match on Save before applying edits.
  • Normalize authorStyles[].tag via authorTokenOrEmpty, dedupe collided repairs deterministically, and align setControlValue('authorTag', ...) with the same repair path; add regression tests.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated no comments.

Show a summary per file
File Description
settings.ts Normalizes and dedupes authorStyles, exports repairAuthorTag, and routes authorTag control updates through the same repair logic.
parser.ts Splits author token repair into authorTokenOrEmpty (no fallback) and sanitizeAuthorToken (with fallback) for reuse by settings and serialization.
main.ts Threads the originating view into composer openers so Save can validate “same tab/same file” at write time.
composer.ts Adds write-time “wrong file” refusal, captures marker source text for id-less edit safety, and strengthens id-less target resolution checks.
CHANGELOG.md Documents the three fixes and their user-visible behavior changes.
.github/copilot-instructions.md Codifies the new “re-check file at write time” and id-less marker identity rules for future contributors/assistants.
tests/settings-normalize.test.ts Adds coverage for author-style tag repair/deduping and setControlValue as an additional settings ingress.
tests/composer.test.ts Adds regression tests for id-less marker drift cases and for refusing writes after the tab switches files.
Suppressed comments (1)

settings.ts:364

  • repairAuthorTag currently treats whitespace-only input as a non-empty string and runs it through sanitizeAuthorToken, which turns it into the fallback token "user" (via sanitizeAuthorToken’s empty-result fallback). Since normalizeSettings uses this path, a hand-edited or synced data.json value like " " would incorrectly set authorTag to "user" instead of the intended empty-tag state ("no tag set").
export function repairAuthorTag(raw: string): string {
	// Empty is a legitimate stored value: it is what "no tag set" looks like,
	// and sanitizing it would invent the token "user" for someone who never
	// asked for one. isAuthorToken deliberately answers only the grammar
	// question, so the "no tag set" case is spelled out here.

@ckelsoe
ckelsoe merged commit b9a503d into main Aug 7, 2026
5 checks passed
@ckelsoe
ckelsoe deleted the fix/wrong-target-writes branch August 7, 2026 03:49
ckelsoe added a commit that referenced this pull request Aug 7, 2026
…8) (#34)

The last seven defects from the 2026-08-05 ledger, plus the openEditModal
path derivation that #32 deferred. 766 tests, 36 new.

M12b is the one the mocks could not settle, so it was driven over CDP
against a leaf restored deferred. loadIfDeferred resolves with view.file
STILL NULL and a zero-length document, and coordsAtPos then threw
"Invalid position 6413 in document of length 0". It is evaluated eagerly
as an argument to decideScrollAction and every caller uses `void`, so it
surfaced as an unhandled rejection and the first hub click did nothing.

openFile finishes the load, but its resolving is not the signal either:
measured live, the buffer is still empty through a microtask, an
animation frame and a 0 ms timeout, filling three frames later, so the
cursor still landed at 0. waitForEditorContent waits on the editor
rather than on a delay, short-circuits on stat.size for a genuinely
empty note, and uses setTimeout rather than requestAnimationFrame
because rAF does not fire in a hidden window and that await would hang
instead of degrading. Re-verified on the FINAL build: cursor lands on
the marker on the first click, no duplicate tab, no rejection.

The old harness for this asserted the bug away by having loadIfDeferred
hand back a ready editor. The new one models what was measured.

M12a is NOT fixed, and the entry says so rather than claiming it. A
deferred leaf's view is not `instanceof MarkdownView` and has no editor,
checked live, so the outline tab still cannot mark the cursor's heading.
That change only removes a duplicated predicate. Fixing it needs an
async load plus a re-render inside a synchronous renderer.

M8: the outside-click listener re-binds when the view's document
changes, mirroring perWindowTooltipHost. It inherits that pattern's
dependency on an update() following the move, and the test says so
rather than hiding it.

M9: remapPinnedTooltip falls back when the exact-offset find misses, by
id where there is one and by containment plus a category/body tie where
there is not. A straddle across the marker start leaves the document
byte-identical while moving mapPos by one, which used to tear the
composer down with unsent text in it. Id-less comments now get a draft,
keyed by their own text rather than an offset, so it survives the note
moving and cannot be picked up by a different comment.

M10: the hub follows the comment, not the offset. Selection and card
expansion are keyed by identity, the parent moves the selection through
setActiveComment so a stale id cannot snap the panel backwards, and
recovery prefers the selected file so a copied id cannot jump files.

m2: notifyComposerSubmitted asks currentContentFor rather than the
ACTIVE view, which in panel mode was never this note, so the index was
built from pre-Send disk bytes.

m3: a file scope carries its anchorPath, so a pinned scope stops reading
"This file" while listing another file's comments.

m8: a comment keeps a category the settings no longer offer. The
grandfather clause applies to an EDIT only, never to a create form's
default.

Codex ran twice, because the second pass reviews the first pass's fixes.
It caught four regressions introduced by those fixes.

The commit gate's async-lifecycle class caught one more in this change's
own fix: waitForEditorContent read view.editor after an await without
re-validating, so closing the tab mid-wait threw in a void-called path,
which is the exact class this change exists to end.

Every fix is mutation-checked: 19 mutants, all killed. Three survivors
along the way each exposed a genuinely untested distinction and got a
test rather than a shrug.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants