Repository navigation
Description
Summary
Settings "Replace with a file" gives every heading a new toc-id, and every picture a new random keyId. Two things break.
- The change digest email rewrites whole sections. After the 2026-10-13 paste of
docs/DEMO.mdon/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. - Every heading chat loses its room. A heading chat is keyed by
(workspace_id, heading_id), andheading_idis the headingtoc-id. A newtoc-idopens 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 toPOST /api/documents/:documentId/import, then runs the result in the browser throughapplyImportedContent(called atImportExportSection.tsx:171). applyImportedContentcallseditor.commands.setContent(sanitizeJsonContent(content)). The import JSON carries notoc-id, and nothing copies the old ids across.- The pad's
UniqueID(TipTap.tsx:147-152) then stamps a random id on every heading. ItsfilterTransactionskips only remote transactions, so a localsetContentis stamped. A probe measured 42 headings before the replace and 0 old ids kept after it. - The digest pairs Sections by
toc-idfirst. Nothing pairs by id, so the leftovers go to the content-hash matcher. zippablerefuses to join two sections that both carry atoc-id. So every edited Section becomesremovedplusadded.- 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,commitImportedImageSizeswrites the natural size andkeyId: crypto.randomUUID()on each unsized picture. It does this on every replace. keyIdis 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. ThekeyIdvalue 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-27looks a room up by the newtoc-id, finds none, and creates an empty one for a writer. The old room keeps its messages under the oldheading_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.
- Should a replace keep the old heading ids? Recommended: yes. In
applyImportedContent, beforesetContent, give each imported heading the oldtoc-idof a heading with the same level and the same text. Use each old id once. A heading with no match gets a new id fromUniqueID. This fixes the digest, the chats and the?id=links in one place, and leaveszippableas it is. - Should the server ignore
keyIdwhen it compares? Recommended: yes. AddkeyIdtoVOLATILE_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 andblockAuthors.ts:35. A change tokeyIdalone then stops counting there too, which is the intended result. No server code readskeyIdtoday. - 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.
- 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. - Should the repair run on other documents too? Ruled 2026-10-14: no. Repair only
/demoin 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
/demoacross the 2026-10-13 paste. Resolve the documentId withGET /api/documents/demo. Then callGET /api/documents/:documentId/changes?since=<before the paste>&until=<after the paste>&scope=headingswith the service-role key. - If a section with no picture and no edit shows as
removedplusadded, 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 inVOLATILE_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
keyIdtoVOLATILE_BLOCK_ATTRSinapps/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 imagekeyId(and carry differenttoc-ids) pair asunchanged. Prove the test by sabotage: removekeyIdfrom 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 bylevelplus heading text, and setsattrs['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
applyImportedContentaftersanitizeJsonContentand beforesetContent. Both the Settings replace and the Android share receiver then keep their ids. - Do not change
UniqueID,zippable, or thepairSectionsrule inapps/hocuspocus.server/CLAUDE.md(§HTTP Modules, thezippablebullet). 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
UniqueIDkeeps a supplied unique id on a localsetContent. Measure it, do not assume it: run the oldDEMO.md, then the new one, through a Y.Doc-backed editor with the pad'sUniqueIDconfig, 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) thatkeyIdis ignored, liketoc-id. - Add one line to
apps/webapp/src/components/TipTap/CLAUDE.md: a whole-document replace keeps headingtoc-ids by level and text, because chats,?id=links and the digest depend on them. API.md:981still holds for REST callers ofPATCH /contentwith 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--applyto write. Followscripts/backfill-strip-ghosts.tsfor the dry-run shape. - Input: one documentId. Read its version rows and decode each one locally with
readContent. Build a map from every historical headingtoc-idto itsleveland text. Two pastes happened, so an old room may sit two generations back. - Read the head row and map
levelplus text to the currenttoc-id. Skip a text that appears more than once in the head, and report it. - Read the document's rooms from
public.channelswhereworkspace_id = documentId. Skip the document channel, whoseheading_idequals the documentId. A room is orphaned when itsheading_idis 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_idto 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 fromchannels.slug. The unique keys are(workspace_id, heading_id)and(workspace_id, slug). - Print one table per run: old
heading_id, heading text, currenttoc-id, message count, planned action. The maintainer approves that table before--apply. - Prove it on the local stack first. Paste the old
DEMO.mdover the local demo, post a message in two heading chats, paste the newDEMO.mdwith 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}ande={"modified":20,"unchanged":22,"added":12}. - On the local stack, a Settings replace of the old
DEMO.mdand then the new one keeps thetoc-idof every heading whose level and text did not change. Check withGET /api/documents/:documentId/content?format=jsonbefore and after. - A heading chat opened before that replace still shows its messages after it.
-
GET /api/documents/:documentId/changesacross that replace showsmodifiedfor the edited sections, andunchangedfor "👋 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.mdandapps/webapp/src/components/TipTap/CLAUDE.mdare updated. - After deploy, the repair dry-run table for
/demois posted here, the maintainer approves it, and--applyruns.
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 /contentwithmode=replacefor REST callers.encodeContentkeeps a suppliedtoc-id, andAPI.md:981already tells callers to send one.- A "replaced" label in the digest. The mail has only
added,removed,modified,movedandunchanged, 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.

Activity
HMarzban commentedon Oct 14, 2026
Maintainer ruling, 2026-10-14
toc-idby level plus heading text inapplyImportedContent(Step 2).keyIdwhen the server compares: yes. AddkeyIdtoVOLATILE_BLOCK_ATTRS(Step 1)./demochat rooms on production: yes. Use the dry-run table first, and run--applyonly 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.
HMarzban commentedon Oct 14, 2026
Maintainer ruling update, 2026-10-14
/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./demoonly. 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.
HMarzban commentedon Oct 15, 2026
Related issues
pairSections.ts. AddingkeyIdtoVOLATILE_BLOCK_ATTRSchanges thecanonicalizeBlockkey that Stop the digest painting kept text as deleted when a heading is deleted or inserted #450 matches on.Cross-link review, 2026-10-15. Generated by Claude Code
fix: keep heading identity and ignore keyId across a file replace
feat(hocuspocus): add a repair script for orphaned heading chats
HMarzban commentedon Nov 3, 2026
Status, 2026-11-03. Steps 1 to 3 shipped in
42b70ac83, and the repair script shipped in65afb233e. Both are pushed and deployed. Left:repair-heading-chat-ids.tsas a dry run on production/demo.--apply.fix(webapp): stop a file replace swapping heading ids
fix(webapp): keep the pad's own id out of a file replace
fix(webapp): name only chats with messages on the replace card
refactor(webapp): parse a link's destination once