SPB Git

Repository Public License

AnalysisViews.swift 23.3 KB 408 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Monitor9// File             : App/Sources/Features/AnalysisViews.swift10// Description      : Insights (findings with their evidence) and Alerts (active11//                    alerts, rule editor, history, snooze).12// Module           : Features13// Repository       : https://git.spboucher.ai/orix-monitor14// Created          : 2026-11-2115// Last Modified    : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : Proprietary, all rights reserved (see license file)82// License File     : LICENSE83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import ORIXMonitorCore91import SwiftUI9293enum FindingText {94    static func title(_ f: Finding) -> String {95        switch f.kind {96        case .sustainedCPU: L("Sustained high CPU usage")97        case .memoryPressure: L("Elevated memory pressure")98        case .swapGrowth: L("Swap usage grew")99        case .diskExhaustion: L("Startup volume is filling up")100        case .networkAnomaly: f.metric == .netUp ? L("Unusual upload volume") : L("Unusual download volume")101        case .processSpikes: String(format: L("“%@” repeatedly used a full core"), f.subject ?? "")102        case .thermalPressure: L("Thermal pressure")103        }104    }105106    static func explanation(_ f: Finding, _ v: ValueFormatter) -> String {107        switch f.kind {108        case .sustainedCPU:109            String(format: L("Average CPU usage stayed above %1$@ for %2$@ (mean %3$@, peak %4$@)."), v.percent(f.threshold), v.duration(f.duration), v.percent(f.mean, digits: 1), v.percent(f.peak, digits: 1))110        case .memoryPressure:111            String(format: L("The kernel reported memory pressure at warning level or higher for %1$@. Highest level: %2$@."), v.duration(f.duration), f.peak >= 2 ? L("Critical") : L("Warning"))112        case .swapGrowth:113            String(format: L("Swap in use grew by %1$@ over %2$@, reaching %3$@."), v.bytes(f.mean, memory: true), v.duration(f.duration), v.bytes(f.peak, memory: true))114        case .diskExhaustion:115            String(format: L("Available space fell by about %1$@ per day over the last %2$@. %3$@ remain. At that rate the volume would be full around %4$@. This is a straight-line estimate, not a measurement."),116                   v.bytes(f.mean), v.duration(f.duration), v.bytes(f.peak), f.projected.map { $0.formatted(date: .abbreviated, time: .omitted) } ?? "—")117        case .networkAnomaly:118            String(format: L("%1$d one-minute periods carried far more traffic than usual: up to %2$@, against a typical %3$@."), f.occurrences, v.rate(f.peak), v.rate(f.threshold))119        case .processSpikes:120            String(format: L("It kept at least 80 %% of one core busy for 30 seconds or more on %1$d occasions. Highest reading: %2$@ of one core."), f.occurrences, v.percent(f.peak))121        case .thermalPressure:122            String(format: L("macOS reported a thermal state of Serious or higher for %@."), v.duration(f.duration))123        }124    }125126    static func action(_ f: Finding) -> String {127        switch f.kind {128        case .sustainedCPU: L("Open Processes sorted by CPU to see what is running. Sustained load is normal during builds, exports or indexing.")129        case .memoryPressure: L("Look at the top processes by memory and close what you do not need. Pressure, not free memory, is the signal that matters.")130        case .swapGrowth: L("Growing swap means memory was needed beyond the installed RAM. Check which processes hold the most memory.")131        case .diskExhaustion: L("Review large files in System Settings › General › Storage before the volume fills.")132        case .networkAnomaly: L("If you were not expecting a large transfer (backup, sync, update), check which apps were active at that time.")133        case .processSpikes: L("If this is not expected work for that process, check it for an update or a runaway task.")134        case .thermalPressure: L("Make sure the vents are clear and the Mac is on a hard surface. One event alone does not indicate a hardware fault.")135        }136    }137}138139struct InsightsView: View {140    @Environment(MonitorModel.self) private var model141142    var body: some View {143        let v = model.format144        Page {145            PageHeader(title: "Insights", subtitle: L("Patterns found in the last 24 hours of stored history"), family: .system, symbol: "lightbulb")146            HStack {147                if let updated = model.findingsUpdated {148                    Text("Analysed \(updated, format: .relative(presentation: .named))").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)149                }150                Spacer()151                Button { model.refreshFindings() } label: { Label("Analyse Now", systemImage: "arrow.clockwise") }152                    .accessibilityIdentifier("insights.refresh")153            }154            if model.findings.isEmpty {155                Card {156                    ContentUnavailableView {157                        Label("Nothing to report", systemImage: "checkmark.seal")158                    } description: {159                        Text("No pattern in the stored history crossed a threshold. Findings appear only when there is evidence for them.")160                    }161                    .frame(maxWidth: .infinity, minHeight: 180)162                }163            }164            ForEach(model.findings) { finding in165                Card {166                    HStack(alignment: .top, spacing: ORIX.Space.sm) {167                        Image(systemName: finding.severity.symbol).font(.system(size: 18)).foregroundStyle(finding.severity.color).accessibilityHidden(true)168                        VStack(alignment: .leading, spacing: 6) {169                            HStack {170                                Text(FindingText.title(finding)).font(.system(size: 14, weight: .semibold))171                                Text(finding.severity.title).font(.system(size: 10, weight: .semibold)).textCase(.uppercase).padding(.horizontal, 6).padding(.vertical, 2)172                                    .foregroundStyle(finding.severity.color).background(finding.severity.color.opacity(0.14), in: Capsule())173                                if finding.kind == .diskExhaustion { QualityBadge(.estimated) }174                                Spacer()175                            }176                            Text(FindingText.explanation(finding, v)).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary).fixedSize(horizontal: false, vertical: true)177                            Grid(alignment: .leading, horizontalSpacing: ORIX.Space.lg, verticalSpacing: 3) {178                                GridRow {179                                    evidence("Metric", L(MetricCatalog.descriptor(finding.metric).name))180                                    evidence("From", v.date(finding.start))181                                    evidence("Duration", v.duration(finding.duration))182                                    evidence("Samples", String(finding.sampleCount))183                                }184                            }185                            Label(FindingText.action(finding), systemImage: "arrow.right.circle").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)186                        }187                    }188                    .accessibilityElement(children: .combine)189                }190            }191            Card("What is checked") {192                let t = model.settings.thresholds193                VStack(alignment: .leading, spacing: 4) {194                    rule(String(format: L("CPU usage above %1$@ for %2$@ or more"), v.percent(t.cpuPercent), v.duration(t.cpuMinutes * 60)))195                    rule(String(format: L("Memory pressure at warning or critical for %@ or more"), v.duration(t.pressureMinutes * 60)))196                    rule(String(format: L("Swap growing by %@ or more within the window"), v.bytes(t.swapGrowthBytes, memory: true)))197                    rule(String(format: L("Startup volume projected to fill within %d days (needs 6 hours of history)"), Int(t.diskHorizonDays)))198                    rule(String(format: L("Network minutes far above the usual level and above %@"), v.rate(t.networkFloor)))199                    rule(String(format: L("A process holding a full core for 30 s, %d times or more"), t.processEpisodes))200                    rule(L("Thermal state Serious or Critical for a minute or more"))201                }202                Text("A single unusual reading never produces a finding, and no finding claims a hardware fault.").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)203            }204        }205    }206207    private func evidence(_ label: LocalizedStringKey, _ value: String) -> some View {208        VStack(alignment: .leading, spacing: 0) {209            Text(label).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textTertiary)210            Text(value).font(ORIX.Typeface.caption)211        }212    }213214    private func rule(_ text: String) -> some View {215        Label(text, systemImage: "checkmark").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)216    }217}218219struct AlertsView: View {220    @Environment(MonitorModel.self) private var model221    @Environment(AppSettings.self) private var settings222    @State private var history: [StoredEvent] = []223    @State private var editing: AlertRule?224225    var body: some View {226        let v = model.format227        Page {228            PageHeader(title: "Alerts", subtitle: String(format: L("%1$d rules enabled · %2$d active now"), settings.rules.filter(\.isEnabled).count, model.firing.count), family: .system, symbol: "bell")229            Card("Active now") {230                if model.firing.isEmpty {231                    Label("No active alert", systemImage: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.success).font(.system(size: 13, weight: .medium))232                }233                ForEach(model.firing) { rule in234                    HStack {235                        Image(systemName: rule.severity.symbol).foregroundStyle(rule.severity.color).accessibilityHidden(true)236                        Text(AlertText.title(rule)).font(.system(size: 13, weight: .semibold))237                        Text(AlertText.condition(rule, formatter: v)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)238                        Spacer()239                        Text(model.latest(rule.metric).map { AlertText.formatted($0, metric: rule.metric, formatter: v) } ?? "—").font(ORIX.Typeface.value)240                    }241                    .accessibilityElement(children: .combine)242                }243            }244            Card("Notifications") {245                HStack {246                    switch model.notificationStatus {247                    case .authorized, .provisional:248                        Toggle("Show alerts in Notification Center", isOn: Bindable(settings).notifications)249                    case .denied:250                        Label("Notifications are turned off for ORIX Monitor in System Settings.", systemImage: "bell.slash").font(.system(size: 12))251                        Button("Open System Settings") { NSWorkspace.shared.open(URL(string: "x-apple.systempreferences:com.apple.Notifications-Settings.extension")!) }252                    default:253                        Text("Alerts always appear here and in the menu bar. Notification Center is optional.").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)254                        Button("Enable Notifications…") { model.enableNotifications() }.accessibilityIdentifier("alerts.enableNotifications")255                    }256                    Spacer()257                    if let until = model.snoozedUntil, until > Date() {258                        Text("Snoozed until \(until, style: .time)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.warning)259                        Button("Resume") { model.snoozedUntil = nil }260                    } else {261                        Menu("Snooze") {262                            Button("For 15 minutes") { model.snoozedUntil = Date().addingTimeInterval(900) }263                            Button("For 1 hour") { model.snoozedUntil = Date().addingTimeInterval(3600) }264                            Button("For 8 hours") { model.snoozedUntil = Date().addingTimeInterval(8 * 3600) }265                        }266                        .fixedSize().accessibilityIdentifier("alerts.snooze")267                    }268                }269                Text("Each rule waits for its condition to hold, then stays quiet for its cooldown, so one sustained problem produces one alert.")270                    .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)271            }272            Card("Rules") {273                ForEach(settings.rules) { rule in274                    HStack(spacing: ORIX.Space.sm) {275                        Toggle("", isOn: binding(rule.id).isEnabled).labelsHidden().toggleStyle(.switch).controlSize(.mini)276                            .accessibilityLabel(Text(AlertText.title(rule)))277                        Image(systemName: rule.metric.family.symbol).frame(width: 16).foregroundStyle(ORIX.Palette.textSecondary).accessibilityHidden(true)278                        VStack(alignment: .leading, spacing: 1) {279                            Text(L(MetricCatalog.descriptor(rule.metric).name)).font(.system(size: 13, weight: .medium))280                            Text(AlertText.condition(rule, formatter: v) + " · " + String(format: L("cooldown %@"), v.duration(rule.cooldown)))281                                .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)282                        }283                        Spacer()284                        Text(rule.severity.title).font(ORIX.Typeface.caption).foregroundStyle(rule.severity.color)285                        Button("Edit") { editing = rule }.controlSize(.small)286                        Button { settings.rules.removeAll { $0.id == rule.id } } label: { Image(systemName: "trash") }.buttonStyle(.borderless)287                            .accessibilityLabel(Text("Delete rule"))288                    }289                    .opacity(rule.isEnabled ? 1 : 0.55)290                    if rule.id != settings.rules.last?.id { Divider() }291                }292                HStack {293                    Button { editing = AlertRule(metric: .cpuTotal, comparison: .above, threshold: 90, duration: 60) } label: { Label("Add Rule", systemImage: "plus") }294                        .accessibilityIdentifier("alerts.add")295                    Button("Restore Defaults") { settings.rules = AlertRule.defaults }296                    Spacer()297                }298            }299            Card("History") {300                HStack {301                    Text(String(format: L("%d events"), history.count)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)302                    Spacer()303                    Button("Clear History") { model.clearEvents([.alert]) }.controlSize(.small).disabled(history.isEmpty)304                }305                if history.isEmpty { Text("No alert has fired yet.").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary) }306                ForEach(history.prefix(60)) { event in307                    HStack {308                        Image(systemName: event.code == "alert.fired" ? event.severity.symbol : "checkmark.circle")309                            .foregroundStyle(event.code == "alert.fired" ? event.severity.color : ORIX.Palette.success).accessibilityHidden(true)310                        Text(event.metric.map { L(MetricCatalog.descriptor($0).name) } ?? "—").font(.system(size: 12, weight: .medium))311                        Text(event.code == "alert.fired" ? L("Fired") : L("Resolved")).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)312                        if let metric = event.metric, let value = event.payload["value"].flatMap(Double.init), value.isFinite {313                            Text(AlertText.formatted(value, metric: metric, formatter: v)).font(ORIX.Typeface.value)314                        }315                        Spacer()316                        Text(v.date(event.date)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)317                    }318                    .accessibilityElement(children: .combine)319                }320            }321        }322        .task(id: model.eventsRevision) { history = await model.events(kinds: [.alert]) }323        .onChange(of: settings.rules) { _, _ in model.applySettings() }324        .sheet(item: $editing) { rule in325            RuleEditor(rule: rule) { saved in326                if let index = settings.rules.firstIndex(where: { $0.id == saved.id }) { settings.rules[index] = saved } else { settings.rules.append(saved) }327            }328        }329    }330331    private func binding(_ id: UUID) -> Binding<AlertRule> {332        Binding(get: { settings.rules.first { $0.id == id } ?? AlertRule(metric: .cpuTotal, comparison: .above, threshold: 0, duration: 0) },333                set: { new in if let i = settings.rules.firstIndex(where: { $0.id == id }) { settings.rules[i] = new } })334    }335}336337struct RuleEditor: View {338    @State var rule: AlertRule339    var onSave: (AlertRule) -> Void340    @Environment(\.dismiss) private var dismiss341342    /// Metrics that make sense as alert conditions.343    static let metrics: [MetricID] = [.cpuTotal, .memPressure, .memUsed, .swapUsed, .diskFree, .diskRead, .diskWrite, .netDown, .netUp, .batteryCharge, .thermalState, .gpuUtilization]344345    /// Threshold as edited: percent, gigabytes, megabytes per second or a level, depending on the metric.346    private var scale: (factor: Double, unit: String) {347        switch MetricCatalog.descriptor(rule.metric).unit {348        case .bytes: (1_000_000_000, "GB")349        case .bytesPerSecond: (1_000_000, "MB/s")350        case .percent: (1, "%")351        default: (1, "")352        }353    }354355    var body: some View {356        Form {357            Picker("Metric", selection: $rule.metric) {358                ForEach(Self.metrics, id: \.self) { Text(L(MetricCatalog.descriptor($0).name)).tag($0) }359            }360            .onChange(of: rule.metric) { _, new in361                switch new {362                case .memPressure: (rule.comparison, rule.threshold) = (.above, 0.5)363                case .thermalState: (rule.comparison, rule.threshold) = (.above, 1.5)364                case .diskFree: (rule.comparison, rule.threshold) = (.below, 20e9)365                case .batteryCharge: (rule.comparison, rule.threshold) = (.below, 15)366                default: (rule.comparison, rule.threshold) = (.above, MetricCatalog.descriptor(new).unit == .percent ? 90 : 50e6)367                }368            }369            if rule.metric == .memPressure {370                Picker("Level", selection: $rule.threshold) {371                    Text("Warning or higher").tag(0.5)372                    Text("Critical").tag(1.5)373                }374            } else if rule.metric == .thermalState {375                Picker("Level", selection: $rule.threshold) {376                    Text("Fair or higher").tag(0.5)377                    Text("Serious or higher").tag(1.5)378                    Text("Critical").tag(2.5)379                }380            } else {381                Picker("Condition", selection: $rule.comparison) {382                    Text("Above").tag(AlertComparison.above)383                    Text("Below").tag(AlertComparison.below)384                }385                HStack {386                    TextField("Threshold", value: Binding(get: { rule.threshold / scale.factor }, set: { rule.threshold = max(0, $0) * scale.factor }), format: .number.precision(.fractionLength(0...1)))387                    Text(scale.unit).foregroundStyle(.secondary)388                }389            }390            Stepper(value: $rule.duration, in: 0...3600, step: 10) { LabeledContent("Must hold for", value: "\(Int(rule.duration)) s") }391            Stepper(value: $rule.cooldown, in: 60...86400, step: 60) { LabeledContent("Cooldown", value: "\(Int(rule.cooldown / 60)) min") }392            Picker("Severity", selection: $rule.severity) { ForEach(Severity.allCases, id: \.self) { Text($0.title).tag($0) } }393            Toggle("Enabled", isOn: $rule.isEnabled)394        }395        .formStyle(.grouped)396        .frame(width: 440)397        .toolbar {398            ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }399            ToolbarItem(placement: .confirmationAction) {400                Button("Save") {401                    onSave(rule)402                    dismiss()403                }404            }405        }406    }407}408
Files main
Menu

Theme