Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ Releases are triggered by pushing a version tag. The release workflow:
- **Category name rules are strict.** An invalid category name silently fails to match the parser regex and markers with that category will not be indexed.
- **`-->` is escaped by `serialize()`, not forbidden.** Every free-text field round-trips through `escapeTerminator` / `unescapeTerminator` in `parser.ts`. Do not add a caller-side check that rejects `-->`, and do not write a marker without going through `serialize()`.
- **Stale marker snapshots, not just stale positions.** A panel card holds the `Comment` captured when it was drawn. Re-resolving the marker's `id` for its OFFSETS is necessary but not sufficient: building the write from the cached object serializes its replies, author, timestamps, and addressed state as of render time, silently discarding anything that landed in between. `replaceMarker` in `comment-service.ts` therefore takes a TRANSITION (`current => next`) applied to the freshly re-read comment, and returns whether it wrote so the caller can pick the right Notice. Add new lifecycle verbs that way; do not reintroduce a `next`-shaped parameter.
- **An `Editor` does not belong to a file, so re-check the file at WRITE time.** Obsidian reuses the same `Editor` object when a markdown leaf switches file, and the stale reference then reads and writes the NEW file's buffer. 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 it is open is ordinary rather than exotic. Any surface holding an `Editor` across user interaction therefore carries the view it came from (`ComposerRequest.view`, a required field on purpose) and compares `view.file?.path` to the captured path immediately before writing, refusing rather than redirecting. Open-time checks do not count; the one this replaced ran when the form opened and Save still wrote into whatever the tab had moved on to. Take the path from that view too, never from `getActiveFile()`, or the check has nothing it can agree with.
- **An id-less marker is identified by its own text, plus the card that asked for it.** The format allows a marker with no `[id=...]`, and `convert comments` emits them 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 plus category plus extent is therefore not an identity: deleting a line above slides the next marker onto the remembered offset. Compare the marker's exact source text as captured when the form opened, AND the category and body of the snapshot that was clicked. Both, not either: the fingerprint is read using the snapshot's offsets, so on its own it agrees with itself whenever the snapshot was already stale. Two byte-identical markers stay indistinguishable, which is a placement cost and never a content one.
- **Comment text renders as markdown through one entry point.** `markdown-render.ts` owns it. Never call `MarkdownRenderer.render` directly from a surface. Two rules go with it: the inline body widget in `decorations.ts` stays plain `textContent` (rendered headings and lists repeated at every marker destroy the document's layout, which is the opposite of what that feature is for), and the `annoteca-original` text stays plain everywhere (it is the verbatim prose Reject would restore, so it must be shown as what would be written back, not as what it renders to).
- **Every ephemeral markdown surface needs a `Component` that is later unloaded.** `MarkdownRenderer.render` attaches child components for embeds and code-block processors. A CodeMirror tooltip gets one per instance, unloaded in its `destroy` hook; the Hub panel cycles one per render pass via `cycleLifetime`. Passing a long-lived component (the plugin, the view) leaks on every hover and every panel refresh.
- **Markdown renders asynchronously, and CodeMirror tooltips size themselves synchronously.** A popover built with `create()` is measured and positioned before an async render lands, so it ends up mis-sized and visibly misplaced above its anchor. Call `repositionTooltips(view)` once the render settles; that is what the host's `onRendered` hook is for.
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Comment bodies, replies, and notes render as Markdown in the marker popover and the Hub panel. The format has always described a comment body as Markdown, and AI assistants write Markdown by default, so the usual result was a comment full of visible asterisks, backticks, and `-` list markers. Links, emphasis, code, lists, quotes, and tables now render, and a `[[wikilink]]` in a comment resolves against the note the comment lives in. There is a "Render Markdown in comments" setting under Editor indicators to turn it off. The one-line body shown beside a marker in the editor stays plain text either way, so turning this on cannot reflow the document you are reading.

### Fixed
- Saving a comment no longer writes it into whichever note the tab has moved on to. The Add and Edit forms open beside the editor and leave it usable on purpose, and Obsidian hands a tab's editor over to whatever file that tab shows next, so clicking a link, clicking a note in the sidebar, or using "Make a copy" while the form was open sent Save into the new note. The comment landed in a note you were not commenting on, nothing said so, the note you meant to write to was left untouched, and the panel refreshed as though it had worked. Saving now checks that the tab is still showing the note the form was opened on, and says so and stays open rather than writing somewhere else. This covers writing a new comment as well as editing one; only editing had any check at all before, and it ran when the form opened rather than when you pressed Save.
- Editing a comment that has no identifier no longer lands on a different comment. Comments produced by "Convert comments" carry no identifier, so they are told apart by where they sit, which category they are, and how long they are. A run of them differs only in wording, and two of the same length matched on all three, so deleting a line above the one being edited while the form was open slid the next comment into its place: Save overwrote that one instead, destroying its text, the edit never reached the comment it was meant for, and no warning appeared. What the comment says is now part of what identifies it, which is what every other action already required. Two comments that are word-for-word identical still cannot be told apart, but nothing is lost in that case, because the two carry the same text either way.
- A collaborator colour set for a name with a space in it now applies. Names are folded into a form the comment format can hold, with spaces becoming hyphens, whenever they are written into a note, but a name stored in the settings file was kept exactly as found. The colour was filed under `Bob Smith` while every comment in the note said `Bob-Smith`, so the colour you chose silently never appeared and the reply box offered both spellings. Names are now folded the same way wherever they arrive, including from a settings file edited by hand or arriving over sync, and two spellings that fold to the same name collapse into one entry keeping the colour.
- A comment missing its closing `-->` no longer swallows the paragraph below it. The plugin paired that comment's opening with the NEXT comment's closing, so everything in between, your prose included, became one comment's contents: the paragraph vanished from reading view, the second comment vanished from the panel, and the merged result carried the second comment's identifier under the first one's category. Deleting it removed the paragraph from the note. A closing now belongs to the last comment opened before it, so the second comment reads normally and your prose stays outside both.
- Writing about the comment format inside a comment no longer changes the comment. Details are stored at the end of a comment, one per line, so a comment whose text ended in a line of that shape was read as carrying that detail, and the line was removed from what you wrote. A body ending in `[resolved bob 2026-01-01]: done` silently marked the comment resolved; `[author=someone]` silently changed who it was from; `[reply ...]` added a reply nobody wrote. Those lines are now stored so the plugin can tell them apart from the real thing, and they come back exactly as typed. Comments already damaged this way cannot be recovered by the fix; the line left the file when it was last written.
- A detail the plugin does not recognise inside a comment is no longer deleted. Comments written by a future version of Annoteca, or by hand, can carry fields this version has no name for, and the format has always promised those are ignored rather than rejected. They were being ignored and then dropped: the next time anything touched the comment, the line was gone. They are now kept exactly as written and put back.
Expand Down
234 changes: 232 additions & 2 deletions __tests__/composer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@
// and the defect is in the submit path, not the form.

import { noticeLog } from '../__mocks__/obsidian';
import type { Editor, EditorPosition } from 'obsidian';
import type { Editor, EditorPosition, MarkdownFileInfo } from 'obsidian';
import type AnnotecaPlugin from '../main';
import { ComposerForm, type ComposerRequest } from '../composer';
import { convertNativeComments } from '../imports';
import { parseAll, serialize } from '../parser';
import { DEFAULT_SETTINGS } from '../settings';
import type { Comment } from '../types';
Expand All @@ -28,8 +29,13 @@ beforeEach(() => {
// Positions are (line, ch); offsets are absolute. The stub implements the pair
// honestly, because the whole point of the range defect is that a line/column
// pair keeps pointing at the same LINE while the marker moves to another one.
function makeEditor(initial: string) {
// `showing` is the path the host's view reports, and it is settable because
// Obsidian hands the SAME Editor object back after a leaf switches file: the
// buffer changes under it and the view starts naming the other note. That pair
// of moves is the whole of the wrong-file defect.
function makeEditor(initial: string, path = 'note.md') {
let content = initial;
let showing: string | null = path;
const posToOffset = (pos: EditorPosition): number => {
const lines = content.split('\n');
let offset = 0;
Expand Down Expand Up @@ -58,14 +64,26 @@ function makeEditor(initial: string) {
content = content.slice(0, start) + insert + content.slice(end);
},
};
const view = {
get file() {
return showing === null ? null : { path: showing };
},
};
return {
editor: editor as unknown as Editor,
view: view as unknown as MarkdownFileInfo,
get content() {
return content;
},
set content(updated: string) {
content = updated;
},
// Model a tab switching to another note: the buffer swaps and the view
// names the new file, both under the Editor object the form is holding.
switchTo(otherPath: string | null, otherContent: string) {
showing = otherPath;
content = otherContent;
},
};
}

Expand All @@ -91,6 +109,7 @@ function openEditor(
let submittedAt = -1;
const request: ComposerRequest = {
editor: host.editor,
view: host.view,
filePath: 'note.md',
editing: { comment, from, to },
};
Expand All @@ -109,6 +128,26 @@ function openEditor(
};
}

// The create path, which shares `submit` with the edit path and therefore
// shares the editor that decides which document gets written.
function openCreate(host: ReturnType<typeof makeEditor>): {
form: ComposerInternals;
closed: () => boolean;
} {
let closed = false;
const request: ComposerRequest = {
editor: host.editor,
view: host.view,
filePath: 'note.md',
};
const form = new ComposerForm(makePlugin(), request, {
close: () => {
closed = true;
},
});
return { form: form as unknown as ComposerInternals, closed: () => closed };
}

function only(content: string): Comment {
const parsed = parseAll(content);
expect(parsed).toHaveLength(1);
Expand Down Expand Up @@ -274,6 +313,124 @@ describe('composer edit: markers with no id', () => {
expect(closed()).toBe(false);
});

// The document below is the SHIPPED importer's output rather than a
// hand-built string, because `convert comments` is where id-less markers
// come from in practice: it emits `serialize({ category, body })` with no id,
// no date and no author, so a run of them differs only in body. Two bodies of
// equal length then give two markers of equal extent, and category plus
// extent plus start offset stops being an identity.
it('refuses when a whole line is deleted above an imported run of markers', async () => {
const imported = convertNativeComments(
[
'%%fix the wording%%',
'%%cite the source%%',
'%%cut this aside.%%',
'Closing prose.',
].join('\n'),
'clarify',
);
const host = makeEditor(imported.updated);

const before = parseAll(host.content);
// The premise the defect rests on: the importer assigns no ids.
expect(before.map((c) => c.id)).toEqual([
undefined,
undefined,
undefined,
]);
const target = before[1];
if (!target) throw new Error('no second marker');
const { form, closed } = openEditor(host, target);

// A plain whole-line delete above, which is the ordinary thing to do
// while the panel composer is open. It slides marker #3 onto the offset
// marker #2 was opened at, where the old category and extent guards both
// passed and Save destroyed "cut this aside." with no notice at all.
host.content = host.content.slice(host.content.indexOf('\n') + 1);
const unchanged = host.content;

form.state.body = 'EDIT MEANT FOR cite the source';
await form.submit();

expect(host.content).toBe(unchanged);
expect(parseAll(host.content).map((c) => c.body)).toEqual([
'cite the source',
'cut this aside.',
]);
expect(noticeLog.join('\n')).toContain('moved or been deleted');
expect(closed()).toBe(false);
});

// Category, extent and body together are still not an identity. Two markers
// can agree on all three and differ in a field of the same length, and the
// rewrite carries the target's author, date and thread forward, so landing on
// the wrong one attaches the edit to somebody else's comment.
it('refuses when a marker differing only in equal-length metadata lands on the offset', async () => {
const twinA = serialize({
category: 'clarify',
body: 'note',
author: 'aa',
});
const twinB = serialize({
category: 'clarify',
body: 'note',
author: 'bb',
});
// The premise: identical but for two characters of author.
expect(twinB).toHaveLength(twinA.length);
expect(twinB).not.toBe(twinA);

const padding = `${'P'.repeat(twinA.length + 8)}\n`;
const host = makeEditor(`${padding}${twinA}\n${twinB}\ntail`);
const [first, second] = parseAll(host.content);
if (!first || !second) throw new Error('expected two markers');
const { form, closed } = openEditor(host, first);

// Delete exactly the distance between the two marker starts, from above
// both, so the SECOND marker comes to rest on the offset the form
// remembers.
const gap = second.marker.start - first.marker.start;
host.content = host.content.slice(gap);
expect(parseAll(host.content)[1]?.marker.start).toBe(
first.marker.start,
);
const unchanged = host.content;

form.state.body = 'EDIT MEANT FOR the first marker';
await form.submit();

expect(host.content).toBe(unchanged);
expect(noticeLog.join('\n')).toContain('moved or been deleted');
expect(closed()).toBe(false);
});

// The fingerprint is read out of the document using the snapshot's offsets,
// so on its own it can only ever agree with itself. If the snapshot was
// already stale when the form opened, that self-agreement would accept the
// marker sitting there instead of the comment the user clicked.
it('refuses when the snapshot was already stale before the form opened', async () => {
const wanted = serialize({ category: 'clarify', body: 'wanted' });
// Same total length, so the extent check cannot be what refuses and the
// tie back to the clicked card is what has to do the work.
const other = serialize({ category: 'tone', body: 'other!!!!' });
expect(other).toHaveLength(wanted.length);

// The document holds `other` where the Hub card still believes `wanted`
// is: an edit landed and the index refresh has not caught up.
const host = makeEditor(`Prose.\n${other}\ntail`);
const stale = parseAll(`Prose.\n${wanted}\ntail`)[0];
if (!stale) throw new Error('no snapshot parsed');
const { form, closed } = openEditor(host, stale);
const unchanged = host.content;

form.state.body = 'EDIT MEANT FOR wanted';
await form.submit();

expect(host.content).toBe(unchanged);
expect(noticeLog.join('\n')).toContain('moved or been deleted');
expect(closed()).toBe(false);
});

it('refuses when a different marker of the same category now starts there', async () => {
const host = makeEditor(IDLESS_NOTE);
const { form, closed } = openEditor(host, only(host.content));
Expand Down Expand Up @@ -344,3 +501,76 @@ describe('composer edit: a vanished marker refuses instead of writing', () => {
expect(closed()).toBe(false);
});
});

// The tab the composer was opened from can move on to another file while the
// form is open, and the panel composer is BUILT for the editor to stay usable
// behind it. Obsidian hands back the same Editor object across that switch
// (checked live on 1.13.4), so `editor.replaceRange` writes into whichever file
// the tab now shows unless something re-checks at Save time.
describe('composer: the write refuses when the tab moved to another file', () => {
const OTHER_NOTE = ['Chapter one.', '', 'Tail of the other note.'].join(
'\n',
);

it('refuses to EDIT into the file the tab switched to', async () => {
const host = makeEditor(ADDRESSED_NOTE);
const { form, closed, submitted } = openEditor(
host,
only(host.content),
);

// "Make a copy" is the nastiest shape: identical text, identical marker
// id, so resolving by id finds a perfectly good target in the wrong file.
host.switchTo('note copy.md', ADDRESSED_NOTE);

form.state.body = 'the edited body';
await form.submit();

expect(host.content).toBe(ADDRESSED_NOTE);
expect(noticeLog.join('\n')).toContain('no longer shows note.md');
expect(closed()).toBe(false);
expect(submitted()).toBe(-1);
});

it('refuses to CREATE into the file the tab switched to', async () => {
const host = makeEditor(ADDRESSED_NOTE);
const { form, closed } = openCreate(host);

host.switchTo('note copy.md', OTHER_NOTE);

form.state.selectedCategory = 'clarify';
form.state.body = 'a new comment meant for note.md';
await form.submit();

expect(host.content).toBe(OTHER_NOTE);
expect(noticeLog.join('\n')).toContain('no longer shows note.md');
expect(closed()).toBe(false);
});

it('refuses when the tab is showing no file at all', async () => {
const host = makeEditor(ADDRESSED_NOTE);
const { form } = openEditor(host, only(host.content));

host.switchTo(null, ADDRESSED_NOTE);

form.state.body = 'the edited body';
await form.submit();

expect(host.content).toBe(ADDRESSED_NOTE);
expect(noticeLog.join('\n')).toContain('no longer shows note.md');
});

// The control. Without it the three refusals above would also pass against a
// composer that refused everything.
it('still saves when the tab is showing the file it was opened on', async () => {
const host = makeEditor(ADDRESSED_NOTE);
const { form, closed } = openEditor(host, only(host.content));

form.state.body = 'the edited body';
await form.submit();

expect(host.content).toContain('the edited body');
expect(noticeLog).toEqual([]);
expect(closed()).toBe(true);
});
});
Loading
Loading