Repository Public
1import AppKit2import MCCCore3import Observation4import SwiftUI56enum AppearancePreference: String, CaseIterable, Identifiable, Sendable {7 case dark, light, system8 var id: String { rawValue }9 var colorScheme: ColorScheme? {10 switch self {11 case .dark: .dark12 case .light: .light13 case .system: nil14 }15 }16 var title: String { Localization.shared.string("appearance." + rawValue) }17}1819/// Application state above the windows: the core session, navigation requests coming from outside a window20/// (menu bar extra, notifications, deep links), the pending invitation, the app lock and the notifier.21@MainActor22@Observable23final class AppModel {24 let environment: AppEnvironment25 let session: AppSession26 let lock: AppLock27 let notifier: AlertNotifier2829 /// Selection of the main window's sidebar.30 var selection: SidebarItem = .overview31 /// Global period of the charts.32 var range: API.TimeRange = ._24h33 var focus: FocusTarget?34 var invitation: InvitationSetupModel?35 var presentedError: APIError?36 var actionIntent: ActionIntent?37 /// The pending action request, seen only by the window that hosts it.38 func actionIntentBinding(host: String) -> Binding<ActionIntent?> {39 Binding(get: { self.actionIntent?.host == host ? self.actionIntent : nil },40 set: { if $0 == nil, self.actionIntent?.host == host { self.actionIntent = nil } })41 }42 var paletteVisible = false43 var quickNoteRequested = false44 var operationsCentre = false45 var appearance: AppearancePreference {46 didSet { UserDefaults.standard.set(appearance.rawValue, forKey: "mcc.appearance") }47 }48 private(set) var isSigningIn = false49 private(set) var signInError: APIError?5051 @ObservationIgnored private var openWindowAction: OpenWindowAction?52 @ObservationIgnored private var started = false5354 init(environment: AppEnvironment = .resolve()) {55 self.environment = environment56 environment.resetLocalStateIfRequested()57 Localization.shared.register(bundle: .main)58 Localization.shared.language = UserDefaults.standard.string(forKey: Localization.defaultsKey).flatMap(AppLanguage.init(rawValue:)) ?? .fr59 if let l = environment.language { Localization.shared.language = l }60 appearance = UserDefaults.standard.string(forKey: "mcc.appearance").flatMap(AppearancePreference.init(rawValue:)) ?? .dark61 let session = AppSession(configuration: environment.makeConfiguration())62 self.session = session63 lock = AppLock(disabled: environment.uiTesting)64 notifier = AlertNotifier(enabled: !environment.uiTesting)65 }6667 func start() async {68 guard !started else { return }69 started = true70 notifier.attach(to: self)71 await session.start()72 #if DEBUG73 if let token = environment.setupToken, session.phase == .signedOut { await beginInvitation(token: token) }74 #endif75 if session.phase == .signedIn { sessionBecameActive() }76 }7778 // MARK: Identity7980 func signIn() async {81 isSigningIn = true82 signInError = nil83 defer { isSigningIn = false }84 do {85 try await session.signIn()86 sessionBecameActive()87 } catch {88 let e = APIError.from(error)89 if !e.isPasskeyCancelled { signInError = e }90 }91 }9293 func signOut() async {94 await session.signOut()95 invitation = nil96 selection = .overview97 }9899 /// Starts the in-app setup of an invitation. The token goes straight to the exchange and is not kept.100 func beginInvitation(token: String) async {101 let model = InvitationSetupModel(session: session)102 invitation = model103 await model.begin(token: token)104 }105106 func finishInvitation() {107 invitation = nil108 if session.phase == .signedIn { sessionBecameActive() }109 }110111 func cancelInvitation() async {112 await invitation?.cancel()113 invitation = nil114 }115116 private func sessionBecameActive() {117 notifier.requestAuthorizationIfNeeded()118 // Language follows the account's preference at first sign-in on this Mac only if the user never chose one.119 if UserDefaults.standard.string(forKey: Localization.defaultsKey) == nil, environment.language == nil,120 let locale = session.user?.locale {121 Localization.shared.language = locale == .en ? .en : .fr122 }123 }124125 // MARK: Navigation126127 func registerOpenWindow(_ action: OpenWindowAction) { openWindowAction = action }128129 /// Shows a section of the main window, opening the window if it is closed.130 func show(_ item: SidebarItem, focus: FocusTarget? = nil) {131 selection = item132 self.focus = focus133 bringMainWindowForward()134 }135136 /// Activates the existing main window; opens one only when none is left (`openWindow(id:)` always creates a new137 /// window, which would also restore its own remembered section over the one just requested).138 private func bringMainWindowForward() {139 if let window = NSApp.windows.first(where: { $0.identifier?.rawValue.hasPrefix("main") == true && !$0.isMiniaturized }) ?? NSApp.windows.first(where: { $0.identifier?.rawValue.hasPrefix("main") == true }) {140 window.makeKeyAndOrderFront(nil)141 } else {142 openWindowAction?(id: "main")143 }144 NSApp.activate(ignoringOtherApps: true)145 }146147 func openNode(_ id: String) { openWindowAction?(value: NodeRef(id: id)); NSApp.activate(ignoringOtherApps: true) }148 func openAction(_ id: String) { openWindowAction?(value: ActionRef(id: id)) }149 func openLogs(_ ref: LogsRef) { openWindowAction?(value: ref) }150 func openCompare(_ ids: [String]) { openWindowAction?(value: CompareRef(nodeIDs: ids)) }151152 /// Routes a search result, a deep link target or a notification to the right place.153 func open(_ result: API.SearchResult) {154 switch result.kind {155 case .node: openNode(result.id)156 case .service: show(.services, focus: .service(result.id))157 case .alert: show(.alerts, focus: .alert(result.id))158 case .incident: show(.alerts, focus: .incident(result.id))159 case .action: openAction(result.id)160 case .job: show(.jobs, focus: .job(result.id))161 case .inferenceServer: show(.models, focus: .model(result.id))162 case .maintenanceWindow: show(.maintenance, focus: .maintenanceWindow(result.id))163 case .maintenanceNote: show(.maintenance, focus: .maintenanceNote(result.id))164 }165 }166167 /// Handles `https://clustr.spboucher.ai/setup#…`, `/open/<kind>/<id>` (and the Debug-only custom scheme).168 func handle(url: URL) {169 if let token = SetupLink.token(from: url.absoluteString) {170 guard session.phase != .starting else { return }171 Task { await beginInvitation(token: token) }172 return173 }174 guard let route = DeepLink.parse(url) else { return }175 switch route {176 case .section(let item): show(item)177 case .node(let id): openNode(id)178 case .action(let id): openAction(id)179 case .focus(let item, let target): show(item, focus: target)180 }181 }182183 // MARK: Mutations184185 /// Opens the action request sheet for a typed action of the catalog.186 func requestAction(_ typeName: String, on kind: API.ActionTargetKind, id: String, label: String, params: [String: JSONValue] = [:],187 host: String = ActionHost.main) {188 actionIntent = ActionIntent(typeName: typeName, targetKind: kind, targetID: id, targetLabel: label, presetParams: params, host: host)189 if host == ActionHost.main { bringMainWindowForward() }190 }191192 /// Runs a mutation and presents its failure (with the correlation id). A cancelled passkey sheet is not an error.193 @discardableResult194 func perform(_ operation: () async throws -> Void) async -> Bool {195 do {196 try await operation()197 return true198 } catch {199 let e = APIError.from(error)200 if !e.isPasskeyCancelled && !e.isCancelled && !e.isSignedOut { presentedError = e }201 return false202 }203 }204205 /// Why a mutation control is disabled, or nil when it is allowed.206 func mutationBlocker(permission: String?) -> String? {207 if session.isOffline { return tr("mutation.offline") }208 if let permission, !session.can(permission) { return tr("mutation.forbidden", permission) }209 return nil210 }211}212213enum DeepLink: Equatable {214 case section(SidebarItem)215 case node(String)216 case action(String)217 case focus(SidebarItem, FocusTarget)218219 /// `/open/<section>` or `/open/<kind>/<id>` on the product domain (universal link) or `mcc-debug://open/...`.220 static func parse(_ url: URL) -> DeepLink? {221 var parts = url.pathComponents.filter { $0 != "/" }222 if url.scheme == "mcc-debug", let host = url.host { parts.insert(host, at: 0) }223 guard parts.first == "open", parts.count >= 2 else { return nil }224 if parts.count == 2 { return SidebarItem(rawValue: parts[1]).map(DeepLink.section) }225 let id = parts[2]226 guard UUID(uuidString: id) != nil else { return nil }227 switch parts[1] {228 case "nodes": return .node(id)229 case "actions": return .action(id)230 case "alerts": return .focus(.alerts, .alert(id))231 case "incidents": return .focus(.alerts, .incident(id))232 case "services": return .focus(.services, .service(id))233 case "jobs": return .focus(.jobs, .job(id))234 case "models": return .focus(.models, .model(id))235 case "maintenance": return .focus(.maintenance, .maintenanceWindow(id))236 default: return nil237 }238 }239}240