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
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
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)
}
184 changes: 184 additions & 0 deletions mac-app/Sources/CloudMachineCore/AppKeepAlive.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import AppKit
import Foundation

/// Keeps the menu bar app alive, and brings it back when it vanishes.
///
/// On 1 Dec 2026 the icon disappeared: loginwindow logged `appDeath` for
/// com.renacode.cloudmachine with no crash report, under disk pressure. A
/// `LSUIElement` app without open windows is exactly what macOS may end by
/// Automatic Termination. The Info.plist now opts out, and the app calls
/// `ProcessInfo.disableAutomaticTermination` too. Nothing restarted it
/// afterwards, and the `app` launchd agent has only `RunAtLoad` (no
/// KeepAlive: `open` exits at once, so KeepAlive would loop).
///
/// NOTE on the cause: the icon that never appeared was NOT Automatic
/// Termination but a render loop in the label (see `MenuBarClock`). The opt-out
/// above is a precaution; the real fix for the loop is the clock.
///
/// The 30-minute watchdog (`backup-health`) calls `revive` AFTER it printed its
/// report: when the app is not running it opens it, unless
/// - the person quit it from its own menu (marker `app-quit-by-user`),
/// - an upgrade is under way (bundle changed < 5 min ago, or brew running),
/// - it already tried `maxAttempts` times since the app last started (a crash
/// loop must not become an open loop), or tried < `minInterval` ago.
/// Homebrew quits the app for an upgrade without the marker, so an upgrade is
/// followed by a reopen on the first watchdog run after it settles.
///
/// A running but hung app is only reported (`isHung`, from the heartbeat the
/// app writes on every clock tick); the process is never killed.
///
/// Known limitation: a second copy (a local build, another path) counts as
/// "running" by bundle id, and only /Applications/CloudMachine.app is reopened.
public struct AppKeepAlive {
public enum Reason: Equatable { case running, quitByUser, tooSoon, tooManyAttempts, upgrading }
public enum Decision: Equatable {
case launch
case skip(Reason)
}

public static let minInterval: TimeInterval = 5 * 60
public static let maxAttempts = 3
public static let upgradeQuietPeriod: TimeInterval = 5 * 60
public static let hangAfter: TimeInterval = 5 * 60
public static let launchTimeout: TimeInterval = 15
public static let bundleIdentifier = "com.renacode.cloudmachine"
public static let appPath = "/Applications/CloudMachine.app"

private let quitMarker: URL
private let attemptFile: URL
private let heartbeatFile: URL

public init(stateDir: URL = CMPaths.stateDir) {
quitMarker = stateDir.appendingPathComponent("app-quit-by-user")
attemptFile = stateDir.appendingPathComponent("app-relaunch-attempts")
heartbeatFile = stateDir.appendingPathComponent("app-heartbeat")
}

public static func decide(
appRunning: Bool, quitByUser: Bool, attempts: Int = 0, lastAttempt: Date?,
upgrading: Bool = false, now: Date
) -> Decision {
if appRunning { return .skip(.running) }
if quitByUser { return .skip(.quitByUser) }
if upgrading { return .skip(.upgrading) }
if attempts >= maxAttempts { return .skip(.tooManyAttempts) }
// A timestamp in the future (clock change) must not block forever.
if let last = lastAttempt, last <= now, now.timeIntervalSince(last) < minInterval {
return .skip(.tooSoon)
}
return .launch
}

/// Running, yet no sign of life from its main thread for `hangAfter`.
/// No heartbeat at all (an older app version) is not a hang.
public static func isHung(appRunning: Bool, heartbeat: Date?, now: Date) -> Bool {
guard appRunning, let heartbeat else { return false }
return now.timeIntervalSince(heartbeat) > hangAfter
}

// MARK: - Markers

public var quitByUser: Bool { FileManager.default.fileExists(atPath: quitMarker.path) }

public func markQuitByUser() {
try? Data().write(to: quitMarker)
}

/// The app started: an earlier deliberate Quit and the failed attempts no
/// longer apply.
public func appStarted() {
try? FileManager.default.removeItem(at: quitMarker)
try? FileManager.default.removeItem(at: attemptFile)
}

public func recordHeartbeat(_ now: Date = Date()) {
try? String(now.timeIntervalSince1970).write(
to: heartbeatFile, atomically: true, encoding: .utf8)
}

public var heartbeat: Date? { Self.readDate(heartbeatFile) }

private static func readDate(_ url: URL) -> Date? {
guard let text = try? String(contentsOf: url, encoding: .utf8),
let t = TimeInterval(text.split(separator: " ").first.map(String.init) ?? "")
else { return nil }
return Date(timeIntervalSince1970: t)
}

/// "<count> <last attempt timestamp>"
private var attemptState: (count: Int, last: Date?) {
guard let text = try? String(contentsOf: attemptFile, encoding: .utf8) else { return (0, nil) }
let parts = text.split(separator: " ")
guard parts.count == 2, let n = Int(parts[0]), let t = TimeInterval(parts[1]) else {
return (0, nil)
}
return (n, Date(timeIntervalSince1970: t))
}

// MARK: - Acting

/// Opens the app when `decide` says so. The attempt is recorded before the
/// launch, and a failed launch counts too (no retry storm). Returns whether
/// a launch succeeded.
@discardableResult
public func revive(
appRunning: Bool = AppKeepAlive.isRunning(),
upgrading: Bool = AppKeepAlive.upgradeInProgress(),
now: Date = Date(),
launch: () -> Bool = AppKeepAlive.openApp
) -> Bool {
let state = attemptState
guard
case .launch = Self.decide(
appRunning: appRunning, quitByUser: quitByUser, attempts: state.count,
lastAttempt: state.last, upgrading: upgrading, now: now)
else { return false }
try? "\(state.count + 1) \(now.timeIntervalSince1970)".write(
to: attemptFile, atomically: true, encoding: .utf8)
return launch()
}

public static func isRunning() -> Bool {
!NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier).isEmpty
}

/// The bundle was replaced a moment ago, or Homebrew is working on it:
/// reopening now would race the upgrade (half-copied bundle).
public static func upgradeInProgress(now: Date = Date()) -> Bool {
let plist = URL(fileURLWithPath: appPath).appendingPathComponent("Contents/Info.plist")
if let m = (try? FileManager.default.attributesOfItem(atPath: plist.path))?[.modificationDate]
as? Date, now.timeIntervalSince(m) < upgradeQuietPeriod
{
return true
}
let p = Process()
p.executableURL = URL(fileURLWithPath: "/usr/bin/pgrep")
p.arguments = ["-f", "brew (upgrade|reinstall|install)"]
p.standardOutput = FileHandle.nullDevice
do {
try p.run()
p.waitUntilExit()
return p.terminationStatus == 0
} catch { return false }
}

/// `open -g` (no focus steal), through Launch Services so the app gets its
/// Aqua session. Gives up after `launchTimeout`: a hung `open` must not hold
/// the watchdog. Does nothing when the app is not installed.
public static func openApp() -> Bool {
guard FileManager.default.fileExists(atPath: appPath) else { return false }
let p = Process()
p.executableURL = URL(fileURLWithPath: "/usr/bin/open")
p.arguments = ["-g", "-a", appPath]
do {
try p.run()
let deadline = Date().addingTimeInterval(launchTimeout)
while p.isRunning, Date() < deadline { Thread.sleep(forTimeInterval: 0.1) }
if p.isRunning {
p.terminate()
return false
}
return p.terminationStatus == 0
} catch { return false }
}
}
Loading
Loading