Skip to content

Settings file replace re-keys every heading, so the digest rewrites whole sections and heading chats lose their rooms #474

Open

Description

@HMarzban

Summary

Settings "Replace with a file" gives every heading a new toc-id, and every picture a new random keyId. Two things break.

  1. The change digest email rewrites whole sections. After the 2026-10-13 paste of docs/DEMO.md on /demo, the digest showed sections fully struck out in red, then fully re-added in green. "👋 Start here" did not change at all and still showed this way. Expected: an untouched section stays out of the mail, and an edited section shows as one edit.
  2. Every heading chat loses its room. A heading chat is keyed by (workspace_id, heading_id), and heading_id is the heading toc-id. A new toc-id opens a new, empty room. The old messages stay in the database, but no heading reaches them. Both production pastes of /demo (August and 2026-10-13) did this.

The top section ("✨ docs.plus demo") did change: commit f575ef3 added one link line to it. The digest should show that as a one-line edit, not as a delete and an add.

Root cause

Three agents traced the write path, the compare path and the render path on 2026-10-14. A pure-function reproduction confirmed the result (see Reproduce).

Cause 1: the replace gives every heading a new toc-id

  • Settings replace does not use PATCH /content. It posts the file to POST /api/documents/:documentId/import, then runs the result in the browser through applyImportedContent (called at ImportExportSection.tsx:171).
  • applyImportedContent calls editor.commands.setContent(sanitizeJsonContent(content)). The import JSON carries no toc-id, and nothing copies the old ids across.
  • The pad's UniqueID (TipTap.tsx:147-152) then stamps a random id on every heading. Its filterTransaction skips only remote transactions, so a local setContent is stamped. A probe measured 42 headings before the replace and 0 old ids kept after it.
  • The digest pairs Sections by toc-id first. Nothing pairs by id, so the leftovers go to the content-hash matcher.
  • zippable refuses to join two sections that both carry a toc-id. So every edited Section becomes removed plus added.
  • The Android share receiver calls the same function (receiveSharedFile.ts:147), so it re-keys headings the same way.

Cause 2: the replace gives every picture a new random keyId

  • After setContent, commitImportedImageSizes writes the natural size and keyId: crypto.randomUUID() on each unsized picture. It does this on every replace.
  • keyId is a DOM handle for the media gripper and toolbar (media-node-attrs.ts:7-13). It is not content.
  • The Section hash drops only toc-id: VOLATILE_BLOCK_ATTRS = new Set(['toc-id']) (document-versions/types.ts:201). So a section with a picture never matches its earlier copy.
  • "👋 Start here" holds /demo-assets/d1-idea.png. The keyId value is its only difference.

Why both causes are needed for the symptom

Run Result
Fresh ids only, same Markdown twice 42 of 42 unchanged. The content hash pairs them.
Fresh ids and random keyId, same Markdown twice 16 removed, 16 added. Exactly the 16 sections that hold a picture.
Fresh ids and random keyId, old to new (the real case) 28 removed, 40 added, 14 unchanged
Ids carried, random keyId left 28 modified. 8 of them are untouched picture sections.
Ids carried, keyId stable 20 modified, 22 unchanged, 12 added, 0 removed. Correct.

Fixing only one cause is not enough.

Why the rows came out in that order

Neither "✨ docs.plus demo" nor "👋 Start here" paired. Both sit before the first paired Section, so pairSections puts both in the "removed before the first pair" bucket (pairSections.ts:79-100). Both red rows print first, then both green rows. "💬 A chatroom on every heading" has no picture and no edit, so it pairs unchanged and stays out of the mail (digestContentChanges.ts:97-98).

Impact beyond the email

  • Heading chats. useHeadingChannel.ts:12-27 looks a room up by the new toc-id, finds none, and creates an empty one for a writer. The old room keeps its messages under the old heading_id (04-channels.sql:33).
  • TOC unread badges find a room by heading_id, so old unread counts lose their rows.
  • Deep links. ?id= resolves only by [data-toc-id], so an old shared link scrolls nowhere. Digest ?id= links in mail already sent go dead.
  • Digest chat placement. A heading chat moves under its heading by heading_id, so an old room shows as a leftover notice row.
  • Fold state is keyed by toc-id. Whether a fold survives was not checked.

Decisions

Each question lists the recommended answer first. The maintainer rulings are posted as a comment.

  1. Should a replace keep the old heading ids? Recommended: yes. In applyImportedContent, before setContent, give each imported heading the old toc-id of a heading with the same level and the same text. Use each old id once. A heading with no match gets a new id from UniqueID. This fixes the digest, the chats and the ?id= links in one place, and leaves zippable as it is.
  2. Should the server ignore keyId when it compares? Recommended: yes. Add keyId to VOLATILE_BLOCK_ATTRS. Stored rows already hold random UUIDs, so a fix only in the browser would still break the next mail. The same set feeds History canonicalization and blockAuthors.ts:35. A change to keyId alone then stops counting there too, which is the intended result. No server code reads keyId today.
  3. Should we reconnect the demo's orphaned chat rooms on production? Recommended: yes, with a dry-run first and a maintainer go-ahead before any write.
  4. What if an old room and the new room for one heading both hold messages? Ruled 2026-10-14: build no conflict branch. On /demo, the old room always takes the heading. See the ruling update comment.
  5. Should the repair run on other documents too? Ruled 2026-10-14: no. Repair only /demo in this issue.

Fix plan

Work on main. Read AGENTS.md, apps/webapp/CLAUDE.md, apps/webapp/src/components/TipTap/CLAUDE.md and apps/hocuspocus.server/CLAUDE.md first. Do the steps in this order.

Step 0. Close the open gap

The reproduction leaves 14 untouched sections with no picture out of the mail. The report says every section showed. The reproduction's baseline is a fresh paste of the old Markdown. The real baseline is whatever version row a reader's window starts on. It may be the August paste, from before #151 and #152, with other attributes.

  • Read the real compute for /demo across the 2026-10-13 paste. Resolve the documentId with GET /api/documents/demo. Then call GET /api/documents/:documentId/changes?since=<before the paste>&until=<after the paste>&scope=headings with the service-role key.
  • If a section with no picture and no edit shows as removed plus added, diff its canonical form between the two rows, the way the reproduction script does. Report the extra attribute. Then decide with the maintainer whether it also belongs in VOLATILE_BLOCK_ATTRS.
  • Production reads run in the main session, never in a subagent. Run only small count queries inside a production container. Decode snapshots on a local machine.

Step 1. Server: make keyId volatile

  • Add keyId to VOLATILE_BLOCK_ATTRS in apps/hocuspocus.server/src/modules/document-versions/types.ts.
  • Pin the regression with one unit test in apps/hocuspocus.server/src/modules/document-changes/__tests__/unit/: two Sections that differ only by an image keyId (and carry different toc-ids) pair as unchanged. Prove the test by sabotage: remove keyId from the set and watch it fail.

Step 2. Webapp: keep heading ids across a replace

  • Add a pure helper beside applyImportedContent.ts. It reads the live document's headings, builds a pool keyed by level plus heading text, and sets attrs['toc-id'] on each matching imported heading. Use each old id once, in document order. Leave a heading with no match without an id.
  • Call it in applyImportedContent after sanitizeJsonContent and before setContent. Both the Settings replace and the Android share receiver then keep their ids.
  • Do not change UniqueID, zippable, or the pairSections rule in apps/hocuspocus.server/CLAUDE.md (§HTTP Modules, the zippable bullet). That rule stops a far deletion and a far addition from reading as one edit, and this fix does not need to touch it.
  • Check that UniqueID keeps a supplied unique id on a local setContent. Measure it, do not assume it: run the old DEMO.md, then the new one, through a Y.Doc-backed editor with the pad's UniqueID config, and count the kept ids.
  • Pin the helper with a Jest unit test: a kept heading, a renamed heading (new id), a level change (new id), two headings with the same text, and a new heading. The helper has dense branching, so a unit test is allowed under AGENTS.md §Test Policy.

Step 3. Docs

  • Fix API.md:864. It says "No editor produces this, because the webapp keeps its ids". That was false for Settings replace. State that Settings replace now carries ids by level and text.
  • Note in API.md (document-changes) that keyId is ignored, like toc-id.
  • Add one line to apps/webapp/src/components/TipTap/CLAUDE.md: a whole-document replace keeps heading toc-ids by level and text, because chats, ?id= links and the digest depend on them.
  • API.md:981 still holds for REST callers of PATCH /content with import JSON. Leave it.

Step 4. Production repair of the /demo chat rooms

Run this only after Steps 1 and 2 are deployed. Otherwise the next paste orphans the rooms again.

  • Write apps/hocuspocus.server/scripts/repair-heading-chat-ids.ts, dry-run by default, with --apply to write. Follow scripts/backfill-strip-ghosts.ts for the dry-run shape.
  • Input: one documentId. Read its version rows and decode each one locally with readContent. Build a map from every historical heading toc-id to its level and text. Two pastes happened, so an old room may sit two generations back.
  • Read the head row and map level plus text to the current toc-id. Skip a text that appears more than once in the head, and report it.
  • Read the document's rooms from public.channels where workspace_id = documentId. Skip the document channel, whose heading_id equals the documentId. A room is orphaned when its heading_id is not in the head.
  • For each orphaned room that holds messages and maps to a current id: if no room exists for the current id, set heading_id to the current id. If a room already exists for the current id, the old room wins: remove the newer room, then repoint the old one (Decision 4). The dry-run table shows the newer room's message count, because removing it also removes those messages.
  • Before writing, check what references channels.id (members, messages, notifications, pins) and how a delete cascades. Check whether anything derives a room from channels.slug. The unique keys are (workspace_id, heading_id) and (workspace_id, slug).
  • Print one table per run: old heading_id, heading text, current toc-id, message count, planned action. The maintainer approves that table before --apply.
  • Prove it on the local stack first. Paste the old DEMO.md over the local demo, post a message in two heading chats, paste the new DEMO.md with the pre-fix code, then run the repair.

Reproduce

Pure functions only: no server, no database. Save old.md and new.md beside the script, then run it from apps/hocuspocus.server.

D=$(mktemp -d)
git show f575ef3cb^:docs/DEMO.md > "$D/old.md"
git show f575ef3cb:docs/DEMO.md > "$D/new.md"
# save the script below as "$D/repro.ts"
cd apps/hocuspocus.server && env -u DATABASE_URL -u REDIS_HOST -u REDIS_PORT bun "$D/repro.ts"

Output measured on 2026-10-14. encodeContent stands in for the browser's UniqueID stamp, and browserImageSizes copies commitImportedImageSizes.

MAIN old -> new, fresh ids                   {"removed":20,"added":32,"unchanged":22}
a: old -> old, fresh ids                     {"unchanged":42}
b: old -> new, ids carried                   {"modified":20,"unchanged":22,"added":12}
d1: old -> old, fresh ids + random keyId     {"removed":16,"added":16,"unchanged":26}
d2: old -> new, fresh ids + random keyId     {"removed":28,"added":40,"unchanged":14}
e: old -> new, ids carried + random keyId    {"modified":28,"unchanged":14,"added":12}

After Step 1, d1 must read {"unchanged":42} and e must match b.

repro.ts
// Run from apps/hocuspocus.server: env -u DATABASE_URL -u REDIS_HOST -u REDIS_PORT bun <dir>/repro.ts
// <dir> holds old.md and new.md (git show f575ef3cb^:docs/DEMO.md, git show f575ef3cb:docs/DEMO.md).
const Y = await import(Bun.resolveSync('yjs', `${process.cwd()}/src/lib`))
const SRC = `${process.cwd()}/src/modules`
const { importMarkdown } = await import(`${SRC}/document-conversion/domain/markdownImport.ts`)
const { encodeContent } = await import(`${SRC}/document-content/domain/encodeContent.ts`)
const { readContent } = await import(`${SRC}/document-content/domain/readContent.ts`)
const { segmentSections } = await import(`${SRC}/document-changes/domain/segmentSections.ts`)
const { pairSections, movedTocIds } = await import(`${SRC}/document-changes/domain/pairSections.ts`)
const { diffSections } = await import(`${SRC}/document-changes/domain/diffSections.ts`)

type Json = Record<string, any>
const oldMd = await Bun.file(`${import.meta.dir}/old.md`).text()
const newMd = await Bun.file(`${import.meta.dir}/new.md`).text()

// Copies commitImportedImageSizes: a random keyId and a size on each unsized picture.
const browserImageSizes = (doc: Json): Json => {
  const walk = (n: Json) => {
    if (n.type === 'image' && n.attrs?.width == null) {
      n.attrs = { ...n.attrs, keyId: crypto.randomUUID(), width: 1280, height: 720 }
    }
    n.content?.forEach(walk)
  }
  walk(doc)
  return doc
}

// Gives head headings the baseline toc-id with the same level and text, each id once.
const carryIds = (baseDoc: Json, headDoc: Json): Json => {
  const pool = new Map<string, string[]>()
  for (const s of segmentSections(baseDoc)) {
    if (!s.tocId) continue
    const key = `${s.level}|${s.headingText}`
    pool.set(key, [...(pool.get(key) ?? []), s.tocId])
  }
  for (const node of headDoc.content) {
    if (node.type !== 'heading') continue
    const s = segmentSections({ type: 'doc', content: [node] })[0]
    const id = pool.get(`${s.level}|${s.headingText}`)?.shift()
    if (id) node.attrs = { ...node.attrs, 'toc-id': id }
  }
  return headDoc
}

// Markdown -> import JSON -> optional tweak -> encodeContent (stamps missing toc-ids) -> stored bytes -> JSON.
const pipeline = (md: string, tweak?: (doc: Json) => Json): Json => {
  let doc = JSON.parse(JSON.stringify(importMarkdown(md, 'demo').content))
  if (tweak) doc = tweak(doc)
  const enc = encodeContent(doc, { requireTitleHeading: true })
  if (!enc.ok) throw new Error(`encode failed: ${enc.detail}`)
  const read = readContent(Y.encodeStateAsUpdate(enc.scratch), 'json')
  if (!read.ok) throw new Error('read failed')
  return read.content
}

const run = (label: string, baseDoc: Json, headDoc: Json) => {
  const base = segmentSections(baseDoc)
  const pairs = pairSections(base, segmentSections(headDoc))
  const counts: Record<string, number> = {}
  for (const c of diffSections(pairs, undefined, movedTocIds(base, pairs))) counts[c.status] = (counts[c.status] ?? 0) + 1
  console.log(label.padEnd(44), JSON.stringify(counts))
}

const oldDoc = pipeline(oldMd)
run('MAIN old -> new, fresh ids', oldDoc, pipeline(newMd))
run('a: old -> old, fresh ids', oldDoc, pipeline(oldMd))
run('b: old -> new, ids carried', oldDoc, pipeline(newMd, (d) => carryIds(oldDoc, d)))
const oldB = pipeline(oldMd, browserImageSizes)
run('d1: old -> old, fresh ids + random keyId', oldB, pipeline(oldMd, browserImageSizes))
run('d2: old -> new, fresh ids + random keyId', oldB, pipeline(newMd, browserImageSizes))
run('e: old -> new, ids carried + random keyId', oldB, pipeline(newMd, (d) => browserImageSizes(carryIds(oldB, d))))

Acceptance criteria

  • Step 0 is done, and its finding is posted on this issue.
  • The reproduction gives d1 = {"unchanged":42} and e = {"modified":20,"unchanged":22,"added":12}.
  • On the local stack, a Settings replace of the old DEMO.md and then the new one keeps the toc-id of every heading whose level and text did not change. Check with GET /api/documents/:documentId/content?format=json before and after.
  • A heading chat opened before that replace still shows its messages after it.
  • GET /api/documents/:documentId/changes across that replace shows modified for the edited sections, and unchanged for "👋 Start here".
  • The two new unit tests pass and were proved by sabotage.
  • bun run typecheck, the hocuspocus suite, webapp Jest and lint pass.
  • API.md and apps/webapp/src/components/TipTap/CLAUDE.md are updated.
  • After deploy, the repair dry-run table for /demo is posted here, the maintainer approves it, and --apply runs.

Out of scope

  • The other four actions that re-key a heading: heading to paragraph and back, a level change over a multi-block selection, cut and paste, and select-all paste. See docs/roadmap/section-changes-in-heading-chat/rfc.md.
  • PATCH /content with mode=replace for REST callers. encodeContent keeps a supplied toc-id, and API.md:981 already tells callers to send one.
  • A "replaced" label in the digest. The mail has only added, removed, modified, moved and unchanged, and this fix does not need another.

After the fix

One more coarse digest may still reach a reader whose last visit predates the 2026-10-13 paste. That window starts on a version row with the old ids, and the Step 4 repair does not change version rows. No action needed.

Image

Activity

  1. added
    bug
    Editor
    Chat
    on Oct 14, 2026
  2. HMarzban commented on Oct 14, 2026

    @HMarzban
    CollaboratorAuthor

    Maintainer ruling, 2026-10-14

    1. Keep the old heading ids across a replace: yes. Carry each toc-id by level plus heading text in applyImportedContent (Step 2).
    2. Ignore keyId when the server compares: yes. Add keyId to VOLATILE_BLOCK_ATTRS (Step 1).
    3. Reconnect the /demo chat rooms on production: yes. Use the dry-run table first, and run --apply only after the maintainer approves it (Step 4).

    Decisions 4 and 5 are still open. Until the maintainer rules on them, follow the recommended answers in the issue body.

  3. HMarzban commented on Oct 14, 2026

    @HMarzban
    CollaboratorAuthor

    Maintainer ruling update, 2026-10-14

    1. An old room and a new room for one heading: the maintainer's words: "since we are in early stages, do not consider this and for demo page just consider the old one." So build no conflict branch. On /demo, the old room always takes the heading, and the newer room for that heading is removed. The dry-run table still shows the newer room's message count before --apply.
    2. Repair other documents: the maintainer's words: "yes, right now just repair only demo." Step 4 runs on /demo only. No fleet-wide run is part of this issue.

    The issue body is updated to match: Decisions 4 and 5, and the repair rule in Step 4. Every decision on this issue now has a ruling.

  4. HMarzban commented on Oct 15, 2026

    @HMarzban
    CollaboratorAuthor

    Related issues


    Cross-link review, 2026-10-15. Generated by Claude Code

  5. added this to the v2.3.0 milestone on Nov 2, 2026
  6. HMarzban commented on Nov 3, 2026

    @HMarzban
    CollaboratorAuthor

    Status, 2026-11-03. Steps 1 to 3 shipped in 42b70ac83, and the repair script shipped in 65afb233e. Both are pushed and deployed. Left:

    • Run repair-heading-chat-ids.ts as a dry run on production /demo.
    • Maintainer: approve the dry-run table.
    • Run it again with --apply.
  7. modified the milestones: v2.3.0, v2.4.0 on Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ChatEditorbug

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions