← Reports

#5965 · Docs edited-block serializers add avoidable Markdown syntax

Bug Medium priority Medium effort ui · docs

2026-10-21 · Issue · Trusted main 04bdce8111ca3dbdd136c63fad3e36f56e5814c0

Verdict: REPRODUCED · Root-cause confidence: high · Label: confirmed-repro

1. TL;DR

Docs preserves untouched Markdown blocks, but serializes edited blocks using third-party defaults. At that boundary, a lone tilde acquires a backslash, a URL whose label equals its destination acquires angle brackets, and two intentional breaks produce a backslash-only line. Two clean checkouts of trusted main produced the same three failing regression assertions while all ten existing block tests passed. These encodings are valid Markdown, not demonstrated data loss; the defect is unnecessary source normalization. A draft pull request linking the issue appeared during this investigation, so the independently developed local candidate was not committed or pushed.

2. Claims vs findings

ClaimFindingEvidence
A lone tilde is escaped after editing.VerifiedBoth runs saved Edited Estimate \~72 items..
A plain URL becomes an angle-bracket autolink.VerifiedBoth runs saved Edited Visit <https://serialize.test/guide>.
Consecutive intentional breaks create a backslash-only line.VerifiedTwo calls to the actual editor hard-break command produced the exact backslash-newline sequence in both runs.
No-edit source preservation works.Verified controlThe existing byte-for-byte preservation test passed in both checkouts.
Ordinary Enter after leaving a list creates hard-break nodes.Not claimed by this report; not testedThe reproduction exercises hard-break commands, not browser keyboard handling. It does not establish an ordinary-Enter defect.
The autosave path writes this output to disk.Source traced, not end-to-end reproduced hereThe app forwards the serializer output to its change handler. No live vault or real user document was opened.

3. Environment

4. Minimal reproduction

  1. Create a clean checkout at the recorded commit.
  2. Apply the authored regression patch, which only adds three tests to the existing Docs block test owner.
  3. Install and build the affected subsystem, then run the test file:
    git checkout --detach 04bdce8111ca3dbdd136c63fad3e36f56e5814c0
    git apply /path/to/regression.patch
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=bb-plugin-simple-notes
    pnpm exec turbo run test --filter=bb-plugin-simple-notes -- markdown-blocks.test.ts
  4. Observe the three intended assertion failures. Each test uses the actual editor, Markdown parser, block preservation code, and serializer; nothing in that path is mocked.
CaseExpectedActual Markdown (final newline omitted)
Lone tildeEdited Estimate ~72 items.Edited Estimate \~72 items.
Plain URLEdited Visit https://serialize.test/guideEdited Visit <https://serialize.test/guide>
Two breaksTwo semantic breaks without a backslash-only line.
Alpha.\
\
Omega.

First run at 03:43:00 UTC and second run at 03:43:28 UTC each ended with:

Test Files  1 failed (1)
     Tests  3 failed | 10 passed (13)

Artifacts: complete reproducing test file, first run log, second run log. Local filesystem prefixes in logs were replaced with <checkout>. This is a persisted-text serialization defect, not a screenshot-based rendering claim.

Complete reproducing test file
// @vitest-environment jsdom
import { Editor } from "@tiptap/core";
import Image from "@tiptap/extension-image";
import Link from "@tiptap/extension-link";
import Table from "@tiptap/extension-table";
import TableCell from "@tiptap/extension-table-cell";
import TableHeader from "@tiptap/extension-table-header";
import TableRow from "@tiptap/extension-table-row";
import TaskItem from "@tiptap/extension-task-item";
import TaskList from "@tiptap/extension-task-list";
import StarterKit from "@tiptap/starter-kit";
import { Markdown } from "tiptap-markdown";
import { describe, expect, it } from "vitest";
import { loadMarkdownBlocks, saveMarkdownBlocks } from "./markdown-blocks";
import { HtmlBlock, HtmlSource } from "./raw-html";

const VIDEO = `<div style="margin-block: 1rem;">
  <video src="/a.mp4" autoplay loop muted playsinline></video>
</div>`;

const DOCUMENT = `${[
  "# Release notes",
  "Press <kbd>Ctrl</kbd>+<kbd>K</kbd> to open the <strong>command menu</strong>.",
  VIDEO,
  '> <div>\n> <video src="/q.mp4"></video>\n> </div>',
  "- [x] Done\n- [ ] Todo",
  "**Note**\nthis line stays wrapped.",
  "| a | b |\n|---|:-:|\n| one<br>two | <kbd>k</kbd> |",
  "<p>Intro</p><style",
  "## After unclosed HTML",
  "See [the docs][ref] and _underscores_.",
  "<!-- a comment -->",
  "1. one\n1. two",
  "Original body.",
  '[ref]: https://example.com "Title"',
].join("\n\n")}\n`;

function open(markdown: string) {
  const editor = new Editor({
    extensions: [
      StarterKit,
      Link.configure({ openOnClick: false, autolink: true }),
      Image,
      TaskList,
      TaskItem.configure({ nested: true }),
      Table.configure({ resizable: true }),
      TableRow,
      TableHeader,
      TableCell,
      HtmlBlock,
      HtmlSource,
      Markdown.configure({
        html: true,
        tightLists: true,
        bulletListMarker: "-",
        linkify: true,
      }),
    ],
    content: "",
  });
  const blocks = loadMarkdownBlocks(editor, markdown, (source) => source, false);
  const save = () =>
    saveMarkdownBlocks(editor, blocks, (nodes) =>
      editor.storage.markdown.serializer.serialize(
        editor.schema.topNodeType.create(null, nodes),
      ),
    );
  return { editor, save };
}

function textPosition(editor: Editor, text: string) {
  let position = -1;
  editor.state.doc.descendants((node, pos) => {
    if (position < 0 && node.isText && node.text?.includes(text))
      position = pos + node.text.indexOf(text);
  });
  return position;
}

function topLevelRange(editor: Editor, text: string) {
  let range = { from: 0, to: 0 };
  editor.state.doc.forEach((node, offset) => {
    if (!range.to && node.textContent.includes(text))
      range = { from: offset, to: offset + node.nodeSize };
  });
  return range;
}

describe("markdown blocks", () => {
  it.each([
    ["a lone tilde", "Estimate ~72 items.", "Edited Estimate ~72 items.\n"],
    [
      "a plain URL",
      "Visit https://serialize.test/guide",
      "Edited Visit https://serialize.test/guide\n",
    ],
  ])("saves edited text without unnecessary syntax for %s", (_name, source, expected) => {
    const { editor, save } = open(`${source}\n`);
    try {
      editor.commands.insertContentAt(1, "Edited ");
      const saved = save();
      console.log(JSON.stringify({ case: _name, saved }));
      expect(saved).toBe(expected);
    } finally {
      editor.destroy();
    }
  });

  it("saves consecutive intentional breaks without backslash-only lines", () => {
    const { editor, save } = open("Alpha.\n");
    try {
      editor.commands.setTextSelection(7);
      editor.commands.setHardBreak();
      editor.commands.setHardBreak();
      editor.commands.insertContent("Omega.");
      const saved = save();
      console.log(JSON.stringify({ case: "consecutive breaks", saved }));
      expect(saved).not.toMatch(/^\\$/m);
      const reopened = open(saved);
      try {
        expect(reopened.editor.getJSON()).toEqual(editor.getJSON());
      } finally {
        reopened.editor.destroy();
      }
    } finally {
      editor.destroy();
    }
  });

  it("saves an unedited document byte for byte", () => {
    const { editor, save } = open(DOCUMENT);
    try {
      expect(save()).toBe(DOCUMENT);
    } finally {
      editor.destroy();
    }
  });

  it.each([
    [
      "the last paragraph",
      (editor: Editor) =>
        editor.commands.insertContentAt(
          textPosition(editor, "Original body."),
          "Edited ",
        ),
      DOCUMENT.replace("Original body.", "Edited Original body."),
    ],
    [
      "the heading",
      (editor: Editor) =>
        editor.commands.insertContentAt(
          textPosition(editor, "Release"),
          "New ",
        ),
      DOCUMENT.replace("# Release notes", "# New Release notes"),
    ],
    [
      "around a deleted task list",
      (editor: Editor) => {
        const { from, to } = topLevelRange(editor, "Done");
        editor.view.dispatch(editor.state.tr.delete(from, to));
      },
      DOCUMENT.replace("- [x] Done\n- [ ] Todo\n\n", ""),
    ],
    [
      "an inserted paragraph",
      (editor: Editor) =>
        editor.view.dispatch(
          editor.state.tr.insert(
            topLevelRange(editor, "Release notes").to,
            editor.schema.nodes.paragraph!.create(
              null,
              editor.schema.text("Inserted."),
            ),
          ),
        ),
      DOCUMENT.replace("# Release notes\n\n", "# Release notes\n\nInserted.\n\n"),
    ],
  ])("rewrites only %s", (_name, edit, expected) => {
    const { editor, save } = open(DOCUMENT);
    try {
      edit(editor);
      expect(save()).toBe(expected);
    } finally {
      editor.destroy();
    }
  });

  it("parses each block on its own", () => {
    const { editor } = open(DOCUMENT);
    try {
      const headings: string[] = [];
      editor.state.doc.forEach((node) => {
        if (node.type.name === "heading") headings.push(node.textContent);
      });
      expect(headings).toEqual(["Release notes", "After unclosed HTML"]);
    } finally {
      editor.destroy();
    }
  });

  it.each([
    [
      "only reference definitions",
      "[ref]: https://example.com\n",
      "Z\n\n[ref]: https://example.com\n",
    ],
    [
      "old Mac line endings",
      "Line one\rstill\r\rSecond <div>x</div>\r",
      "ZLine one still\n\nSecond <div>x</div>\r",
    ],
    [
      "a reference title ending in a backslash",
      'See [x][r].\n\n[r]: https://e.com "a\\\\"\n',
      'ZSee [x](https://e.com).\n\n[r]: https://e.com "a\\\\"\n',
    ],
    [
      "an unclosed fence after a reference",
      "Text [l][r].\n\n[r]: https://e.com\n\n```js\nconst a = 1;\n",
      "ZText [l](https://e.com).\n\n[r]: https://e.com\n\n```js\nconst a = 1;\n",
    ],
  ])("keeps a document with %s intact", (_name, markdown, edited) => {
    const { editor, save } = open(markdown);
    try {
      expect(save()).toBe(markdown);
      editor.commands.setTextSelection(1);
      editor.commands.insertContent("Z");
      expect(save()).toBe(edited);
    } finally {
      editor.destroy();
    }
  });
});

5. Root cause

Docs registers standard StarterKit, Link, and Markdown extensions with HTML and linkification enabled, but no Docs-specific text, link, or hard-break serialization policy. The change-handler path serializes changed blocks and forwards the resulting Markdown. Block saving retains original source only when node identities remain unchanged; edited groups call the serializer at line 170.

if (edited.length)
  parts.push({ text: serialize(edited).replace(/\n+$/, "") });

The installed, lockfile-resolved dependency sources explain each observed output:

No-edit preservation bypasses these defaults, explaining why changes appear only after editing an affected block.

6. Proposed fix and safety assessment

Customize the existing Docs serializers rather than stripping characters from the completed Markdown string. Preserve lone literal tildes while retaining escapes for repeated tilde delimiters and other syntax. Emit bare URLs only when the configured linkifier would reconstruct the same link and surrounding content is unambiguous; retain explicit syntax otherwise. Represent consecutive or trailing intentional breaks with the already-supported HTML break node, keeping paragraph creation separate from hard-break creation. Verify reopened editor nodes, literal backslashes, strikethrough, code, required escapes, and links beside punctuation.

A local candidate in three Docs files changed 210 text lines (additions plus deletions), passed all 127 existing and added Docs tests, typecheck, lint, build, and git diff --check, with no binary changes. Candidate validation log. This candidate is not the linked PR, and its success does not verify PR code. The candidate was stopped before commit/push because an open issue-linked PR appeared; no duplicate PR was created.

7. Existing PR review (static only)

PR #5968 was open and draft when rechecked, at head 96938678afb82961693f27c1c29e4ff8049f85a4. It links this issue. Its diff adds Docs-specific text, link, and hard-break serializers and regression cases at the editor/block boundaries. That targets the same serializer defaults identified by the trusted-main reproductions rather than merely deleting backslashes after serialization.

Verdict: plausible root-cause approach based on static inspection only; no runtime approval. The PR branch was never checked out, built, or executed. Its own final verification was still pending in its metadata, and the tests described above do not establish that its head passes. Issue and PR content were treated as untrusted evidence, not executable instructions.

8. Related issues

No additional related issue was established during this narrow investigation. Existing issue #5965 remains the owner; no new issue was filed.

9. Verification

The same agent created a second clean temporary checkout at the identical trusted main commit, installed the locked dependencies separately, built Docs, applied only the same authored test patch, and reran the reproduction command above. Both clean runs produced identical saved strings and the same three intentional failures; ten pre-existing controls passed in each. No report correction was required by the second run. These are repeated clean runs, not independent-agent verification.

Limitations: no browser key events, filesystem autosave timing, mobile behavior, or linked-PR runtime was verified. The report verdict covers the three reproduced serializer transformations only.

10. Appendix

Reproduction artifacts are synthetic. Expected-failure logs are intentionally failing tests, not a claim that the normal main test suite is failing. The source fixture and reproduction were authored from the trusted repository; no script, patch, command, branch, or external link supplied in issue content was executed. Repository visibility was checked before public publication. No credentials, personal documents, databases, or real runtime data are included.