mirror of
https://github.com/wu736139669/hapi.git
synced 2026-12-06 07:17:02 +00:00
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>
This commit is contained in:
@@ -0,0 +1,372 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -62,9 +62,9 @@ final class SettingsModel {
|
||||
}
|
||||
|
||||
/// Settings home (A-M4e), presented as a sheet off the home toolbar: Hubs
|
||||
/// (switch / add / sign out), Appearance (theme mode), Language (persist-only
|
||||
/// until M5), the owner-only Usage/Storage entries, and About (app/protocol
|
||||
/// versions + hub health).
|
||||
/// (switch / add / sign out), Machines (health / runner restart), Appearance
|
||||
/// (theme mode), Language (persist-only until M5), the owner-only
|
||||
/// Usage/Storage entries, and About (app/protocol versions + hub health).
|
||||
struct SettingsView: View {
|
||||
@State private var model: SettingsModel
|
||||
@State private var languagePrefs: LanguagePrefs
|
||||
@@ -87,6 +87,7 @@ struct SettingsView: View {
|
||||
NavigationStack {
|
||||
List {
|
||||
hubsSection
|
||||
machinesSection
|
||||
appearanceSection
|
||||
languageSection
|
||||
notificationsSection
|
||||
@@ -156,6 +157,20 @@ struct SettingsView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var machinesSection: some View {
|
||||
Section {
|
||||
NavigationLink {
|
||||
MachinesView(session: session)
|
||||
} label: {
|
||||
detailRow(
|
||||
title: "Machines & runners",
|
||||
detail: "Health, version and runner restart"
|
||||
)
|
||||
}
|
||||
.accessibilityIdentifier("settings.machines")
|
||||
}
|
||||
}
|
||||
|
||||
private var signOutSection: some View {
|
||||
Section {
|
||||
Button("Sign Out…", role: .destructive) {
|
||||
@@ -260,8 +275,6 @@ struct SettingsView: View {
|
||||
UserDefaults.standard.set(["zh-Hans"], forKey: "AppleLanguages")
|
||||
case .russian:
|
||||
UserDefaults.standard.set(["ru"], forKey: "AppleLanguages")
|
||||
case .japanese:
|
||||
UserDefaults.standard.set(["ja"], forKey: "AppleLanguages")
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -300,6 +313,13 @@ struct SettingsView: View {
|
||||
set: { appModel.setLiveActivitiesEnabled($0) }
|
||||
)
|
||||
)
|
||||
Toggle(
|
||||
"App icon badge",
|
||||
isOn: Binding(
|
||||
get: { appModel.appBadgePrefs.enabled },
|
||||
set: { appModel.setAppIconBadgeEnabled($0) }
|
||||
)
|
||||
)
|
||||
} header: {
|
||||
Text("Notifications")
|
||||
} footer: {
|
||||
@@ -310,6 +330,7 @@ struct SettingsView: View {
|
||||
Text("Pushes are end-to-end encrypted; only this device can read them.")
|
||||
}
|
||||
Text("Live Activities show running sessions on the Lock Screen; their content is end-to-end encrypted too.")
|
||||
Text("The app icon badge shows the number of unread sessions on the active hub.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import HapiClient
|
||||
import HapiProtocol
|
||||
import Observation
|
||||
import SwiftUI
|
||||
import UserNotifications
|
||||
|
||||
/// A pairing that awaits user confirmation — from a deep link. Drives the
|
||||
/// confirm sheet.
|
||||
@@ -59,6 +60,7 @@ final class AppModel {
|
||||
// `let` storage is inert under @Observable (no annotation needed).
|
||||
let registry: HubRegistry
|
||||
let liveActivityPrefs: LiveActivityPrefs
|
||||
let appBadgePrefs: AppBadgePrefs
|
||||
let liveActivity: any LiveActivityControlling
|
||||
let widgetSnapshots: any WidgetSnapshotControlling
|
||||
private let credentialStore: any CredentialStoring
|
||||
@@ -83,6 +85,7 @@ final class AppModel {
|
||||
)
|
||||
let liveActivityPrefs = LiveActivityPrefs()
|
||||
self.liveActivityPrefs = liveActivityPrefs
|
||||
self.appBadgePrefs = AppBadgePrefs()
|
||||
self.liveActivity = LiveActivityControllerFactory.make(prefs: liveActivityPrefs)
|
||||
self.widgetSnapshots = WidgetSnapshotControllerFactory.make()
|
||||
WidgetRefreshBridge.shared.install { [weak self] in
|
||||
@@ -126,6 +129,7 @@ final class AppModel {
|
||||
}
|
||||
widgetSnapshots.clear()
|
||||
state = .unpaired
|
||||
updateAppBadge()
|
||||
}
|
||||
|
||||
// MARK: - Pairing
|
||||
@@ -188,6 +192,7 @@ final class AppModel {
|
||||
widgetSnapshots.clear()
|
||||
session?.shutdown()
|
||||
session = nil
|
||||
updateAppBadge()
|
||||
}
|
||||
// Best-effort push unregister, ordered before the credential wipe
|
||||
// below (the coordinator snapshots the record synchronously, so the
|
||||
@@ -283,6 +288,7 @@ final class AppModel {
|
||||
} else {
|
||||
widgetSnapshots.clear()
|
||||
}
|
||||
updateAppBadge()
|
||||
// Re-registers every hub when the APNs token arrives — the
|
||||
// cheap-upsert healing pass (Android registrar `start()`).
|
||||
PushCoordinator.shared.appDidBecomeActive(isPaired: state != .unpaired)
|
||||
@@ -304,6 +310,25 @@ final class AppModel {
|
||||
liveActivity.setEnabled(enabled)
|
||||
}
|
||||
|
||||
/// Settings toggle; turning it off clears the icon immediately.
|
||||
func setAppIconBadgeEnabled(_ enabled: Bool) {
|
||||
appBadgePrefs.setEnabled(enabled)
|
||||
updateAppBadge()
|
||||
}
|
||||
|
||||
/// Unread sessions across the active hub, matching the widget's read
|
||||
/// watermark. Other paired hubs are dormant until switched to, so their
|
||||
/// unread rows are not in memory here.
|
||||
private func updateAppBadge() {
|
||||
let count: Int
|
||||
if appBadgePrefs.enabled, let session {
|
||||
count = Self.unreadSessionIds(for: session).count
|
||||
} else {
|
||||
count = 0
|
||||
}
|
||||
UNUserNotificationCenter.current().setBadgeCount(count) { _ in }
|
||||
}
|
||||
|
||||
/// Background/silent-push refresh for the Home Screen widget. Fetches the
|
||||
/// active hub's list, rewrites the App Group snapshot, and waits for the
|
||||
/// write before the background task completes.
|
||||
@@ -321,12 +346,14 @@ final class AppModel {
|
||||
do {
|
||||
try await session.sessionStore.refresh()
|
||||
widgetSnapshots.update(session.sessionStore.sessions, unreadSessionIds: Self.unreadSessionIds(for: session), hubUrl: session.hubUrl)
|
||||
updateAppBadge()
|
||||
await widgetSnapshots.flushAndWait()
|
||||
return true
|
||||
} catch {
|
||||
// The cached snapshot is still better than an empty widget; the
|
||||
// next app/silent wake retries.
|
||||
widgetSnapshots.update(session.sessionStore.sessions, unreadSessionIds: Self.unreadSessionIds(for: session), hubUrl: session.hubUrl)
|
||||
updateAppBadge()
|
||||
await widgetSnapshots.flushAndWait()
|
||||
return false
|
||||
}
|
||||
@@ -345,6 +372,7 @@ final class AppModel {
|
||||
let previousStore = session?.lastSeenStore
|
||||
session?.shutdown()
|
||||
session = nil
|
||||
updateAppBadge()
|
||||
let token = UUID()
|
||||
activationToken = token
|
||||
if previousStore?.isPersisting == true || activationTask != nil {
|
||||
@@ -381,6 +409,7 @@ final class AppModel {
|
||||
// Unreachable for registry-normalized origins; fail closed.
|
||||
widgetSnapshots.clear()
|
||||
state = .unpaired
|
||||
updateAppBadge()
|
||||
return
|
||||
}
|
||||
newSession.onTerminalAuthFailure = { [weak self] in
|
||||
@@ -393,6 +422,7 @@ final class AppModel {
|
||||
unreadSessionIds: Self.unreadSessionIds(for: newSession),
|
||||
hubUrl: newSession.hubUrl
|
||||
)
|
||||
self.updateAppBadge()
|
||||
}
|
||||
newSession.sessionStore.onSessionsChanged = { [weak self, weak newSession] sessions in
|
||||
// A refresh that lands after a hub switch must not repopulate the
|
||||
@@ -400,12 +430,14 @@ final class AppModel {
|
||||
guard let self, let newSession, self.session === newSession else { return }
|
||||
self.liveActivity.sessionsChanged(sessions)
|
||||
self.widgetSnapshots.update(sessions, unreadSessionIds: Self.unreadSessionIds(for: newSession), hubUrl: newSession.hubUrl)
|
||||
self.updateAppBadge()
|
||||
}
|
||||
session = newSession
|
||||
state = .paired(activeHub: hub)
|
||||
hubs = registry.hubs
|
||||
liveActivity.attach(to: newSession)
|
||||
widgetSnapshots.update(newSession.sessionStore.sessions, unreadSessionIds: Self.unreadSessionIds(for: newSession), hubUrl: newSession.hubUrl)
|
||||
updateAppBadge()
|
||||
if isForeground {
|
||||
newSession.enterForeground()
|
||||
}
|
||||
@@ -419,6 +451,7 @@ final class AppModel {
|
||||
liveActivity.detach()
|
||||
widgetSnapshots.clear()
|
||||
session = nil // the session shut itself down before calling back
|
||||
updateAppBadge()
|
||||
authFailureNotice = hub
|
||||
// No JWT left to authenticate a push unregister; just drop the hub
|
||||
// from the status row (the hub prunes dead tokens itself).
|
||||
|
||||
@@ -1491,6 +1491,57 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"%lld days ago" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"ru" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "%lld дн назад"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "%lld天前"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"%lld hours ago" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"ru" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "%lld ч назад"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "%lld小时前"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"%lld min ago" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"ru" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "%lld мин назад"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "%lld分钟前"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"● Recording… %@" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
@@ -11104,6 +11155,23 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"Shared" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"ru" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Доступ"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "已分享"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Shared memory" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import HapiProtocol
|
||||
import XCTest
|
||||
@testable import Hapi
|
||||
|
||||
final class MachineRowPresentationTests: XCTestCase {
|
||||
private func machine(
|
||||
displayName: String? = nil,
|
||||
host: String = "mac-mini",
|
||||
capabilities: [String]? = ["agent-availability", "cursor-chat-store-status"],
|
||||
started: Double? = nil,
|
||||
installed: Double? = nil,
|
||||
supervised: Bool? = nil,
|
||||
cpu: Double? = 12,
|
||||
memory: Double? = 45
|
||||
) -> Machine {
|
||||
Machine(
|
||||
id: "machine-123456789",
|
||||
namespace: "default",
|
||||
seq: 1,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
active: true,
|
||||
activeAt: 0,
|
||||
metadata: MachineMetadata(
|
||||
host: host,
|
||||
platform: "darwin",
|
||||
happyCliVersion: "0.36.5",
|
||||
displayName: displayName,
|
||||
capabilities: capabilities,
|
||||
startedCliMtimeMs: started,
|
||||
installedCliMtimeMs: installed,
|
||||
supervisedRestart: supervised
|
||||
),
|
||||
metadataVersion: 1,
|
||||
runnerState: nil,
|
||||
runnerStateVersion: 1,
|
||||
health: MachineHealth(
|
||||
collectedAt: 0,
|
||||
cpuPercent: cpu,
|
||||
memoryPercent: memory
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
func testDisplayNameFallsBackToHostThenIdPrefix() {
|
||||
XCTAssertEqual(MachineRowUI(machine: machine(displayName: " Studio ")).title, "Studio")
|
||||
XCTAssertEqual(MachineRowUI(machine: machine(displayName: " ")).title, "mac-mini")
|
||||
}
|
||||
|
||||
func testSubtitleAndHealthAreCompact() {
|
||||
let row = MachineRowUI(machine: machine())
|
||||
XCTAssertEqual(row.subtitle, "darwin · CLI 0.36.5")
|
||||
XCTAssertEqual(row.health, "CPU 12% · Mem 45%")
|
||||
}
|
||||
|
||||
func testCapabilitySkewSurfacesEvenWhenTheRunnerIsOnline() {
|
||||
let row = MachineRowUI(machine: machine(capabilities: ["agent-availability"]))
|
||||
XCTAssertTrue(row.capabilitySkewed)
|
||||
XCTAssertFalse(row.canRestart)
|
||||
XCTAssertEqual(row.restartAvailability, .needsNewerBinary)
|
||||
}
|
||||
|
||||
func testRestartNeedsANewerBinaryOnDiskAndASupervisor() {
|
||||
let restartable = MachineRowUI(machine: machine(
|
||||
started: 100,
|
||||
installed: 200,
|
||||
supervised: true
|
||||
))
|
||||
XCTAssertTrue(restartable.binaryUpdated)
|
||||
XCTAssertTrue(restartable.canRestart)
|
||||
|
||||
let unsupervised = MachineRowUI(machine: machine(
|
||||
started: 100,
|
||||
installed: 200,
|
||||
supervised: false
|
||||
))
|
||||
XCTAssertEqual(unsupervised.restartAvailability, .needsSupervisor)
|
||||
|
||||
let sameBinary = MachineRowUI(machine: machine(
|
||||
started: 200,
|
||||
installed: 200,
|
||||
supervised: true
|
||||
))
|
||||
XCTAssertEqual(sameBinary.restartAvailability, .needsNewerBinary)
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,13 @@ extension APIClient {
|
||||
)
|
||||
}
|
||||
|
||||
/// `POST /api/machines/:id/restart-runner` — supervised hosts only. The
|
||||
/// hub asks the running runner to stop; the supervisor brings it back
|
||||
/// with the newly installed CLI.
|
||||
public func restartMachineRunner(id: String) async throws -> MachineRestartResponse {
|
||||
try await request(.post, "/api/machines/\(encodePathComponent(id))/restart-runner")
|
||||
}
|
||||
|
||||
/// `POST /api/machines/:id/spawn`. The response is discriminated on
|
||||
/// `type`, not HTTP status — a failed spawn is still HTTP 200 with
|
||||
/// `.error`.
|
||||
|
||||
@@ -48,7 +48,6 @@ public enum AppLanguage: String, CaseIterable, Sendable {
|
||||
case english = "en"
|
||||
case simplifiedChinese = "zh-Hans"
|
||||
case russian = "ru"
|
||||
case japanese = "ja"
|
||||
|
||||
/// Unknown/corrupt/absent stored values degrade to ``system``.
|
||||
public init(storageKey: String?) {
|
||||
@@ -66,7 +65,6 @@ public enum AppLanguage: String, CaseIterable, Sendable {
|
||||
case .english: return "English"
|
||||
case .simplifiedChinese: return "简体中文"
|
||||
case .russian: return "Русский"
|
||||
case .japanese: return "日本語"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,3 +111,24 @@ public final class LanguagePrefs {
|
||||
defaults.set(language.storageKey, forKey: Self.languageKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// App icon badge preference (web `useAppBadgePreference` twin). Defaults to
|
||||
/// on; the system permission still decides whether the badge is painted.
|
||||
@MainActor @Observable
|
||||
public final class AppBadgePrefs {
|
||||
public static let enabledKey = "settings.appIconBadge"
|
||||
|
||||
public private(set) var enabled: Bool
|
||||
|
||||
private let defaults: UserDefaults
|
||||
|
||||
public init(defaults: UserDefaults = .standard) {
|
||||
self.defaults = defaults
|
||||
self.enabled = defaults.object(forKey: Self.enabledKey) as? Bool ?? true
|
||||
}
|
||||
|
||||
public func setEnabled(_ enabled: Bool) {
|
||||
self.enabled = enabled
|
||||
defaults.set(enabled, forKey: Self.enabledKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,6 +178,15 @@ public struct Machine: Codable, Equatable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Body of `POST /api/machines/:id/restart-runner`.
|
||||
public struct MachineRestartResponse: Codable, Equatable, Sendable {
|
||||
public var message: String
|
||||
|
||||
public init(message: String) {
|
||||
self.message = message
|
||||
}
|
||||
}
|
||||
|
||||
/// A flat `machine-updated` patch.
|
||||
///
|
||||
/// Mirrors `MachinePatchSchema` (`shared/src/schemas.ts:509-513`), zod
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import Foundation
|
||||
|
||||
/// Ports `shared/src/runnerCapabilities.ts` for the native machine screen.
|
||||
/// The hub hard-depends on these machine RPCs, so a runner missing one is
|
||||
/// stale even when it still answers the heartbeat.
|
||||
public enum RunnerSkew {
|
||||
/// `REQUIRED_MACHINE_CAPABILITIES` values.
|
||||
public static let requiredMachineCapabilities: [String] = [
|
||||
"agent-availability",
|
||||
"cursor-chat-store-status",
|
||||
]
|
||||
|
||||
public static func missingRequiredCapabilities(_ advertised: [String]?) -> [String] {
|
||||
let set = Set(advertised ?? [])
|
||||
return requiredMachineCapabilities.filter { !set.contains($0) }
|
||||
}
|
||||
|
||||
public static func isCapabilitySkewed(_ advertised: [String]?) -> Bool {
|
||||
!missingRequiredCapabilities(advertised).isEmpty
|
||||
}
|
||||
|
||||
/// True when the running process started from a different CLI binary or
|
||||
/// mtime than the one currently installed on disk
|
||||
/// (`cliBinaryUpdatedOnDisk` in the shared package).
|
||||
public static func cliBinaryUpdatedOnDisk(_ metadata: MachineMetadata?) -> Bool {
|
||||
guard let started = metadata?.startedCliMtimeMs,
|
||||
let installed = metadata?.installedCliMtimeMs,
|
||||
started.isFinite,
|
||||
installed.isFinite else { return false }
|
||||
return started != installed
|
||||
}
|
||||
|
||||
/// Web banner restart gate: a newer binary is already on disk and the
|
||||
/// runner is under a supervisor that can bring it back.
|
||||
public static func canRestartRunner(_ machine: Machine) -> Bool {
|
||||
machine.active
|
||||
&& machine.metadata?.supervisedRestart == true
|
||||
&& cliBinaryUpdatedOnDisk(machine.metadata)
|
||||
}
|
||||
}
|
||||
@@ -223,6 +223,20 @@ struct EndpointRequestTests {
|
||||
#expect(account.buckets.first?.group == nil)
|
||||
}
|
||||
|
||||
@Test func restartMachineRunnerPostsToTheMachine() async throws {
|
||||
let harness = try makeHarness(jwt: freshJWT())
|
||||
await harness.performer.enqueue(json: "{\"message\":\"Runner restart requested\"}")
|
||||
|
||||
let response = try await harness.client.restartMachineRunner(id: "m 1")
|
||||
let request = await harness.performer.requests.first
|
||||
#expect(
|
||||
request?.url?.absoluteString
|
||||
== "\(testHubURLString)/api/machines/m%201/restart-runner"
|
||||
)
|
||||
#expect(request?.httpMethod == "POST")
|
||||
#expect(response.message == "Runner restart requested")
|
||||
}
|
||||
|
||||
@Test func sessionShareCreateReadAndRevoke() async throws {
|
||||
let harness = try makeHarness(jwt: freshJWT())
|
||||
await harness.performer.enqueue(
|
||||
@@ -260,6 +274,22 @@ struct EndpointRequestTests {
|
||||
#expect(deleteRequest?.httpMethod == "DELETE")
|
||||
}
|
||||
|
||||
@Test func sessionSharesListReturnsEveryActiveShare() async throws {
|
||||
let harness = try makeHarness(jwt: freshJWT())
|
||||
await harness.performer.enqueue(
|
||||
json: "{\"shares\":[{\"share\":{\"id\":\"sh 1\",\"sessionId\":\"s-1\","
|
||||
+ "\"shareToken\":\"tok\",\"createdAt\":1,\"updatedAt\":2},"
|
||||
+ "\"session\":{\"id\":\"s-1\"}},"
|
||||
+ "{\"share\":{\"id\":\"sh-2\",\"sessionId\":\"s-2\","
|
||||
+ "\"shareToken\":\"tok2\",\"createdAt\":3,\"updatedAt\":4},\"session\":null}]}"
|
||||
)
|
||||
let shares = try await harness.client.sessionShares()
|
||||
let request = await harness.performer.requests.last
|
||||
#expect(request?.url?.absoluteString == "\(testHubURLString)/api/session-shares")
|
||||
#expect(request?.httpMethod == "GET")
|
||||
#expect(shares.map(\.sessionId) == ["s-1", "s-2"])
|
||||
}
|
||||
|
||||
@Test func sessionContentSearchPostsScopedQuery() async throws {
|
||||
let harness = try makeHarness(jwt: freshJWT())
|
||||
await harness.performer.enqueue(
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import Foundation
|
||||
import HapiClient
|
||||
import Testing
|
||||
|
||||
/// App icon badge preference persistence (web `useAppBadgePreference` twin).
|
||||
@MainActor
|
||||
@Suite("App badge prefs")
|
||||
struct AppBadgePrefsTests {
|
||||
|
||||
private func makeDefaults() throws -> (UserDefaults, String) {
|
||||
let suiteName = "AppBadgePrefsTests-\(UUID().uuidString)"
|
||||
let defaults = try #require(UserDefaults(suiteName: suiteName))
|
||||
return (defaults, suiteName)
|
||||
}
|
||||
|
||||
@Test func defaultsToEnabled() throws {
|
||||
let (defaults, suiteName) = try makeDefaults()
|
||||
defer { defaults.removePersistentDomain(forName: suiteName) }
|
||||
|
||||
#expect(AppBadgePrefs(defaults: defaults).enabled)
|
||||
}
|
||||
|
||||
@Test func roundTripsThroughUserDefaults() throws {
|
||||
let (defaults, suiteName) = try makeDefaults()
|
||||
defer { defaults.removePersistentDomain(forName: suiteName) }
|
||||
|
||||
AppBadgePrefs(defaults: defaults).setEnabled(false)
|
||||
#expect(AppBadgePrefs(defaults: defaults).enabled == false)
|
||||
|
||||
AppBadgePrefs(defaults: defaults).setEnabled(true)
|
||||
#expect(AppBadgePrefs(defaults: defaults).enabled)
|
||||
}
|
||||
|
||||
@Test func corruptStoredValueFallsBackToEnabled() throws {
|
||||
let (defaults, suiteName) = try makeDefaults()
|
||||
defer { defaults.removePersistentDomain(forName: suiteName) }
|
||||
|
||||
defaults.set("no", forKey: AppBadgePrefs.enabledKey)
|
||||
#expect(AppBadgePrefs(defaults: defaults).enabled)
|
||||
}
|
||||
}
|
||||
@@ -94,7 +94,6 @@ struct ThemePrefsTests {
|
||||
#expect(AppLanguage.english.displayName == "English")
|
||||
#expect(AppLanguage.simplifiedChinese.displayName == "简体中文")
|
||||
#expect(AppLanguage.russian.displayName == "Русский")
|
||||
#expect(AppLanguage.japanese.displayName == "日本語")
|
||||
// The follow-system row's label is localized at the app layer; the
|
||||
// package carries the English source string.
|
||||
#expect(AppLanguage.system.displayName == "Follow system")
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import Foundation
|
||||
import HapiProtocol
|
||||
import Testing
|
||||
|
||||
@Suite("Runner skew")
|
||||
struct RunnerSkewTests {
|
||||
|
||||
private func metadata(
|
||||
capabilities: [String]? = nil,
|
||||
startedCliMtimeMs: Double? = nil,
|
||||
installedCliMtimeMs: Double? = nil,
|
||||
supervisedRestart: Bool? = nil
|
||||
) -> MachineMetadata {
|
||||
MachineMetadata(
|
||||
host: "mac-mini",
|
||||
platform: "darwin",
|
||||
happyCliVersion: "0.36.5",
|
||||
capabilities: capabilities,
|
||||
startedCliMtimeMs: startedCliMtimeMs,
|
||||
installedCliMtimeMs: installedCliMtimeMs,
|
||||
supervisedRestart: supervisedRestart
|
||||
)
|
||||
}
|
||||
|
||||
private func machine(_ metadata: MachineMetadata?) -> Machine {
|
||||
Machine(
|
||||
id: "m1",
|
||||
namespace: "default",
|
||||
seq: 1,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
active: true,
|
||||
activeAt: 0,
|
||||
metadata: metadata,
|
||||
metadataVersion: 1,
|
||||
runnerStateVersion: 1
|
||||
)
|
||||
}
|
||||
|
||||
@Test func missingOrEmptyCapabilitiesAreSkewed() {
|
||||
#expect(RunnerSkew.isCapabilitySkewed(nil))
|
||||
#expect(RunnerSkew.isCapabilitySkewed([]))
|
||||
}
|
||||
|
||||
@Test func currentRequiredCapabilitiesAreNotSkewed() {
|
||||
#expect(!RunnerSkew.isCapabilitySkewed(["agent-availability", "cursor-chat-store-status"]))
|
||||
#expect(!RunnerSkew.isCapabilitySkewed(["agent-availability", "cursor-chat-store-status", "agent-quotas"]))
|
||||
#expect(RunnerSkew.isCapabilitySkewed(["agent-availability"]))
|
||||
}
|
||||
|
||||
@Test func binaryUpdatedOnlyWhenBothMtimesDiffer() {
|
||||
#expect(RunnerSkew.cliBinaryUpdatedOnDisk(metadata(startedCliMtimeMs: 100, installedCliMtimeMs: 200)))
|
||||
#expect(!RunnerSkew.cliBinaryUpdatedOnDisk(metadata(startedCliMtimeMs: 200, installedCliMtimeMs: 200)))
|
||||
#expect(!RunnerSkew.cliBinaryUpdatedOnDisk(metadata(startedCliMtimeMs: 100)))
|
||||
#expect(!RunnerSkew.cliBinaryUpdatedOnDisk(nil))
|
||||
}
|
||||
|
||||
@Test func restartNeedsANewerBinaryAndASupervisor() {
|
||||
let restarted = machine(metadata(
|
||||
startedCliMtimeMs: 100,
|
||||
installedCliMtimeMs: 200,
|
||||
supervisedRestart: true
|
||||
))
|
||||
#expect(RunnerSkew.canRestartRunner(restarted))
|
||||
|
||||
let sameBinary = machine(metadata(
|
||||
startedCliMtimeMs: 200,
|
||||
installedCliMtimeMs: 200,
|
||||
supervisedRestart: true
|
||||
))
|
||||
#expect(!RunnerSkew.canRestartRunner(sameBinary))
|
||||
|
||||
let unsupervised = machine(metadata(
|
||||
startedCliMtimeMs: 100,
|
||||
installedCliMtimeMs: 200,
|
||||
supervisedRestart: false
|
||||
))
|
||||
#expect(!RunnerSkew.canRestartRunner(unsupervised))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user