#if os(macOS) import AppKit import Combine import Foundation import Observation import Synchronization import SwiftUI import XCTest import RastrilloApple import RastrilloTestSupport @testable import DocsKit @testable import DocsMac /// Launching with a saved account (Docs 0.1.7/0.1.8, fixed in 84d1008): the /// window's body built a workspace whose init read and then changed state /// the body watched, so every pass invalidated the next and the main thread /// never came back, but only for someone already signed in. A clean launch /// never shows it. These host Docs' real home window with an Oficina ID /// already on the device, so Docs goes straight in, let it settle, and check /// that it stops changing. @MainActor final class SignedInLaunchTests: XCTestCase { /// `.invalid`, so the workspace's first requests fail at once. static let docsOrigin = URL(string: "https://paulca.docs.invalid")! static let sheetsOrigin = URL(string: "https://paulca.sheets.invalid")! private var account: String? override func tearDown() async throws { if let account { DocsOfflineAccount.accounts[account] = nil } UserDefaults.standard.removeObject(forKey: DocsSignInRoute.key) } /// An Oficina ID Sheets saved on this device, and Docs' session after /// going straight in with it. The account's offline store is in memory, /// registered before the window exists: a known account is the path /// that hung. private func signedInSession() async throws -> DocsOficinaSession { let service = FakeOficinaIDService() let shared = OficinaMemoryStore(), notifier = OficinaLocalNotifier() let group = UserDefaults(suiteName: "DocsSignedInLaunchTests.\(UUID().uuidString)")! func model(_ slug: String, _ name: String) -> OficinaIDModel { OficinaIDModel(configuration: OficinaIDConfiguration(app: slug, appName: name, platform: "macos"), store: OficinaIDStore(shared: shared, appPrivate: OficinaMemoryStore(), group: group, notifier: notifier), service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, appDefaults: UserDefaults(suiteName: "DocsSignedInLaunchTests.\(UUID().uuidString)")!) } let team = OficinaTeam(sqid: "t1", label: "paulca", name: "Paul", role: "member", apps: [OficinaTeamApp(app: "docs", origin: Self.docsOrigin.absoluteString, consumerID: "t1-docs"), OficinaTeamApp(app: "sheets", origin: Self.sheetsOrigin.absoluteString, consumerID: "t1-sheets")]) service.addPerson(email: "paul@tito.io", identityID: "id-1") service.setTeams([team], for: "id-1") service.admit("id-1", at: Self.docsOrigin, as: .linked) service.admit("id-1", at: Self.sheetsOrigin, as: .linked) let sheets = model("sheets", "Sheets") await sheets.start() sheets.continueWithEmail() sheets.email = "paul@tito.io" await sheets.submitEmail() sheets.code = FakeOficinaIDService.goodCode await sheets.submitCode() let docs = DocsOficinaSession(model: model("docs", "Docs")) await docs.start() // Failing, not skipping: a skip here would hide the whole launch suite. guard let mounted = docs.mounted else { XCTFail("Docs did not go straight in: \(docs.model.step); Sheets is \(sheets.step)") throw CancellationError() } let account = DocsOficinaSession.accountID(mounted) self.account = account DocsOfflineAccount.accounts[account] = DocsOfflineAccount( store: EphemeralDocsStore(), accountID: account, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: docs.transport(for: account)) UserDefaults.standard.removeObject(forKey: DocsSignInRoute.key) return docs } func testTheSignedInHomeWindowSettlesWithASavedIdentity() async throws { let docs = try await signedInSession() let mounted = try XCTUnwrap(docs.mounted) let windows = DocsWindows() // If the window loops, the main thread never returns here; say why // rather than hang the run. let finished = Mutex(false) DispatchQueue.global().asyncAfter(deadline: .now() + 60) { if !finished.withLock({ $0 }) { fatalError("Docs' signed-in home window never let the main thread go: a view loop (84d1008)") } } let host = NSHostingView(rootView: DocsAccountWindow(oficina: docs, windows: windows)) let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 760), styleMask: [.titled, .resizable], backing: .buffered, defer: false) window.contentView = host window.orderFrontRegardless() defer { window.orderOut(nil); window.contentView = nil } func pump(_ seconds: Double) async { let end = Date().addingTimeInterval(seconds) while Date() < end { host.layoutSubtreeIfNeeded() try? await Task.sleep(nanoseconds: 20_000_000) } } // Launch: the body runs, its .task and .onChange(initial:) fire, the // workspace's first request fails at once (.invalid). await pump(1.5) XCTAssertEqual(windows.activeAccount, DocsOficinaSession.accountID(mounted), "the signed-in workspace is what showed") XCTAssertFalse(docs.model.straightInSuspended, "the Oficina ID route does not suspend straight in") // Settled: nothing the window watches keeps changing. var published = 0 let watches = [docs.objectWillChange.sink { _ in published += 1 }, docs.model.objectWillChange.sink { _ in published += 1 }] let invalidated = Mutex(0) withObservationTracking { _ = windows.activeAccount _ = windows.entries _ = windows.accountsRequested _ = windows.settingsAccount _ = windows.settingsIdentity } onChange: { invalidated.withLock { $0 += 1 } } await pump(1.0) watches.forEach { $0.cancel() } finished.withLock { $0 = true } XCTAssertEqual(published, 0, "the session and model stay still once the window has settled") XCTAssertEqual(invalidated.withLock { $0 }, 0, "the window state it writes stays still once settled") XCTAssertEqual(docs.mounted, mounted, "still signed in to the same team") } /// The subtitle's team comes from the identity's own record for each /// document window, not from the home window having appeared (Fable on /// #169, finding 9). func testADocumentWindowsTeamNameIsDerivedFromItsAccount() async throws { let docs = try await signedInSession() let mounted = try XCTUnwrap(docs.mounted) let account = DocsOficinaSession.accountID(mounted) let windows = DocsWindows() XCTAssertTrue(windows.teamNames.isEmpty, "no home window has appeared") XCTAssertEqual(DocsDocumentWindow.team(for: account, oficina: docs, windows: windows), "Paul") let other = DocsOficinaSession.accountID(identity: mounted.identity.id, team: "unknown-team") XCTAssertNil(DocsDocumentWindow.team(for: other, oficina: docs, windows: windows), "a team never seen: the state alone") let server = UUID().uuidString windows.teamNames[server] = "Tito's server" XCTAssertEqual(DocsDocumentWindow.team(for: server, oficina: docs, windows: windows), "Tito's server") } /// Docs' real home window, shown, with a way to let it run. private func show(_ docs: DocsOficinaSession, _ windows: DocsWindows) -> (window: NSWindow, pump: (Double) async -> Void) { let host = NSHostingView(rootView: DocsAccountWindow(oficina: docs, windows: windows)) let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 760), styleMask: [.titled, .resizable], backing: .buffered, defer: false) window.contentView = host window.orderFrontRegardless() return (window, { seconds in let end = Date().addingTimeInterval(seconds) while Date() < end { host.layoutSubtreeIfNeeded() try? await Task.sleep(nanoseconds: 20_000_000) } }) } /// #130, finding 2: while the kit asks to replace the identity, File ▸ /// Recent or ⌘N can still open one of its documents. The question is /// withdrawn, so confirming can't sign the identity out under it. func testADocumentWindowOpeningWithdrawsTheReplaceQuestion() async throws { let docs = try await signedInSession() let mounted = try XCTUnwrap(docs.mounted) let windows = DocsWindows() let (window, pump) = show(docs, windows) defer { window.orderOut(nil); window.contentView = nil } await pump(1.0) docs.model.useAnother() await pump(0.3) XCTAssertTrue(docs.model.confirmingReplace, "nothing stops the question yet") _ = windows.reserve(account: DocsOficinaSession.accountID(mounted), document: "k", title: "Notes", client: mounted.client()) await pump(0.5) XCTAssertFalse(docs.model.confirmingReplace, "a document window of the identity opened: the question is withdrawn") XCTAssertEqual(docs.model.identity?.id, mounted.identity.id) XCTAssertEqual(docs.mounted, mounted, "still signed in") } /// The backstop for a question asked with changes unsent (Fable on #130, /// finding 6): however the confirmation went up, the window withdraws it. func testTheReplaceQuestionIsWithdrawnWithChangesUnsent() async throws { let docs = try await signedInSession() let mounted = try XCTUnwrap(docs.mounted) let offline = try XCTUnwrap(DocsOfflineAccount.accounts[DocsOficinaSession.accountID(mounted)]) try await offline.outbox.enqueue(lane: "doc:k", kind: "update", payload: Data([1])) let windows = DocsWindows() let (window, pump) = show(docs, windows) defer { window.orderOut(nil); window.contentView = nil } await pump(1.0) docs.model.useAnother() await pump(0.5) XCTAssertFalse(docs.model.confirmingReplace, "changes are unsent: the question is withdrawn") XCTAssertEqual(docs.mounted, mounted, "still signed in") } /// The window's body itself, evaluated as SwiftUI would, three times /// over, under observation: building it must change nothing it watches. func testBuildingTheSignedInWindowBodyChangesNothingItWatches() async throws { let docs = try await signedInSession() let windows = DocsWindows() var published = 0 let watches = [docs.objectWillChange.sink { _ in published += 1 }, docs.model.objectWillChange.sink { _ in published += 1 }] let changed = Mutex(false) let view = DocsAccountWindow(oficina: docs, windows: windows) withObservationTracking { _ = windows.activeAccount _ = windows.entries _ = windows.transports.count _ = view.body } onChange: { changed.withLock { $0 = true } } for _ in 0..<3 { _ = view.body } watches.forEach { $0.cancel() } XCTAssertFalse(changed.withLock { $0 }, "a body pass must not invalidate the next") XCTAssertEqual(published, 0) } } #endif