oficina / docs Public

Delete…: drop only the deleted document's own data (#178, finding 1)

deleteDocument() awaited the network and then ran discardAll() on whatever
document was open by then: delete A on a slow link, go back, open B, and
A's answer dropped B's replica, metadata and unsent outbox lane, and closed
B. It now takes A's sqid, key and persistence before the request. If A is
still open when the answer comes, it is discarded as before. Otherwise only
A's lane, replica and metadata are dropped by key, and the model and B are
left alone. The result says whether A was still open, and the window closes
(Mac) or the iPhone goes back to the library only then; the lists and File
▸ Recent forget A either way. The input hold during the request is tied to
A's epoch, so B is not held by it.

Test: DocsDeletionTests.testADeleteAnsweredAfterAnotherDocumentOpenedDropsOnlyItsOwn
(delete A, open B and type in it mid-request; B's replica, metadata and
lane survive, A's go). With the old unconditional discard it fails on all
of those.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev cb077b985251367037873beef5a288d73698ac9e parent 2463114
3 files changed, +111 −21
  • native/apple/Sources/DocsKit/DocsModel.swift +38 −14
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +7 −3
  • native/apple/Tests/DocsKitTests/DocsDeletionTests.swift +66 −4
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index 0f3f4d5..d0a4d7d 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -121,11 +121,14 @@ import RastrilloNative
/// The pause came from a read-only answer to `refreshAccess`: a later
/// writable answer lifts it.
@ObservationIgnored private var pausedAsReader = false
- /// A Delete… is waiting for the server: typing and commands wait too, so
- /// nothing new reaches the outbox of a document about to be gone.
- @ObservationIgnored private var deleting = false {
- didSet { if oldValue != deleting { pushEditability(); refreshToolbarSelection() } }
- }
+ /// A Delete… of the document opened at this epoch is waiting for the
+ /// server: its typing and commands wait too, so nothing new reaches the
+ /// outbox of a document about to be gone. Another document opened
+ /// meanwhile is not held by it.
+ @ObservationIgnored private var deletingEpoch: UUID? {
+ didSet { if oldValue != deletingEpoch { pushEditability(); refreshToolbarSelection() } }
+ }
+ private var deleting: Bool { deletingEpoch != nil && deletingEpoch == documentEpoch }
/// Typing and commands are refused: paused for any reason.
var inputBlocked: Bool { inputPaused || sessionPaused || deleting }
/// What the window may do with the document (§6 rows 1 and 10).
@@ -964,21 +967,42 @@ import RastrilloNative
return nil
}
+ /// What a Delete… came to, and whether the deleted document was still
+ /// the open one when the answer came (the window closes, or the iPhone
+ /// goes back to the library, only then).
+ struct DeleteResult: Equatable {
+ let outcome: DocsDeletion.Outcome
+ let wasOpen: Bool
+ }
+
/// Deletes the open document (`DocsDeletion`'s rule). Sends what is
/// waiting first and refuses if anything is still unsent; only a
- /// `.deleted` answer drops the document's outbox lane and replica, and
- /// then the model holds no document.
- func deleteDocument() async -> DocsDeletion.Outcome? {
+ /// `.deleted` answer drops the document's outbox lane and replica.
+ ///
+ /// The document, its key and its persistence are taken before the
+ /// request: another document may be open by the time the answer comes
+ /// (back to the library, open B, on a slow link). Then only the deleted
+ /// document's lane, replica and metadata go, by its key, and the model
+ /// and the open document are left alone (Fable on #178, finding 1).
+ func deleteDocument() async -> DeleteResult? {
await flush()
- guard deleteBlock(offline: false) == nil, let sqid = detail?.sqid, let client = transport() else { return nil }
- deleting = true
+ guard deleteBlock(offline: false) == nil, let sqid = detail?.sqid, let client = transport(),
+ let key = documentKey, let deleted = persistence else { return nil }
+ let epoch = documentEpoch
+ deletingEpoch = epoch
let outcome = await DocsDeletion.run(sqid: sqid, transport: client)
- deleting = false
- if outcome == .deleted {
+ if deletingEpoch == epoch { deletingEpoch = nil }
+ guard outcome == .deleted else { return DeleteResult(outcome: outcome, wasOpen: detail?.sqid == sqid) }
+ documents.removeAll { $0.sqid == sqid }
+ if detail?.sqid == sqid {
await discardAll()
- documents.removeAll { $0.sqid == sqid }
+ return DeleteResult(outcome: outcome, wasOpen: true)
}
- return outcome
+ do {
+ try await deleted.discard()
+ try offlineAccount.removeMetadata(key)
+ } catch { /* The document is gone on the server; what is left here is refused there and never shown. */ }
+ return DeleteResult(outcome: outcome, wasOpen: false)
}
/// Another window deleted `sqid`: it leaves the list now, before the reload.
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift
index f851897..321cf15 100644
--- a/native/apple/Sources/DocsKit/DocsWorkspace.swift
+++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift
@@ -341,12 +341,16 @@ import SwiftUI
guard let sqid = model.detail?.sqid else { return }
let origin = client.origin
Task {
- switch await model.deleteDocument() {
+ let result = await model.deleteDocument()
+ switch result?.outcome {
case .deleted?:
- // Every list leaves it (the home window, the iPhone library),
- // File ▸ Recent forgets it, and its window closes.
+ // Every list leaves it (the home window, the iPhone library)
+ // and File ▸ Recent forgets it. Its window closes, or the
+ // iPhone goes back to the library, only if it is still the
+ // document open: another may have been opened meanwhile.
NotificationCenter.default.post(name: .docsDocumentDeleted, object: nil, userInfo: ["origin": origin, "sqid": sqid])
documentDeleted?(sqid)
+ guard result?.wasOpen == true else { return }
#if os(macOS)
closer.close()
#else
diff --git a/native/apple/Tests/DocsKitTests/DocsDeletionTests.swift b/native/apple/Tests/DocsKitTests/DocsDeletionTests.swift
index e16ed66..a57fc0f 100644
--- a/native/apple/Tests/DocsKitTests/DocsDeletionTests.swift
+++ b/native/apple/Tests/DocsKitTests/DocsDeletionTests.swift
@@ -87,8 +87,8 @@ import XCTest
func testDeletedDropsTheLaneAndTheReplica() async throws {
let (model, _, key) = try await open([.respond(status: 200, body: ok, headers: json)])
XCTAssertNil(model.deleteBlock(offline: false))
- let outcome = await model.deleteDocument()
- XCTAssertEqual(outcome, .deleted)
+ let result = await model.deleteDocument()
+ XCTAssertEqual(result, .init(outcome: .deleted, wasOpen: true))
XCTAssertFalse(try model.offlineAccount.replicaCache.hasBase(key), "the replica is gone")
XCTAssertNil(try model.offlineAccount.metadata(key), "and its metadata")
let lane = await model.offlineAccount.outbox.summary.only("doc:" + key)
@@ -99,8 +99,8 @@ import XCTest
func testNotDeletedKeepsTheLaneAndTheReplica() async throws {
let (model, server, key) = try await open([.respond(status: 404)])
await server.answerDetail(200)
- let outcome = await model.deleteDocument()
- XCTAssertEqual(outcome, .stillThere)
+ let result = await model.deleteDocument()
+ XCTAssertEqual(result?.outcome, .stillThere)
XCTAssertTrue(try model.offlineAccount.replicaCache.hasBase(key), "the replica is kept")
XCTAssertNotNil(try model.offlineAccount.metadata(key))
XCTAssertEqual(model.detail?.sqid, "doc", "the document stays open")
@@ -109,6 +109,50 @@ import XCTest
await model.stop()
}
+ /// Fable on #178, finding 1: the answer comes after another document
+ /// was opened (back to the library, open B, on a slow link). Only A's
+ /// lane, replica and metadata go; B, open now, keeps all of its own, and
+ /// the model stays on B.
+ func testADeleteAnsweredAfterAnotherDocumentOpenedDropsOnlyItsOwn() async throws {
+ let (model, server, keyA) = try await open([.respond(status: 200, body: ok, headers: json)])
+ try await server.b.seed([.object(["type": .string("paragraph"), "children": .array([
+ .object(["type": .string("text"), "runs": .array([.object(["insert": .string("B's text"), "marks": .object([:])])])])])])])
+ await server.holdDelete()
+ let deleting = Task { await model.deleteDocument() }
+ let deadline = Date().addingTimeInterval(5)
+ while !(await server.deleteWaiting) {
+ guard Date() < deadline else { return XCTFail("the delete never reached the server") }
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ await model.open("b")
+ XCTAssertEqual(model.detail?.sqid, "b", "B is open while A's delete waits")
+ let keyB = try model.offlineAccount.key(for: "b")
+ XCTAssertNotEqual(keyA, keyB)
+ // An unsent change in B: its lane must survive A's delete.
+ XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("x")]),
+ "B takes typing: A's delete does not hold it")
+ let typedDeadline = Date().addingTimeInterval(5)
+ while await model.offlineAccount.outbox.summary.only("doc:" + keyB).isEmpty {
+ guard Date() < typedDeadline else { return XCTFail("B's change never reached its lane") }
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ await model.persistReplica()
+
+ await server.releaseDelete()
+ let result = await deleting.value
+ XCTAssertEqual(result, .init(outcome: .deleted, wasOpen: false), "A was deleted, and it was no longer the open document")
+ XCTAssertEqual(model.detail?.sqid, "b", "the model stays on B")
+ XCTAssertTrue(try model.offlineAccount.replicaCache.hasBase(keyB), "B's replica survives")
+ XCTAssertNotNil(try model.offlineAccount.metadata(keyB), "and its metadata")
+ let laneB = await model.offlineAccount.outbox.summary.only("doc:" + keyB)
+ XCTAssertFalse(laneB.isEmpty, "and its unsent lane")
+ XCTAssertFalse(try model.offlineAccount.replicaCache.hasBase(keyA), "A's replica is gone")
+ XCTAssertNil(try model.offlineAccount.metadata(keyA), "and A's metadata")
+ let laneA = await model.offlineAccount.outbox.summary.only("doc:" + keyA)
+ XCTAssertTrue(laneA.isEmpty, "and A's lane")
+ await model.stop()
+ }
+
/// Owners only; never a draft; refused while anything is unsent.
func testDeleteIsRefusedWithUnsentChangesAndForNonOwners() async throws {
let (model, _, _) = try await open([])
@@ -130,16 +174,33 @@ import XCTest
actor DeleteServer: NativeTransport {
nonisolated let origin = URL(string: "https://docs.delete.invalid")!
let inner = LoopServer()
+ /// A second document, "b": the same LoopServer routes under /d/b. Its
+ /// update POSTs are refused (503), so what B types stays in its lane.
+ let b = LoopServer()
private var deleteSteps: [ScriptedTransport.Step]
private var detailStatus = 200
private(set) var deleteCalls = 0
+ private var holding = false
+ private var gate: CheckedContinuation<Void, Never>?
init(_ steps: [ScriptedTransport.Step]) { deleteSteps = steps }
func answerDetail(_ status: Int) { detailStatus = status }
+ func holdDelete() { holding = true }
+ var deleteWaiting: Bool { gate != nil }
+ func releaseDelete() { holding = false; gate?.resume(); gate = nil }
func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
+ if path == "/d/b" || path.hasPrefix("/d/b/") || path.hasPrefix("/d/b?") {
+ if method == "GET", path == "/d/b" {
+ let detail = DocumentDetail(sqid: "b", title: "B", guid: "render-loop", can_write: true, can_share: true)
+ return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:])
+ }
+ if method == "POST" { return NativeResponse(data: Data(), status: 503, headers: [:]) }
+ return try await b.responseDetails("/d/doc" + path.dropFirst(4), method: method, body: body, contentType: contentType, maxBytes: maxBytes)
+ }
if method == "POST", path == "/d/doc/delete" {
deleteCalls += 1
+ if holding { await withCheckedContinuation { gate = $0 } }
guard !deleteSteps.isEmpty else { throw NativeClientError.message("DeleteServer: no scripted answer left for the delete") }
switch deleteSteps.removeFirst() {
case .respond(let status, let body, let headers):
@@ -157,6 +218,7 @@ actor DeleteServer: NativeTransport {
return try await inner.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes)
}
func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws {
+ if path.hasPrefix("/d/b/") { return try await b.stream("/d/doc" + path.dropFirst(4), onOpen: onOpen, onLine: onLine) }
try await inner.stream(path, onOpen: onOpen, onLine: onLine)
}
func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound }