Repository Public
1// SP Notes iOS2// File: Tests/SystemNextTests.swift3// Description: System integration added in 2.0: Home Screen Quick Actions, the task and capture intents' model paths, the4// « ask my notes » request, task due notifications (plan, identifiers, responses) and tasks in Spotlight.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import SPNotesCore10import Testing11import UserNotifications12@testable import SPNotes1314@MainActor15private func systemApp() throws -> AppModel {16 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-sysnext-\(UUID().uuidString)", isDirectory: true)17 return try AppModel(configuration: AppConfiguration(api: .production(appVersion: "tests"), dataDirectory: directory, inMemoryStore: true))18}1920@MainActor21@Suite("Actions rapides de l’écran d’accueil") struct QuickActionTests {22 @Test func everyDeclaredShortcutItemHasAnActionAndALinkTheAppUnderstands() throws {23 let items = try #require(Bundle.main.object(forInfoDictionaryKey: "UIApplicationShortcutItems") as? [[String: Any]])24 let types = items.compactMap { $0["UIApplicationShortcutItemType"] as? String }25 #expect(types.count == 4)26 #expect(Set(types) == Set(QuickAction.allCases.map(\.rawValue)))27 for action in QuickAction.allCases {28 #expect(DeepLink(url: action.url) != nil, "\(action) → \(action.url) is not a link of the app")29 }30 #expect(QuickAction(type: "com.example.other") == nil)31 }3233 @Test func anActionBecomesARouteOfTheApp() throws {34 let app = try systemApp()35 #expect(QuickAction.perform(type: QuickAction.search.rawValue, on: app))36 #expect(app.pendingRoute == .search(""))37 #expect(QuickAction.perform(type: QuickAction.dictation.rawValue, on: app))38 #expect(!QuickAction.perform(type: "unknown", on: app))39 #expect(!QuickAction.perform(type: QuickAction.capture.rawValue, on: nil))40 #expect(DeepLink(url: QuickAction.dictation.url) == .capture(kind: .dictation))41 #expect(DeepLink(url: QuickAction.capture.url) == .capture(kind: nil))42 }43}4445@MainActor46@Suite("Intents 2.0 — tâches, capture, demander") struct TaskIntentModelTests {47 @Test func aTaskIsCreatedOfflineWithABareDayOrAnInstant() async throws {48 let app = try systemApp()49 var calendar = Calendar(identifier: .gregorian)50 calendar.timeZone = TimeZone(identifier: "America/Toronto")!51 let midnight = calendar.date(from: DateComponents(year: 2026, month: 11, day: 21))!52 let bare = try await app.createTask(title: "Payer le loyer", due: midnight, priority: .high, calendar: calendar)53 #expect(bare.priority == "high")54 #expect(TaskDueRule.isBareDay(try #require(bare.dueAt)))55 #expect(calendar.component(.day, from: TaskDueRule.localDay(try #require(bare.dueAt), calendar: calendar)) == 21)56 let timed = try await app.createTask(title: "Appel", due: midnight.addingTimeInterval(15 * 3600 + 60), calendar: calendar)57 #expect(timed.dueAt == midnight.addingTimeInterval(15 * 3600 + 60))58 let none = try await app.createTask(title: "Sans date", due: nil)59 #expect(none.dueAt == nil)60 let open = try await app.repositories.tasks.list(.open)61 #expect(Set(open.map(\.title)) == ["Payer le loyer", "Appel", "Sans date"])62 #expect(try await app.repositories.tasks.isPending(id: bare.id), "created without a server: waits in the outbox")63 }6465 @Test func aCaptureFromShortcutsLandsInTheInbox() async throws {66 let app = try systemApp()67 let id = try await app.capture(CaptureDraft(kind: CaptureKindName.note, text: "Idée dictée à Siri"))68 let page = try #require(try await app.store.page(id: id))69 #expect(page.inboxAt != nil)70 #expect(try await app.noteEntity(id: id).id == id)71 }7273 @Test func askingKeepsTheQuestionForTheAssistantAndNeverAnswersItself() throws {74 let app = try systemApp()75 let url = AskRequests.url(for: "Où en est le budget ?")76 #expect(url.scheme == "spnotes" && url.host == "ask")77 #expect(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first?.value == "Où en est le budget ?")78 let requests = AskRequests()79 let routed = requests.ask(" Où en est le budget ? ", app: app)80 #expect(routed || requests.pending?.question == "Où en est le budget ?")81 }82}8384@Suite("Notifications d’échéance des tâches") struct TaskNotificationTests {85 private var toronto: Calendar { var c = Calendar(identifier: .gregorian); c.timeZone = TimeZone(identifier: "America/Toronto")!; return c }86 private func date(_ text: String) -> Date { ISO8601DateFormatter().date(from: text)! }8788 @Test func thePlanKeepsTheNearestOpenTasksAndLeavesRoomForReminders() {89 let now = date("2026-11-19T15:00:00Z")90 var tasks: [WidgetTask] = (1...60).map { WidgetTask(id: "t\($0)", title: "Tâche \($0)", dueAt: now.addingTimeInterval(Double($0) * 3600)) }91 tasks.append(WidgetTask(id: "past", title: "Passée", dueAt: now.addingTimeInterval(-3600)))92 tasks.append(WidgetTask(id: "nodue", title: "Sans date"))93 tasks.append(WidgetTask(id: "rem", title: "Rappel 1.0", dueAt: now.addingTimeInterval(60)))94 let capacity = TaskNotificationPlan.capacity(otherPending: 10)95 #expect(capacity == 40)96 #expect(TaskNotificationPlan.capacity(otherPending: 60) == 4)97 #expect(TaskNotificationPlan.capacity(otherPending: 80) == 0)98 let plan = TaskNotificationPlan.plan(tasks: tasks, reminderTaskIds: ["rem"], now: now, calendar: toronto, capacity: capacity)99 #expect(plan.count == 40)100 #expect(plan.first?.taskId == "t1" && plan.last?.taskId == "t40")101 #expect(!plan.contains { ["past", "nodue", "rem"].contains($0.taskId) })102 }103104 @Test func aBareDayNotifiesAtNineLocalAndIdentifiersNeverCollideWithReminders() {105 let bare = date("2026-11-21T12:00:00Z")106 let fire = TaskDueRule.notificationDate(bare, calendar: toronto)107 let parts = toronto.dateComponents([.day, .hour, .minute], from: fire)108 #expect(parts.day == 21 && parts.hour == 9 && parts.minute == 0)109 let id = TaskNotificationPlan.identifier("abc")110 #expect(id == "task-abc" && TaskNotificationPlan.taskId(fromIdentifier: id) == "abc")111 #expect(TaskNotificationPlan.taskId(fromIdentifier: "reminder-abc") == nil)112 #expect(!id.hasPrefix("reminder-"))113 }114115 @Test func responsesAreReadFromTheNotificationTexts() {116 let info = [TaskNotifications.taskIdKey: "t1", TaskNotifications.pageIdKey: "0b7f6c0e-3f0a-4d5e-9b0a-111111111111", TaskNotifications.blockIdKey: "blk1"]117 #expect(TaskNotifications.response(action: TaskNotifications.completeAction, category: TaskNotifications.category, userInfo: info) == .complete(taskId: "t1"))118 if case .postpone(let id, _)? = TaskNotifications.response(action: TaskNotifications.postponeAction, category: TaskNotifications.category, userInfo: info) { #expect(id == "t1") } else { Issue.record("postpone") }119 #expect(TaskNotifications.response(action: UNNotificationDefaultActionIdentifier, category: TaskNotifications.category, userInfo: info)120 == .open(URL(string: "spnotes://note/0b7f6c0e-3f0a-4d5e-9b0a-111111111111?block=blk1")!))121 #expect(TaskNotifications.response(action: UNNotificationDismissActionIdentifier, category: TaskNotifications.category, userInfo: info) == nil)122 #expect(TaskNotifications.response(action: UNNotificationDefaultActionIdentifier, category: "other", userInfo: info) == nil, "a 1.0 reminder is not a task")123 #expect(TaskNotifications.response(action: UNNotificationDefaultActionIdentifier, category: TaskNotifications.category, userInfo: [TaskNotifications.taskIdKey: "t2"]) == .open(SystemLinks.tasks))124 }125126 @MainActor @Test func completingAndPostponingFromANotificationGoThroughTheRepository() async throws {127 let app = try systemApp()128 let center = FakeTaskCenter()129 let notifications = TaskNotifications(store: app.store, tasks: app.repositories.tasks, center: center, defaults: UserDefaults(suiteName: "tasknotif-\(UUID().uuidString)")!)130 let soon = Date().addingTimeInterval(7200)131 let a = try await app.repositories.tasks.create(title: "À terminer", dueAt: soon)132 let b = try await app.repositories.tasks.create(title: "À reporter", dueAt: soon)133 #expect(await notifications.perform(.complete(taskId: a.id)) == nil)134 #expect(try await app.repositories.tasks.task(id: a.id)?.status == "done")135 await notifications.perform(.postpone(taskId: b.id, due: soon))136 let moved = try #require(try await app.repositories.tasks.task(id: b.id)?.dueAt)137 #expect(moved > soon.addingTimeInterval(3600))138 let url = URL(string: "spnotes://tasks")!139 #expect(await notifications.perform(.open(url)) == url)140 }141}142143final class FakeTaskCenter: TaskNotificationCenter, @unchecked Sendable {144 private let lock = NSLock()145 private var pending: [String] = []146 var status: TaskNotificationAuthorization = .authorized147 func authorization() async -> TaskNotificationAuthorization { status }148 func requestAuthorization() async -> Bool { status == .authorized }149 func pendingIdentifiers() async -> [String] { lock.withLock { pending } }150 func add(_ notification: PlannedTaskNotification) async { lock.withLock { pending.append(notification.identifier) } }151 func remove(identifiers: [String]) async { lock.withLock { pending.removeAll { identifiers.contains($0) } } }152 func registerCategory() async {}153}154155@Suite("Spotlight — tâches") struct SpotlightTaskTests {156 @Test func identifiersOfTasksNeverLookLikeNoteIds() {157 let id = SpotlightTaskIndexer.identifier("0b7f6c0e-3f0a-4d5e-9b0a-111111111111")158 #expect(id.hasPrefix("task:"))159 #expect(SpotlightTaskIndexer.taskId(fromIdentifier: id) == "0b7f6c0e-3f0a-4d5e-9b0a-111111111111")160 #expect(SpotlightTaskIndexer.taskId(fromIdentifier: "0b7f6c0e-3f0a-4d5e-9b0a-111111111111") == nil)161 #expect(!DeepLink.isValidNoteID(id))162 }163}164165@MainActor166@Suite("Liens universels") struct UniversalLinkTests {167 @Test func aWebPageActivityOpensTheNoteAtItsBlock() throws {168 let app = try systemApp()169 let activity = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)170 activity.webpageURL = URL(string: "https://note.spboucher.ai/p/0b7f6c0e-3f0a-4d5e-9b0a-111111111111#blk_9")171 app.continueActivity(activity)172 #expect(app.pendingRoute == .note("0b7f6c0e-3f0a-4d5e-9b0a-111111111111", blockId: "blk_9"))173 let other = try systemApp()174 let foreign = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)175 foreign.webpageURL = URL(string: "https://example.com/p/0b7f6c0e-3f0a-4d5e-9b0a-111111111111")176 other.continueActivity(foreign)177 #expect(other.pendingRoute == nil, "only pages of note.spboucher.ai")178 }179180 @Test func theEntitlementsDeclareTheAssociatedDomain() throws {181 // the entitlements file of the app target, read from the sources (the simulator build is not provisioned)182 let file = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Resources/SPNotes.entitlements")183 let plist = try #require(try PropertyListSerialization.propertyList(from: Data(contentsOf: file), format: nil) as? [String: Any])184 let domains = try #require(plist["com.apple.developer.associated-domains"] as? [String])185 #expect(domains.contains("applinks:note.spboucher.ai") && domains.contains("webcredentials:note.spboucher.ai"))186 }187}188