Repository Public
1import MCCCore2import SwiftUI34/// Alerts & incidents: alerts, incidents, silences, rules.5struct AlertsView: View {6 enum Tab: String, CaseIterable, Identifiable {7 case alerts, incidents, silences, rules8 var id: String { rawValue }9 var title: String { Localization.shared.string("alerts.tab." + rawValue) }10 }1112 @Environment(AppModel.self) private var app13 @SceneStorage("mcc.alerts.tab") private var storedTab = Tab.alerts.rawValue14 @State private var tab: Tab = .alerts1516 var body: some View {17 Page(title: tr("nav.alerts"), subtitle: tr("alerts.subtitle"), scrolls: false) {18 SectionTabs(selection: $tab) { $0.title }19 .accessibilityLabel(tr("alerts.tabs.label"))20 .accessibilityIdentifier("alerts-tabs")21 } content: {22 switch tab {23 case .alerts: AlertsListView(showIncidents: { tab = .incidents })24 case .incidents: IncidentsView()25 case .silences: SilencesView()26 case .rules: RulesView()27 }28 }29 .onAppear { if app.focus == nil, let t = Tab(rawValue: storedTab) { tab = t } }30 .onChange(of: tab) { _, new in storedTab = new.rawValue }31 .onChange(of: app.focus, initial: true) { _, focus in32 switch focus {33 case .alert: tab = .alerts34 case .incident: tab = .incidents35 default: break36 }37 }38 .task {39 await app.session.nodes.list.loadIfNeeded(maxAge: 60)40 }41 }42}4344/// Node picker ("all nodes" + the inventory).45struct NodeFilterPicker: View {46 @Environment(AppModel.self) private var app47 let title: String48 @Binding var selection: String?49 var allLabel: String = tr("alerts.filter.all_nodes")50 var body: some View {51 Picker(title, selection: $selection) {52 Text(allLabel).tag(String?.none)53 ForEach((app.session.nodes.list.value ?? []).sorted { $0.alias.localizedCaseInsensitiveCompare($1.alias) == .orderedAscending }, id: \.id) { n in54 Text(n.alias).tag(String?.some(n.id))55 }56 }57 .fixedSize()58 }59}6061struct AlertsListView: View {62 @Environment(AppModel.self) private var app63 @Environment(\.mccTheme) private var theme64 let showIncidents: () -> Void65 @State private var filter = AlertFilter()66 @State private var sortOrder: [KeyPathComparator<AlertRow>] = [KeyPathComparator(\.severityRank, order: .reverse), KeyPathComparator(\.started, order: .reverse)]67 @State private var selection = Set<String>()68 @State private var inspector = true69 @State private var bulkMessage: String?70 @State private var incidentDraftAlerts: [String]?7172 private var resource: Resource<[API.Alert]> { app.session.alerts.alerts }7374 private func rows(_ alerts: [API.Alert]) -> [AlertRow] {75 filter.apply(alerts).map(AlertRow.init).sorted(using: sortOrder)76 }7778 var body: some View {79 ResourceView(resource) { alerts in80 let rows = rows(alerts)81 VStack(alignment: .leading, spacing: Tokens.Space.s3) {82 filterBar(count: rows.count, total: alerts.count)83 if rows.isEmpty {84 EmptyStateView(alerts.isEmpty ? tr("alerts.empty.title") : tr("alerts.empty.filtered"),85 message: alerts.isEmpty ? tr("alerts.empty.message") : nil, systemImage: "bell.slash")86 } else {87 table(rows)88 }89 }90 .padding(.horizontal, Tokens.Space.s7)91 .padding(.bottom, Tokens.Space.s5)92 }93 .sidePane(isPresented: $inspector) {94 Group {95 if selection.count == 1, let id = selection.first {96 AlertDetailPane(alertID: id, showIncidents: showIncidents)97 } else if selection.count > 1 {98 InspectorPane { Text(tr("alerts.selection.count", selection.count)).foregroundStyle(theme.textSecondary) }99 } else {100 EmptyStateView(tr("alerts.detail.none"), systemImage: "bell")101 }102 }103 .frame(width: 380)104 }105 .task { await resource.loadIfNeeded() }106 .onChange(of: app.focus, initial: true) { _, focus in107 guard case .alert(let id) = focus else { return }108 filter.openOnly = false // the alert asked for may be resolved109 selection = [id]110 inspector = true111 app.focus = nil112 }113 .alert(tr("alerts.bulk.title"), isPresented: Binding(get: { bulkMessage != nil }, set: { if !$0 { bulkMessage = nil } })) {114 Button(tr("action.close"), role: .cancel) {}115 } message: { Text(bulkMessage ?? "") }116 .sheet(isPresented: Binding(get: { incidentDraftAlerts != nil }, set: { if !$0 { incidentDraftAlerts = nil } })) {117 IncidentCreateSheet(alertIDs: incidentDraftAlerts ?? [])118 }119 }120121 private func filterBar(count: Int, total: Int) -> some View {122 HStack(spacing: Tokens.Space.s3) {123 Toggle(tr("alerts.filter.open_only"), isOn: $filter.openOnly).toggleStyle(.checkbox)124 .accessibilityIdentifier("alerts-open-only")125 Picker(tr("alerts.filter.state"), selection: $filter.state) {126 Text(tr("alerts.filter.any_state")).tag(API.AlertState?.none)127 ForEach(API.AlertState.allCases, id: \.self) { Text($0.label).tag(API.AlertState?.some($0)) }128 }.fixedSize()129 Picker(tr("alerts.filter.severity"), selection: $filter.severity) {130 Text(tr("alerts.filter.any_severity")).tag(API.Severity?.none)131 ForEach(API.Severity.allCases, id: \.self) { Text($0.label).tag(API.Severity?.some($0)) }132 }.fixedSize()133 NodeFilterPicker(title: tr("alerts.filter.node"), selection: $filter.nodeID)134 TextField(tr("alerts.filter.search"), text: $filter.text).textFieldStyle(.roundedBorder).frame(maxWidth: 220)135 .accessibilityLabel(tr("alerts.filter.search"))136 Spacer(minLength: 0)137 Text(tr("alerts.count", count, total)).font(.callout).foregroundStyle(theme.textSecondary).monospacedDigit()138 Button(tr("alerts.bulk.ack", selection.count)) { Task { await acknowledgeSelection() } }139 .disabled(selection.count < 2)140 .mutation(app, permission: "alerts.ack")141 Button(tr("incidents.create.from_selection")) { incidentDraftAlerts = Array(selection) }142 .disabled(selection.isEmpty)143 .mutation(app, permission: "alerts.manage")144 Button { inspector.toggle() } label: { Label(tr("alerts.inspector.toggle"), systemImage: "sidebar.trailing") }145 .labelStyle(.iconOnly).help(tr("alerts.inspector.toggle"))146 }147 .labelsHidden()148 }149150 private func table(_ rows: [AlertRow]) -> some View {151 Table(rows, selection: $selection, sortOrder: $sortOrder) {152 TableColumn(tr("alerts.col.severity"), value: \.severityRank) { r in153 StatusLabel(r.alert.severity.label, tone: r.alert.severity.tone)154 }.width(min: 90, ideal: 110)155 TableColumn(tr("alerts.col.state"), value: \.stateRank) { r in156 StatusLabel(r.alert.state.label, tone: r.alert.tone)157 }.width(min: 90, ideal: 120)158 TableColumn(tr("alerts.col.node"), value: \.node) { r in159 if let alias = r.alert.nodeAlias { Text(alias) } else { Text(tr("alerts.node.cluster")).foregroundStyle(theme.textTertiary) }160 }.width(min: 70, ideal: 100)161 TableColumn(tr("alerts.col.rule"), value: \.rule).width(min: 90, ideal: 140)162 TableColumn(tr("alerts.col.summary"), value: \.summary) { r in163 Text(r.alert.summary).lineLimit(2).help(r.alert.summary)164 }.width(min: 160, ideal: 280)165 TableColumn(tr("alerts.col.started"), value: \.started) { r in166 Text(Format.relative(r.alert.startedAt)).help(Format.dateTime(r.alert.startedAt))167 }.width(min: 80, ideal: 110)168 TableColumn(tr("alerts.col.value"), value: \.lastValue) { r in169 OptionalValueText(r.alert.lastValue.map { Format.number($0, fractionDigits: 2) })170 }.width(min: 60, ideal: 80)171 TableColumn(tr("alerts.col.flaps"), value: \.flaps) { r in172 Text("\(r.alert.flapCount)").monospacedDigit()173 }.width(min: 50, ideal: 60)174 TableColumn(tr("alerts.col.suppressed"), value: \.suppressed) { r in175 if let s = r.alert.suppressedBy {176 StatusLabel(Localization.shared.string("alerts.suppressed." + s.rawValue), tone: s == .maintenance ? .maintenance : .neutral)177 } else {178 Text("—").foregroundStyle(theme.textTertiary).accessibilityLabel(tr("alerts.suppressed.none"))179 }180 }.width(min: 80, ideal: 110)181 }182 .contextMenu(forSelectionType: String.self) { ids in183 if let id = ids.first, ids.count == 1, let a = resource.value?.first(where: { $0.id == id }) {184 if let node = a.nodeId { Button(tr("alerts.open_node")) { app.openNode(node) } }185 Button(tr("alerts.ack")) { Task { await app.perform { _ = try await app.session.alerts.acknowledge(id: id, comment: nil) } } }186 .disabled(a.state != .firing && a.state != .pending || app.mutationBlocker(permission: "alerts.ack") != nil)187 }188 }189 .accessibilityIdentifier("alerts-table")190 }191192 private func acknowledgeSelection() async {193 let targets = (resource.value ?? []).filter { selection.contains($0.id) && ($0.state == .firing || $0.state == .pending) }194 var done = 0195 var failures: [String] = []196 for a in targets {197 do {198 _ = try await app.session.alerts.acknowledge(id: a.id, comment: nil)199 done += 1200 } catch {201 let e = APIError.from(error)202 if e.isPasskeyCancelled || e.isSignedOut { break }203 failures.append("\(a.nodeAlias ?? "—") · \(a.summary): \(e.message)" + (e.correlationID.map { " [\($0)]" } ?? ""))204 }205 }206 bulkMessage = tr("alerts.bulk.result", done, targets.count) + (failures.isEmpty ? "" : "\n" + failures.joined(separator: "\n"))207 }208}209210struct AlertDetailPane: View {211 @Environment(AppModel.self) private var app212 @Environment(\.mccTheme) private var theme213 let alertID: String214 let showIncidents: () -> Void215 @State private var comment = ""216217 private var resource: Resource<API.AlertDetail> { app.session.alerts.detail[alertID] }218219 var body: some View {220 ResourceView(resource) { detail in221 InspectorPane { content(detail) }222 }223 .task(id: alertID) { await resource.load() }224 .accessibilityIdentifier("alert-detail")225 }226227 @ViewBuilder228 private func content(_ detail: API.AlertDetail) -> some View {229 let a = detail.alert230 VStack(alignment: .leading, spacing: Tokens.Space.s2) {231 HStack(spacing: Tokens.Space.s2) {232 StatusBadge(a.severity.label, tone: a.severity.tone)233 StatusBadge(a.state.label, tone: a.tone)234 }235 Text(a.summary).font(.headline).foregroundStyle(theme.textPrimary).textSelection(.enabled)236 }237 DetailSection(title: tr("alerts.detail.facts")) {238 KeyValueRow(tr("alerts.col.rule"), a.ruleName)239 if let alias = a.nodeAlias {240 HStack {241 KeyValueRow(tr("alerts.col.node"), alias)242 if let id = a.nodeId { LinkButton(title: tr("action.open")) { app.openNode(id) } }243 }244 }245 if !a.label.isEmpty { KeyValueRow(tr("alerts.detail.label"), a.label, monospaced: true) }246 KeyValueRow(tr("alerts.col.value"), a.lastValue.map { Format.number($0, fractionDigits: 3) } ?? tr("metric.not_measured"))247 KeyValueRow(tr("alerts.col.started"), Format.dateTime(a.startedAt))248 if let t = a.firedAt { KeyValueRow(tr("alerts.detail.fired"), Format.dateTime(t)) }249 if let t = a.acknowledgedAt {250 KeyValueRow(tr("alerts.detail.acknowledged"), Format.dateTime(t) + (a.acknowledgedByDisplayName.map { " · \($0)" } ?? ""))251 }252 if let t = a.resolvedAt { KeyValueRow(tr("alerts.detail.resolved"), Format.dateTime(t)) }253 KeyValueRow(tr("alerts.detail.last_eval"), Format.relative(a.lastEvalAt))254 KeyValueRow(tr("alerts.col.flaps"), "\(a.flapCount)")255 if let s = a.suppressedBy { KeyValueRow(tr("alerts.col.suppressed"), Localization.shared.string("alerts.suppressed." + s.rawValue)) }256 if let inc = a.incidentId {257 HStack {258 KeyValueRow(tr("alerts.detail.incident"), String(inc.prefix(8)), monospaced: true)259 LinkButton(title: tr("action.open")) { app.focus = .incident(inc); showIncidents() }260 }261 }262 }263 DetailSection(title: tr("alerts.detail.actions")) {264 TextField(tr("alerts.comment.optional"), text: $comment, axis: .vertical).textFieldStyle(.roundedBorder).lineLimit(1...3)265 .accessibilityLabel(tr("alerts.comment.optional"))266 HStack {267 Button(tr("alerts.ack")) { transition(resolve: false) }268 .disabled(a.state == .acknowledged || a.state == .resolved)269 .accessibilityIdentifier("alert-ack")270 Button(tr("alerts.resolve")) { transition(resolve: true) }271 .disabled(a.state == .resolved)272 .accessibilityIdentifier("alert-resolve")273 }274 .mutation(app, permission: "alerts.ack")275 }276 DetailSection(title: tr("alerts.timeline.title")) {277 CommentField(placeholder: tr("alerts.comment.placeholder")) { body in278 await app.perform { try await app.session.alerts.comment(alertID: alertID, body: body) }279 }280 .mutation(app, permission: "alerts.ack")281 TimelineList(events: detail.timeline)282 }283 }284285 private func transition(resolve: Bool) {286 let c = comment.trimmingCharacters(in: .whitespacesAndNewlines)287 Task {288 let ok = await app.perform {289 if resolve { _ = try await app.session.alerts.resolve(id: alertID, comment: c.isEmpty ? nil : c) }290 else { _ = try await app.session.alerts.acknowledge(id: alertID, comment: c.isEmpty ? nil : c) }291 }292 if ok { comment = "" }293 }294 }295}296