Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Storage Node9// File : MacLustrStorageNode/Features/Settings/SettingsView.swift10// Description : Settings: network and power policy, reserve, station mode,11// suspend, drain, removal, emergency release, diagnostics.12// Module : MacLustrStorageNode13// Repository : https://git.spboucher.ai/maclustr-storage-ios14// Project Website : https://storage.spboucher.ai15// Created : 2026-12-0116// Last Modified : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: admin@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import SwiftUI9192struct SettingsView: View {93 @EnvironmentObject private var node: NodeController94 @State private var confirm: Confirm?95 @State private var message: String?96 @State private var showDiagnostics = false97 @State private var showBenchmark = false98 @State private var working = false99100 enum Confirm: String, Identifiable { case drain, remove, emergency, emergencyRemove; var id: String { rawValue } }101102 private func binding<T>(_ key: WritableKeyPath<NodeSettings, T>) -> Binding<T> {103 Binding(get: { node.settings[keyPath: key] }, set: { v in var s = node.settings; s[keyPath: key] = v; Task { await node.save(s) } })104 }105106 var body: some View {107 let s = node.snapshot108 NavigationStack {109 Form {110 Section {111 TextField("Name", text: binding(\.nodeName)).submitLabel(.done)112 Toggle("Suspend the node", isOn: binding(\.suspended))113 } header: { Text("Node") } footer: { Text("While suspended, fragments stay on this device and nothing is exchanged with the cluster.") }114115 Section {116 Toggle("Wi-Fi only", isOn: binding(\.wifiOnly))117 Toggle("Allow cellular data", isOn: binding(\.allowCellular)).disabled(node.settings.wifiOnly)118 Toggle("Use the local network when available", isOn: binding(\.useLocalNetwork))119 Picker("Bandwidth limit", selection: binding(\.rateLimitKbps)) {120 Text("Unlimited").tag(0)121 ForEach([1, 5, 10, 25, 50, 100, 250], id: \.self) { Text("\($0) Mbit/s").tag($0 * 1000) }122 }123 } header: { Text("Network") } footer: { Text("Transfers never run in Low Data Mode. On the same network as the cluster, fragments travel directly to the coordinator; elsewhere they go through storage.spboucher.ai. The bandwidth limit applies to each transfer.") }124125 Section {126 Toggle("Only while charging", isOn: binding(\.chargingOnly))127 } header: { Text("Power") } footer: { Text("New fragments are always paused under 20 % battery, in Low Power Mode and when the device runs hot.") }128129 Section {130 Picker("Minimum reserve", selection: binding(\.reserveBytes)) {131 Text("Automatic (\(Format.bytes(CapacityMonitor.defaultReserve(total: s.capacity.total))))").tag(Int64?.none)132 ForEach([5, 10, 20, 50, 100], id: \.self) { Text("\($0) GB").tag(Int64?.some(Int64($0) * Format.gb)) }133 }134 } header: { Text("Storage") } footer: { Text("Space that is never given to the cluster. Automatic keeps the larger of 20 GB and 10 % of the device. The quota is set in Storage Allocation.") }135136 Section {137 Toggle("Keep the screen awake when plugged in", isOn: binding(\.keepAwakeInStationMode))138 Button("Enter station mode") { var st = node.settings; st.stationMode = true; Task { await node.save(st) }; node.enterStation() }139 } header: { Text("Station mode") } footer: { Text("For a device left plugged in as a dedicated node: dimmed status screen, more parallel transfers. The screen is never kept awake on battery.") }140141 Section {142 if s.serverStatus == "draining" || s.serverStatus == "drained" {143 Button(s.serverStatus == "drained" ? "Rejoin the cluster" : "Cancel the drain") { run { await node.cancelDrain() } }144 } else {145 Button("Drain this node…") { confirm = .drain }146 }147 Button("Remove this node from the cluster…") { confirm = .remove }148 Button("Emergency release…", role: .destructive) { confirm = .emergency }149 } header: { Text("Give storage back") } footer: { Text("Draining hands every fragment back in order, then frees the space. Emergency release frees the space immediately; the cluster rebuilds from its own copies.") }150151 Section("Diagnostics") {152 Button("Connection diagnostic") { showDiagnostics = true }153 Button("Storage benchmark") { showBenchmark = true }154 Button("Rotate the device key now") { Task { working = true; let ok = await node.rotateKey(); working = false; message = ok ? "A new key was generated and registered; the old one was destroyed." : "The key could not be rotated (cluster unreachable?)." } }155 row("Node ID", node.pairing.map { String($0.deviceID.prefix(16)) + "…" } ?? "—")156 row("Cluster", node.pairing?.host ?? "—")157 row("Device key", node.keyHardwareBacked ? "Secure Enclave" : "Keychain")158 row("Version", NodeController.deviceInfo.app)159 }160 }161 .scrollContentBackground(.hidden).background(Theme.canvas)162 .navigationTitle("Settings")163 .disabled(working)164 .confirmationDialog(title(confirm), isPresented: Binding(get: { confirm != nil }, set: { if !$0 { confirm = nil } }), titleVisibility: .visible, presenting: confirm) { c in165 switch c {166 case .drain: Button("Drain") { run { await node.drain(remove: false) } }167 case .remove:168 Button("Drain, then remove") { run { await node.drain(remove: true) } }169 Button("Remove now and erase", role: .destructive) { confirm = nil; DispatchQueue.main.async { confirm = .emergencyRemove } }170 case .emergency: Button("Erase all fragments now", role: .destructive) { release(remove: false) }171 case .emergencyRemove: Button("Erase and remove now", role: .destructive) { release(remove: true) }172 }173 Button("Cancel", role: .cancel) {}174 } message: { c in Text(explain(c)) }175 .alert("Storage Node", isPresented: Binding(get: { message != nil }, set: { if !$0 { message = nil } })) { Button("OK") {} } message: { Text(message ?? "") }176 .sheet(isPresented: $showDiagnostics) { DiagnosticsSheet().environmentObject(node) }177 .sheet(isPresented: $showBenchmark) { BenchmarkSheet().environmentObject(node) }178 }179 }180181 private func row(_ label: String, _ value: String) -> some View {182 HStack { Text(label); Spacer(); Text(value).font(.system(.footnote, design: .monospaced)).foregroundStyle(Theme.textSecondary).lineLimit(1) }183 }184 private func title(_ c: Confirm?) -> String {185 switch c {186 case .drain: return "Drain this node?"187 case .remove: return "Remove this node?"188 case .emergency: return "Free the space now?"189 case .emergencyRemove: return "Erase and remove now?"190 case nil: return ""191 }192 }193 private func explain(_ c: Confirm) -> String {194 let used = Format.bytes(node.snapshot.capacity.used)195 switch c {196 case .drain: return "The cluster stops sending fragments, confirms its own copy of each of the \(node.snapshot.capacity.fragments) held here, then deletes them from this device. Keep the app open until it is done. You can rejoin afterwards."197 case .remove: return "Draining first is the clean way: the node is removed once it is empty. Removing now erases \(used) immediately."198 case .emergency: return "\(used) of fragments are erased from this device at once. No data is lost: the cluster keeps a stable copy of every fragment and will rebuild its redundancy elsewhere. The node stays paired, empty."199 case .emergencyRemove: return "\(used) of fragments are erased and this device leaves the cluster. Pairing again will need a new code."200 }201 }202 private func run(_ action: @escaping () async -> String?) {203 working = true204 Task { if let err = await action() { message = err }; working = false }205 }206 private func release(remove: Bool) {207 working = true208 Task { let freed = await node.emergencyRelease(remove: remove); working = false; message = "\(Format.bytes(freed)) freed." }209 }210}211212struct DiagnosticsSheet: View {213 @EnvironmentObject private var node: NodeController214 @Environment(\.dismiss) private var dismiss215 @State private var lines: [DiagnosticLine] = []216 @State private var running = true217218 var body: some View {219 NavigationStack {220 List {221 if running { HStack(spacing: 10) { ProgressView(); Text("Testing the connection…").foregroundStyle(Theme.textSecondary) } }222 ForEach(lines) { l in223 HStack(alignment: .top, spacing: 12) {224 Image(systemName: l.ok ? "checkmark.circle" : "xmark.octagon").foregroundStyle(l.ok ? Theme.ok : Theme.critical)225 VStack(alignment: .leading, spacing: 3) {226 Text(l.label).font(.subheadline.weight(.medium))227 Text(l.detail).font(.footnote).foregroundStyle(Theme.textSecondary)228 }229 }.accessibilityElement(children: .combine)230 }231 }232 .navigationTitle("Connection diagnostic").navigationBarTitleDisplayMode(.inline)233 .toolbar {234 ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } }235 ToolbarItem(placement: .cancellationAction) { Button("Run again") { Task { await run() } }.disabled(running) }236 }237 .task { await run() }238 }239 }240 private func run() async { running = true; lines = []; lines = await node.diagnose(); running = false }241}242243struct BenchmarkSheet: View {244 @EnvironmentObject private var node: NodeController245 @Environment(\.dismiss) private var dismiss246 @State private var report = BenchmarkReport.load()247 @State private var running = false248249 var body: some View {250 NavigationStack {251 List {252 Section {253 Text("Writes, hashes and reads incompressible test data of 4, 16 and 64 MiB in the app's private storage (three passes each, median kept), then deletes it. The result is measured on this device, now, and sent to the cluster with the next heartbeat.")254 .font(.footnote).foregroundStyle(Theme.textSecondary)255 Button(running ? "Running…" : "Run the benchmark") { running = true; Task { if let r = await node.benchmark() { report = r }; running = false } }.disabled(running)256 }257 if let report {258 Section {259 ForEach(report.results) { r in260 VStack(alignment: .leading, spacing: 4) {261 Text("\(r.fragmentMiB) MiB fragments").font(.subheadline.weight(.medium))262 Text(String(format: "write + fsync %.0f MiB/s · SHA-256 %.0f MiB/s · read %.0f MiB/s", r.writeMiBps, r.hashMiBps, r.readMiBps)).font(.footnote.monospacedDigit()).foregroundStyle(Theme.textSecondary)263 }264 }265 Text("Thermal state: \(report.thermalBefore) before, \(report.thermalAfter) after").font(.footnote).foregroundStyle(Theme.textTertiary)266 }267 }268 }269 .navigationTitle("Storage benchmark").navigationBarTitleDisplayMode(.inline)270 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }271 }272 }273}274