Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteCore/Notifications.swift10// Module : ClaudeRemoteCore11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteAPI89import ClaudeRemoteModels90import Foundation91import Observation92@preconcurrency import UserNotifications9394/// What a local notification shows. Built only from the server notification's own fields95/// (generic title, optional body chosen by the user's detail setting) — never terminal content.96public struct LocalNotificationContent: Hashable, Sendable {97 public var identifier: String98 public var title: String99 public var body: String100 /// Groups notifications of the same kind.101 public var threadIdentifier: String102 public var timeSensitive: Bool103 /// `["cr": ["kind", "link", "notificationId"]]`, same shape as the APNs payload.104 public var kind: String105 public var link: String?106107 public init(_ notification: ServerNotification) {108 identifier = notification.id109 title = notification.title110 body = notification.body111 threadIdentifier = notification.kind.rawValue112 timeSensitive = notification.kind == .sessionWaiting113 kind = notification.kind.rawValue114 link = notification.link115 }116117 public var userInfo: [String: Any] {118 var cr: [String: Any] = ["kind": kind, "notificationId": identifier]119 if let link { cr["link"] = link }120 return ["cr": cr]121 }122}123124/// The part of `UNUserNotificationCenter` used here, abstracted for tests.125public protocol UserNotificationPosting: Sendable {126 func authorizationGranted() async -> Bool127 func requestAuthorization() async -> Bool128 func post(_ content: LocalNotificationContent) async129 func remove(identifiers: [String]) async130 func setBadge(_ count: Int) async131}132133public struct SystemUserNotifications: UserNotificationPosting {134 public init() {}135 private var center: UNUserNotificationCenter { .current() }136137 public func authorizationGranted() async -> Bool {138 let status = await center.notificationSettings().authorizationStatus139 return status == .authorized || status == .provisional140 }141142 public func requestAuthorization() async -> Bool {143 (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false144 }145146 public func post(_ content: LocalNotificationContent) async {147 let c = UNMutableNotificationContent()148 c.title = content.title149 c.body = content.body150 c.sound = .default151 c.threadIdentifier = content.threadIdentifier152 // Category `cr.<kind>`: apps may register actions for it (unregistered categories are ignored by the system).153 c.categoryIdentifier = "cr." + content.kind154 c.userInfo = content.userInfo155 if content.timeSensitive { c.interruptionLevel = .timeSensitive }156 // Same identifier as the server notification: a push for the same event replaces it.157 try? await center.add(UNNotificationRequest(identifier: content.identifier, content: c, trigger: nil))158 }159160 public func remove(identifiers: [String]) async {161 center.removeDeliveredNotifications(withIdentifiers: identifiers)162 }163164 public func setBadge(_ count: Int) async {165 try? await center.setBadgeCount(count)166 }167}168169/// Turns live `ServerEvent.notification`s into local notifications while the app is connected170/// (the server also pushes through APNs when configured; identifiers match, so nothing doubles).171@MainActor172public final class LocalNotifier {173 private let center: any UserNotificationPosting174 /// User's in-app notification switch (`UserSettings.notifications.inApp`).175 public var isEnabled = true176 /// Return false to skip one (e.g. the session being looked at right now).177 public var shouldPost: (@MainActor (ServerNotification) -> Bool)?178179 public init(center: any UserNotificationPosting = SystemUserNotifications()) { self.center = center }180181 @discardableResult182 public func requestAuthorization() async -> Bool { await center.requestAuthorization() }183 public func isAuthorized() async -> Bool { await center.authorizationGranted() }184185 public func post(_ notification: ServerNotification) async {186 guard isEnabled, notification.isUnread, shouldPost?(notification) ?? true else { return }187 guard await center.authorizationGranted() else { return }188 await center.post(LocalNotificationContent(notification))189 }190191 public func clear(ids: [String]) async { await center.remove(identifiers: ids) }192 public func setBadge(_ count: Int) async { await center.setBadge(count) }193}194195/// APNs registration plumbing: the app delegate hands the device token here.196///197/// func application(_:didRegisterForRemoteNotificationsWithDeviceToken token: Data) {198/// Task { await session.push.register(deviceToken: token) }199/// }200@MainActor201@Observable202public final class PushRegistrar {203 public enum Status: Hashable, Sendable {204 case notRegistered205 /// Registered; `serverConfigured == false` means the server has no APNs key (nothing is pushed).206 case registered(serverConfigured: Bool)207 case failed(APIError)208 }209210 public private(set) var status: Status = .notRegistered211 @ObservationIgnored private let client: APIClient212 @ObservationIgnored private let topic: String213 @ObservationIgnored private let environment: APNsEnvironment214 @ObservationIgnored private var lastToken: Data?215216 /// - Parameters:217 /// - topic: bundle identifier of the running build (`profile.pushTopic(debug:)`).218 /// - environment: `.sandbox` for development-signed builds, `.production` for TestFlight / App Store / Developer ID.219 public init(client: APIClient, topic: String, environment: APNsEnvironment) {220 self.client = client221 self.topic = topic222 self.environment = environment223 }224225 /// Sends the token to the server (`PUT /native/push`). Safe to call at every launch.226 public func register(deviceToken: Data) async {227 lastToken = deviceToken228 do {229 let result = try await client.registerPush(PushRegistration(deviceToken: deviceToken, environment: environment, topic: topic))230 status = .registered(serverConfigured: result.configured)231 } catch {232 status = .failed(APIError.wrap(error))233 }234 }235236 /// After sign-in: re-sends the token received earlier in this launch, if any.237 public func registerPendingToken() async {238 if let lastToken { await register(deviceToken: lastToken) }239 }240241 /// `DELETE /native/push` (user turned push off). Sign-out drops the token server-side by itself.242 public func unregister() async {243 try? await client.unregisterPush()244 status = .notRegistered245 }246247 func reset() { status = .notRegistered }248}249