Files
hapi/ios/Hapi/Features/Settings/MachinesView.swift
T
wushenghuaandHAPI c7c2a660b8 feat(ios): machines panel and app icon badge
Settings gains a Machines screen: health, CLI version, capability and
binary skew, rename, and the supervised runner restart the web banner
exposes. Skew derivation lives in HapiProtocol so it is testable
without a hub.

The icon badge counts unread sessions on the active hub, with a
notification-settings toggle that clears it immediately. The Japanese
app-language option is dropped (no shipped catalog).

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>
2026-12-05 12:10:17 +08:00

373 lines
13 KiB
Swift

import HapiClient
import HapiProtocol
import Observation
import SwiftUI
/// Pure row projection for the machine screen. Kept free of view state so the
/// restart gate and title fallbacks can be unit-tested without a hub.
struct MachineRowUI: Identifiable, Equatable {
enum RestartAvailability: Equatable {
case available
case needsNewerBinary
case needsSupervisor
}
let machine: Machine
let title: String
let subtitle: String
let health: String?
let isOnline: Bool
let runnerStatus: String?
let capabilitySkewed: Bool
let binaryUpdated: Bool
let restartAvailability: RestartAvailability
var id: String { machine.id }
var canRestart: Bool { restartAvailability == .available }
init(machine: Machine) {
self.machine = machine
let metadata = machine.metadata
let displayName = metadata?.displayName?.trimmingCharacters(in: .whitespacesAndNewlines)
title = (displayName?.isEmpty == false ? displayName : nil)
?? metadata?.host
?? String(machine.id.prefix(8))
var subtitleParts: [String] = []
if let platform = metadata?.platform, !platform.isEmpty {
subtitleParts.append(platform)
}
if let version = metadata?.happyCliVersion, !version.isEmpty {
subtitleParts.append("CLI \(version)")
}
subtitle = subtitleParts.joined(separator: " · ")
var healthParts: [String] = []
if let cpu = machine.health?.cpuPercent {
healthParts.append("CPU \(Int(cpu))%")
}
if let memory = machine.health?.memoryPercent {
healthParts.append("Mem \(Int(memory))%")
}
health = healthParts.isEmpty ? nil : healthParts.joined(separator: " · ")
isOnline = machine.active
runnerStatus = machine.runnerState?.status == "running"
? nil
: machine.runnerState?.status
capabilitySkewed = RunnerSkew.isCapabilitySkewed(metadata?.capabilities)
binaryUpdated = RunnerSkew.cliBinaryUpdatedOnDisk(metadata)
if !binaryUpdated {
restartAvailability = .needsNewerBinary
} else if metadata?.supervisedRestart != true {
restartAvailability = .needsSupervisor
} else {
restartAvailability = .available
}
}
}
/// One hub's machine list. `MachineStore` owns online/offline transitions via
/// `machine-updated`; this model only adds refresh, rename, and restart
/// actions plus their in-flight state.
@MainActor @Observable
final class MachinesModel {
private let session: HubSession
private(set) var isLoading = false
private(set) var isRefreshing = false
private(set) var restartingMachineId: String?
private(set) var errorMessage: String?
private(set) var notice: String?
@ObservationIgnored private var hasLoaded = false
init(session: HubSession) {
self.session = session
}
var rows: [MachineRowUI] {
session.machineStore.machines.map(MachineRowUI.init)
}
func loadIfNeeded() async {
guard !hasLoaded else { return }
hasLoaded = true
isLoading = rows.isEmpty
defer { isLoading = false }
await refresh()
}
func refresh() async {
errorMessage = nil
isRefreshing = true
defer { isRefreshing = false }
do {
try await session.machineStore.refresh()
} catch {
errorMessage = error.localizedDescription
}
}
func rename(machineId: String, displayName: String) async {
let trimmed = displayName.trimmingCharacters(in: .whitespacesAndNewlines)
let capped = String(trimmed.prefix(64))
errorMessage = nil
notice = nil
do {
try await session.api.renameMachine(id: machineId, displayName: capped)
await refresh()
} catch {
errorMessage = error.localizedDescription
}
}
func restart(machineId: String) async {
guard restartingMachineId == nil else { return }
restartingMachineId = machineId
errorMessage = nil
notice = nil
defer { restartingMachineId = nil }
do {
let response = try await session.api.restartMachineRunner(id: machineId)
notice = response.message
// The supervisor may take a moment to bring the runner back.
try? await Task.sleep(for: .seconds(1.5))
await refresh()
} catch {
errorMessage = error.localizedDescription
}
}
}
/// Settings → Machines: health, CLI version, capability skew, rename, and the
/// supervised runner restart that the web banner exposes.
struct MachinesView: View {
@State private var model: MachinesModel
@State private var renameTarget: MachineRowUI?
@State private var renameText = ""
@State private var restartTarget: MachineRowUI?
init(session: HubSession) {
_model = State(initialValue: MachinesModel(session: session))
}
var body: some View {
List {
if let error = model.errorMessage {
Section {
Text(verbatim: error)
.font(.footnote)
.foregroundStyle(.red)
Button("Retry") {
Task { await model.refresh() }
}
.disabled(model.isRefreshing)
}
}
if let notice = model.notice {
Section {
Label {
Text(verbatim: notice)
} icon: {
Image(systemName: "checkmark.circle")
}
.font(.footnote)
.foregroundStyle(.green)
}
}
if model.isLoading && model.rows.isEmpty {
Section {
HStack {
Spacer(minLength: 0)
ProgressView()
Spacer(minLength: 0)
}
}
} else if model.rows.isEmpty {
Section {
VStack(alignment: .leading, spacing: 10) {
Label("No machines online", systemImage: "desktopcomputer")
.font(.headline)
Text("Start the HAPI runner on a paired machine.")
.font(.footnote)
.foregroundStyle(.secondary)
Button("Refresh") {
Task { await model.refresh() }
}
.disabled(model.isRefreshing)
}
.padding(.vertical, 6)
}
} else {
Section {
ForEach(model.rows) { row in
machineRow(row)
}
} header: {
Text("Machines")
} footer: {
Text("Restart Runner appears when a newer HAPI CLI is installed on the host and the runner is supervised.")
}
}
}
.navigationTitle("Machines")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button {
Task { await model.refresh() }
} label: {
if model.isRefreshing {
ProgressView()
} else {
Image(systemName: "arrow.clockwise")
}
}
.disabled(model.isRefreshing)
.accessibilityLabel("Refresh")
}
}
.task { await model.loadIfNeeded() }
.refreshable { await model.refresh() }
.alert(
"Rename Machine",
isPresented: Binding(
get: { renameTarget != nil },
set: { if !$0 { renameTarget = nil } }
)
) {
TextField("Name", text: $renameText)
Button("Cancel", role: .cancel) { renameTarget = nil }
Button("Save") {
guard let id = renameTarget?.id else { return }
let name = renameText
renameTarget = nil
Task { await model.rename(machineId: id, displayName: name) }
}
} message: {
Text("Leave blank to use the host name.")
}
.confirmationDialog(
restartTitle,
isPresented: Binding(
get: { restartTarget != nil },
set: { if !$0 { restartTarget = nil } }
),
titleVisibility: .visible,
presenting: restartTarget
) { row in
Button("Restart", role: .destructive) {
restartTarget = nil
Task { await model.restart(machineId: row.id) }
}
Button("Cancel", role: .cancel) { restartTarget = nil }
} message: { _ in
Text("Running sessions may briefly disconnect.")
}
}
private var restartTitle: String {
guard let title = restartTarget?.title else {
return String(localized: "Restart Runner")
}
return String(
format: String(localized: "Restart runner on %@?"),
title
)
}
private func machineRow(_ row: MachineRowUI) -> some View {
VStack(alignment: .leading, spacing: 6) {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Text(verbatim: row.title)
.font(.headline)
Spacer(minLength: 8)
if model.restartingMachineId == row.id {
ProgressView()
.controlSize(.small)
} else {
Menu {
Button {
renameText = row.machine.metadata?.displayName ?? ""
renameTarget = row
} label: {
Label("Rename…", systemImage: "pencil")
}
Button {
restartTarget = row
} label: {
Label("Restart Runner", systemImage: "arrow.triangle.2.circlepath")
}
.disabled(!row.canRestart || model.restartingMachineId != nil)
} label: {
Image(systemName: "ellipsis.circle")
.frame(width: 32, height: 32)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityLabel(Text("Machine actions"))
}
}
if !row.subtitle.isEmpty {
Text(verbatim: row.subtitle)
.font(.caption)
.foregroundStyle(.secondary)
}
if let health = row.health {
Text(verbatim: health)
.font(.caption2)
.foregroundStyle(.secondary)
.monospacedDigit()
}
HStack(spacing: 6) {
if row.isOnline {
Text("Online")
.font(.caption2)
.foregroundStyle(.green)
} else {
Text("Offline")
.font(.caption2)
.foregroundStyle(.secondary)
}
if let runner = row.runnerStatus {
Text(verbatim: "· \(runner)")
.font(.caption2)
.foregroundStyle(.secondary)
}
}
if row.capabilitySkewed {
Label("Runner update required", systemImage: "exclamationmark.triangle.fill")
.font(.caption)
.foregroundStyle(.orange)
} else if row.binaryUpdated {
Label("Newer CLI binary installed — restart to apply", systemImage: "arrow.triangle.2.circlepath")
.font(.caption)
.foregroundStyle(.orange)
}
if row.capabilitySkewed || row.binaryUpdated {
switch row.restartAvailability {
case .available:
EmptyView()
case .needsNewerBinary:
Text("Install the newer HAPI CLI on the host first.")
.font(.caption2)
.foregroundStyle(.secondary)
case .needsSupervisor:
Text("This runner is not supervised; restart it from the host.")
.font(.caption2)
.foregroundStyle(.secondary)
}
}
}
.padding(.vertical, 2)
}
}