| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import Combine |
| 4 | import Foundation |
| 5 | import Observation |
| 6 | import Synchronization |
| 7 | import SwiftUI |
| 8 | import XCTest |
| 9 | import RastrilloApple |
| 10 | import RastrilloTestSupport |
| 11 | @testable import DocsKit |
| 12 | @testable import DocsMac |
| 13 | |
| 14 | /// Launching with a saved account (Docs 0.1.7/0.1.8, fixed in 84d1008): the |
| 15 | /// window's body built a workspace whose init read and then changed state |
| 16 | /// the body watched, so every pass invalidated the next and the main thread |
| 17 | /// never came back, but only for someone already signed in. A clean launch |
| 18 | /// never shows it. These host Docs' real home window with an Oficina ID |
| 19 | /// already on the device, so Docs goes straight in, let it settle, and check |
| 20 | /// that it stops changing. |
| 21 | @MainActor final class SignedInLaunchTests: XCTestCase { |
| 22 | /// `.invalid`, so the workspace's first requests fail at once. |
| 23 | static let docsOrigin = URL(string: "https://paulca.docs.invalid")! |
| 24 | static let sheetsOrigin = URL(string: "https://paulca.sheets.invalid")! |
| 25 | |
| 26 | private var account: String? |
| 27 | |
| 28 | override func tearDown() async throws { |
| 29 | if let account { DocsOfflineAccount.accounts[account] = nil } |
| 30 | UserDefaults.standard.removeObject(forKey: DocsSignInRoute.key) |
| 31 | } |
| 32 | |
| 33 | /// An Oficina ID Sheets saved on this device, and Docs' session after |
| 34 | /// going straight in with it. The account's offline store is in memory, |
| 35 | /// registered before the window exists: a known account is the path |
| 36 | /// that hung. |
| 37 | private func signedInSession() async throws -> DocsOficinaSession { |
| 38 | let service = FakeOficinaIDService() |
| 39 | let shared = OficinaMemoryStore(), notifier = OficinaLocalNotifier() |
| 40 | let group = UserDefaults(suiteName: "DocsSignedInLaunchTests.\(UUID().uuidString)")! |
| 41 | func model(_ slug: String, _ name: String) -> OficinaIDModel { |
| 42 | OficinaIDModel(configuration: OficinaIDConfiguration(app: slug, appName: name, platform: "macos"), |
| 43 | store: OficinaIDStore(shared: shared, appPrivate: OficinaMemoryStore(), group: group, notifier: notifier), |
| 44 | service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, |
| 45 | appDefaults: UserDefaults(suiteName: "DocsSignedInLaunchTests.\(UUID().uuidString)")!) |
| 46 | } |
| 47 | let team = OficinaTeam(sqid: "t1", label: "paulca", name: "Paul", role: "member", |
| 48 | apps: [OficinaTeamApp(app: "docs", origin: Self.docsOrigin.absoluteString, consumerID: "t1-docs"), |
| 49 | OficinaTeamApp(app: "sheets", origin: Self.sheetsOrigin.absoluteString, consumerID: "t1-sheets")]) |
| 50 | service.addPerson(email: "paul@tito.io", identityID: "id-1") |
| 51 | service.setTeams([team], for: "id-1") |
| 52 | service.admit("id-1", at: Self.docsOrigin, as: .linked) |
| 53 | service.admit("id-1", at: Self.sheetsOrigin, as: .linked) |
| 54 | let sheets = model("sheets", "Sheets") |
| 55 | await sheets.start() |
| 56 | sheets.continueWithEmail() |
| 57 | sheets.email = "paul@tito.io" |
| 58 | await sheets.submitEmail() |
| 59 | sheets.code = FakeOficinaIDService.goodCode |
| 60 | await sheets.submitCode() |
| 61 | let docs = DocsOficinaSession(model: model("docs", "Docs")) |
| 62 | await docs.start() |
| 63 | // Failing, not skipping: a skip here would hide the whole launch suite. |
| 64 | guard let mounted = docs.mounted else { |
| 65 | XCTFail("Docs did not go straight in: \(docs.model.step); Sheets is \(sheets.step)") |
| 66 | throw CancellationError() |
| 67 | } |
| 68 | let account = DocsOficinaSession.accountID(mounted) |
| 69 | self.account = account |
| 70 | DocsOfflineAccount.accounts[account] = DocsOfflineAccount( |
| 71 | store: EphemeralDocsStore(), accountID: account, |
| 72 | connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: docs.transport(for: account)) |
| 73 | UserDefaults.standard.removeObject(forKey: DocsSignInRoute.key) |
| 74 | return docs |
| 75 | } |
| 76 | |
| 77 | func testTheSignedInHomeWindowSettlesWithASavedIdentity() async throws { |
| 78 | let docs = try await signedInSession() |
| 79 | let mounted = try XCTUnwrap(docs.mounted) |
| 80 | let windows = DocsWindows() |
| 81 | |
| 82 | // If the window loops, the main thread never returns here; say why |
| 83 | // rather than hang the run. |
| 84 | let finished = Mutex(false) |
| 85 | DispatchQueue.global().asyncAfter(deadline: .now() + 60) { |
| 86 | if !finished.withLock({ $0 }) { |
| 87 | fatalError("Docs' signed-in home window never let the main thread go: a view loop (84d1008)") |
| 88 | } |
| 89 | } |
| 90 | let host = NSHostingView(rootView: DocsAccountWindow(oficina: docs, windows: windows)) |
| 91 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 760), styleMask: [.titled, .resizable], |
| 92 | backing: .buffered, defer: false) |
| 93 | window.contentView = host |
| 94 | window.orderFrontRegardless() |
| 95 | defer { window.orderOut(nil); window.contentView = nil } |
| 96 | |
| 97 | func pump(_ seconds: Double) async { |
| 98 | let end = Date().addingTimeInterval(seconds) |
| 99 | while Date() < end { |
| 100 | host.layoutSubtreeIfNeeded() |
| 101 | try? await Task.sleep(nanoseconds: 20_000_000) |
| 102 | } |
| 103 | } |
| 104 | // Launch: the body runs, its .task and .onChange(initial:) fire, the |
| 105 | // workspace's first request fails at once (.invalid). |
| 106 | await pump(1.5) |
| 107 | XCTAssertEqual(windows.activeAccount, DocsOficinaSession.accountID(mounted), "the signed-in workspace is what showed") |
| 108 | XCTAssertFalse(docs.model.straightInSuspended, "the Oficina ID route does not suspend straight in") |
| 109 | |
| 110 | // Settled: nothing the window watches keeps changing. |
| 111 | var published = 0 |
| 112 | let watches = [docs.objectWillChange.sink { _ in published += 1 }, docs.model.objectWillChange.sink { _ in published += 1 }] |
| 113 | let invalidated = Mutex(0) |
| 114 | withObservationTracking { |
| 115 | _ = windows.activeAccount |
| 116 | _ = windows.entries |
| 117 | _ = windows.accountsRequested |
| 118 | _ = windows.settingsAccount |
| 119 | _ = windows.settingsIdentity |
| 120 | } onChange: { invalidated.withLock { $0 += 1 } } |
| 121 | await pump(1.0) |
| 122 | watches.forEach { $0.cancel() } |
| 123 | finished.withLock { $0 = true } |
| 124 | XCTAssertEqual(published, 0, "the session and model stay still once the window has settled") |
| 125 | XCTAssertEqual(invalidated.withLock { $0 }, 0, "the window state it writes stays still once settled") |
| 126 | XCTAssertEqual(docs.mounted, mounted, "still signed in to the same team") |
| 127 | } |
| 128 | |
| 129 | /// The subtitle's team comes from the identity's own record for each |
| 130 | /// document window, not from the home window having appeared (Fable on |
| 131 | /// #169, finding 9). |
| 132 | func testADocumentWindowsTeamNameIsDerivedFromItsAccount() async throws { |
| 133 | let docs = try await signedInSession() |
| 134 | let mounted = try XCTUnwrap(docs.mounted) |
| 135 | let account = DocsOficinaSession.accountID(mounted) |
| 136 | let windows = DocsWindows() |
| 137 | XCTAssertTrue(windows.teamNames.isEmpty, "no home window has appeared") |
| 138 | XCTAssertEqual(DocsDocumentWindow.team(for: account, oficina: docs, windows: windows), "Paul") |
| 139 | let other = DocsOficinaSession.accountID(identity: mounted.identity.id, team: "unknown-team") |
| 140 | XCTAssertNil(DocsDocumentWindow.team(for: other, oficina: docs, windows: windows), "a team never seen: the state alone") |
| 141 | let server = UUID().uuidString |
| 142 | windows.teamNames[server] = "Tito's server" |
| 143 | XCTAssertEqual(DocsDocumentWindow.team(for: server, oficina: docs, windows: windows), "Tito's server") |
| 144 | } |
| 145 | |
| 146 | /// Docs' real home window, shown, with a way to let it run. |
| 147 | private func show(_ docs: DocsOficinaSession, _ windows: DocsWindows) -> (window: NSWindow, pump: (Double) async -> Void) { |
| 148 | let host = NSHostingView(rootView: DocsAccountWindow(oficina: docs, windows: windows)) |
| 149 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 760), styleMask: [.titled, .resizable], |
| 150 | backing: .buffered, defer: false) |
| 151 | window.contentView = host |
| 152 | window.orderFrontRegardless() |
| 153 | return (window, { seconds in |
| 154 | let end = Date().addingTimeInterval(seconds) |
| 155 | while Date() < end { |
| 156 | host.layoutSubtreeIfNeeded() |
| 157 | try? await Task.sleep(nanoseconds: 20_000_000) |
| 158 | } |
| 159 | }) |
| 160 | } |
| 161 | |
| 162 | /// #130, finding 2: while the kit asks to replace the identity, File ▸ |
| 163 | /// Recent or ⌘N can still open one of its documents. The question is |
| 164 | /// withdrawn, so confirming can't sign the identity out under it. |
| 165 | func testADocumentWindowOpeningWithdrawsTheReplaceQuestion() async throws { |
| 166 | let docs = try await signedInSession() |
| 167 | let mounted = try XCTUnwrap(docs.mounted) |
| 168 | let windows = DocsWindows() |
| 169 | let (window, pump) = show(docs, windows) |
| 170 | defer { window.orderOut(nil); window.contentView = nil } |
| 171 | await pump(1.0) |
| 172 | |
| 173 | docs.model.useAnother() |
| 174 | await pump(0.3) |
| 175 | XCTAssertTrue(docs.model.confirmingReplace, "nothing stops the question yet") |
| 176 | _ = windows.reserve(account: DocsOficinaSession.accountID(mounted), document: "k", title: "Notes", client: mounted.client()) |
| 177 | await pump(0.5) |
| 178 | XCTAssertFalse(docs.model.confirmingReplace, "a document window of the identity opened: the question is withdrawn") |
| 179 | XCTAssertEqual(docs.model.identity?.id, mounted.identity.id) |
| 180 | XCTAssertEqual(docs.mounted, mounted, "still signed in") |
| 181 | } |
| 182 | |
| 183 | /// The backstop for a question asked with changes unsent (Fable on #130, |
| 184 | /// finding 6): however the confirmation went up, the window withdraws it. |
| 185 | func testTheReplaceQuestionIsWithdrawnWithChangesUnsent() async throws { |
| 186 | let docs = try await signedInSession() |
| 187 | let mounted = try XCTUnwrap(docs.mounted) |
| 188 | let offline = try XCTUnwrap(DocsOfflineAccount.accounts[DocsOficinaSession.accountID(mounted)]) |
| 189 | try await offline.outbox.enqueue(lane: "doc:k", kind: "update", payload: Data([1])) |
| 190 | let windows = DocsWindows() |
| 191 | let (window, pump) = show(docs, windows) |
| 192 | defer { window.orderOut(nil); window.contentView = nil } |
| 193 | await pump(1.0) |
| 194 | |
| 195 | docs.model.useAnother() |
| 196 | await pump(0.5) |
| 197 | XCTAssertFalse(docs.model.confirmingReplace, "changes are unsent: the question is withdrawn") |
| 198 | XCTAssertEqual(docs.mounted, mounted, "still signed in") |
| 199 | } |
| 200 | |
| 201 | /// The window's body itself, evaluated as SwiftUI would, three times |
| 202 | /// over, under observation: building it must change nothing it watches. |
| 203 | func testBuildingTheSignedInWindowBodyChangesNothingItWatches() async throws { |
| 204 | let docs = try await signedInSession() |
| 205 | let windows = DocsWindows() |
| 206 | var published = 0 |
| 207 | let watches = [docs.objectWillChange.sink { _ in published += 1 }, docs.model.objectWillChange.sink { _ in published += 1 }] |
| 208 | let changed = Mutex(false) |
| 209 | let view = DocsAccountWindow(oficina: docs, windows: windows) |
| 210 | withObservationTracking { |
| 211 | _ = windows.activeAccount |
| 212 | _ = windows.entries |
| 213 | _ = windows.transports.count |
| 214 | _ = view.body |
| 215 | } onChange: { changed.withLock { $0 = true } } |
| 216 | for _ in 0..<3 { _ = view.body } |
| 217 | watches.forEach { $0.cancel() } |
| 218 | XCTAssertFalse(changed.withLock { $0 }, "a body pass must not invalidate the next") |
| 219 | XCTAssertEqual(published, 0) |
| 220 | } |
| 221 | } |
| 222 | #endif |
| 223 | |