oficina / docs Public

Docs native S1a: an edit across blocks the replica refuses is undone (#170, 1)

Fable's finding 1. Selecting from the middle of one block to the middle
of a later one and typing, cutting or pasting marked only the runs that
held the inserted text. The block that lost its head was not marked; if
the replica refused or clamped the edit, the next publication named
nothing, and that block was kept as an anchor, truncated, for good.

- typed(around:) marks from the character before the edit through the
  one after it, so both ends of an edit across blocks are drawn again.
- Each drawn block remembers its length, and a block is kept as an
  anchor only when its run in the storage is that length.

DeltaSafetyTests.testAReplaceAcrossBlocksTheReplicaRefusesIsUndone
types, cuts and pastes across aaaa/bbbb/cccc/dddd with the replica taking
none of it; it failed before (the storage kept "aa…cc" without "cccc").
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 12c78dbfaa1e18747bbc5563a291f7d56505bbab parent 2f8d4fe
3 files changed, +79 −18
  • native/apple/Sources/DocsKit/DocumentSurface.swift +29 −18
  • native/apple/Tests/DocsKitTests/DeltaSafetyTests.swift +42 −0
  • native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift +8 −0
diff --git a/native/apple/Sources/DocsKit/DocumentSurface.swift b/native/apple/Sources/DocsKit/DocumentSurface.swift
index 01fbed6..a6406f1 100644
--- a/native/apple/Sources/DocsKit/DocumentSurface.swift
+++ b/native/apple/Sources/DocsKit/DocumentSurface.swift
@@ -77,6 +77,10 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
/// Its first paragraph's top margin when not first of the document.
var firstBefore: CGFloat?
var sources: Set<String>
+ /// Its length as drawn. A block whose run in the storage is any
+ /// other length has been edited there (or lost characters to an
+ /// edit across blocks) and is never kept as it stands.
+ var length: Int
}
private var entries: [String: Entry] = [:]
private var order: [String] = []
@@ -195,6 +199,7 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
applying = true
if entries.isEmpty { drawWhole(newest.projection, into: text, storage: storage) }
else { drawChanged(newest.projection, storage: storage, textOnly: !advancing) }
+ report(sources: sourceCounts.keys.sorted())
let length = storage.length
let range = NSRange(location: min(selected.location, length), length: min(selected.length, max(0, length - selected.location)))
if selectedRange != range { Self.select(range, in: text) }
@@ -220,12 +225,17 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
#endif
#endif
index.rebuild(from: storage)
+ rememberWhole(projection.children)
+ }
+ /// After a whole draw: every block as the storage now holds it.
+ private func rememberWhole(_ nodes: [CRDTNode]) {
entries = [:]; sourceCounts = [:]
- let contexts = DocumentBlockSpacing.contexts(projection.children)
- for (node, context) in zip(projection.children, contexts) { remember(node, context: context) }
- order = projection.children.map(\.id)
+ var lengths: [String: Int] = [:]
+ for run in index.runs { if let id = run.id { lengths[id, default: 0] += run.length } }
+ let contexts = DocumentBlockSpacing.contexts(nodes)
+ for (node, context) in zip(nodes, contexts) { remember(node, context: context, length: lengths[node.id] ?? 0) }
+ order = nodes.map(\.id)
pendingDirty = []; fullDiff = false
- report(sources: sourceCounts.keys.sorted())
}
/// Everything since: the blocks that changed (or whose neighbours
@@ -240,11 +250,7 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
// Two blocks under one id: no per-block identity to go by.
DocumentRenderReconciliation.apply(NativeTextProjection.render(projection, images: images), to: storage)
index.rebuild(from: storage)
- let contexts = DocumentBlockSpacing.contexts(nodes)
- entries = [:]; sourceCounts = [:]
- for (node, context) in zip(nodes, contexts) { remember(node, context: context) }
- order = ids; pendingDirty = []; fullDiff = false
- report(sources: sourceCounts.keys.sorted())
+ rememberWhole(nodes)
return
}
// What changed, by id.
@@ -282,7 +288,7 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
for (block, id) in ids.enumerated() where !draw.contains(id) {
guard let runs = positions[id], runs.count == 1 else { draw.insert(id); continue }
let run = index.runs[runs[0]]
- guard run.location >= lastEnd else { draw.insert(id); continue }
+ guard run.location >= lastEnd, run.length == entries[id]?.length else { draw.insert(id); continue }
anchors.append((block, run)); lastEnd = run.end
}
// Gaps, last first, so earlier ranges stay where they are.
@@ -296,29 +302,31 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
var waiting = Set<String>()
for gap in gaps.reversed() {
let rendered = NSMutableAttributedString()
+ var lengths: [Int] = []
for block in gap.blocks {
- rendered.append(NativeTextProjection.renderBlock(nodes[block], context: contexts[block], images: images))
+ let drawn = NativeTextProjection.renderBlock(nodes[block], context: contexts[block], images: images)
+ lengths.append(drawn.length)
+ rendered.append(drawn)
}
if textOnly, (storage.string as NSString).substring(with: gap.range) != rendered.string {
for block in gap.blocks { waiting.insert(nodes[block].id) }
continue
}
DocumentRenderReconciliation.apply(rendered, to: storage, in: gap.range)
- for block in gap.blocks { remember(nodes[block], context: contexts[block]) }
+ for (block, length) in zip(gap.blocks, lengths) { remember(nodes[block], context: contexts[block], length: length) }
}
for (block, _) in anchors { entries[nodes[block].id]?.context = contexts[block] }
let kept = Set(ids)
for id in order where !kept.contains(id) { forget(id) }
order = ids
pendingDirty = waiting; fullDiff = false
- report(sources: sourceCounts.keys.sorted())
}
- private func remember(_ node: CRDTNode, context: DocumentBlockSpacing.Context) {
+ private func remember(_ node: CRDTNode, context: DocumentBlockSpacing.Context, length: Int) {
forget(node.id)
let sources = DocsImageStore.sources(in: node)
for source in sources { sourceCounts[source, default: 0] += 1 }
- entries[node.id] = Entry(node: node, context: context, firstBefore: DocumentBlockSpacing.firstBefore(node), sources: sources)
+ entries[node.id] = Entry(node: node, context: context, firstBefore: DocumentBlockSpacing.firstBefore(node), sources: sources, length: length)
}
private func forget(_ id: String) {
guard let old = entries.removeValue(forKey: id) else { return }
@@ -341,9 +349,12 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
/// edit it refused (or one a dropped publication carried) would
/// otherwise stay on screen until something else touched the block.
private func typed(around edited: NSRange) {
- // The characters inserted, or the two either side of a deletion.
- let first = edited.length > 0 ? edited.location : max(0, edited.location - 1)
- let last = edited.length > 0 ? NSMaxRange(edited) - 1 : edited.location
+ // From the character before the edit through the one after it: an
+ // edit across blocks leaves the head of one and the tail of
+ // another, and both must be drawn again even if the replica
+ // changes neither (it refused the edit, or clamped it).
+ let first = max(0, edited.location - 1)
+ let last = NSMaxRange(edited)
let touched = index.runs(holding: first, through: last)
for run in touched { if let id = run.id { pendingDirty.insert(id) } }
// Text typed with no block (UIKit's typing attributes may not carry
diff --git a/native/apple/Tests/DocsKitTests/DeltaSafetyTests.swift b/native/apple/Tests/DocsKitTests/DeltaSafetyTests.swift
index 48bca07..254be09 100644
--- a/native/apple/Tests/DocsKitTests/DeltaSafetyTests.swift
+++ b/native/apple/Tests/DocsKitTests/DeltaSafetyTests.swift
@@ -18,6 +18,48 @@ import XCTest
for seed: UInt64 in [21, 22, 23] { try await run(seed: seed, logLimit: 2) }
}
+ /// A replace across blocks, from the middle of one to the middle of a
+ /// later one, by typing, a cut and a paste; the replica takes none of
+ /// them (it rolled the edit back, or clamped it), so the publication
+ /// that follows names no block as changed. The storage must still come
+ /// back to the replica's text: the block that lost its head too, not
+ /// only the one holding what was typed (Fable on #170, finding 1).
+ func testAReplaceAcrossBlocksTheReplicaRefusesIsUndone() async throws {
+ enum Edit { case type, cut, paste }
+ for edit in [Edit.type, .cut, .paste] {
+ let replica = CRDTReplica(guid: "across-\(edit)")
+ try await replica.open(update: Data())
+ _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ let blocks: [JSONValue] = ["aaaa", "bbbb", "cccc", "dddd"].map { text in
+ .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string(text), "marks": .object([:])])])])])])
+ }
+ _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)])
+ let state = SurfaceState(width: 640)
+ state.surface.hooks.edit = { _ in true } // accepted, then refused by the replica: never applied
+ func publish() async throws {
+ await replica.retainGenerations([state.surface.generation])
+ let answer = try await replica.presentation(source: state.surface.generation, selection: NSRange(location: 0, length: 0), since: state.surface.appliedRevision)
+ let presented = try XCTUnwrap(answer)
+ state.allowed = presented.generation
+ state.surface.apply(DocumentSurface.Publication(generation: presented.generation, projection: presented.projection, revision: presented.revision, dirty: presented.dirty))
+ }
+ try await publish()
+ let text = state.text
+ let shown = state.surface.content.string as NSString
+ let from = shown.range(of: "aaaa").location + 2, to = shown.range(of: "cccc").location + 2
+ Keyboard.select(NSRange(location: from, length: to - from), in: text)
+ switch edit {
+ case .type: Keyboard.type("X", in: text)
+ case .cut: Keyboard.cutSelection(in: text, surface: state.surface)
+ case .paste: Keyboard.paste(BlockRenderEquivalenceTests.pasted, in: text, surface: state.surface)
+ }
+ XCTAssertNotEqual(state.surface.content.string, "aaaa\nbbbb\ncccc\ndddd\n", "\(edit): the text view showed the edit")
+ try await publish()
+ SurfaceFixture.assertMatchesWholeRender(state.surface.content, try await replica.projection(), "\(edit) across blocks, refused")
+ await replica.close()
+ }
+ }
+
private final class Harness {
let replica: CRDTReplica
let peer: CRDTReplica
diff --git a/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift b/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift
index a158e2b..e0e7cc0 100644
--- a/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift
+++ b/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift
@@ -157,6 +157,14 @@ enum SurfaceFixture {
storage(of: text).replaceCharacters(in: range, with: replacement)
select(NSRange(location: range.location + replacement.length, length: 0), in: text)
}
+ /// A cut of the selection, as `DocsTextView.cut` does it once the
+ /// clipboard is written.
+ static func cutSelection(in text: DocsTextView, surface: DocumentSurface) {
+ let range = selection(text)
+ guard range.length > 0, surface.clipboardEdit(blocks: nil, range: range, replacement: "") else { return }
+ storage(of: text).replaceCharacters(in: range, with: "")
+ select(NSRange(location: range.location, length: 0), in: text)
+ }
static func storage(of text: DocsTextView) -> NSTextStorage {
#if os(macOS)
text.textStorage!