Repository Public
1import MCCCore2import SwiftUI34/// Families of metrics charted together (same unit per chart). Names are the catalog's.5enum MetricFamily: String, CaseIterable, Identifiable {6 case cpu, memory, disk, network, gpu, agent7 var id: String { rawValue }8 var title: String { Localization.shared.string("nodes.family." + rawValue) }910 /// Charts of the family: each groups metrics that share a unit.11 var charts: [(key: String, metrics: [String])] {12 switch self {13 case .cpu: [("cpu", ["cpu.usage", "cpu.user", "cpu.system"]), ("load", ["load.1", "load.5", "load.15"]), ("procs", ["procs.count"])]14 case .memory: [("mem", ["mem.used", "mem.wired", "mem.compressed"]), ("mem_available", ["mem.available.percent"]), ("swap", ["swap.used"])]15 case .disk: [("disk_used", ["disk.used"]), ("disk_io", ["disk.read", "disk.write"])]16 case .network: [("net", ["net.rx", "net.tx"]), ("net_errors", ["net.errors"]), ("net_latency", ["net.latency"]), ("net_loss", ["net.loss"])]17 case .gpu: [("gpu", ["gpu.usage"]), ("gpu_mem", ["gpu.mem.used"]), ("thermal", ["thermal.pressure", "thermal.temp"]), ("power", ["power.draw"])]18 case .agent: [("agent_cpu", ["agent.cpu"]), ("agent_rss", ["agent.rss"])]19 }20 }21}2223struct NodeDetailView: View {24 enum Tab: String, CaseIterable, Identifiable { case summary, metrics, processes, services, storage, health, maintenance; var id: String { rawValue } }25 @Environment(AppModel.self) private var app26 @Environment(\.mccTheme) private var theme27 let nodeID: String28 @SceneStorage("mcc.node.tab") private var tabRaw = Tab.summary.rawValue29 @SceneStorage("mcc.node.family") private var familyRaw = MetricFamily.cpu.rawValue30 @State private var showsEdit = false31 @State private var confirmsRetire = false3233 private var tab: Tab { Tab(rawValue: tabRaw) ?? .summary }34 private var family: MetricFamily { MetricFamily(rawValue: familyRaw) ?? .cpu }35 private var resource: Resource<API.NodeDetail> { app.session.nodes.detail[nodeID] }3637 var body: some View {38 @Bindable var app = app39 VStack(spacing: 0) {40 OfflineBanner()41 ResourceView(resource) { detail in42 VStack(alignment: .leading, spacing: 0) {43 header(detail)44 ScrollView(.horizontal, showsIndicators: false) {45 SectionTabs(selection: Binding(get: { tab }, set: { tabRaw = $0.rawValue })) { Localization.shared.string("nodes.tab." + $0.rawValue) }46 .padding(.horizontal, Tokens.Space.s6)47 .padding(.bottom, Tokens.Space.s3)48 }49 Divider()50 ScrollView {51 tabContent(detail)52 .padding(Tokens.Space.s6)53 .frame(maxWidth: .infinity, alignment: .topLeading)54 }55 }56 }57 }58 .navigationTitle(resource.value?.node.alias ?? tr("nav.nodes"))59 .toolbar {60 ToolbarItem(placement: .principal) {61 Picker(tr("menu.period"), selection: $app.range) {62 ForEach(API.TimeRange.allCases, id: \.self) { Text($0.label).tag($0) }63 }64 .pickerStyle(.segmented)65 }66 }67 .task(id: nodeID) {68 await resource.loadIfNeeded(maxAge: 10)69 await app.session.nodes.catalog.loadIfNeeded(maxAge: 600)70 }71 .environment(\.actionHost, "node:" + nodeID)72 .sheet(item: app.actionIntentBinding(host: "node:" + nodeID)) { ActionRequestSheet(intent: $0) }73 .sheet(isPresented: $showsEdit) { if let n = resource.value?.node { NodeEditSheet(node: n) } }74 .confirmationDialog(tr("nodes.retire.title"), isPresented: $confirmsRetire) {75 Button(tr("nodes.retire.confirm"), role: .destructive) { Task { await app.perform { try await app.session.nodes.retire(id: nodeID) } } }76 } message: { Text(tr("nodes.retire.message")) }77 }7879 private func header(_ d: API.NodeDetail) -> some View {80 let n = d.node81 return HStack(alignment: .center, spacing: Tokens.Space.s4) {82 Image(systemName: n.kind.symbol).font(.title).foregroundStyle(theme.textSecondary).accessibilityHidden(true)83 VStack(alignment: .leading, spacing: 2) {84 HStack(spacing: Tokens.Space.s3) {85 Text(n.alias).font(.title2.weight(.semibold)).foregroundStyle(theme.textPrimary)86 if n.maintenance { StatusBadge(tr("overview.nodes.maintenance"), tone: .maintenance) }87 if n.retiredAt != nil { StatusBadge(tr("nodes.retired"), tone: .offline) }88 if let a = n.openAlerts, a > 0 {89 Button { app.show(.alerts) } label: { StatusBadge(tr("glance.alerts", a), tone: .warning) }.buttonStyle(.plain)90 }91 }92 HStack(spacing: Tokens.Space.s3) {93 FreshnessLabel(n.freshness, observedAt: n.observedAt ?? n.lastSeenAt).font(.callout)94 if n.maintenance, !n.maintenanceReason.isEmpty { Text(n.maintenanceReason).font(.callout).foregroundStyle(theme.textSecondary) }95 }96 }97 Spacer()98 ActionMenu(kind: .node, targetID: n.id, targetLabel: n.alias)99 Menu {100 Button(tr("action.edit")) { showsEdit = true }.disabled(app.mutationBlocker(permission: "nodes.write") != nil)101 Button(tr("nodes.retire.title"), role: .destructive) { confirmsRetire = true }.disabled(app.mutationBlocker(permission: "nodes.write") != nil || n.retiredAt != nil)102 Divider()103 Button(tr("action.refresh")) { Task { await resource.load() } }104 } label: { Label(tr("nodes.more"), systemImage: "ellipsis.circle") }105 .menuStyle(.borderlessButton)106 .fixedSize()107 }108 .padding(.horizontal, Tokens.Space.s6)109 .padding(.vertical, Tokens.Space.s4)110 }111112 @ViewBuilder113 private func tabContent(_ d: API.NodeDetail) -> some View {114 switch tab {115 case .summary: NodeSummary(detail: d)116 case .metrics:117 VStack(alignment: .leading, spacing: Tokens.Space.s5) {118 SectionTabs(selection: Binding(get: { family }, set: { familyRaw = $0.rawValue })) { $0.title }119 NodeMetricCharts(nodeID: nodeID, family: family, range: app.range)120 }121 case .processes: NodeProcesses(nodeID: nodeID)122 case .services: NodeServices(nodeID: nodeID)123 case .storage: NodeStorageNetwork(detail: d)124 case .health: NodeHealth(nodeID: nodeID, range: app.range)125 case .maintenance: NodeMaintenancePanel(nodeID: nodeID)126 }127 }128}129130// MARK: Summary131132struct NodeSummary: View {133 @Environment(AppModel.self) private var app134 @Environment(\.mccTheme) private var theme135 let detail: API.NodeDetail136137 var body: some View {138 let n = detail.node139 LazyVGrid(columns: [GridItem(.adaptive(minimum: 360), spacing: Tokens.Space.s5, alignment: .top)], alignment: .leading, spacing: Tokens.Space.s5) {140 DetailSection(title: tr("nodes.hardware")) {141 row(tr("nodes.hw.model"), n.model)142 row(tr("nodes.hw.chip"), n.chip)143 row(tr("nodes.hw.arch"), n.arch)144 row(tr("nodes.hw.cpu_cores"), n.cpuCores.map(String.init))145 // Performance levels under the names the machine itself reports (Super / Performance / Efficiency…).146 if detail.cpuLevels.isEmpty {147 row(tr("nodes.hw.cpu_levels"), nil)148 } else {149 ForEach(detail.cpuLevels, id: \.name) { level in150 KeyValueRow(tr("nodes.hw.cpu_level", level.name), tr("overview.capacity.cores", level.cores))151 }152 }153 row(tr("nodes.hw.gpu_cores"), n.gpuCores.map(String.init))154 row(tr("nodes.hw.memory"), n.memBytes.map { Format.bytes($0, binary: true) })155 row(tr("nodes.hw.storage"), n.storageBytes.map { Format.bytes($0) })156 // Private fields: shown only when the server returned them (nodes.private.read).157 if let s = detail.serialNumber { KeyValueRow(tr("nodes.hw.serial"), s, monospaced: true) }158 if let u = detail.hardwareUuid { KeyValueRow(tr("nodes.hw.uuid"), u, monospaced: true) }159 }160 DetailSection(title: tr("nodes.system")) {161 row(tr("nodes.sys.hostname"), n.hostname.isEmpty ? nil : n.hostname)162 row(tr("nodes.sys.os"), [n.osName, n.osVersion].compactMap { $0 }.joined(separator: " ").nilIfEmpty)163 row(tr("nodes.sys.build"), detail.osBuild)164 if let ip = n.primaryIp { KeyValueRow(tr("nodes.sys.ip"), ip, monospaced: true) }165 KeyValueRow(tr("nodes.col.site"), n.site.isEmpty ? "—" : n.site)166 KeyValueRow(tr("nodes.col.role"), n.role.isEmpty ? "—" : n.role)167 KeyValueRow(tr("nodes.sys.environment"), n.environment.isEmpty ? "—" : n.environment)168 KeyValueRow(tr("nodes.sys.tags"), n.tags.isEmpty ? "—" : n.tags.joined(separator: ", "))169 KeyValueRow(tr("nodes.sys.registered"), "\(Localization.shared.string("nodes.registered." + n.registeredVia.rawValue)) · \(Format.date(n.createdAt))")170 row(tr("nodes.sys.inventory"), detail.inventoryAt.map { Format.dateTime($0) })171 }172 agentCard173 DetailSection(title: tr("nodes.latest")) {174 let latest = detail.latest.additionalProperties175 if latest.isEmpty {176 Text(tr("nodes.latest.none")).font(.callout).foregroundStyle(theme.textSecondary)177 } else {178 LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), alignment: .topLeading)], alignment: .leading, spacing: Tokens.Space.s4) {179 ForEach(latest.keys.sorted(), id: \.self) { name in180 MetricValueView(name, value: latest[name])181 }182 }183 }184 }185 }186 }187188 @ViewBuilder private var agentCard: some View {189 DetailSection(title: tr("nodes.agent")) {190 if let a = detail.agent {191 KeyValueRow(tr("nodes.agent.version"), a.version)192 KeyValueRow(tr("nodes.agent.os"), a.os)193 HStack { Text(tr("nodes.agent.state")).font(.callout).foregroundStyle(theme.textSecondary); Spacer(); FreshnessLabel(a.freshness, observedAt: a.lastSeenAt).font(.callout) }194 if let r = a.revokedAt { KeyValueRow(tr("nodes.agent.revoked"), Format.dateTime(r) + (a.revokedReason.map { " — \($0)" } ?? "")) }195 KeyValueRow(tr("nodes.agent.cert_expiry"), Format.date(a.certNotAfter))196 KeyValueRow(tr("nodes.agent.enrolled"), Format.date(a.enrolledAt))197 KeyValueRow(tr("nodes.agent.overhead"),198 tr("nodes.agent.overhead.value", a.overhead?.cpuPct.map { Format.percent($0, fractionDigits: 1) } ?? "—",199 a.overhead?.rssBytes.map { Format.bytes($0, binary: true) } ?? "—"))200 KeyValueRow(tr("nodes.agent.capabilities"), a.capabilities.isEmpty ? "—" : a.capabilities.sorted().joined(separator: ", "))201 } else {202 Label(tr("nodes.agent.none"), systemImage: "antenna.radiowaves.left.and.right.slash").font(.callout).foregroundStyle(theme.textSecondary)203 }204 }205 }206207 private func row(_ key: String, _ value: String?) -> some View {208 KeyValueRow(key, value ?? tr("metric.not_reported"))209 }210}211212extension String {213 var nilIfEmpty: String? { isEmpty ? nil : self }214}215216// MARK: Charts217218struct NodeMetricCharts: View {219 @Environment(AppModel.self) private var app220 @Environment(\.mccTheme) private var theme221 let nodeID: String222 let family: MetricFamily223 let range: API.TimeRange224225 var body: some View {226 LazyVGrid(columns: [GridItem(.adaptive(minimum: 420), spacing: Tokens.Space.s5, alignment: .top)], alignment: .leading, spacing: Tokens.Space.s5) {227 ForEach(family.charts, id: \.key) { chart in228 MetricChartCard(query: MetricQuery(nodeID: nodeID, metrics: chart.metrics, range: range),229 title: Localization.shared.string("nodes.chart." + chart.key))230 }231 }232 }233}234235struct MetricChartCard: View {236 @Environment(AppModel.self) private var app237 @Environment(\.mccTheme) private var theme238 let query: MetricQuery239 let title: String240241 var body: some View {242 let resource = app.session.nodes.metrics[query]243 Card {244 VStack(alignment: .leading, spacing: Tokens.Space.s3) {245 SectionTitle(title) {246 if let r = resource.value { Text(tr("nodes.chart.resolution", r.resolution.rawValue)).font(.caption).foregroundStyle(theme.textTertiary) }247 }248 if let r = resource.value {249 let series = r.series.map { s in250 ChartSeries(id: s.metric + "|" + s.label, name: s.label.isEmpty ? s.metric : "\(s.metric) · \(s.label)", metricPoints: s.points)251 }252 TimeSeriesChart(title: title, unit: r.series.first?.unit, series: series, domain: r.from...max(r.to, r.from.addingTimeInterval(1)))253 // Metrics the node cannot provide are named with their state instead of an empty line.254 let states = r.availability.additionalProperties.filter { $0.value != .available }255 ForEach(states.keys.sorted(), id: \.self) { metric in256 if let a = states[metric] { StatusLabel("\(metric) — \(a.label)", tone: a.tone).font(.caption) }257 }258 } else if let reason = resource.state.unavailableReason {259 UnavailableInline(reason: reason, error: resource.state.error)260 } else if let e = resource.state.error {261 InlineErrorView(e)262 } else {263 ProgressView().controlSize(.small).frame(maxWidth: .infinity, minHeight: 180)264 }265 }266 }267 .task(id: query) { await resource.loadIfNeeded(maxAge: 30) }268 }269}270271// MARK: Processes, services272273struct NodeProcesses: View {274 @Environment(AppModel.self) private var app275 @Environment(\.mccTheme) private var theme276 let nodeID: String277 @State private var sortOrder = [KeyPathComparator(\ProcessRow.cpu, order: .reverse)]278279 struct ProcessRow: Identifiable {280 let p: API.Process281 var id: Int { p.pid }282 var name: String { p.name }283 var user: String { p.user ?? "" }284 var cpu: Double { p.cpuPct ?? -1 }285 var mem: Int64 { p.memBytes ?? -1 }286 }287288 var body: some View {289 let resource = app.session.nodes.processes[nodeID]290 ResourceView(resource) { list in291 VStack(alignment: .leading, spacing: Tokens.Space.s3) {292 HStack {293 FreshnessLabel(list.freshness, observedAt: list.observedAt).font(.callout)294 if list.availability != .available { StatusBadge(list.availability.label, tone: list.availability.tone, compact: true) }295 Spacer()296 Button(tr("action.refresh")) { Task { await resource.load() } }297 }298 if list.items.isEmpty {299 EmptyStateView(list.availability == .available ? tr("nodes.processes.empty") : list.availability.label, systemImage: "cpu")300 } else {301 Table(list.items.map(ProcessRow.init).sorted(using: sortOrder), sortOrder: $sortOrder) {302 TableColumn("PID", value: \.id) { Text(String($0.id)).monospacedDigit() }.width(70)303 TableColumn(tr("nodes.processes.name"), value: \.name) { Text($0.name) }304 TableColumn(tr("nodes.processes.user"), value: \.user) { r in OptionalValueText(r.p.user) }.width(min: 70, ideal: 110)305 TableColumn(tr("nodes.col.cpu"), value: \.cpu) { r in OptionalValueText(r.p.cpuPct.map { Format.percent($0, fractionDigits: 1) }) }.width(70)306 TableColumn(tr("nodes.col.memory"), value: \.mem) { r in OptionalValueText(r.p.memBytes.map { Format.bytes($0, binary: true) }) }.width(90)307 TableColumn(tr("nodes.processes.command")) { r in OptionalValueText(r.p.command).lineLimit(1).help(r.p.command ?? "") }308 }309 .frame(minHeight: 360)310 }311 }312 }313 .task(id: nodeID) { await resource.loadIfNeeded(maxAge: 10) }314 }315}316317struct NodeServices: View {318 @Environment(AppModel.self) private var app319 let nodeID: String320321 var body: some View {322 let resource = app.session.nodes.services[nodeID]323 Group {324 if !app.session.can("services.read") {325 UnavailableStateView(reason: .forbidden)326 } else {327 ResourceView(resource) { services in328 if services.isEmpty {329 EmptyStateView(tr("nodes.services.empty"), systemImage: "gearshape.2")330 } else {331 Table(services.rows(\.id)) {332 TableColumn(tr("nodes.services.name")) { Text($0.value.name).fontWeight(.medium) }333 TableColumn(tr("nodes.services.manager")) { Text($0.value.manager.rawValue) }.width(80)334 TableColumn(tr("nodes.col.state")) { StatusLabel($0.value.state.label, tone: $0.value.state.tone) }.width(110)335 TableColumn(tr("nodes.services.ports")) { r in OptionalValueText(r.value.ports.isEmpty ? nil : r.value.ports.map(String.init).joined(separator: ", ")) }.width(90)336 TableColumn(tr("nodes.services.restarts")) { r in OptionalValueText(r.value.restarts.map(String.init)) }.width(80)337 TableColumn(tr("nodes.col.memory")) { r in OptionalValueText(r.value.memBytes.map { Format.bytes($0, binary: true) }) }.width(90)338 TableColumn(tr("nodes.services.uptime")) { r in OptionalValueText(r.value.uptimeS.map { Format.duration(seconds: Double($0)) }) }.width(90)339 TableColumn("") { r in Button(tr("action.open")) { app.show(.services, focus: .service(r.id)) }.buttonStyle(.textLink) }.width(70)340 }341 .frame(minHeight: 360)342 }343 }344 }345 }346 .task(id: nodeID) { if app.session.can("services.read") { await resource.loadIfNeeded(maxAge: 15) } }347 }348}349350// MARK: Storage and network351352struct NodeStorageNetwork: View {353 @Environment(\.mccTheme) private var theme354 let detail: API.NodeDetail355356 var body: some View {357 VStack(alignment: .leading, spacing: Tokens.Space.s5) {358 DetailSection(title: tr("nodes.volumes")) {359 if detail.volumes.isEmpty { Text(tr("nodes.volumes.none")).font(.callout).foregroundStyle(theme.textSecondary) }360 ForEach(detail.volumes, id: \.id) { v in361 VStack(alignment: .leading, spacing: Tokens.Space.s1) {362 UsageMeter(label: v.mount,363 ratio: { if let u = v.usedBytes, let t = v.totalBytes, t > 0 { return Double(u) / Double(t) }; return nil }(),364 detail: [v.kind.label, v.fs, v.device, v.remote,365 v.usedBytes.flatMap { u in v.totalBytes.map { tr("overview.capacity.used_of", Format.bytes(u), Format.bytes($0)) } },366 v.smartStatus.map { "SMART : \($0)" }].compactMap { $0 }.joined(separator: " · "))367 if v.goneAt != nil { StatusLabel(tr("nodes.volumes.gone"), tone: .offline).font(.caption) }368 }369 }370 }371 DetailSection(title: tr("nodes.interfaces")) {372 if detail.interfaces.isEmpty { Text(tr("nodes.interfaces.none")).font(.callout).foregroundStyle(theme.textSecondary) }373 // Addresses and MAC are private: the server omits them below nodes.private.read, and then they are not shown.374 let showsAddresses = detail.interfaces.contains { !$0.ipv4.isEmpty || !$0.ipv6.isEmpty || $0.mac != nil }375 ForEach(detail.interfaces, id: \.name) { i in376 VStack(alignment: .leading, spacing: 2) {377 HStack(spacing: Tokens.Space.s3) {378 Text(i.name).font(.callout.weight(.medium).monospaced()).foregroundStyle(theme.textPrimary)379 Text(Localization.shared.string("nodes.interface.kind." + i.kind.rawValue)).font(.caption).foregroundStyle(theme.textSecondary)380 StatusLabel(i.up ? tr("nodes.interface.up") : tr("nodes.interface.down"), tone: i.up ? .ok : .offline).font(.caption)381 Spacer()382 Text(tr("nodes.interface.rates", i.rxBytesPerS.map { Format.bytesPerSecond($0) } ?? "—", i.txBytesPerS.map { Format.bytesPerSecond($0) } ?? "—"))383 .font(.caption.monospacedDigit()).foregroundStyle(theme.textSecondary)384 if let s = i.linkSpeedMbps { Text("\(s) Mb/s").font(.caption.monospacedDigit()).foregroundStyle(theme.textTertiary) }385 }386 if showsAddresses {387 Text(([i.mac].compactMap { $0 } + i.ipv4 + i.ipv6).joined(separator: " ")).font(.caption.monospaced()).foregroundStyle(theme.textTertiary).textSelection(.enabled)388 }389 }390 .accessibilityElement(children: .combine)391 }392 if !showsAddresses, !detail.interfaces.isEmpty {393 Text(tr("nodes.interfaces.private_hidden")).font(.caption).foregroundStyle(theme.textTertiary)394 }395 }396 }397 }398}399400// MARK: Health history401402struct NodeHealth: View {403 @Environment(AppModel.self) private var app404 @Environment(\.mccTheme) private var theme405 let nodeID: String406 let range: API.TimeRange407408 static func tone(_ state: API.HealthBucket.StatePayload) -> StatusTone {409 switch state {410 case .up: .ok411 case .degraded: .warning412 case .down: .critical413 case .maintenance: .maintenance414 case .unknown: .neutral415 }416 }417418 /// Share of each state over the period, by duration.419 static func shares(_ items: [API.HealthBucket]) -> [(state: API.HealthBucket.StatePayload, ratio: Double)] {420 let total = items.reduce(0.0) { $0 + $1.end.timeIntervalSince($1.start) }421 guard total > 0 else { return [] }422 return API.HealthBucket.StatePayload.allCases.compactMap { s in423 let d = items.filter { $0.state == s }.reduce(0.0) { $0 + $1.end.timeIntervalSince($1.start) }424 return d > 0 ? (s, d / total) : nil425 }426 }427428 var body: some View {429 let resource = app.session.nodes.health[HealthQuery(nodeID: nodeID, range: range)]430 ResourceView(resource) { h in431 let shares = Self.shares(h.items)432 let summary = shares.map { "\(Localization.shared.string("nodes.health.state." + $0.state.rawValue)) \(Format.percent(ratio: $0.ratio, fractionDigits: 1))" }.joined(separator: ", ")433 DetailSection(title: tr("nodes.health.title", h.range.label)) {434 HStack {435 if let u = h.uptimeRatio {436 Text(tr("nodes.health.uptime", Format.percent(ratio: u, fractionDigits: 2))).font(.title3.weight(.semibold).monospacedDigit()).foregroundStyle(theme.textPrimary)437 } else {438 NotReported(tr("nodes.health.uptime.unknown"))439 }440 Spacer()441 Text(tr("nodes.health.bucket", Format.duration(seconds: Double(h.bucketSeconds)))).font(.caption).foregroundStyle(theme.textTertiary)442 }443 if h.items.isEmpty {444 Text(tr("chart.no_data")).font(.callout).foregroundStyle(theme.textSecondary)445 } else {446 // One segment per bucket; the pattern (height) differs by state so that colour is not the only cue.447 GeometryReader { geo in448 HStack(alignment: .bottom, spacing: 1) {449 ForEach(Array(h.items.enumerated()), id: \.offset) { _, b in450 let t = Self.tone(b.state)451 Rectangle().fill(t.color(theme))452 .frame(height: b.state == .up ? geo.size.height * 0.55 : b.state == .unknown ? geo.size.height * 0.25 : geo.size.height)453 .help("\(Format.dateTime(b.start)) — \(Localization.shared.string("nodes.health.state." + b.state.rawValue))" + (b.alertsFiring > 0 ? " · \(tr("glance.alerts", b.alertsFiring))" : ""))454 }455 }456 }457 .frame(height: 44)458 .accessibilityElement(children: .ignore)459 .accessibilityLabel(tr("nodes.health.title", h.range.label))460 .accessibilityValue(summary)461 HStack(spacing: Tokens.Space.s4) {462 ForEach(shares, id: \.state) { s in463 StatusLabel("\(Localization.shared.string("nodes.health.state." + s.state.rawValue)) \(Format.percent(ratio: s.ratio, fractionDigits: 1))", tone: Self.tone(s.state)).font(.caption)464 }465 }466 }467 }468 }469 .task(id: HealthQuery(nodeID: nodeID, range: range)) { await resource.loadIfNeeded(maxAge: 30) }470 }471}472473// MARK: Edit474475struct NodeEditSheet: View {476 @Environment(AppModel.self) private var app477 @Environment(\.dismiss) private var dismiss478 let node: API.Node479 @State private var alias = ""480 @State private var site = ""481 @State private var role = ""482 @State private var environment = ""483 @State private var tags = ""484 @State private var error: APIError?485486 var body: some View {487 VStack(alignment: .leading, spacing: Tokens.Space.s4) {488 Text(tr("nodes.edit.title", node.alias)).font(.title2.weight(.semibold))489 Form {490 TextField(tr("nodes.col.alias"), text: $alias)491 TextField(tr("nodes.col.site"), text: $site)492 TextField(tr("nodes.col.role"), text: $role)493 TextField(tr("nodes.sys.environment"), text: $environment)494 TextField(tr("nodes.add.tags"), text: $tags)495 }496 if let error { InlineErrorView(error) }497 HStack {498 Spacer()499 Button(tr("action.cancel")) { dismiss() }.keyboardShortcut(.cancelAction)500 Button(tr("action.save")) {501 Task {502 do {503 let t = tags.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }504 _ = try await app.session.nodes.update(id: node.id, .init(alias: alias == node.alias ? nil : alias, site: site, role: role, environment: environment, tags: t))505 dismiss()506 } catch {507 let e = APIError.from(error)508 if !e.isPasskeyCancelled { self.error = e }509 }510 }511 }512 .buttonStyle(.borderedProminent)513 .keyboardShortcut(.return, modifiers: .command)514 .disabled(alias.trimmingCharacters(in: .whitespaces).isEmpty || app.mutationBlocker(permission: "nodes.write") != nil)515 }516 }517 .padding(Tokens.Space.s6)518 .frame(width: 440)519 .onAppear { alias = node.alias; site = node.site; role = node.role; environment = node.environment; tags = node.tags.joined(separator: ", ") }520 }521}522