oficina / docs Public

Resolve the Docs model's transport per request, from a supplier

K1 of the offline-kit spec (§3.1), Docs half. DocsModel captured one
NativeHTTP for its whole life, but it can hold unsent edits for longer
than one session, and re-sign-in (K5) must swap the transport under it.
It now takes `@MainActor () -> NativeTransport?` and asks for it on
every request; nil (no session) fails as .unauthorized. The account
window supplies the connection's current client only while the model's
own account is active; document windows keep their captured client
until K5.

Pins rastrillo/native feat/k1-typed-errors-transport (d9dac72) for
NativeTransport and RastrilloTestSupport. Re-pin to main once that
branch merges.

Tests (ScriptedTransport, no fixture server): a list load after the
session's transport changes uses the new one, and an edit made under
one session is sent on its replacement, never on the ended one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 96820a322ff9edc6b8498adc961ea2dae8edaf82 parent e2db36e
9 files changed, +127 −23
  • native/apple/Package.resolved +1 −1
  • native/apple/Package.swift +2 −2
  • native/apple/Sources/DocsApp/DocsAccountWindow.swift +13 −2
  • native/apple/Sources/DocsKit/DocsModel.swift +25 −13
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +4 −2
  • native/apple/Tests/DocsKitTests/TransportSupplierTests.swift +79 −0
  • native/ios/project.yml +1 −1
  • native/macos/project.yml +1 −1
  • native/smoke/document-window/Package.resolved +1 −1

CI passed — run details

diff --git a/native/apple/Package.resolved b/native/apple/Package.resolved
index b97f847..a90a78c 100644
--- a/native/apple/Package.resolved
+++ b/native/apple/Package.resolved
@@ -6,7 +6,7 @@
"kind" : "remoteSourceControl",
"location" : "https://amadan.net/rastrillo/native",
"state" : {
- "revision" : "2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67"
+ "revision" : "d9dac7226ade1f3743f4742ed7f4021cd0918ac3"
}
},
{
diff --git a/native/apple/Package.swift b/native/apple/Package.swift
index 12a98cb..2a72df3 100644
--- a/native/apple/Package.swift
+++ b/native/apple/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
import Foundation
let sharedNative: Package.Dependency = ProcessInfo.processInfo.environment["OFICINA_NATIVE_PACKAGE_PATH"].map { .package(name: "native", path: $0) }
- ?? .package(url: "https://amadan.net/rastrillo/native", revision: "2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67")
+ ?? .package(url: "https://amadan.net/rastrillo/native", revision: "d9dac7226ade1f3743f4742ed7f4021cd0918ac3")
let package = Package(name: "DocsNative", defaultLocalization: "en", platforms: [.macOS(.v26), .iOS(.v26)],
products: [.library(name: "DocsKit", targets: ["DocsKit"]), .executable(name: "DocsMac", targets: ["DocsMac"])],
@@ -12,6 +12,6 @@ let package = Package(name: "DocsNative", defaultLocalization: "en", platforms:
.binaryTarget(name: "DocsCRDT", path: "Artifacts/DocsCRDT.xcframework"),
.target(name: "DocsKit", dependencies: ["DocsCRDT", .product(name: "RastrilloApple", package: "native")], resources: [.process("Resources")]),
.executableTarget(name: "DocsMac", dependencies: [.product(name: "RastrilloMacUpdates", package: "native", condition: .when(platforms: [.macOS])), "DocsKit", .product(name: "RastrilloApple", package: "native")], path: "Sources/DocsApp"),
- .testTarget(name: "DocsKitTests", dependencies: ["DocsKit"]),
+ .testTarget(name: "DocsKitTests", dependencies: ["DocsKit", .product(name: "RastrilloTestSupport", package: "native")]),
.testTarget(name: "DocsWindowTests", dependencies: ["DocsMac", .product(name: "RastrilloApple", package: "native")]),
])
diff --git a/native/apple/Sources/DocsApp/DocsAccountWindow.swift b/native/apple/Sources/DocsApp/DocsAccountWindow.swift
index 4ae4781..810f218 100644
--- a/native/apple/Sources/DocsApp/DocsAccountWindow.swift
+++ b/native/apple/Sources/DocsApp/DocsAccountWindow.swift
@@ -10,12 +10,23 @@ struct DocsAccountWindow: View {
@Bindable var windows: DocsWindows
@Environment(\.openWindow) private var openWindow
#endif
+ /// The workspace's model outlives any one session of its account, so it
+ /// asks for the connection's current client on every request. It never gets
+ /// another account's client: `.id(account)` gives each account its own model.
+ private func transport(for account: String?) -> @MainActor () -> NativeTransport? {
+ let connection = connection
+ return { [weak connection] in
+ guard let connection, account != nil, connection.activeAccountID == account else { return nil }
+ return connection.client
+ }
+ }
+
var body: some View {
Group {
if let client = connection.client {
#if os(macOS)
if let account = connection.activeAccountID {
- DocsWorkspace(client: client, accounts: connection.showAccounts, signOut: {
+ DocsWorkspace(client: client, transport: transport(for: account), accounts: connection.showAccounts, signOut: {
guard connection.activeAccountID == account, windows.canSignOut(account) else { return }
windows.entries.removeAll { $0.account == account }
connection.signOut()
@@ -34,7 +45,7 @@ struct DocsAccountWindow: View {
.id(account)
}
#else
- DocsWorkspace(client: client, accounts: connection.showAccounts, signOut: connection.signOut)
+ DocsWorkspace(client: client, transport: transport(for: connection.activeAccountID), accounts: connection.showAccounts, signOut: connection.signOut)
.id(connection.activeAccountID)
#endif
} else {
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index 545f7f0..6f5dad7 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -38,8 +38,20 @@ import RastrilloApple
private var saving = false
private var documentEpoch = UUID()
private let publications = DocumentPublication()
- private let client: NativeHTTP
- init(client: NativeHTTP, draft: Bool = false) { self.client = client; if draft { draftToken = UUID().uuidString } }
+ /// Resolved on every request, never captured: this model can hold unsent
+ /// edits for longer than one session, and signing in again replaces the
+ /// transport under it. A captured client would keep sending with the ended
+ /// session. nil means no session; requests then fail as `.unauthorized`.
+ private let transport: @MainActor () -> NativeTransport?
+ init(transport: @escaping @MainActor () -> NativeTransport?, draft: Bool = false) {
+ self.transport = transport
+ if draft { draftToken = UUID().uuidString }
+ }
+ convenience init(client: NativeTransport, draft: Bool = false) { self.init(transport: { client }, draft: draft) }
+ private func client() throws -> NativeTransport {
+ guard let current = transport() else { throw NativeClientError.unauthorized }
+ return current
+ }
var hasPendingInput: Bool { !editing.isEmpty || editingTask != nil }
var hasUnsavedChanges: Bool { (renameInput != nil && renameInput != detail?.title) || isDraft || pendingTitle != nil || composing || !pending.isEmpty || !editing.isEmpty || editingTask != nil }
func load(query: String = "") async {
@@ -48,7 +60,7 @@ import RastrilloApple
do {
var components = URLComponents(); components.queryItems = [URLQueryItem(name: "q", value: query)]
let q = (components.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B")
- let response: DocumentList = try await client.request("/?\(q)")
+ let response: DocumentList = try await client().request("/?\(q)")
guard listRequest == request, !Task.isCancelled else { return }
documents = response.documents; canCreate = response.can_create
listState = .loaded; errorKey = nil
@@ -91,12 +103,12 @@ import RastrilloApple
guard let token = draftToken, let local = replica else { return }
do {
let body = Self.form(["title": detail?.title ?? "", "creation_token": token])
- let (data, status) = try await client.response("/documents", method: "POST", body: body, contentType: "application/x-www-form-urlencoded")
+ let (data, status) = try await client().response("/documents", method: "POST", body: body, contentType: "application/x-www-form-urlencoded")
guard status == 201 else { throw CRDTReplica.Failure.rejected }
let item = try JSONDecoder().decode(DocumentSummary.self, from: data)
guard documentEpoch == epoch else { return }
- let attached: DocumentDetail = try await client.request("/d/\(item.sqid)")
- let reply = try await client.responseDetails("/d/\(item.sqid)/updates", maxBytes: 8 * 1024 * 1024)
+ let attached: DocumentDetail = try await client().request("/d/\(item.sqid)")
+ let reply = try await client().responseDetails("/d/\(item.sqid)/updates", maxBytes: 8 * 1024 * 1024)
guard reply.status == 200, let seq = Int64(reply.header("Docs-Seq") ?? ""), attached.can_write else { throw CRDTReplica.Failure.rejected }
guard documentEpoch == epoch else { return }
if !reply.data.isEmpty { _ = try await local.apply(reply.data) }
@@ -142,8 +154,8 @@ import RastrilloApple
guard documentEpoch == epoch else { return }
defer { if documentEpoch == epoch { loading = false } }
do {
- let detail: DocumentDetail = try await client.request("/d/\(sqid)")
- let reply = try await client.responseDetails("/d/\(sqid)/updates", maxBytes: 8 * 1024 * 1024)
+ let detail: DocumentDetail = try await client().request("/d/\(sqid)")
+ let reply = try await client().responseDetails("/d/\(sqid)/updates", maxBytes: 8 * 1024 * 1024)
guard reply.status == 200, let seq = Int64(reply.header("Docs-Seq") ?? "") else { throw CRDTReplica.Failure.rejected }
guard documentEpoch == epoch else { return }
let replica = CRDTReplica(guid: detail.guid)
@@ -267,7 +279,7 @@ import RastrilloApple
while !pending.isEmpty || pendingTitle != nil {
if let title = pendingTitle {
do {
- let (_, status) = try await client.response("/d/\(detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded")
+ let (_, status) = try await client().response("/d/\(detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded")
guard documentEpoch == epoch else { return }
guard status == 204 else { throw CRDTReplica.Failure.rejected }
if pendingTitle == title { pendingTitle = nil }
@@ -293,7 +305,7 @@ import RastrilloApple
count = 1
}
guard documentEpoch == epoch else { return }
- let (_, status) = try await client.response("/d/\(detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream")
+ let (_, status) = try await client().response("/d/\(detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream")
guard documentEpoch == epoch else { return }
guard status == 204 else {
if status == 401 || status == 403 || status == 404 { await refreshAccess(detail.sqid, epoch: epoch) }
@@ -309,7 +321,7 @@ import RastrilloApple
while !Task.isCancelled, documentEpoch == epoch, detail?.sqid == sqid {
await flush()
do {
- try await client.stream("/d/\(sqid)/stream") { [weak self] line in
+ try await client().stream("/d/\(sqid)/stream") { [weak self] line in
if line.hasPrefix("data:"), let seq = Int64(line.dropFirst(5).trimmingCharacters(in: .whitespaces)) {
await self?.refresh(sqid, remoteSequence: seq)
}
@@ -327,7 +339,7 @@ import RastrilloApple
let epoch = documentEpoch
guard detail?.sqid == sqid, remoteSequence > sequence, let replica else { return }
do {
- let reply = try await client.responseDetails("/d/\(sqid)/updates?since=\(sequence)", maxBytes: 8 * 1024 * 1024)
+ let reply = try await client().responseDetails("/d/\(sqid)/updates?since=\(sequence)", maxBytes: 8 * 1024 * 1024)
guard reply.status == 200, let seq = Int64(reply.header("Docs-Seq") ?? "") else { throw CRDTReplica.Failure.rejected }
guard self.detail?.sqid == sqid, self.replica === replica else { return }
_ = try await replica.apply(reply.data)
@@ -342,7 +354,7 @@ import RastrilloApple
let revision = titleRevision
let hadPendingTitle = pendingTitle != nil
do {
- let reply = try await client.responseDetails("/d/\(sqid)", maxBytes: 1024 * 1024)
+ let reply = try await client().responseDetails("/d/\(sqid)", maxBytes: 1024 * 1024)
guard documentEpoch == epoch else { return }
if reply.status == 200 {
let current = try JSONDecoder().decode(DocumentDetail.self, from: reply.data)
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift
index 5c28ab3..1ecf7bd 100644
--- a/native/apple/Sources/DocsKit/DocsWorkspace.swift
+++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift
@@ -27,10 +27,12 @@ import SwiftUI
private let signOut: () -> Void
private let accounts: (() -> Void)?
private let client: NativeHTTP
- public init(client: NativeHTTP, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) {
+ /// `transport` supplies the account's current session to the model on every
+ /// request; without one the model keeps `client` for its whole lifetime.
+ public init(client: NativeHTTP, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) {
self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument
self.newDocument = newDocument; self.createDocument = createDocument; self.documentChanged = documentChanged
- _model = State(initialValue: DocsModel(client: client, draft: newDocument)); self.signOut = signOut; self.accounts = accounts; self.client = client
+ _model = State(initialValue: transport.map { DocsModel(transport: $0, draft: newDocument) } ?? DocsModel(client: client, draft: newDocument)); self.signOut = signOut; self.accounts = accounts; self.client = client
}
private var library: some View {
List {
diff --git a/native/apple/Tests/DocsKitTests/TransportSupplierTests.swift b/native/apple/Tests/DocsKitTests/TransportSupplierTests.swift
new file mode 100644
index 0000000..69dc031
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/TransportSupplierTests.swift
@@ -0,0 +1,79 @@
+import Foundation
+import RastrilloApple
+import RastrilloTestSupport
+import XCTest
+@testable import DocsKit
+
+/// Stands in for NativeConnection: which transport the account has right now.
+@MainActor private final class Session {
+ var current: NativeTransport?
+ init(_ current: NativeTransport?) { self.current = current }
+}
+
+private func list(_ titles: [String]) -> Data {
+ let documents = titles.enumerated().map { #"{"sqid":"d\#($0.offset)","title":"\#($0.element)"}"# }
+ return Data(#"{"documents":[\#(documents.joined(separator: ","))],"can_create":true}"#.utf8)
+}
+
+/// A server for one writable, empty document: its stream stays open without
+/// events, and every update is accepted. Answers by request, since the model's
+/// stream and saves race.
+private func documentServer() -> ScriptedTransport {
+ ScriptedTransport { call in
+ switch (call.kind, call.method, call.path) {
+ case (.request, "GET", "/d/doc"):
+ return .respond(status: 200, body: Data(#"{"sqid":"doc","title":"Doc","guid":"doc-guid","can_write":true,"can_share":false}"#.utf8))
+ case (.request, "GET", "/d/doc/updates"):
+ return .respond(status: 200, headers: ["Docs-Seq": "0"])
+ case (.stream, _, "/d/doc/stream"):
+ return .hang
+ case (.request, "POST", "/d/doc/updates"):
+ return .respond(status: 204)
+ default:
+ return nil
+ }
+ }
+}
+
+final class TransportSupplierTests: XCTestCase {
+ @MainActor func testEachRequestUsesTheSessionsCurrentTransport() async {
+ let first = ScriptedTransport([.respond(status: 200, body: list(["Before"]))])
+ let replacement = ScriptedTransport([.respond(status: 200, body: list(["After", "Signing in again"]))])
+ let session = Session(first)
+ let model = DocsModel(transport: { session.current })
+ await model.load()
+ XCTAssertEqual(model.documents.map(\.title), ["Before"])
+ session.current = replacement
+ await model.load()
+ XCTAssertEqual(model.listState, .loaded)
+ XCTAssertEqual(model.documents.map(\.title), ["After", "Signing in again"])
+ XCTAssertEqual(first.calls.count, 1, "The model kept using the transport it was created with")
+ XCTAssertEqual(replacement.calls.count, 1)
+ }
+
+ /// The case the supplier exists for: an edit made while one session
+ /// is in place is sent with whichever session is current when it is sent.
+ @MainActor func testUnsentEditGoesOutOnTheReplacementTransport() async throws {
+ let ended = documentServer()
+ let session = Session(ended)
+ let model = DocsModel(transport: { session.current })
+ await model.open("doc")
+ XCTAssertEqual(model.detail?.sqid, "doc")
+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))
+ // Opening an empty document inserts its first paragraph and saves it.
+ while model.hasUnsavedChanges && .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
+ XCTAssertFalse(model.hasUnsavedChanges)
+ let sentBefore = ended.committed.filter { $0.method == "POST" }.count
+
+ let replacement = documentServer()
+ session.current = replacement
+ model.didRender(model.projectionGeneration)
+ XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Hello")]))
+ while model.hasUnsavedChanges && .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
+ XCTAssertFalse(model.hasUnsavedChanges, "The edit was never acknowledged")
+
+ XCTAssertEqual(ended.committed.filter { $0.method == "POST" }.count, sentBefore, "The edit went out on the ended session")
+ XCTAssertEqual(replacement.committed.map(\.path), ["/d/doc/updates"])
+ await model.discardAll()
+ }
+}
diff --git a/native/ios/project.yml b/native/ios/project.yml
index 12b17bc..3d7fd8f 100644
--- a/native/ios/project.yml
+++ b/native/ios/project.yml
@@ -8,7 +8,7 @@ packages:
path: ../apple
RastrilloNative:
url: https://amadan.net/rastrillo/native
- revision: 2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67
+ revision: d9dac7226ade1f3743f4742ed7f4021cd0918ac3
settings:
base:
SWIFT_VERSION: '6.0'
diff --git a/native/macos/project.yml b/native/macos/project.yml
index 2ce2237..0f023e7 100644
--- a/native/macos/project.yml
+++ b/native/macos/project.yml
@@ -7,7 +7,7 @@ packages:
path: ../apple
RastrilloNative:
url: https://amadan.net/rastrillo/native
- revision: 2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67
+ revision: d9dac7226ade1f3743f4742ed7f4021cd0918ac3
settings:
base:
SWIFT_VERSION: '6.0'
diff --git a/native/smoke/document-window/Package.resolved b/native/smoke/document-window/Package.resolved
index 7ebafdc..589dc8e 100644
--- a/native/smoke/document-window/Package.resolved
+++ b/native/smoke/document-window/Package.resolved
@@ -6,7 +6,7 @@
"kind" : "remoteSourceControl",
"location" : "https://amadan.net/rastrillo/native",
"state" : {
- "revision" : "2a5d07b2c8d3dfb3fd8526dc7e1c802f97865c67"
+ "revision" : "d9dac7226ade1f3743f4742ed7f4021cd0918ac3"
}
},
{