Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions launchd/com.renacode.cloudmachine.app.plist.template
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
would launch it over and over. The user closing the window should stay
closed, not be an invitation to restart.

If the app vanishes anyway (Automatic Termination, an upgrade), the
backup-health watchdog reopens it - see AppKeepAlive - unless the person
chose Quit from its menu.

The backups themselves do NOT depend on this app - the machine (started
by vm-start) and the vm-guard agent do them. This is only a viewer.
-->
Expand Down
9 changes: 9 additions & 0 deletions mac-app/Resources/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@
<string>14.0</string>
<key>LSUIElement</key>
<true/>
<!--
A menu bar app without open windows is a candidate for macOS Automatic
Termination, and the icon vanished (1 Dec 2026, loginwindow appDeath, no
crash report). It must only end when the person quits it.
-->
<key>NSSupportsAutomaticTermination</key>
<false/>
<key>NSSupportsSuddenTermination</key>
<false/>
<key>NSHumanReadableCopyright</key>
<string>Copyright (c) 2026 RenaCode. MIT License.</string>
<key>NSHighResolutionCapable</key>
Expand Down
23 changes: 23 additions & 0 deletions mac-app/Sources/CloudMachineAgent/MaintenanceCommands.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,23 @@ struct BackupHealthCommand: AsyncParsableCommand {
if !notice.detail.isEmpty { print(L10n.tr(" %@", notice.detail)) }
}

// A hung app is reported, never killed (see `AppKeepAlive.isHung`).
let keepAlive = AppKeepAlive()
if AppKeepAlive.isHung(
appRunning: AppKeepAlive.isRunning(), heartbeat: keepAlive.heartbeat, now: Date())
{
let age =
keepAlive.heartbeat.map { BackupHealth.formatAge(Date().timeIntervalSince($0)) } ?? ""
print(
L10n.tr(
"NOTE: %@",
L10n.tr("The CloudMachine app does not respond (no sign of life for %@).", age)))
}

guard !report.healthy else {
print(L10n.tr("Backup cycle: OK"))
if !quiet { await HealthAlert.report(report) }
reopenAppIfGone(keepAlive)
return
}

Expand All @@ -85,13 +99,22 @@ struct BackupHealthCommand: AsyncParsableCommand {
print(L10n.tr(" %@", problem.detail))
}
if !quiet { await HealthAlert.report(report) }
reopenAppIfGone(keepAlive)

// A non-zero exit code, so that launchd, `&&` in a script and a person
// looking at `echo $?` get the same signal as the text above.
throw ExitCode(1)
}
}

/// After the report: a vanished icon looks like a dead backup to the person,
/// but a slow `open` must never hold the report back (see `AppKeepAlive`).
private func reopenAppIfGone(_ keepAlive: AppKeepAlive) {
if keepAlive.revive() {
print(L10n.tr("CloudMachine was not running: reopened it."))
}
}

// MARK: - Safe shutdown

struct PrepareShutdown: AsyncParsableCommand {
Expand Down
2 changes: 1 addition & 1 deletion mac-app/Sources/CloudMachineAgent/VMCommands.swift
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ struct FixDestination: AsyncParsableCommand {
))

func run() async throws {
let result = await TimeMachineDestinationFix.run(
let result = await TimeMachineDestinationFix.runPreferringName(
address: await VMLayout.currentAddress(), mac: await VMLayout.instanceMAC())
print(result.message)
if let detail = result.detail { print(detail) }
Expand Down
22 changes: 15 additions & 7 deletions mac-app/Sources/CloudMachineApp/CloudMachineApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ import SwiftUI
@main
struct CloudMachineApp: App {
@StateObject private var controller = CloudMachineController()
@StateObject private var clock = MenuBarClock(heartbeat: { AppKeepAlive().recordHeartbeat($0) })

init() {
// The icon must stay until the person quits (see `AppKeepAlive`).
ProcessInfo.processInfo.disableAutomaticTermination("menu bar app")
ProcessInfo.processInfo.disableSuddenTermination()
// Started again: an earlier deliberate Quit and failed reopen attempts no longer apply.
AppKeepAlive().appStarted()
}

var body: some Scene {
MenuBarExtra {
Expand All @@ -12,7 +21,7 @@ struct CloudMachineApp: App {
.preferredColorScheme(.dark)
.environment(\.layoutDirection, layoutDirection)
} label: {
MenuBarIconView(status: controller.status)
MenuBarIconView(status: controller.status, clock: clock)
}
.menuBarExtraStyle(.window)

Expand All @@ -37,15 +46,14 @@ struct CloudMachineApp: App {

/// Observes the status itself: the scene's body does not re-run when a nested
/// object changes, and an icon that never updated would be the old bug again.
/// The clock is a separate object, NOT a periodic SwiftUI timeline (see `MenuBarClock`).
private struct MenuBarIconView: View {
@ObservedObject var status: AppStatus
@ObservedObject var clock: MenuBarClock

var body: some View {
// The clock matters too: an old read turns the icon to "unknown".
TimelineView(.periodic(from: .now, by: 30)) { _ in
let state = MenuBarIcon.state(for: status)
Image(systemName: MenuBarIcon.symbol(for: state))
.accessibilityLabel(MenuBarIcon.accessibilityLabel(for: state))
}
let state = MenuBarIcon.state(for: status, now: clock.now)
Image(systemName: MenuBarIcon.symbol(for: state))
.accessibilityLabel(MenuBarIcon.accessibilityLabel(for: state))
}
}
44 changes: 44 additions & 0 deletions mac-app/Sources/CloudMachineApp/Models/MenuBarClock.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import Combine
import Foundation

/// The "now" the menu bar icon is judged against (an old read turns the icon
/// to "unknown"). It lives outside the label view on purpose: the label used
/// `TimelineView(.periodic(from: .now, ...))`, whose schedule restarted on
/// every render and put the status item into an endless refresh loop, so the
/// icon never appeared (1 Dec 2026). Here ONE timer publishes once per interval,
/// and it is cancelled with the object (no `deinit` on a main-actor class).
///
/// Every tick also writes the app's heartbeat (`AppKeepAlive.isHung`).
@MainActor
final class MenuBarClock: ObservableObject {
/// Starts a repeating action; the returned token cancels it when released.
typealias Scheduler = (TimeInterval, @escaping @MainActor () -> Void) -> AnyCancellable

static let liveScheduler: Scheduler = { interval, action in
let timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in
Task { @MainActor in action() }
}
return AnyCancellable { timer.invalidate() }
}

@Published private(set) var now: Date
private var schedule: AnyCancellable?
private let heartbeat: (Date) -> Void

/// `scheduler == nil`: no timer (tests tick by hand).
init(
start: Date = Date(), interval: TimeInterval = 30,
scheduler: Scheduler? = MenuBarClock.liveScheduler,
heartbeat: @escaping (Date) -> Void = { _ in }
) {
now = start
self.heartbeat = heartbeat
heartbeat(start)
schedule = scheduler?(interval) { [weak self] in self?.tick() }
}

func tick(at date: Date = Date()) {
heartbeat(date)
now = date
}
}
4 changes: 2 additions & 2 deletions mac-app/Sources/CloudMachineApp/Models/MenuBarIcon.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ enum MenuBarIcon {
}

@MainActor
static func state(for status: AppStatus) -> State {
static func state(for status: AppStatus, now: Date = Date()) -> State {
if status.isChecking { return .checking }
if status.dataIsStale() { return .unknown }
if status.dataIsStale(now: now) { return .unknown }
switch status.overallTone {
case .success: return status.uploadCardState.isMovingData ? .uploading : .healthy
case .danger: return .actionNeeded
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ final class CloudMachineController: ObservableObject {
/// administrator dialog (`cloudmachine-agent fix-destination` does the same).
func setDestination() async {
await run(L10n.tr("Setting the Time Machine destination"), log: "Setting the destination") {
await TimeMachineDestinationFix.run(
await TimeMachineDestinationFix.runPreferringName(
address: status.machine.address, mac: await VMLayout.instanceMAC())
}
}
Expand Down
11 changes: 9 additions & 2 deletions mac-app/Sources/CloudMachineApp/Views/MenuBarContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ struct MenuBarPanel: View {
}
}
.buttonStyle(SecondaryGlassButtonStyle())
Button(action: { NSApplication.shared.terminate(nil) }) {
Button(action: quitByUser) {
Image(systemName: "power")
}
.buttonStyle(SecondaryGlassButtonStyle())
Expand Down Expand Up @@ -315,7 +315,7 @@ struct MenuBarPanel: View {
}
.buttonStyle(SecondaryGlassButtonStyle())

Button(action: { NSApplication.shared.terminate(nil) }) {
Button(action: quitByUser) {
Image(systemName: "power")
}
.buttonStyle(SecondaryGlassButtonStyle())
Expand Down Expand Up @@ -354,3 +354,10 @@ struct MenuBarPanel: View {
.tileCard()
}
}

/// Quit from the menu: the watchdog must not reopen the app after this
/// (`AppKeepAlive`).
@MainActor private func quitByUser() {
AppKeepAlive().markQuitByUser()
NSApplication.shared.terminate(nil)
}
Loading
Loading